]> git.proxmox.com Git - rustc.git/blob - src/librustc_hir_pretty/lib.rs
New upstream version 1.47.0~beta.2+dfsg1
[rustc.git] / src / librustc_hir_pretty / lib.rs
1 #![feature(or_patterns)]
2 #![recursion_limit = "256"]
3
4 use rustc_ast as ast;
5 use rustc_ast::util::parser::{self, AssocOp, Fixity};
6 use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent};
7 use rustc_ast_pretty::pp::{self, Breaks};
8 use rustc_ast_pretty::pprust::{Comments, PrintState};
9 use rustc_hir as hir;
10 use rustc_hir::{GenericArg, GenericParam, GenericParamKind, Node};
11 use rustc_hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier};
12 use rustc_span::source_map::{SourceMap, Spanned};
13 use rustc_span::symbol::{kw, Ident, IdentPrinter, Symbol};
14 use rustc_span::{self, BytePos, FileName};
15 use rustc_target::spec::abi::Abi;
16
17 use std::borrow::Cow;
18 use std::cell::Cell;
19 use std::vec;
20
21 pub fn id_to_string(map: &dyn rustc_hir::intravisit::Map<'_>, hir_id: hir::HirId) -> String {
22 to_string(&map, |s| s.print_node(map.find(hir_id).unwrap()))
23 }
24
25 pub enum AnnNode<'a> {
26 Name(&'a Symbol),
27 Block(&'a hir::Block<'a>),
28 Item(&'a hir::Item<'a>),
29 SubItem(hir::HirId),
30 Expr(&'a hir::Expr<'a>),
31 Pat(&'a hir::Pat<'a>),
32 Arm(&'a hir::Arm<'a>),
33 }
34
35 pub enum Nested {
36 Item(hir::ItemId),
37 TraitItem(hir::TraitItemId),
38 ImplItem(hir::ImplItemId),
39 Body(hir::BodyId),
40 BodyParamPat(hir::BodyId, usize),
41 }
42
43 pub trait PpAnn {
44 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
45 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
46 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
47 fn try_fetch_item(&self, _: hir::HirId) -> Option<&hir::Item<'_>> {
48 None
49 }
50 }
51
52 pub struct NoAnn;
53 impl PpAnn for NoAnn {}
54 pub const NO_ANN: &dyn PpAnn = &NoAnn;
55
56 impl PpAnn for hir::Crate<'_> {
57 fn try_fetch_item(&self, item: hir::HirId) -> Option<&hir::Item<'_>> {
58 Some(self.item(item))
59 }
60 fn nested(&self, state: &mut State<'_>, nested: Nested) {
61 match nested {
62 Nested::Item(id) => state.print_item(self.item(id.id)),
63 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
64 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
65 Nested::Body(id) => state.print_expr(&self.body(id).value),
66 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
67 }
68 }
69 }
70
71 /// Identical to the `PpAnn` implementation for `hir::Crate`,
72 /// except it avoids creating a dependency on the whole crate.
73 impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
74 fn nested(&self, state: &mut State<'_>, nested: Nested) {
75 match nested {
76 Nested::Item(id) => state.print_item(self.item(id.id)),
77 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
78 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
79 Nested::Body(id) => state.print_expr(&self.body(id).value),
80 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
81 }
82 }
83 }
84
85 pub struct State<'a> {
86 pub s: pp::Printer,
87 comments: Option<Comments<'a>>,
88 ann: &'a (dyn PpAnn + 'a),
89 }
90
91 impl<'a> State<'a> {
92 pub fn print_node(&mut self, node: Node<'_>) {
93 match node {
94 Node::Param(a) => self.print_param(&a),
95 Node::Item(a) => self.print_item(&a),
96 Node::ForeignItem(a) => self.print_foreign_item(&a),
97 Node::TraitItem(a) => self.print_trait_item(a),
98 Node::ImplItem(a) => self.print_impl_item(a),
99 Node::Variant(a) => self.print_variant(&a),
100 Node::AnonConst(a) => self.print_anon_const(&a),
101 Node::Expr(a) => self.print_expr(&a),
102 Node::Stmt(a) => self.print_stmt(&a),
103 Node::PathSegment(a) => self.print_path_segment(&a),
104 Node::Ty(a) => self.print_type(&a),
105 Node::TraitRef(a) => self.print_trait_ref(&a),
106 Node::Binding(a) | Node::Pat(a) => self.print_pat(&a),
107 Node::Arm(a) => self.print_arm(&a),
108 Node::Block(a) => {
109 // Containing cbox, will be closed by print-block at `}`.
110 self.cbox(INDENT_UNIT);
111 // Head-ibox, will be closed by print-block after `{`.
112 self.ibox(0);
113 self.print_block(&a)
114 }
115 Node::Lifetime(a) => self.print_lifetime(&a),
116 Node::Visibility(a) => self.print_visibility(&a),
117 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
118 Node::Field(_) => panic!("cannot print StructField"),
119 // These cases do not carry enough information in the
120 // `hir_map` to reconstruct their full structure for pretty
121 // printing.
122 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
123 Node::Local(a) => self.print_local_decl(&a),
124 Node::MacroDef(_) => panic!("cannot print MacroDef"),
125 Node::Crate(..) => panic!("cannot print Crate"),
126 }
127 }
128 }
129
130 impl std::ops::Deref for State<'_> {
131 type Target = pp::Printer;
132 fn deref(&self) -> &Self::Target {
133 &self.s
134 }
135 }
136
137 impl std::ops::DerefMut for State<'_> {
138 fn deref_mut(&mut self) -> &mut Self::Target {
139 &mut self.s
140 }
141 }
142
143 impl<'a> PrintState<'a> for State<'a> {
144 fn comments(&mut self) -> &mut Option<Comments<'a>> {
145 &mut self.comments
146 }
147
148 fn print_ident(&mut self, ident: Ident) {
149 self.s.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
150 self.ann.post(self, AnnNode::Name(&ident.name))
151 }
152
153 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
154 panic!("AST generic args printed by HIR pretty-printer");
155 }
156 }
157
158 pub const INDENT_UNIT: usize = 4;
159
160 /// Requires you to pass an input filename and reader so that
161 /// it can scan the input text for comments to copy forward.
162 pub fn print_crate<'a>(
163 sm: &'a SourceMap,
164 krate: &hir::Crate<'_>,
165 filename: FileName,
166 input: String,
167 ann: &'a dyn PpAnn,
168 ) -> String {
169 let mut s = State::new_from_input(sm, filename, input, ann);
170
171 // When printing the AST, we sometimes need to inject `#[no_std]` here.
172 // Since you can't compile the HIR, it's not necessary.
173
174 s.print_mod(&krate.item.module, &krate.item.attrs);
175 s.print_remaining_comments();
176 s.s.eof()
177 }
178
179 impl<'a> State<'a> {
180 pub fn new_from_input(
181 sm: &'a SourceMap,
182 filename: FileName,
183 input: String,
184 ann: &'a dyn PpAnn,
185 ) -> State<'a> {
186 State { s: pp::mk_printer(), comments: Some(Comments::new(sm, filename, input)), ann }
187 }
188 }
189
190 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
191 where
192 F: FnOnce(&mut State<'_>),
193 {
194 let mut printer = State { s: pp::mk_printer(), comments: None, ann };
195 f(&mut printer);
196 printer.s.eof()
197 }
198
199 pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility<'_>, w: S) -> String {
200 to_string(NO_ANN, |s| {
201 s.print_visibility(vis);
202 s.s.word(w)
203 })
204 }
205
206 pub fn generic_params_to_string(generic_params: &[GenericParam<'_>]) -> String {
207 to_string(NO_ANN, |s| s.print_generic_params(generic_params))
208 }
209
210 pub fn bounds_to_string<'b>(bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>) -> String {
211 to_string(NO_ANN, |s| s.print_bounds("", bounds))
212 }
213
214 pub fn param_to_string(arg: &hir::Param<'_>) -> String {
215 to_string(NO_ANN, |s| s.print_param(arg))
216 }
217
218 pub fn ty_to_string(ty: &hir::Ty<'_>) -> String {
219 to_string(NO_ANN, |s| s.print_type(ty))
220 }
221
222 pub fn path_segment_to_string(segment: &hir::PathSegment<'_>) -> String {
223 to_string(NO_ANN, |s| s.print_path_segment(segment))
224 }
225
226 pub fn path_to_string(segment: &hir::Path<'_>) -> String {
227 to_string(NO_ANN, |s| s.print_path(segment, false))
228 }
229
230 pub fn fn_to_string(
231 decl: &hir::FnDecl<'_>,
232 header: hir::FnHeader,
233 name: Option<Symbol>,
234 generics: &hir::Generics<'_>,
235 vis: &hir::Visibility<'_>,
236 arg_names: &[Ident],
237 body_id: Option<hir::BodyId>,
238 ) -> String {
239 to_string(NO_ANN, |s| s.print_fn(decl, header, name, generics, vis, arg_names, body_id))
240 }
241
242 pub fn enum_def_to_string(
243 enum_definition: &hir::EnumDef<'_>,
244 generics: &hir::Generics<'_>,
245 name: Symbol,
246 span: rustc_span::Span,
247 visibility: &hir::Visibility<'_>,
248 ) -> String {
249 to_string(NO_ANN, |s| s.print_enum_def(enum_definition, generics, name, span, visibility))
250 }
251
252 impl<'a> State<'a> {
253 pub fn cbox(&mut self, u: usize) {
254 self.s.cbox(u);
255 }
256
257 pub fn nbsp(&mut self) {
258 self.s.word(" ")
259 }
260
261 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
262 self.s.word(w);
263 self.nbsp()
264 }
265
266 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
267 let w = w.into();
268 // outer-box is consistent
269 self.cbox(INDENT_UNIT);
270 // head-box is inconsistent
271 self.ibox(w.len() + 1);
272 // keyword that starts the head
273 if !w.is_empty() {
274 self.word_nbsp(w);
275 }
276 }
277
278 pub fn bopen(&mut self) {
279 self.s.word("{");
280 self.end(); // close the head-box
281 }
282
283 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
284 self.maybe_print_comment(span.hi());
285 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
286 self.s.word("}");
287 if close_box {
288 self.end(); // close the outer-box
289 }
290 }
291
292 pub fn bclose(&mut self, span: rustc_span::Span) {
293 self.bclose_maybe_open(span, true)
294 }
295
296 pub fn space_if_not_bol(&mut self) {
297 if !self.s.is_beginning_of_line() {
298 self.s.space();
299 }
300 }
301
302 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
303 if !self.s.is_beginning_of_line() {
304 self.s.break_offset(n, off)
305 } else {
306 if off != 0 && self.s.last_token().is_hardbreak_tok() {
307 // We do something pretty sketchy here: tuck the nonzero
308 // offset-adjustment we were going to deposit along with the
309 // break into the previous hardbreak.
310 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
311 }
312 }
313 }
314
315 // Synthesizes a comment that was not textually present in the original source
316 // file.
317 pub fn synth_comment(&mut self, text: String) {
318 self.s.word("/*");
319 self.s.space();
320 self.s.word(text);
321 self.s.space();
322 self.s.word("*/")
323 }
324
325 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
326 where
327 F: FnMut(&mut State<'_>, &T),
328 G: FnMut(&T) -> rustc_span::Span,
329 {
330 self.rbox(0, b);
331 let len = elts.len();
332 let mut i = 0;
333 for elt in elts {
334 self.maybe_print_comment(get_span(elt).hi());
335 op(self, elt);
336 i += 1;
337 if i < len {
338 self.s.word(",");
339 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
340 self.space_if_not_bol();
341 }
342 }
343 self.end();
344 }
345
346 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
347 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
348 }
349
350 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
351 self.print_inner_attributes(attrs);
352 for &item_id in _mod.item_ids {
353 self.ann.nested(self, Nested::Item(item_id));
354 }
355 }
356
357 pub fn print_foreign_mod(&mut self, nmod: &hir::ForeignMod<'_>, attrs: &[ast::Attribute]) {
358 self.print_inner_attributes(attrs);
359 for item in nmod.items {
360 self.print_foreign_item(item);
361 }
362 }
363
364 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
365 if !lifetime.is_elided() {
366 self.print_lifetime(lifetime);
367 self.nbsp();
368 }
369 }
370
371 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
372 self.maybe_print_comment(ty.span.lo());
373 self.ibox(0);
374 match ty.kind {
375 hir::TyKind::Slice(ref ty) => {
376 self.s.word("[");
377 self.print_type(&ty);
378 self.s.word("]");
379 }
380 hir::TyKind::Ptr(ref mt) => {
381 self.s.word("*");
382 self.print_mt(mt, true);
383 }
384 hir::TyKind::Rptr(ref lifetime, ref mt) => {
385 self.s.word("&");
386 self.print_opt_lifetime(lifetime);
387 self.print_mt(mt, false);
388 }
389 hir::TyKind::Never => {
390 self.s.word("!");
391 }
392 hir::TyKind::Tup(ref elts) => {
393 self.popen();
394 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
395 if elts.len() == 1 {
396 self.s.word(",");
397 }
398 self.pclose();
399 }
400 hir::TyKind::BareFn(ref f) => {
401 self.print_ty_fn(
402 f.abi,
403 f.unsafety,
404 &f.decl,
405 None,
406 &f.generic_params,
407 &f.param_names[..],
408 );
409 }
410 hir::TyKind::OpaqueDef(..) => self.s.word("/*impl Trait*/"),
411 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
412 hir::TyKind::TraitObject(bounds, ref lifetime) => {
413 let mut first = true;
414 for bound in bounds {
415 if first {
416 first = false;
417 } else {
418 self.nbsp();
419 self.word_space("+");
420 }
421 self.print_poly_trait_ref(bound);
422 }
423 if !lifetime.is_elided() {
424 self.nbsp();
425 self.word_space("+");
426 self.print_lifetime(lifetime);
427 }
428 }
429 hir::TyKind::Array(ref ty, ref length) => {
430 self.s.word("[");
431 self.print_type(&ty);
432 self.s.word("; ");
433 self.print_anon_const(length);
434 self.s.word("]");
435 }
436 hir::TyKind::Typeof(ref e) => {
437 self.s.word("typeof(");
438 self.print_anon_const(e);
439 self.s.word(")");
440 }
441 hir::TyKind::Infer => {
442 self.s.word("_");
443 }
444 hir::TyKind::Err => {
445 self.popen();
446 self.s.word("/*ERROR*/");
447 self.pclose();
448 }
449 }
450 self.end()
451 }
452
453 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
454 self.hardbreak_if_not_bol();
455 self.maybe_print_comment(item.span.lo());
456 self.print_outer_attributes(&item.attrs);
457 match item.kind {
458 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
459 self.head("");
460 self.print_fn(
461 decl,
462 hir::FnHeader {
463 unsafety: hir::Unsafety::Normal,
464 constness: hir::Constness::NotConst,
465 abi: Abi::Rust,
466 asyncness: hir::IsAsync::NotAsync,
467 },
468 Some(item.ident.name),
469 generics,
470 &item.vis,
471 arg_names,
472 None,
473 );
474 self.end(); // end head-ibox
475 self.s.word(";");
476 self.end() // end the outer fn box
477 }
478 hir::ForeignItemKind::Static(ref t, m) => {
479 self.head(visibility_qualified(&item.vis, "static"));
480 if m == hir::Mutability::Mut {
481 self.word_space("mut");
482 }
483 self.print_ident(item.ident);
484 self.word_space(":");
485 self.print_type(&t);
486 self.s.word(";");
487 self.end(); // end the head-ibox
488 self.end() // end the outer cbox
489 }
490 hir::ForeignItemKind::Type => {
491 self.head(visibility_qualified(&item.vis, "type"));
492 self.print_ident(item.ident);
493 self.s.word(";");
494 self.end(); // end the head-ibox
495 self.end() // end the outer cbox
496 }
497 }
498 }
499
500 fn print_associated_const(
501 &mut self,
502 ident: Ident,
503 ty: &hir::Ty<'_>,
504 default: Option<hir::BodyId>,
505 vis: &hir::Visibility<'_>,
506 ) {
507 self.s.word(visibility_qualified(vis, ""));
508 self.word_space("const");
509 self.print_ident(ident);
510 self.word_space(":");
511 self.print_type(ty);
512 if let Some(expr) = default {
513 self.s.space();
514 self.word_space("=");
515 self.ann.nested(self, Nested::Body(expr));
516 }
517 self.s.word(";")
518 }
519
520 fn print_associated_type(
521 &mut self,
522 ident: Ident,
523 generics: &hir::Generics<'_>,
524 bounds: Option<hir::GenericBounds<'_>>,
525 ty: Option<&hir::Ty<'_>>,
526 ) {
527 self.word_space("type");
528 self.print_ident(ident);
529 self.print_generic_params(&generics.params);
530 if let Some(bounds) = bounds {
531 self.print_bounds(":", bounds);
532 }
533 self.print_where_clause(&generics.where_clause);
534 if let Some(ty) = ty {
535 self.s.space();
536 self.word_space("=");
537 self.print_type(ty);
538 }
539 self.s.word(";")
540 }
541
542 fn print_item_type(
543 &mut self,
544 item: &hir::Item<'_>,
545 generics: &hir::Generics<'_>,
546 inner: impl Fn(&mut Self),
547 ) {
548 self.head(visibility_qualified(&item.vis, "type"));
549 self.print_ident(item.ident);
550 self.print_generic_params(&generics.params);
551 self.end(); // end the inner ibox
552
553 self.print_where_clause(&generics.where_clause);
554 self.s.space();
555 inner(self);
556 self.s.word(";");
557 self.end(); // end the outer ibox
558 }
559
560 /// Pretty-print an item
561 pub fn print_item(&mut self, item: &hir::Item<'_>) {
562 self.hardbreak_if_not_bol();
563 self.maybe_print_comment(item.span.lo());
564 self.print_outer_attributes(&item.attrs);
565 self.ann.pre(self, AnnNode::Item(item));
566 match item.kind {
567 hir::ItemKind::ExternCrate(orig_name) => {
568 self.head(visibility_qualified(&item.vis, "extern crate"));
569 if let Some(orig_name) = orig_name {
570 self.print_name(orig_name);
571 self.s.space();
572 self.s.word("as");
573 self.s.space();
574 }
575 self.print_ident(item.ident);
576 self.s.word(";");
577 self.end(); // end inner head-block
578 self.end(); // end outer head-block
579 }
580 hir::ItemKind::Use(ref path, kind) => {
581 self.head(visibility_qualified(&item.vis, "use"));
582 self.print_path(path, false);
583
584 match kind {
585 hir::UseKind::Single => {
586 if path.segments.last().unwrap().ident != item.ident {
587 self.s.space();
588 self.word_space("as");
589 self.print_ident(item.ident);
590 }
591 self.s.word(";");
592 }
593 hir::UseKind::Glob => self.s.word("::*;"),
594 hir::UseKind::ListStem => self.s.word("::{};"),
595 }
596 self.end(); // end inner head-block
597 self.end(); // end outer head-block
598 }
599 hir::ItemKind::Static(ref ty, m, expr) => {
600 self.head(visibility_qualified(&item.vis, "static"));
601 if m == hir::Mutability::Mut {
602 self.word_space("mut");
603 }
604 self.print_ident(item.ident);
605 self.word_space(":");
606 self.print_type(&ty);
607 self.s.space();
608 self.end(); // end the head-ibox
609
610 self.word_space("=");
611 self.ann.nested(self, Nested::Body(expr));
612 self.s.word(";");
613 self.end(); // end the outer cbox
614 }
615 hir::ItemKind::Const(ref ty, expr) => {
616 self.head(visibility_qualified(&item.vis, "const"));
617 self.print_ident(item.ident);
618 self.word_space(":");
619 self.print_type(&ty);
620 self.s.space();
621 self.end(); // end the head-ibox
622
623 self.word_space("=");
624 self.ann.nested(self, Nested::Body(expr));
625 self.s.word(";");
626 self.end(); // end the outer cbox
627 }
628 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
629 self.head("");
630 self.print_fn(
631 &sig.decl,
632 sig.header,
633 Some(item.ident.name),
634 param_names,
635 &item.vis,
636 &[],
637 Some(body),
638 );
639 self.s.word(" ");
640 self.end(); // need to close a box
641 self.end(); // need to close a box
642 self.ann.nested(self, Nested::Body(body));
643 }
644 hir::ItemKind::Mod(ref _mod) => {
645 self.head(visibility_qualified(&item.vis, "mod"));
646 self.print_ident(item.ident);
647 self.nbsp();
648 self.bopen();
649 self.print_mod(_mod, &item.attrs);
650 self.bclose(item.span);
651 }
652 hir::ItemKind::ForeignMod(ref nmod) => {
653 self.head("extern");
654 self.word_nbsp(nmod.abi.to_string());
655 self.bopen();
656 self.print_foreign_mod(nmod, &item.attrs);
657 self.bclose(item.span);
658 }
659 hir::ItemKind::GlobalAsm(ref ga) => {
660 self.head(visibility_qualified(&item.vis, "global asm"));
661 self.s.word(ga.asm.to_string());
662 self.end()
663 }
664 hir::ItemKind::TyAlias(ref ty, ref generics) => {
665 self.print_item_type(item, &generics, |state| {
666 state.word_space("=");
667 state.print_type(&ty);
668 });
669 }
670 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
671 self.print_item_type(item, &opaque_ty.generics, |state| {
672 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
673 for b in opaque_ty.bounds.iter() {
674 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
675 state.s.space();
676 state.word_space("for ?");
677 state.print_trait_ref(&ptr.trait_ref);
678 } else {
679 real_bounds.push(b);
680 }
681 }
682 state.print_bounds("= impl", real_bounds);
683 });
684 }
685 hir::ItemKind::Enum(ref enum_definition, ref params) => {
686 self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis);
687 }
688 hir::ItemKind::Struct(ref struct_def, ref generics) => {
689 self.head(visibility_qualified(&item.vis, "struct"));
690 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
691 }
692 hir::ItemKind::Union(ref struct_def, ref generics) => {
693 self.head(visibility_qualified(&item.vis, "union"));
694 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
695 }
696 hir::ItemKind::Impl {
697 unsafety,
698 polarity,
699 defaultness,
700 constness,
701 defaultness_span: _,
702 ref generics,
703 ref of_trait,
704 ref self_ty,
705 items,
706 } => {
707 self.head("");
708 self.print_visibility(&item.vis);
709 self.print_defaultness(defaultness);
710 self.print_unsafety(unsafety);
711 self.word_nbsp("impl");
712
713 if !generics.params.is_empty() {
714 self.print_generic_params(&generics.params);
715 self.s.space();
716 }
717
718 if constness == hir::Constness::Const {
719 self.word_nbsp("const");
720 }
721
722 if let hir::ImplPolarity::Negative(_) = polarity {
723 self.s.word("!");
724 }
725
726 if let Some(ref t) = of_trait {
727 self.print_trait_ref(t);
728 self.s.space();
729 self.word_space("for");
730 }
731
732 self.print_type(&self_ty);
733 self.print_where_clause(&generics.where_clause);
734
735 self.s.space();
736 self.bopen();
737 self.print_inner_attributes(&item.attrs);
738 for impl_item in items {
739 self.ann.nested(self, Nested::ImplItem(impl_item.id));
740 }
741 self.bclose(item.span);
742 }
743 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => {
744 self.head("");
745 self.print_visibility(&item.vis);
746 self.print_is_auto(is_auto);
747 self.print_unsafety(unsafety);
748 self.word_nbsp("trait");
749 self.print_ident(item.ident);
750 self.print_generic_params(&generics.params);
751 let mut real_bounds = Vec::with_capacity(bounds.len());
752 for b in bounds.iter() {
753 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
754 self.s.space();
755 self.word_space("for ?");
756 self.print_trait_ref(&ptr.trait_ref);
757 } else {
758 real_bounds.push(b);
759 }
760 }
761 self.print_bounds(":", real_bounds);
762 self.print_where_clause(&generics.where_clause);
763 self.s.word(" ");
764 self.bopen();
765 for trait_item in trait_items {
766 self.ann.nested(self, Nested::TraitItem(trait_item.id));
767 }
768 self.bclose(item.span);
769 }
770 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
771 self.head("");
772 self.print_visibility(&item.vis);
773 self.word_nbsp("trait");
774 self.print_ident(item.ident);
775 self.print_generic_params(&generics.params);
776 let mut real_bounds = Vec::with_capacity(bounds.len());
777 // FIXME(durka) this seems to be some quite outdated syntax
778 for b in bounds.iter() {
779 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
780 self.s.space();
781 self.word_space("for ?");
782 self.print_trait_ref(&ptr.trait_ref);
783 } else {
784 real_bounds.push(b);
785 }
786 }
787 self.nbsp();
788 self.print_bounds("=", real_bounds);
789 self.print_where_clause(&generics.where_clause);
790 self.s.word(";");
791 }
792 }
793 self.ann.post(self, AnnNode::Item(item))
794 }
795
796 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
797 self.print_path(&t.path, false)
798 }
799
800 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
801 if !generic_params.is_empty() {
802 self.s.word("for");
803 self.print_generic_params(generic_params);
804 self.nbsp();
805 }
806 }
807
808 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
809 self.print_formal_generic_params(&t.bound_generic_params);
810 self.print_trait_ref(&t.trait_ref)
811 }
812
813 pub fn print_enum_def(
814 &mut self,
815 enum_definition: &hir::EnumDef<'_>,
816 generics: &hir::Generics<'_>,
817 name: Symbol,
818 span: rustc_span::Span,
819 visibility: &hir::Visibility<'_>,
820 ) {
821 self.head(visibility_qualified(visibility, "enum"));
822 self.print_name(name);
823 self.print_generic_params(&generics.params);
824 self.print_where_clause(&generics.where_clause);
825 self.s.space();
826 self.print_variants(&enum_definition.variants, span)
827 }
828
829 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
830 self.bopen();
831 for v in variants {
832 self.space_if_not_bol();
833 self.maybe_print_comment(v.span.lo());
834 self.print_outer_attributes(&v.attrs);
835 self.ibox(INDENT_UNIT);
836 self.print_variant(v);
837 self.s.word(",");
838 self.end();
839 self.maybe_print_trailing_comment(v.span, None);
840 }
841 self.bclose(span)
842 }
843
844 pub fn print_visibility(&mut self, vis: &hir::Visibility<'_>) {
845 match vis.node {
846 hir::VisibilityKind::Public => self.word_nbsp("pub"),
847 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate"),
848 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)"),
849 hir::VisibilityKind::Restricted { ref path, .. } => {
850 self.s.word("pub(");
851 if path.segments.len() == 1 && path.segments[0].ident.name == kw::Super {
852 // Special case: `super` can print like `pub(super)`.
853 self.s.word("super");
854 } else {
855 // Everything else requires `in` at present.
856 self.word_nbsp("in");
857 self.print_path(path, false);
858 }
859 self.word_nbsp(")");
860 }
861 hir::VisibilityKind::Inherited => (),
862 }
863 }
864
865 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
866 match defaultness {
867 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
868 hir::Defaultness::Final => (),
869 }
870 }
871
872 pub fn print_struct(
873 &mut self,
874 struct_def: &hir::VariantData<'_>,
875 generics: &hir::Generics<'_>,
876 name: Symbol,
877 span: rustc_span::Span,
878 print_finalizer: bool,
879 ) {
880 self.print_name(name);
881 self.print_generic_params(&generics.params);
882 match struct_def {
883 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
884 if let hir::VariantData::Tuple(..) = struct_def {
885 self.popen();
886 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
887 s.maybe_print_comment(field.span.lo());
888 s.print_outer_attributes(&field.attrs);
889 s.print_visibility(&field.vis);
890 s.print_type(&field.ty)
891 });
892 self.pclose();
893 }
894 self.print_where_clause(&generics.where_clause);
895 if print_finalizer {
896 self.s.word(";");
897 }
898 self.end();
899 self.end() // close the outer-box
900 }
901 hir::VariantData::Struct(..) => {
902 self.print_where_clause(&generics.where_clause);
903 self.nbsp();
904 self.bopen();
905 self.hardbreak_if_not_bol();
906
907 for field in struct_def.fields() {
908 self.hardbreak_if_not_bol();
909 self.maybe_print_comment(field.span.lo());
910 self.print_outer_attributes(&field.attrs);
911 self.print_visibility(&field.vis);
912 self.print_ident(field.ident);
913 self.word_nbsp(":");
914 self.print_type(&field.ty);
915 self.s.word(",");
916 }
917
918 self.bclose(span)
919 }
920 }
921 }
922
923 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
924 self.head("");
925 let generics = hir::Generics::empty();
926 self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
927 if let Some(ref d) = v.disr_expr {
928 self.s.space();
929 self.word_space("=");
930 self.print_anon_const(d);
931 }
932 }
933 pub fn print_method_sig(
934 &mut self,
935 ident: Ident,
936 m: &hir::FnSig<'_>,
937 generics: &hir::Generics<'_>,
938 vis: &hir::Visibility<'_>,
939 arg_names: &[Ident],
940 body_id: Option<hir::BodyId>,
941 ) {
942 self.print_fn(&m.decl, m.header, Some(ident.name), generics, vis, arg_names, body_id)
943 }
944
945 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
946 self.ann.pre(self, AnnNode::SubItem(ti.hir_id));
947 self.hardbreak_if_not_bol();
948 self.maybe_print_comment(ti.span.lo());
949 self.print_outer_attributes(&ti.attrs);
950 match ti.kind {
951 hir::TraitItemKind::Const(ref ty, default) => {
952 let vis =
953 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
954 self.print_associated_const(ti.ident, &ty, default, &vis);
955 }
956 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref arg_names)) => {
957 let vis =
958 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
959 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None);
960 self.s.word(";");
961 }
962 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
963 let vis =
964 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
965 self.head("");
966 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body));
967 self.nbsp();
968 self.end(); // need to close a box
969 self.end(); // need to close a box
970 self.ann.nested(self, Nested::Body(body));
971 }
972 hir::TraitItemKind::Type(ref bounds, ref default) => {
973 self.print_associated_type(
974 ti.ident,
975 &ti.generics,
976 Some(bounds),
977 default.as_ref().map(|ty| &**ty),
978 );
979 }
980 }
981 self.ann.post(self, AnnNode::SubItem(ti.hir_id))
982 }
983
984 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
985 self.ann.pre(self, AnnNode::SubItem(ii.hir_id));
986 self.hardbreak_if_not_bol();
987 self.maybe_print_comment(ii.span.lo());
988 self.print_outer_attributes(&ii.attrs);
989 self.print_defaultness(ii.defaultness);
990
991 match ii.kind {
992 hir::ImplItemKind::Const(ref ty, expr) => {
993 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
994 }
995 hir::ImplItemKind::Fn(ref sig, body) => {
996 self.head("");
997 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
998 self.nbsp();
999 self.end(); // need to close a box
1000 self.end(); // need to close a box
1001 self.ann.nested(self, Nested::Body(body));
1002 }
1003 hir::ImplItemKind::TyAlias(ref ty) => {
1004 self.print_associated_type(ii.ident, &ii.generics, None, Some(ty));
1005 }
1006 }
1007 self.ann.post(self, AnnNode::SubItem(ii.hir_id))
1008 }
1009
1010 pub fn print_local(&mut self, init: Option<&hir::Expr<'_>>, decl: impl Fn(&mut Self)) {
1011 self.space_if_not_bol();
1012 self.ibox(INDENT_UNIT);
1013 self.word_nbsp("let");
1014
1015 self.ibox(INDENT_UNIT);
1016 decl(self);
1017 self.end();
1018
1019 if let Some(ref init) = init {
1020 self.nbsp();
1021 self.word_space("=");
1022 self.print_expr(&init);
1023 }
1024 self.end()
1025 }
1026
1027 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
1028 self.maybe_print_comment(st.span.lo());
1029 match st.kind {
1030 hir::StmtKind::Local(ref loc) => {
1031 self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc));
1032 }
1033 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
1034 hir::StmtKind::Expr(ref expr) => {
1035 self.space_if_not_bol();
1036 self.print_expr(&expr);
1037 }
1038 hir::StmtKind::Semi(ref expr) => {
1039 self.space_if_not_bol();
1040 self.print_expr(&expr);
1041 self.s.word(";");
1042 }
1043 }
1044 if stmt_ends_with_semi(&st.kind) {
1045 self.s.word(";");
1046 }
1047 self.maybe_print_trailing_comment(st.span, None)
1048 }
1049
1050 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
1051 self.print_block_with_attrs(blk, &[])
1052 }
1053
1054 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
1055 self.print_block_maybe_unclosed(blk, &[], false)
1056 }
1057
1058 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
1059 self.print_block_maybe_unclosed(blk, attrs, true)
1060 }
1061
1062 pub fn print_block_maybe_unclosed(
1063 &mut self,
1064 blk: &hir::Block<'_>,
1065 attrs: &[ast::Attribute],
1066 close_box: bool,
1067 ) {
1068 match blk.rules {
1069 hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
1070 hir::BlockCheckMode::PushUnsafeBlock(..) => self.word_space("push_unsafe"),
1071 hir::BlockCheckMode::PopUnsafeBlock(..) => self.word_space("pop_unsafe"),
1072 hir::BlockCheckMode::DefaultBlock => (),
1073 }
1074 self.maybe_print_comment(blk.span.lo());
1075 self.ann.pre(self, AnnNode::Block(blk));
1076 self.bopen();
1077
1078 self.print_inner_attributes(attrs);
1079
1080 for st in blk.stmts {
1081 self.print_stmt(st);
1082 }
1083 if let Some(ref expr) = blk.expr {
1084 self.space_if_not_bol();
1085 self.print_expr(&expr);
1086 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1087 }
1088 self.bclose_maybe_open(blk.span, close_box);
1089 self.ann.post(self, AnnNode::Block(blk))
1090 }
1091
1092 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1093 self.ann.nested(self, Nested::Body(constant.body))
1094 }
1095
1096 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1097 self.popen();
1098 self.commasep_exprs(Inconsistent, args);
1099 self.pclose()
1100 }
1101
1102 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1103 let needs_par = expr.precedence().order() < prec;
1104 if needs_par {
1105 self.popen();
1106 }
1107 self.print_expr(expr);
1108 if needs_par {
1109 self.pclose();
1110 }
1111 }
1112
1113 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1114 /// `if cond { ... }`.
1115 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1116 let needs_par = match expr.kind {
1117 // These cases need parens due to the parse error observed in #26461: `if return {}`
1118 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1119 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) | hir::ExprKind::Break(..) => true,
1120
1121 _ => contains_exterior_struct_lit(expr),
1122 };
1123
1124 if needs_par {
1125 self.popen();
1126 }
1127 self.print_expr(expr);
1128 if needs_par {
1129 self.pclose();
1130 }
1131 }
1132
1133 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1134 self.ibox(INDENT_UNIT);
1135 self.s.word("[");
1136 self.commasep_exprs(Inconsistent, exprs);
1137 self.s.word("]");
1138 self.end()
1139 }
1140
1141 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::AnonConst) {
1142 self.ibox(INDENT_UNIT);
1143 self.s.word("[");
1144 self.print_expr(element);
1145 self.word_space(";");
1146 self.print_anon_const(count);
1147 self.s.word("]");
1148 self.end()
1149 }
1150
1151 fn print_expr_struct(
1152 &mut self,
1153 qpath: &hir::QPath<'_>,
1154 fields: &[hir::Field<'_>],
1155 wth: &Option<&hir::Expr<'_>>,
1156 ) {
1157 self.print_qpath(qpath, true);
1158 self.s.word("{");
1159 self.commasep_cmnt(
1160 Consistent,
1161 &fields[..],
1162 |s, field| {
1163 s.ibox(INDENT_UNIT);
1164 if !field.is_shorthand {
1165 s.print_ident(field.ident);
1166 s.word_space(":");
1167 }
1168 s.print_expr(&field.expr);
1169 s.end()
1170 },
1171 |f| f.span,
1172 );
1173 match *wth {
1174 Some(ref expr) => {
1175 self.ibox(INDENT_UNIT);
1176 if !fields.is_empty() {
1177 self.s.word(",");
1178 self.s.space();
1179 }
1180 self.s.word("..");
1181 self.print_expr(&expr);
1182 self.end();
1183 }
1184 _ => {
1185 if !fields.is_empty() {
1186 self.s.word(",")
1187 }
1188 }
1189 }
1190 self.s.word("}");
1191 }
1192
1193 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1194 self.popen();
1195 self.commasep_exprs(Inconsistent, exprs);
1196 if exprs.len() == 1 {
1197 self.s.word(",");
1198 }
1199 self.pclose()
1200 }
1201
1202 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1203 let prec = match func.kind {
1204 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1205 _ => parser::PREC_POSTFIX,
1206 };
1207
1208 self.print_expr_maybe_paren(func, prec);
1209 self.print_call_post(args)
1210 }
1211
1212 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1213 let base_args = &args[1..];
1214 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1215 self.s.word(".");
1216 self.print_ident(segment.ident);
1217
1218 let generic_args = segment.generic_args();
1219 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1220 self.print_generic_args(generic_args, segment.infer_args, true);
1221 }
1222
1223 self.print_call_post(base_args)
1224 }
1225
1226 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1227 let assoc_op = bin_op_to_assoc_op(op.node);
1228 let prec = assoc_op.precedence() as i8;
1229 let fixity = assoc_op.fixity();
1230
1231 let (left_prec, right_prec) = match fixity {
1232 Fixity::Left => (prec, prec + 1),
1233 Fixity::Right => (prec + 1, prec),
1234 Fixity::None => (prec + 1, prec + 1),
1235 };
1236
1237 let left_prec = match (&lhs.kind, op.node) {
1238 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1239 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1240 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1241 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1242 parser::PREC_FORCE_PAREN
1243 }
1244 _ => left_prec,
1245 };
1246
1247 self.print_expr_maybe_paren(lhs, left_prec);
1248 self.s.space();
1249 self.word_space(op.node.as_str());
1250 self.print_expr_maybe_paren(rhs, right_prec)
1251 }
1252
1253 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1254 self.s.word(op.as_str());
1255 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1256 }
1257
1258 fn print_expr_addr_of(
1259 &mut self,
1260 kind: hir::BorrowKind,
1261 mutability: hir::Mutability,
1262 expr: &hir::Expr<'_>,
1263 ) {
1264 self.s.word("&");
1265 match kind {
1266 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1267 hir::BorrowKind::Raw => {
1268 self.word_nbsp("raw");
1269 self.print_mutability(mutability, true);
1270 }
1271 }
1272 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1273 }
1274
1275 fn print_literal(&mut self, lit: &hir::Lit) {
1276 self.maybe_print_comment(lit.span.lo());
1277 self.word(lit.node.to_lit_token().to_string())
1278 }
1279
1280 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1281 self.maybe_print_comment(expr.span.lo());
1282 self.print_outer_attributes(&expr.attrs);
1283 self.ibox(INDENT_UNIT);
1284 self.ann.pre(self, AnnNode::Expr(expr));
1285 match expr.kind {
1286 hir::ExprKind::Box(ref expr) => {
1287 self.word_space("box");
1288 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1289 }
1290 hir::ExprKind::Array(ref exprs) => {
1291 self.print_expr_vec(exprs);
1292 }
1293 hir::ExprKind::Repeat(ref element, ref count) => {
1294 self.print_expr_repeat(&element, count);
1295 }
1296 hir::ExprKind::Struct(ref qpath, fields, ref wth) => {
1297 self.print_expr_struct(qpath, fields, wth);
1298 }
1299 hir::ExprKind::Tup(ref exprs) => {
1300 self.print_expr_tup(exprs);
1301 }
1302 hir::ExprKind::Call(ref func, ref args) => {
1303 self.print_expr_call(&func, args);
1304 }
1305 hir::ExprKind::MethodCall(ref segment, _, ref args, _) => {
1306 self.print_expr_method_call(segment, args);
1307 }
1308 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1309 self.print_expr_binary(op, &lhs, &rhs);
1310 }
1311 hir::ExprKind::Unary(op, ref expr) => {
1312 self.print_expr_unary(op, &expr);
1313 }
1314 hir::ExprKind::AddrOf(k, m, ref expr) => {
1315 self.print_expr_addr_of(k, m, &expr);
1316 }
1317 hir::ExprKind::Lit(ref lit) => {
1318 self.print_literal(&lit);
1319 }
1320 hir::ExprKind::Cast(ref expr, ref ty) => {
1321 let prec = AssocOp::As.precedence() as i8;
1322 self.print_expr_maybe_paren(&expr, prec);
1323 self.s.space();
1324 self.word_space("as");
1325 self.print_type(&ty);
1326 }
1327 hir::ExprKind::Type(ref expr, ref ty) => {
1328 let prec = AssocOp::Colon.precedence() as i8;
1329 self.print_expr_maybe_paren(&expr, prec);
1330 self.word_space(":");
1331 self.print_type(&ty);
1332 }
1333 hir::ExprKind::DropTemps(ref init) => {
1334 // Print `{`:
1335 self.cbox(INDENT_UNIT);
1336 self.ibox(0);
1337 self.bopen();
1338
1339 // Print `let _t = $init;`:
1340 let temp = Ident::from_str("_t");
1341 self.print_local(Some(init), |this| this.print_ident(temp));
1342 self.s.word(";");
1343
1344 // Print `_t`:
1345 self.space_if_not_bol();
1346 self.print_ident(temp);
1347
1348 // Print `}`:
1349 self.bclose_maybe_open(expr.span, true);
1350 }
1351 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1352 if let Some(label) = opt_label {
1353 self.print_ident(label.ident);
1354 self.word_space(":");
1355 }
1356 self.head("loop");
1357 self.s.space();
1358 self.print_block(&blk);
1359 }
1360 hir::ExprKind::Match(ref expr, arms, _) => {
1361 self.cbox(INDENT_UNIT);
1362 self.ibox(INDENT_UNIT);
1363 self.word_nbsp("match");
1364 self.print_expr_as_cond(&expr);
1365 self.s.space();
1366 self.bopen();
1367 for arm in arms {
1368 self.print_arm(arm);
1369 }
1370 self.bclose(expr.span);
1371 }
1372 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1373 self.print_capture_clause(capture_clause);
1374
1375 self.print_closure_params(&decl, body);
1376 self.s.space();
1377
1378 // This is a bare expression.
1379 self.ann.nested(self, Nested::Body(body));
1380 self.end(); // need to close a box
1381
1382 // A box will be closed by `print_expr`, but we didn't want an overall
1383 // wrapper so we closed the corresponding opening. so create an
1384 // empty box to satisfy the close.
1385 self.ibox(0);
1386 }
1387 hir::ExprKind::Block(ref blk, opt_label) => {
1388 if let Some(label) = opt_label {
1389 self.print_ident(label.ident);
1390 self.word_space(":");
1391 }
1392 // containing cbox, will be closed by print-block at `}`
1393 self.cbox(INDENT_UNIT);
1394 // head-box, will be closed by print-block after `{`
1395 self.ibox(0);
1396 self.print_block(&blk);
1397 }
1398 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
1399 let prec = AssocOp::Assign.precedence() as i8;
1400 self.print_expr_maybe_paren(&lhs, prec + 1);
1401 self.s.space();
1402 self.word_space("=");
1403 self.print_expr_maybe_paren(&rhs, prec);
1404 }
1405 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1406 let prec = AssocOp::Assign.precedence() as i8;
1407 self.print_expr_maybe_paren(&lhs, prec + 1);
1408 self.s.space();
1409 self.s.word(op.node.as_str());
1410 self.word_space("=");
1411 self.print_expr_maybe_paren(&rhs, prec);
1412 }
1413 hir::ExprKind::Field(ref expr, ident) => {
1414 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1415 self.s.word(".");
1416 self.print_ident(ident);
1417 }
1418 hir::ExprKind::Index(ref expr, ref index) => {
1419 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1420 self.s.word("[");
1421 self.print_expr(&index);
1422 self.s.word("]");
1423 }
1424 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1425 hir::ExprKind::Break(destination, ref opt_expr) => {
1426 self.s.word("break");
1427 self.s.space();
1428 if let Some(label) = destination.label {
1429 self.print_ident(label.ident);
1430 self.s.space();
1431 }
1432 if let Some(ref expr) = *opt_expr {
1433 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1434 self.s.space();
1435 }
1436 }
1437 hir::ExprKind::Continue(destination) => {
1438 self.s.word("continue");
1439 self.s.space();
1440 if let Some(label) = destination.label {
1441 self.print_ident(label.ident);
1442 self.s.space()
1443 }
1444 }
1445 hir::ExprKind::Ret(ref result) => {
1446 self.s.word("return");
1447 if let Some(ref expr) = *result {
1448 self.s.word(" ");
1449 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1450 }
1451 }
1452 hir::ExprKind::InlineAsm(ref a) => {
1453 enum AsmArg<'a> {
1454 Template(String),
1455 Operand(&'a hir::InlineAsmOperand<'a>),
1456 Options(ast::InlineAsmOptions),
1457 }
1458
1459 let mut args = vec![];
1460 args.push(AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(&a.template)));
1461 args.extend(a.operands.iter().map(|o| AsmArg::Operand(o)));
1462 if !a.options.is_empty() {
1463 args.push(AsmArg::Options(a.options));
1464 }
1465
1466 self.word("asm!");
1467 self.popen();
1468 self.commasep(Consistent, &args, |s, arg| match arg {
1469 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
1470 AsmArg::Operand(op) => match op {
1471 hir::InlineAsmOperand::In { reg, expr } => {
1472 s.word("in");
1473 s.popen();
1474 s.word(format!("{}", reg));
1475 s.pclose();
1476 s.space();
1477 s.print_expr(expr);
1478 }
1479 hir::InlineAsmOperand::Out { reg, late, expr } => {
1480 s.word(if *late { "lateout" } else { "out" });
1481 s.popen();
1482 s.word(format!("{}", reg));
1483 s.pclose();
1484 s.space();
1485 match expr {
1486 Some(expr) => s.print_expr(expr),
1487 None => s.word("_"),
1488 }
1489 }
1490 hir::InlineAsmOperand::InOut { reg, late, expr } => {
1491 s.word(if *late { "inlateout" } else { "inout" });
1492 s.popen();
1493 s.word(format!("{}", reg));
1494 s.pclose();
1495 s.space();
1496 s.print_expr(expr);
1497 }
1498 hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
1499 s.word(if *late { "inlateout" } else { "inout" });
1500 s.popen();
1501 s.word(format!("{}", reg));
1502 s.pclose();
1503 s.space();
1504 s.print_expr(in_expr);
1505 s.space();
1506 s.word_space("=>");
1507 match out_expr {
1508 Some(out_expr) => s.print_expr(out_expr),
1509 None => s.word("_"),
1510 }
1511 }
1512 hir::InlineAsmOperand::Const { expr } => {
1513 s.word("const");
1514 s.space();
1515 s.print_expr(expr);
1516 }
1517 hir::InlineAsmOperand::Sym { expr } => {
1518 s.word("sym");
1519 s.space();
1520 s.print_expr(expr);
1521 }
1522 },
1523 AsmArg::Options(opts) => {
1524 s.word("options");
1525 s.popen();
1526 let mut options = vec![];
1527 if opts.contains(ast::InlineAsmOptions::PURE) {
1528 options.push("pure");
1529 }
1530 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1531 options.push("nomem");
1532 }
1533 if opts.contains(ast::InlineAsmOptions::READONLY) {
1534 options.push("readonly");
1535 }
1536 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1537 options.push("preserves_flags");
1538 }
1539 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1540 options.push("noreturn");
1541 }
1542 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1543 options.push("nostack");
1544 }
1545 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1546 options.push("att_syntax");
1547 }
1548 s.commasep(Inconsistent, &options, |s, &opt| {
1549 s.word(opt);
1550 });
1551 s.pclose();
1552 }
1553 });
1554 self.pclose();
1555 }
1556 hir::ExprKind::LlvmInlineAsm(ref a) => {
1557 let i = &a.inner;
1558 self.s.word("llvm_asm!");
1559 self.popen();
1560 self.print_symbol(i.asm, i.asm_str_style);
1561 self.word_space(":");
1562
1563 let mut out_idx = 0;
1564 self.commasep(Inconsistent, &i.outputs, |s, out| {
1565 let constraint = out.constraint.as_str();
1566 let mut ch = constraint.chars();
1567 match ch.next() {
1568 Some('=') if out.is_rw => {
1569 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
1570 }
1571 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1572 }
1573 s.popen();
1574 s.print_expr(&a.outputs_exprs[out_idx]);
1575 s.pclose();
1576 out_idx += 1;
1577 });
1578 self.s.space();
1579 self.word_space(":");
1580
1581 let mut in_idx = 0;
1582 self.commasep(Inconsistent, &i.inputs, |s, &co| {
1583 s.print_symbol(co, ast::StrStyle::Cooked);
1584 s.popen();
1585 s.print_expr(&a.inputs_exprs[in_idx]);
1586 s.pclose();
1587 in_idx += 1;
1588 });
1589 self.s.space();
1590 self.word_space(":");
1591
1592 self.commasep(Inconsistent, &i.clobbers, |s, &co| {
1593 s.print_symbol(co, ast::StrStyle::Cooked);
1594 });
1595
1596 let mut options = vec![];
1597 if i.volatile {
1598 options.push("volatile");
1599 }
1600 if i.alignstack {
1601 options.push("alignstack");
1602 }
1603 if i.dialect == ast::LlvmAsmDialect::Intel {
1604 options.push("intel");
1605 }
1606
1607 if !options.is_empty() {
1608 self.s.space();
1609 self.word_space(":");
1610 self.commasep(Inconsistent, &options, |s, &co| {
1611 s.print_string(co, ast::StrStyle::Cooked);
1612 });
1613 }
1614
1615 self.pclose();
1616 }
1617 hir::ExprKind::Yield(ref expr, _) => {
1618 self.word_space("yield");
1619 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1620 }
1621 hir::ExprKind::Err => {
1622 self.popen();
1623 self.s.word("/*ERROR*/");
1624 self.pclose();
1625 }
1626 }
1627 self.ann.post(self, AnnNode::Expr(expr));
1628 self.end()
1629 }
1630
1631 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1632 self.print_pat(&loc.pat);
1633 if let Some(ref ty) = loc.ty {
1634 self.word_space(":");
1635 self.print_type(&ty);
1636 }
1637 }
1638
1639 pub fn print_usize(&mut self, i: usize) {
1640 self.s.word(i.to_string())
1641 }
1642
1643 pub fn print_name(&mut self, name: Symbol) {
1644 self.print_ident(Ident::with_dummy_span(name))
1645 }
1646
1647 pub fn print_for_decl(&mut self, loc: &hir::Local<'_>, coll: &hir::Expr<'_>) {
1648 self.print_local_decl(loc);
1649 self.s.space();
1650 self.word_space("in");
1651 self.print_expr(coll)
1652 }
1653
1654 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1655 self.maybe_print_comment(path.span.lo());
1656
1657 for (i, segment) in path.segments.iter().enumerate() {
1658 if i > 0 {
1659 self.s.word("::")
1660 }
1661 if segment.ident.name != kw::PathRoot {
1662 self.print_ident(segment.ident);
1663 self.print_generic_args(
1664 segment.generic_args(),
1665 segment.infer_args,
1666 colons_before_params,
1667 );
1668 }
1669 }
1670 }
1671
1672 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1673 if segment.ident.name != kw::PathRoot {
1674 self.print_ident(segment.ident);
1675 self.print_generic_args(segment.generic_args(), segment.infer_args, false);
1676 }
1677 }
1678
1679 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1680 match *qpath {
1681 hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params),
1682 hir::QPath::Resolved(Some(ref qself), ref path) => {
1683 self.s.word("<");
1684 self.print_type(qself);
1685 self.s.space();
1686 self.word_space("as");
1687
1688 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1689 if i > 0 {
1690 self.s.word("::")
1691 }
1692 if segment.ident.name != kw::PathRoot {
1693 self.print_ident(segment.ident);
1694 self.print_generic_args(
1695 segment.generic_args(),
1696 segment.infer_args,
1697 colons_before_params,
1698 );
1699 }
1700 }
1701
1702 self.s.word(">");
1703 self.s.word("::");
1704 let item_segment = path.segments.last().unwrap();
1705 self.print_ident(item_segment.ident);
1706 self.print_generic_args(
1707 item_segment.generic_args(),
1708 item_segment.infer_args,
1709 colons_before_params,
1710 )
1711 }
1712 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1713 // If we've got a compound-qualified-path, let's push an additional pair of angle
1714 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1715 // `A::B::C` (since the latter could be ambiguous to the user)
1716 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1717 self.print_type(qself);
1718 } else {
1719 self.s.word("<");
1720 self.print_type(qself);
1721 self.s.word(">");
1722 }
1723
1724 self.s.word("::");
1725 self.print_ident(item_segment.ident);
1726 self.print_generic_args(
1727 item_segment.generic_args(),
1728 item_segment.infer_args,
1729 colons_before_params,
1730 )
1731 }
1732 hir::QPath::LangItem(lang_item, span) => {
1733 self.s.word("#[lang = \"");
1734 self.print_ident(Ident::new(lang_item.name(), span));
1735 self.s.word("\"]");
1736 }
1737 }
1738 }
1739
1740 fn print_generic_args(
1741 &mut self,
1742 generic_args: &hir::GenericArgs<'_>,
1743 infer_args: bool,
1744 colons_before_params: bool,
1745 ) {
1746 if generic_args.parenthesized {
1747 self.s.word("(");
1748 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1749 self.s.word(")");
1750
1751 self.space_if_not_bol();
1752 self.word_space("->");
1753 self.print_type(generic_args.bindings[0].ty());
1754 } else {
1755 let start = if colons_before_params { "::<" } else { "<" };
1756 let empty = Cell::new(true);
1757 let start_or_comma = |this: &mut Self| {
1758 if empty.get() {
1759 empty.set(false);
1760 this.s.word(start)
1761 } else {
1762 this.word_space(",")
1763 }
1764 };
1765
1766 let mut nonelided_generic_args: bool = false;
1767 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1768 GenericArg::Lifetime(lt) => lt.is_elided(),
1769 _ => {
1770 nonelided_generic_args = true;
1771 true
1772 }
1773 });
1774
1775 if nonelided_generic_args {
1776 start_or_comma(self);
1777 self.commasep(
1778 Inconsistent,
1779 &generic_args.args,
1780 |s, generic_arg| match generic_arg {
1781 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1782 GenericArg::Lifetime(_) => {}
1783 GenericArg::Type(ty) => s.print_type(ty),
1784 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1785 },
1786 );
1787 }
1788
1789 // FIXME(eddyb): this would leak into error messages (e.g.,
1790 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1791 if infer_args && false {
1792 start_or_comma(self);
1793 self.s.word("..");
1794 }
1795
1796 for binding in generic_args.bindings.iter() {
1797 start_or_comma(self);
1798 self.print_ident(binding.ident);
1799 self.s.space();
1800 match generic_args.bindings[0].kind {
1801 hir::TypeBindingKind::Equality { ref ty } => {
1802 self.word_space("=");
1803 self.print_type(ty);
1804 }
1805 hir::TypeBindingKind::Constraint { bounds } => {
1806 self.print_bounds(":", bounds);
1807 }
1808 }
1809 }
1810
1811 if !empty.get() {
1812 self.s.word(">")
1813 }
1814 }
1815 }
1816
1817 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1818 self.maybe_print_comment(pat.span.lo());
1819 self.ann.pre(self, AnnNode::Pat(pat));
1820 // Pat isn't normalized, but the beauty of it
1821 // is that it doesn't matter
1822 match pat.kind {
1823 PatKind::Wild => self.s.word("_"),
1824 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1825 match binding_mode {
1826 hir::BindingAnnotation::Ref => {
1827 self.word_nbsp("ref");
1828 self.print_mutability(hir::Mutability::Not, false);
1829 }
1830 hir::BindingAnnotation::RefMut => {
1831 self.word_nbsp("ref");
1832 self.print_mutability(hir::Mutability::Mut, false);
1833 }
1834 hir::BindingAnnotation::Unannotated => {}
1835 hir::BindingAnnotation::Mutable => {
1836 self.word_nbsp("mut");
1837 }
1838 }
1839 self.print_ident(ident);
1840 if let Some(ref p) = *sub {
1841 self.s.word("@");
1842 self.print_pat(&p);
1843 }
1844 }
1845 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1846 self.print_qpath(qpath, true);
1847 self.popen();
1848 if let Some(ddpos) = ddpos {
1849 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1850 if ddpos != 0 {
1851 self.word_space(",");
1852 }
1853 self.s.word("..");
1854 if ddpos != elts.len() {
1855 self.s.word(",");
1856 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1857 }
1858 } else {
1859 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1860 }
1861 self.pclose();
1862 }
1863 PatKind::Path(ref qpath) => {
1864 self.print_qpath(qpath, true);
1865 }
1866 PatKind::Struct(ref qpath, ref fields, etc) => {
1867 self.print_qpath(qpath, true);
1868 self.nbsp();
1869 self.word_space("{");
1870 self.commasep_cmnt(
1871 Consistent,
1872 &fields[..],
1873 |s, f| {
1874 s.cbox(INDENT_UNIT);
1875 if !f.is_shorthand {
1876 s.print_ident(f.ident);
1877 s.word_nbsp(":");
1878 }
1879 s.print_pat(&f.pat);
1880 s.end()
1881 },
1882 |f| f.pat.span,
1883 );
1884 if etc {
1885 if !fields.is_empty() {
1886 self.word_space(",");
1887 }
1888 self.s.word("..");
1889 }
1890 self.s.space();
1891 self.s.word("}");
1892 }
1893 PatKind::Or(ref pats) => {
1894 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1895 }
1896 PatKind::Tuple(ref elts, ddpos) => {
1897 self.popen();
1898 if let Some(ddpos) = ddpos {
1899 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1900 if ddpos != 0 {
1901 self.word_space(",");
1902 }
1903 self.s.word("..");
1904 if ddpos != elts.len() {
1905 self.s.word(",");
1906 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1907 }
1908 } else {
1909 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1910 if elts.len() == 1 {
1911 self.s.word(",");
1912 }
1913 }
1914 self.pclose();
1915 }
1916 PatKind::Box(ref inner) => {
1917 let is_range_inner = match inner.kind {
1918 PatKind::Range(..) => true,
1919 _ => false,
1920 };
1921 self.s.word("box ");
1922 if is_range_inner {
1923 self.popen();
1924 }
1925 self.print_pat(&inner);
1926 if is_range_inner {
1927 self.pclose();
1928 }
1929 }
1930 PatKind::Ref(ref inner, mutbl) => {
1931 let is_range_inner = match inner.kind {
1932 PatKind::Range(..) => true,
1933 _ => false,
1934 };
1935 self.s.word("&");
1936 self.s.word(mutbl.prefix_str());
1937 if is_range_inner {
1938 self.popen();
1939 }
1940 self.print_pat(&inner);
1941 if is_range_inner {
1942 self.pclose();
1943 }
1944 }
1945 PatKind::Lit(ref e) => self.print_expr(&e),
1946 PatKind::Range(ref begin, ref end, ref end_kind) => {
1947 if let Some(expr) = begin {
1948 self.print_expr(expr);
1949 self.s.space();
1950 }
1951 match *end_kind {
1952 RangeEnd::Included => self.s.word("..."),
1953 RangeEnd::Excluded => self.s.word(".."),
1954 }
1955 if let Some(expr) = end {
1956 self.print_expr(expr);
1957 }
1958 }
1959 PatKind::Slice(ref before, ref slice, ref after) => {
1960 self.s.word("[");
1961 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
1962 if let Some(ref p) = *slice {
1963 if !before.is_empty() {
1964 self.word_space(",");
1965 }
1966 if let PatKind::Wild = p.kind {
1967 // Print nothing.
1968 } else {
1969 self.print_pat(&p);
1970 }
1971 self.s.word("..");
1972 if !after.is_empty() {
1973 self.word_space(",");
1974 }
1975 }
1976 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
1977 self.s.word("]");
1978 }
1979 }
1980 self.ann.post(self, AnnNode::Pat(pat))
1981 }
1982
1983 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1984 self.print_outer_attributes(&arg.attrs);
1985 self.print_pat(&arg.pat);
1986 }
1987
1988 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1989 // I have no idea why this check is necessary, but here it
1990 // is :(
1991 if arm.attrs.is_empty() {
1992 self.s.space();
1993 }
1994 self.cbox(INDENT_UNIT);
1995 self.ann.pre(self, AnnNode::Arm(arm));
1996 self.ibox(0);
1997 self.print_outer_attributes(&arm.attrs);
1998 self.print_pat(&arm.pat);
1999 self.s.space();
2000 if let Some(ref g) = arm.guard {
2001 match g {
2002 hir::Guard::If(e) => {
2003 self.word_space("if");
2004 self.print_expr(&e);
2005 self.s.space();
2006 }
2007 }
2008 }
2009 self.word_space("=>");
2010
2011 match arm.body.kind {
2012 hir::ExprKind::Block(ref blk, opt_label) => {
2013 if let Some(label) = opt_label {
2014 self.print_ident(label.ident);
2015 self.word_space(":");
2016 }
2017 // the block will close the pattern's ibox
2018 self.print_block_unclosed(&blk);
2019
2020 // If it is a user-provided unsafe block, print a comma after it
2021 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
2022 {
2023 self.s.word(",");
2024 }
2025 }
2026 _ => {
2027 self.end(); // close the ibox for the pattern
2028 self.print_expr(&arm.body);
2029 self.s.word(",");
2030 }
2031 }
2032 self.ann.post(self, AnnNode::Arm(arm));
2033 self.end() // close enclosing cbox
2034 }
2035
2036 pub fn print_fn(
2037 &mut self,
2038 decl: &hir::FnDecl<'_>,
2039 header: hir::FnHeader,
2040 name: Option<Symbol>,
2041 generics: &hir::Generics<'_>,
2042 vis: &hir::Visibility<'_>,
2043 arg_names: &[Ident],
2044 body_id: Option<hir::BodyId>,
2045 ) {
2046 self.print_fn_header_info(header, vis);
2047
2048 if let Some(name) = name {
2049 self.nbsp();
2050 self.print_name(name);
2051 }
2052 self.print_generic_params(&generics.params);
2053
2054 self.popen();
2055 let mut i = 0;
2056 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2057 assert!(arg_names.is_empty() || body_id.is_none());
2058 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2059 s.ibox(INDENT_UNIT);
2060 if let Some(arg_name) = arg_names.get(i) {
2061 s.s.word(arg_name.to_string());
2062 s.s.word(":");
2063 s.s.space();
2064 } else if let Some(body_id) = body_id {
2065 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2066 s.s.word(":");
2067 s.s.space();
2068 }
2069 i += 1;
2070 s.print_type(ty);
2071 s.end()
2072 });
2073 if decl.c_variadic {
2074 self.s.word(", ...");
2075 }
2076 self.pclose();
2077
2078 self.print_fn_output(decl);
2079 self.print_where_clause(&generics.where_clause)
2080 }
2081
2082 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2083 self.s.word("|");
2084 let mut i = 0;
2085 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2086 s.ibox(INDENT_UNIT);
2087
2088 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2089 i += 1;
2090
2091 if let hir::TyKind::Infer = ty.kind {
2092 // Print nothing.
2093 } else {
2094 s.s.word(":");
2095 s.s.space();
2096 s.print_type(ty);
2097 }
2098 s.end();
2099 });
2100 self.s.word("|");
2101
2102 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2103 return;
2104 }
2105
2106 self.space_if_not_bol();
2107 self.word_space("->");
2108 match decl.output {
2109 hir::FnRetTy::Return(ref ty) => {
2110 self.print_type(&ty);
2111 self.maybe_print_comment(ty.span.lo())
2112 }
2113 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2114 }
2115 }
2116
2117 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2118 match capture_clause {
2119 hir::CaptureBy::Value => self.word_space("move"),
2120 hir::CaptureBy::Ref => {}
2121 }
2122 }
2123
2124 pub fn print_bounds<'b>(
2125 &mut self,
2126 prefix: &'static str,
2127 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2128 ) {
2129 let mut first = true;
2130 for bound in bounds {
2131 if first {
2132 self.s.word(prefix);
2133 }
2134 if !(first && prefix.is_empty()) {
2135 self.nbsp();
2136 }
2137 if first {
2138 first = false;
2139 } else {
2140 self.word_space("+");
2141 }
2142
2143 match bound {
2144 GenericBound::Trait(tref, modifier) => {
2145 if modifier == &TraitBoundModifier::Maybe {
2146 self.s.word("?");
2147 }
2148 self.print_poly_trait_ref(tref);
2149 }
2150 GenericBound::LangItemTrait(lang_item, span, ..) => {
2151 self.s.word("#[lang = \"");
2152 self.print_ident(Ident::new(lang_item.name(), *span));
2153 self.s.word("\"]");
2154 }
2155 GenericBound::Outlives(lt) => {
2156 self.print_lifetime(lt);
2157 }
2158 }
2159 }
2160 }
2161
2162 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2163 if !generic_params.is_empty() {
2164 self.s.word("<");
2165
2166 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2167
2168 self.s.word(">");
2169 }
2170 }
2171
2172 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2173 if let GenericParamKind::Const { .. } = param.kind {
2174 self.word_space("const");
2175 }
2176
2177 self.print_ident(param.name.ident());
2178
2179 match param.kind {
2180 GenericParamKind::Lifetime { .. } => {
2181 let mut sep = ":";
2182 for bound in param.bounds {
2183 match bound {
2184 GenericBound::Outlives(ref lt) => {
2185 self.s.word(sep);
2186 self.print_lifetime(lt);
2187 sep = "+";
2188 }
2189 _ => panic!(),
2190 }
2191 }
2192 }
2193 GenericParamKind::Type { ref default, .. } => {
2194 self.print_bounds(":", param.bounds);
2195 if let Some(default) = default {
2196 self.s.space();
2197 self.word_space("=");
2198 self.print_type(&default)
2199 }
2200 }
2201 GenericParamKind::Const { ref ty } => {
2202 self.word_space(":");
2203 self.print_type(ty)
2204 }
2205 }
2206 }
2207
2208 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2209 self.print_ident(lifetime.name.ident())
2210 }
2211
2212 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause<'_>) {
2213 if where_clause.predicates.is_empty() {
2214 return;
2215 }
2216
2217 self.s.space();
2218 self.word_space("where");
2219
2220 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2221 if i != 0 {
2222 self.word_space(",");
2223 }
2224
2225 match predicate {
2226 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2227 ref bound_generic_params,
2228 ref bounded_ty,
2229 bounds,
2230 ..
2231 }) => {
2232 self.print_formal_generic_params(bound_generic_params);
2233 self.print_type(&bounded_ty);
2234 self.print_bounds(":", bounds);
2235 }
2236 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2237 ref lifetime,
2238 ref bounds,
2239 ..
2240 }) => {
2241 self.print_lifetime(lifetime);
2242 self.s.word(":");
2243
2244 for (i, bound) in bounds.iter().enumerate() {
2245 match bound {
2246 GenericBound::Outlives(lt) => {
2247 self.print_lifetime(lt);
2248 }
2249 _ => panic!(),
2250 }
2251
2252 if i != 0 {
2253 self.s.word(":");
2254 }
2255 }
2256 }
2257 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2258 ref lhs_ty,
2259 ref rhs_ty,
2260 ..
2261 }) => {
2262 self.print_type(lhs_ty);
2263 self.s.space();
2264 self.word_space("=");
2265 self.print_type(rhs_ty);
2266 }
2267 }
2268 }
2269 }
2270
2271 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2272 match mutbl {
2273 hir::Mutability::Mut => self.word_nbsp("mut"),
2274 hir::Mutability::Not => {
2275 if print_const {
2276 self.word_nbsp("const")
2277 }
2278 }
2279 }
2280 }
2281
2282 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2283 self.print_mutability(mt.mutbl, print_const);
2284 self.print_type(&mt.ty)
2285 }
2286
2287 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2288 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2289 return;
2290 }
2291
2292 self.space_if_not_bol();
2293 self.ibox(INDENT_UNIT);
2294 self.word_space("->");
2295 match decl.output {
2296 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2297 hir::FnRetTy::Return(ref ty) => self.print_type(&ty),
2298 }
2299 self.end();
2300
2301 if let hir::FnRetTy::Return(ref output) = decl.output {
2302 self.maybe_print_comment(output.span.lo())
2303 }
2304 }
2305
2306 pub fn print_ty_fn(
2307 &mut self,
2308 abi: Abi,
2309 unsafety: hir::Unsafety,
2310 decl: &hir::FnDecl<'_>,
2311 name: Option<Symbol>,
2312 generic_params: &[hir::GenericParam<'_>],
2313 arg_names: &[Ident],
2314 ) {
2315 self.ibox(INDENT_UNIT);
2316 if !generic_params.is_empty() {
2317 self.s.word("for");
2318 self.print_generic_params(generic_params);
2319 }
2320 let generics = hir::Generics {
2321 params: &[],
2322 where_clause: hir::WhereClause { predicates: &[], span: rustc_span::DUMMY_SP },
2323 span: rustc_span::DUMMY_SP,
2324 };
2325 self.print_fn(
2326 decl,
2327 hir::FnHeader {
2328 unsafety,
2329 abi,
2330 constness: hir::Constness::NotConst,
2331 asyncness: hir::IsAsync::NotAsync,
2332 },
2333 name,
2334 &generics,
2335 &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited },
2336 arg_names,
2337 None,
2338 );
2339 self.end();
2340 }
2341
2342 pub fn maybe_print_trailing_comment(
2343 &mut self,
2344 span: rustc_span::Span,
2345 next_pos: Option<BytePos>,
2346 ) {
2347 if let Some(cmnts) = self.comments() {
2348 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2349 self.print_comment(&cmnt);
2350 }
2351 }
2352 }
2353
2354 pub fn print_remaining_comments(&mut self) {
2355 // If there aren't any remaining comments, then we need to manually
2356 // make sure there is a line break at the end.
2357 if self.next_comment().is_none() {
2358 self.s.hardbreak();
2359 }
2360 while let Some(ref cmnt) = self.next_comment() {
2361 self.print_comment(cmnt)
2362 }
2363 }
2364
2365 pub fn print_opt_abi_and_extern_if_nondefault(&mut self, opt_abi: Option<Abi>) {
2366 match opt_abi {
2367 Some(Abi::Rust) => {}
2368 Some(abi) => {
2369 self.word_nbsp("extern");
2370 self.word_nbsp(abi.to_string())
2371 }
2372 None => {}
2373 }
2374 }
2375
2376 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) {
2377 if let Some(abi) = opt_abi {
2378 self.word_nbsp("extern");
2379 self.word_nbsp(abi.to_string())
2380 }
2381 }
2382
2383 pub fn print_fn_header_info(&mut self, header: hir::FnHeader, vis: &hir::Visibility<'_>) {
2384 self.s.word(visibility_qualified(vis, ""));
2385
2386 match header.constness {
2387 hir::Constness::NotConst => {}
2388 hir::Constness::Const => self.word_nbsp("const"),
2389 }
2390
2391 match header.asyncness {
2392 hir::IsAsync::NotAsync => {}
2393 hir::IsAsync::Async => self.word_nbsp("async"),
2394 }
2395
2396 self.print_unsafety(header.unsafety);
2397
2398 if header.abi != Abi::Rust {
2399 self.word_nbsp("extern");
2400 self.word_nbsp(header.abi.to_string());
2401 }
2402
2403 self.s.word("fn")
2404 }
2405
2406 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2407 match s {
2408 hir::Unsafety::Normal => {}
2409 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2410 }
2411 }
2412
2413 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2414 match s {
2415 hir::IsAuto::Yes => self.word_nbsp("auto"),
2416 hir::IsAuto::No => {}
2417 }
2418 }
2419 }
2420
2421 /// Does this expression require a semicolon to be treated
2422 /// as a statement? The negation of this: 'can this expression
2423 /// be used as a statement without a semicolon' -- is used
2424 /// as an early-bail-out in the parser so that, for instance,
2425 /// if true {...} else {...}
2426 /// |x| 5
2427 /// isn't parsed as (if true {...} else {...} | x) | 5
2428 //
2429 // Duplicated from `parse::classify`, but adapted for the HIR.
2430 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2431 match e.kind {
2432 hir::ExprKind::Match(..) | hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) => false,
2433 _ => true,
2434 }
2435 }
2436
2437 /// This statement requires a semicolon after it.
2438 /// note that in one case (stmt_semi), we've already
2439 /// seen the semicolon, and thus don't need another.
2440 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2441 match *stmt {
2442 hir::StmtKind::Local(_) => true,
2443 hir::StmtKind::Item(_) => false,
2444 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2445 hir::StmtKind::Semi(..) => false,
2446 }
2447 }
2448
2449 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2450 use crate::hir::BinOpKind::*;
2451 match op {
2452 Add => AssocOp::Add,
2453 Sub => AssocOp::Subtract,
2454 Mul => AssocOp::Multiply,
2455 Div => AssocOp::Divide,
2456 Rem => AssocOp::Modulus,
2457
2458 And => AssocOp::LAnd,
2459 Or => AssocOp::LOr,
2460
2461 BitXor => AssocOp::BitXor,
2462 BitAnd => AssocOp::BitAnd,
2463 BitOr => AssocOp::BitOr,
2464 Shl => AssocOp::ShiftLeft,
2465 Shr => AssocOp::ShiftRight,
2466
2467 Eq => AssocOp::Equal,
2468 Lt => AssocOp::Less,
2469 Le => AssocOp::LessEqual,
2470 Ne => AssocOp::NotEqual,
2471 Ge => AssocOp::GreaterEqual,
2472 Gt => AssocOp::Greater,
2473 }
2474 }
2475
2476 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2477 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2478 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2479 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2480 match value.kind {
2481 hir::ExprKind::Struct(..) => true,
2482
2483 hir::ExprKind::Assign(ref lhs, ref rhs, _)
2484 | hir::ExprKind::AssignOp(_, ref lhs, ref rhs)
2485 | hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2486 // `X { y: 1 } + X { y: 2 }`
2487 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2488 }
2489 hir::ExprKind::Unary(_, ref x)
2490 | hir::ExprKind::Cast(ref x, _)
2491 | hir::ExprKind::Type(ref x, _)
2492 | hir::ExprKind::Field(ref x, _)
2493 | hir::ExprKind::Index(ref x, _) => {
2494 // `&X { y: 1 }, X { y: 1 }.y`
2495 contains_exterior_struct_lit(&x)
2496 }
2497
2498 hir::ExprKind::MethodCall(.., ref exprs, _) => {
2499 // `X { y: 1 }.bar(...)`
2500 contains_exterior_struct_lit(&exprs[0])
2501 }
2502
2503 _ => false,
2504 }
2505 }