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