]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_pretty/src/pprust/state/item.rs
Rollup merge of #93613 - crlf0710:rename_to_async_iter, r=yaahc
[rust.git] / compiler / rustc_ast_pretty / src / pprust / state / item.rs
1 use crate::pp::Breaks::Inconsistent;
2 use crate::pprust::state::delimited::IterDelimited;
3 use crate::pprust::state::{AnnNode, PrintState, State, INDENT_UNIT};
4
5 use rustc_ast as ast;
6 use rustc_ast::GenericBound;
7 use rustc_ast::ModKind;
8 use rustc_span::symbol::Ident;
9
10 fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
11     format!("{}{}", State::to_string(|s| s.print_visibility(vis)), s)
12 }
13
14 impl<'a> State<'a> {
15     fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, attrs: &[ast::Attribute]) {
16         self.print_inner_attributes(attrs);
17         for item in &nmod.items {
18             self.print_foreign_item(item);
19         }
20     }
21
22     fn print_foreign_item(&mut self, item: &ast::ForeignItem) {
23         let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
24         self.ann.pre(self, AnnNode::SubItem(id));
25         self.hardbreak_if_not_bol();
26         self.maybe_print_comment(span.lo());
27         self.print_outer_attributes(attrs);
28         match kind {
29             ast::ForeignItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => {
30                 self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs);
31             }
32             ast::ForeignItemKind::Static(ty, mutbl, body) => {
33                 let def = ast::Defaultness::Final;
34                 self.print_item_const(ident, Some(*mutbl), ty, body.as_deref(), vis, def);
35             }
36             ast::ForeignItemKind::TyAlias(box ast::TyAlias {
37                 defaultness,
38                 generics,
39                 bounds,
40                 ty,
41             }) => {
42                 self.print_associated_type(
43                     ident,
44                     generics,
45                     bounds,
46                     ty.as_deref(),
47                     vis,
48                     *defaultness,
49                 );
50             }
51             ast::ForeignItemKind::MacCall(m) => {
52                 self.print_mac(m);
53                 if m.args.need_semicolon() {
54                     self.word(";");
55                 }
56             }
57         }
58         self.ann.post(self, AnnNode::SubItem(id))
59     }
60
61     fn print_item_const(
62         &mut self,
63         ident: Ident,
64         mutbl: Option<ast::Mutability>,
65         ty: &ast::Ty,
66         body: Option<&ast::Expr>,
67         vis: &ast::Visibility,
68         defaultness: ast::Defaultness,
69     ) {
70         self.head("");
71         self.print_visibility(vis);
72         self.print_defaultness(defaultness);
73         let leading = match mutbl {
74             None => "const",
75             Some(ast::Mutability::Not) => "static",
76             Some(ast::Mutability::Mut) => "static mut",
77         };
78         self.word_space(leading);
79         self.print_ident(ident);
80         self.word_space(":");
81         self.print_type(ty);
82         if body.is_some() {
83             self.space();
84         }
85         self.end(); // end the head-ibox
86         if let Some(body) = body {
87             self.word_space("=");
88             self.print_expr(body);
89         }
90         self.word(";");
91         self.end(); // end the outer cbox
92     }
93
94     fn print_associated_type(
95         &mut self,
96         ident: Ident,
97         generics: &ast::Generics,
98         bounds: &ast::GenericBounds,
99         ty: Option<&ast::Ty>,
100         vis: &ast::Visibility,
101         defaultness: ast::Defaultness,
102     ) {
103         self.head("");
104         self.print_visibility(vis);
105         self.print_defaultness(defaultness);
106         self.word_space("type");
107         self.print_ident(ident);
108         self.print_generic_params(&generics.params);
109         self.print_type_bounds(":", bounds);
110         self.print_where_clause(&generics.where_clause);
111         if let Some(ty) = ty {
112             self.space();
113             self.word_space("=");
114             self.print_type(ty);
115         }
116         self.word(";");
117         self.end(); // end inner head-block
118         self.end(); // end outer head-block
119     }
120
121     /// Pretty-prints an item.
122     crate fn print_item(&mut self, item: &ast::Item) {
123         self.hardbreak_if_not_bol();
124         self.maybe_print_comment(item.span.lo());
125         self.print_outer_attributes(&item.attrs);
126         self.ann.pre(self, AnnNode::Item(item));
127         match item.kind {
128             ast::ItemKind::ExternCrate(orig_name) => {
129                 self.head(visibility_qualified(&item.vis, "extern crate"));
130                 if let Some(orig_name) = orig_name {
131                     self.print_name(orig_name);
132                     self.space();
133                     self.word("as");
134                     self.space();
135                 }
136                 self.print_ident(item.ident);
137                 self.word(";");
138                 self.end(); // end inner head-block
139                 self.end(); // end outer head-block
140             }
141             ast::ItemKind::Use(ref tree) => {
142                 self.print_visibility(&item.vis);
143                 self.word_nbsp("use");
144                 self.print_use_tree(tree);
145                 self.word(";");
146             }
147             ast::ItemKind::Static(ref ty, mutbl, ref body) => {
148                 let def = ast::Defaultness::Final;
149                 self.print_item_const(item.ident, Some(mutbl), ty, body.as_deref(), &item.vis, def);
150             }
151             ast::ItemKind::Const(def, ref ty, ref body) => {
152                 self.print_item_const(item.ident, None, ty, body.as_deref(), &item.vis, def);
153             }
154             ast::ItemKind::Fn(box ast::Fn { defaultness, ref sig, ref generics, ref body }) => {
155                 let body = body.as_deref();
156                 self.print_fn_full(
157                     sig,
158                     item.ident,
159                     generics,
160                     &item.vis,
161                     defaultness,
162                     body,
163                     &item.attrs,
164                 );
165             }
166             ast::ItemKind::Mod(unsafety, ref mod_kind) => {
167                 self.head(Self::to_string(|s| {
168                     s.print_visibility(&item.vis);
169                     s.print_unsafety(unsafety);
170                     s.word("mod");
171                 }));
172                 self.print_ident(item.ident);
173
174                 match mod_kind {
175                     ModKind::Loaded(items, ..) => {
176                         self.nbsp();
177                         self.bopen();
178                         self.print_inner_attributes(&item.attrs);
179                         for item in items {
180                             self.print_item(item);
181                         }
182                         let empty = item.attrs.is_empty() && items.is_empty();
183                         self.bclose(item.span, empty);
184                     }
185                     ModKind::Unloaded => {
186                         self.word(";");
187                         self.end(); // end inner head-block
188                         self.end(); // end outer head-block
189                     }
190                 }
191             }
192             ast::ItemKind::ForeignMod(ref nmod) => {
193                 self.head(Self::to_string(|s| {
194                     s.print_unsafety(nmod.unsafety);
195                     s.word("extern");
196                 }));
197                 if let Some(abi) = nmod.abi {
198                     self.print_literal(&abi.as_lit());
199                     self.nbsp();
200                 }
201                 self.bopen();
202                 self.print_foreign_mod(nmod, &item.attrs);
203                 let empty = item.attrs.is_empty() && nmod.items.is_empty();
204                 self.bclose(item.span, empty);
205             }
206             ast::ItemKind::GlobalAsm(ref asm) => {
207                 self.head(visibility_qualified(&item.vis, "global_asm!"));
208                 self.print_inline_asm(asm);
209                 self.end();
210             }
211             ast::ItemKind::TyAlias(box ast::TyAlias {
212                 defaultness,
213                 ref generics,
214                 ref bounds,
215                 ref ty,
216             }) => {
217                 let ty = ty.as_deref();
218                 self.print_associated_type(
219                     item.ident,
220                     generics,
221                     bounds,
222                     ty,
223                     &item.vis,
224                     defaultness,
225                 );
226             }
227             ast::ItemKind::Enum(ref enum_definition, ref params) => {
228                 self.print_enum_def(enum_definition, params, item.ident, item.span, &item.vis);
229             }
230             ast::ItemKind::Struct(ref struct_def, ref generics) => {
231                 self.head(visibility_qualified(&item.vis, "struct"));
232                 self.print_struct(struct_def, generics, item.ident, item.span, true);
233             }
234             ast::ItemKind::Union(ref struct_def, ref generics) => {
235                 self.head(visibility_qualified(&item.vis, "union"));
236                 self.print_struct(struct_def, generics, item.ident, item.span, true);
237             }
238             ast::ItemKind::Impl(box ast::Impl {
239                 unsafety,
240                 polarity,
241                 defaultness,
242                 constness,
243                 ref generics,
244                 ref of_trait,
245                 ref self_ty,
246                 ref items,
247             }) => {
248                 self.head("");
249                 self.print_visibility(&item.vis);
250                 self.print_defaultness(defaultness);
251                 self.print_unsafety(unsafety);
252                 self.word("impl");
253
254                 if generics.params.is_empty() {
255                     self.nbsp();
256                 } else {
257                     self.print_generic_params(&generics.params);
258                     self.space();
259                 }
260
261                 self.print_constness(constness);
262
263                 if let ast::ImplPolarity::Negative(_) = polarity {
264                     self.word("!");
265                 }
266
267                 if let Some(ref t) = *of_trait {
268                     self.print_trait_ref(t);
269                     self.space();
270                     self.word_space("for");
271                 }
272
273                 self.print_type(self_ty);
274                 self.print_where_clause(&generics.where_clause);
275
276                 self.space();
277                 self.bopen();
278                 self.print_inner_attributes(&item.attrs);
279                 for impl_item in items {
280                     self.print_assoc_item(impl_item);
281                 }
282                 let empty = item.attrs.is_empty() && items.is_empty();
283                 self.bclose(item.span, empty);
284             }
285             ast::ItemKind::Trait(box ast::Trait {
286                 is_auto,
287                 unsafety,
288                 ref generics,
289                 ref bounds,
290                 ref items,
291                 ..
292             }) => {
293                 self.head("");
294                 self.print_visibility(&item.vis);
295                 self.print_unsafety(unsafety);
296                 self.print_is_auto(is_auto);
297                 self.word_nbsp("trait");
298                 self.print_ident(item.ident);
299                 self.print_generic_params(&generics.params);
300                 let mut real_bounds = Vec::with_capacity(bounds.len());
301                 for b in bounds.iter() {
302                     if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
303                         self.space();
304                         self.word_space("for ?");
305                         self.print_trait_ref(&ptr.trait_ref);
306                     } else {
307                         real_bounds.push(b.clone());
308                     }
309                 }
310                 self.print_type_bounds(":", &real_bounds);
311                 self.print_where_clause(&generics.where_clause);
312                 self.word(" ");
313                 self.bopen();
314                 self.print_inner_attributes(&item.attrs);
315                 for trait_item in items {
316                     self.print_assoc_item(trait_item);
317                 }
318                 let empty = item.attrs.is_empty() && items.is_empty();
319                 self.bclose(item.span, empty);
320             }
321             ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
322                 self.head(visibility_qualified(&item.vis, "trait"));
323                 self.print_ident(item.ident);
324                 self.print_generic_params(&generics.params);
325                 let mut real_bounds = Vec::with_capacity(bounds.len());
326                 // FIXME(durka) this seems to be some quite outdated syntax
327                 for b in bounds.iter() {
328                     if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
329                         self.space();
330                         self.word_space("for ?");
331                         self.print_trait_ref(&ptr.trait_ref);
332                     } else {
333                         real_bounds.push(b.clone());
334                     }
335                 }
336                 self.nbsp();
337                 self.print_type_bounds("=", &real_bounds);
338                 self.print_where_clause(&generics.where_clause);
339                 self.word(";");
340                 self.end(); // end inner head-block
341                 self.end(); // end outer head-block
342             }
343             ast::ItemKind::MacCall(ref mac) => {
344                 self.print_mac(mac);
345                 if mac.args.need_semicolon() {
346                     self.word(";");
347                 }
348             }
349             ast::ItemKind::MacroDef(ref macro_def) => {
350                 self.print_mac_def(macro_def, &item.ident, item.span, |state| {
351                     state.print_visibility(&item.vis)
352                 });
353             }
354         }
355         self.ann.post(self, AnnNode::Item(item))
356     }
357
358     fn print_enum_def(
359         &mut self,
360         enum_definition: &ast::EnumDef,
361         generics: &ast::Generics,
362         ident: Ident,
363         span: rustc_span::Span,
364         visibility: &ast::Visibility,
365     ) {
366         self.head(visibility_qualified(visibility, "enum"));
367         self.print_ident(ident);
368         self.print_generic_params(&generics.params);
369         self.print_where_clause(&generics.where_clause);
370         self.space();
371         self.print_variants(&enum_definition.variants, span)
372     }
373
374     fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) {
375         self.bopen();
376         for v in variants {
377             self.space_if_not_bol();
378             self.maybe_print_comment(v.span.lo());
379             self.print_outer_attributes(&v.attrs);
380             self.ibox(0);
381             self.print_variant(v);
382             self.word(",");
383             self.end();
384             self.maybe_print_trailing_comment(v.span, None);
385         }
386         let empty = variants.is_empty();
387         self.bclose(span, empty)
388     }
389
390     crate fn print_visibility(&mut self, vis: &ast::Visibility) {
391         match vis.kind {
392             ast::VisibilityKind::Public => self.word_nbsp("pub"),
393             ast::VisibilityKind::Crate(sugar) => match sugar {
394                 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
395                 ast::CrateSugar::JustCrate => self.word_nbsp("crate"),
396             },
397             ast::VisibilityKind::Restricted { ref path, .. } => {
398                 let path = Self::to_string(|s| s.print_path(path, false, 0));
399                 if path == "self" || path == "super" {
400                     self.word_nbsp(format!("pub({})", path))
401                 } else {
402                     self.word_nbsp(format!("pub(in {})", path))
403                 }
404             }
405             ast::VisibilityKind::Inherited => {}
406         }
407     }
408
409     fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
410         if let ast::Defaultness::Default(_) = defaultness {
411             self.word_nbsp("default");
412         }
413     }
414
415     fn print_record_struct_body(&mut self, fields: &[ast::FieldDef], span: rustc_span::Span) {
416         self.nbsp();
417         self.bopen();
418
419         let empty = fields.is_empty();
420         if !empty {
421             self.hardbreak_if_not_bol();
422
423             for field in fields {
424                 self.hardbreak_if_not_bol();
425                 self.maybe_print_comment(field.span.lo());
426                 self.print_outer_attributes(&field.attrs);
427                 self.print_visibility(&field.vis);
428                 self.print_ident(field.ident.unwrap());
429                 self.word_nbsp(":");
430                 self.print_type(&field.ty);
431                 self.word(",");
432             }
433         }
434
435         self.bclose(span, empty);
436     }
437
438     fn print_struct(
439         &mut self,
440         struct_def: &ast::VariantData,
441         generics: &ast::Generics,
442         ident: Ident,
443         span: rustc_span::Span,
444         print_finalizer: bool,
445     ) {
446         self.print_ident(ident);
447         self.print_generic_params(&generics.params);
448         match struct_def {
449             ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
450                 if let ast::VariantData::Tuple(..) = struct_def {
451                     self.popen();
452                     self.commasep(Inconsistent, struct_def.fields(), |s, field| {
453                         s.maybe_print_comment(field.span.lo());
454                         s.print_outer_attributes(&field.attrs);
455                         s.print_visibility(&field.vis);
456                         s.print_type(&field.ty)
457                     });
458                     self.pclose();
459                 }
460                 self.print_where_clause(&generics.where_clause);
461                 if print_finalizer {
462                     self.word(";");
463                 }
464                 self.end();
465                 self.end(); // Close the outer-box.
466             }
467             ast::VariantData::Struct(ref fields, ..) => {
468                 self.print_where_clause(&generics.where_clause);
469                 self.print_record_struct_body(fields, span);
470             }
471         }
472     }
473
474     crate fn print_variant(&mut self, v: &ast::Variant) {
475         self.head("");
476         self.print_visibility(&v.vis);
477         let generics = ast::Generics::default();
478         self.print_struct(&v.data, &generics, v.ident, v.span, false);
479         if let Some(ref d) = v.disr_expr {
480             self.space();
481             self.word_space("=");
482             self.print_expr(&d.value)
483         }
484     }
485
486     fn print_assoc_item(&mut self, item: &ast::AssocItem) {
487         let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
488         self.ann.pre(self, AnnNode::SubItem(id));
489         self.hardbreak_if_not_bol();
490         self.maybe_print_comment(span.lo());
491         self.print_outer_attributes(attrs);
492         match kind {
493             ast::AssocItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => {
494                 self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs);
495             }
496             ast::AssocItemKind::Const(def, ty, body) => {
497                 self.print_item_const(ident, None, ty, body.as_deref(), vis, *def);
498             }
499             ast::AssocItemKind::TyAlias(box ast::TyAlias { defaultness, generics, bounds, ty }) => {
500                 self.print_associated_type(
501                     ident,
502                     generics,
503                     bounds,
504                     ty.as_deref(),
505                     vis,
506                     *defaultness,
507                 );
508             }
509             ast::AssocItemKind::MacCall(m) => {
510                 self.print_mac(m);
511                 if m.args.need_semicolon() {
512                     self.word(";");
513                 }
514             }
515         }
516         self.ann.post(self, AnnNode::SubItem(id))
517     }
518
519     fn print_fn_full(
520         &mut self,
521         sig: &ast::FnSig,
522         name: Ident,
523         generics: &ast::Generics,
524         vis: &ast::Visibility,
525         defaultness: ast::Defaultness,
526         body: Option<&ast::Block>,
527         attrs: &[ast::Attribute],
528     ) {
529         if body.is_some() {
530             self.head("");
531         }
532         self.print_visibility(vis);
533         self.print_defaultness(defaultness);
534         self.print_fn(&sig.decl, sig.header, Some(name), generics);
535         if let Some(body) = body {
536             self.nbsp();
537             self.print_block_with_attrs(body, attrs);
538         } else {
539             self.word(";");
540         }
541     }
542
543     crate fn print_fn(
544         &mut self,
545         decl: &ast::FnDecl,
546         header: ast::FnHeader,
547         name: Option<Ident>,
548         generics: &ast::Generics,
549     ) {
550         self.print_fn_header_info(header);
551         if let Some(name) = name {
552             self.nbsp();
553             self.print_ident(name);
554         }
555         self.print_generic_params(&generics.params);
556         self.print_fn_params_and_ret(decl, false);
557         self.print_where_clause(&generics.where_clause)
558     }
559
560     crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) {
561         let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") };
562         self.word(open);
563         self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure));
564         self.word(close);
565         self.print_fn_ret_ty(&decl.output)
566     }
567
568     fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
569         if where_clause.predicates.is_empty() && !where_clause.has_where_token {
570             return;
571         }
572
573         self.space();
574         self.word_space("where");
575
576         for (i, predicate) in where_clause.predicates.iter().enumerate() {
577             if i != 0 {
578                 self.word_space(",");
579             }
580
581             self.print_where_predicate(predicate);
582         }
583     }
584
585     pub fn print_where_predicate(&mut self, predicate: &ast::WherePredicate) {
586         match predicate {
587             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
588                 bound_generic_params,
589                 bounded_ty,
590                 bounds,
591                 ..
592             }) => {
593                 self.print_formal_generic_params(bound_generic_params);
594                 self.print_type(bounded_ty);
595                 self.print_type_bounds(":", bounds);
596             }
597             ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
598                 lifetime,
599                 bounds,
600                 ..
601             }) => {
602                 self.print_lifetime_bounds(*lifetime, bounds);
603             }
604             ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { lhs_ty, rhs_ty, .. }) => {
605                 self.print_type(lhs_ty);
606                 self.space();
607                 self.word_space("=");
608                 self.print_type(rhs_ty);
609             }
610         }
611     }
612
613     fn print_use_tree(&mut self, tree: &ast::UseTree) {
614         match tree.kind {
615             ast::UseTreeKind::Simple(rename, ..) => {
616                 self.print_path(&tree.prefix, false, 0);
617                 if let Some(rename) = rename {
618                     self.nbsp();
619                     self.word_nbsp("as");
620                     self.print_ident(rename);
621                 }
622             }
623             ast::UseTreeKind::Glob => {
624                 if !tree.prefix.segments.is_empty() {
625                     self.print_path(&tree.prefix, false, 0);
626                     self.word("::");
627                 }
628                 self.word("*");
629             }
630             ast::UseTreeKind::Nested(ref items) => {
631                 if !tree.prefix.segments.is_empty() {
632                     self.print_path(&tree.prefix, false, 0);
633                     self.word("::");
634                 }
635                 if items.is_empty() {
636                     self.word("{}");
637                 } else if items.len() == 1 {
638                     self.print_use_tree(&items[0].0);
639                 } else {
640                     self.cbox(INDENT_UNIT);
641                     self.word("{");
642                     self.zerobreak();
643                     self.ibox(0);
644                     for use_tree in items.iter().delimited() {
645                         self.print_use_tree(&use_tree.0);
646                         if !use_tree.is_last {
647                             self.word(",");
648                             if let ast::UseTreeKind::Nested(_) = use_tree.0.kind {
649                                 self.hardbreak();
650                             } else {
651                                 self.space();
652                             }
653                         }
654                     }
655                     self.end();
656                     self.trailing_comma();
657                     self.offset(-INDENT_UNIT);
658                     self.word("}");
659                     self.end();
660                 }
661             }
662         }
663     }
664 }