]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/item_tree/pretty.rs
b24ba61ea069fd49d30807a60c4d50aa0a29b0b9
[rust.git] / crates / hir_def / src / item_tree / pretty.rs
1 //! `ItemTree` debug printer.
2
3 use std::fmt::{self, Write};
4
5 use itertools::Itertools;
6
7 use crate::{
8     attr::RawAttrs,
9     generics::{TypeOrConstParamData, WherePredicate, WherePredicateTypeTarget},
10     path::GenericArg,
11     type_ref::TraitBoundModifier,
12     visibility::RawVisibility,
13 };
14
15 use super::*;
16
17 pub(super) fn print_item_tree(tree: &ItemTree) -> String {
18     let mut p = Printer { tree, buf: String::new(), indent_level: 0, needs_indent: true };
19
20     if let Some(attrs) = tree.attrs.get(&AttrOwner::TopLevel) {
21         p.print_attrs(attrs, true);
22     }
23     p.blank();
24
25     for item in tree.top_level_items() {
26         p.print_mod_item(*item);
27     }
28
29     let mut s = p.buf.trim_end_matches('\n').to_string();
30     s.push('\n');
31     s
32 }
33
34 macro_rules! w {
35     ($dst:expr, $($arg:tt)*) => {
36         { let _ = write!($dst, $($arg)*); }
37     };
38 }
39
40 macro_rules! wln {
41     ($dst:expr) => {
42         { let _ = writeln!($dst); }
43     };
44     ($dst:expr, $($arg:tt)*) => {
45         { let _ = writeln!($dst, $($arg)*); }
46     };
47 }
48
49 struct Printer<'a> {
50     tree: &'a ItemTree,
51     buf: String,
52     indent_level: usize,
53     needs_indent: bool,
54 }
55
56 impl<'a> Printer<'a> {
57     fn indented(&mut self, f: impl FnOnce(&mut Self)) {
58         self.indent_level += 1;
59         wln!(self);
60         f(self);
61         self.indent_level -= 1;
62         self.buf = self.buf.trim_end_matches('\n').to_string();
63     }
64
65     /// Ensures that a blank line is output before the next text.
66     fn blank(&mut self) {
67         let mut iter = self.buf.chars().rev().fuse();
68         match (iter.next(), iter.next()) {
69             (Some('\n'), Some('\n') | None) | (None, None) => {}
70             (Some('\n'), Some(_)) => {
71                 self.buf.push('\n');
72             }
73             (Some(_), _) => {
74                 self.buf.push('\n');
75                 self.buf.push('\n');
76             }
77             (None, Some(_)) => unreachable!(),
78         }
79     }
80
81     fn whitespace(&mut self) {
82         match self.buf.chars().next_back() {
83             None | Some('\n' | ' ') => {}
84             _ => self.buf.push(' '),
85         }
86     }
87
88     fn print_attrs(&mut self, attrs: &RawAttrs, inner: bool) {
89         let inner = if inner { "!" } else { "" };
90         for attr in &**attrs {
91             wln!(
92                 self,
93                 "#{}[{}{}]  // {:?}",
94                 inner,
95                 attr.path,
96                 attr.input.as_ref().map(|it| it.to_string()).unwrap_or_default(),
97                 attr.id,
98             );
99         }
100     }
101
102     fn print_attrs_of(&mut self, of: impl Into<AttrOwner>) {
103         if let Some(attrs) = self.tree.attrs.get(&of.into()) {
104             self.print_attrs(attrs, false);
105         }
106     }
107
108     fn print_visibility(&mut self, vis: RawVisibilityId) {
109         match &self.tree[vis] {
110             RawVisibility::Module(path) => w!(self, "pub({}) ", path),
111             RawVisibility::Public => w!(self, "pub "),
112         };
113     }
114
115     fn print_fields(&mut self, fields: &Fields) {
116         match fields {
117             Fields::Record(fields) => {
118                 self.whitespace();
119                 w!(self, "{{");
120                 self.indented(|this| {
121                     for field in fields.clone() {
122                         let Field { visibility, name, type_ref } = &this.tree[field];
123                         this.print_attrs_of(field);
124                         this.print_visibility(*visibility);
125                         w!(this, "{}: ", name);
126                         this.print_type_ref(type_ref);
127                         wln!(this, ",");
128                     }
129                 });
130                 w!(self, "}}");
131             }
132             Fields::Tuple(fields) => {
133                 w!(self, "(");
134                 self.indented(|this| {
135                     for field in fields.clone() {
136                         let Field { visibility, name, type_ref } = &this.tree[field];
137                         this.print_attrs_of(field);
138                         this.print_visibility(*visibility);
139                         w!(this, "{}: ", name);
140                         this.print_type_ref(type_ref);
141                         wln!(this, ",");
142                     }
143                 });
144                 w!(self, ")");
145             }
146             Fields::Unit => {}
147         }
148     }
149
150     fn print_fields_and_where_clause(&mut self, fields: &Fields, params: &GenericParams) {
151         match fields {
152             Fields::Record(_) => {
153                 if self.print_where_clause(params) {
154                     wln!(self);
155                 }
156                 self.print_fields(fields);
157             }
158             Fields::Unit => {
159                 self.print_where_clause(params);
160                 self.print_fields(fields);
161             }
162             Fields::Tuple(_) => {
163                 self.print_fields(fields);
164                 self.print_where_clause(params);
165             }
166         }
167     }
168
169     fn print_use_tree(&mut self, use_tree: &UseTree) {
170         match &use_tree.kind {
171             UseTreeKind::Single { path, alias } => {
172                 w!(self, "{}", path);
173                 if let Some(alias) = alias {
174                     w!(self, " as {}", alias);
175                 }
176             }
177             UseTreeKind::Glob { path } => {
178                 if let Some(path) = path {
179                     w!(self, "{}::", path);
180                 }
181                 w!(self, "*");
182             }
183             UseTreeKind::Prefixed { prefix, list } => {
184                 if let Some(prefix) = prefix {
185                     w!(self, "{}::", prefix);
186                 }
187                 w!(self, "{{");
188                 for (i, tree) in list.iter().enumerate() {
189                     if i != 0 {
190                         w!(self, ", ");
191                     }
192                     self.print_use_tree(tree);
193                 }
194                 w!(self, "}}");
195             }
196         }
197     }
198
199     fn print_mod_item(&mut self, item: ModItem) {
200         self.print_attrs_of(item);
201
202         match item {
203             ModItem::Import(it) => {
204                 let Import { visibility, use_tree, ast_id: _ } = &self.tree[it];
205                 self.print_visibility(*visibility);
206                 w!(self, "use ");
207                 self.print_use_tree(use_tree);
208                 wln!(self, ";");
209             }
210             ModItem::ExternCrate(it) => {
211                 let ExternCrate { name, alias, visibility, ast_id: _ } = &self.tree[it];
212                 self.print_visibility(*visibility);
213                 w!(self, "extern crate {}", name);
214                 if let Some(alias) = alias {
215                     w!(self, " as {}", alias);
216                 }
217                 wln!(self, ";");
218             }
219             ModItem::ExternBlock(it) => {
220                 let ExternBlock { abi, ast_id: _, children } = &self.tree[it];
221                 w!(self, "extern ");
222                 if let Some(abi) = abi {
223                     w!(self, "\"{}\" ", abi);
224                 }
225                 w!(self, "{{");
226                 self.indented(|this| {
227                     for child in &**children {
228                         this.print_mod_item(*child);
229                     }
230                 });
231                 wln!(self, "}}");
232             }
233             ModItem::Function(it) => {
234                 let Function {
235                     name,
236                     visibility,
237                     explicit_generic_params,
238                     abi,
239                     params,
240                     ret_type,
241                     async_ret_type: _,
242                     ast_id: _,
243                     flags,
244                 } = &self.tree[it];
245                 if flags.bits != 0 {
246                     wln!(self, "// flags = 0x{:X}", flags.bits);
247                 }
248                 self.print_visibility(*visibility);
249                 if let Some(abi) = abi {
250                     w!(self, "extern \"{}\" ", abi);
251                 }
252                 w!(self, "fn {}", name);
253                 self.print_generic_params(explicit_generic_params);
254                 w!(self, "(");
255                 if !params.is_empty() {
256                     self.indented(|this| {
257                         for param in params.clone() {
258                             this.print_attrs_of(param);
259                             match &this.tree[param] {
260                                 Param::Normal(name, ty) => {
261                                     match name {
262                                         Some(name) => w!(this, "{}: ", name),
263                                         None => w!(this, "_: "),
264                                     }
265                                     this.print_type_ref(ty);
266                                     wln!(this, ",");
267                                 }
268                                 Param::Varargs => {
269                                     wln!(this, "...");
270                                 }
271                             };
272                         }
273                     });
274                 }
275                 w!(self, ") -> ");
276                 self.print_type_ref(ret_type);
277                 self.print_where_clause(explicit_generic_params);
278                 wln!(self, ";");
279             }
280             ModItem::Struct(it) => {
281                 let Struct { visibility, name, fields, generic_params, ast_id: _ } = &self.tree[it];
282                 self.print_visibility(*visibility);
283                 w!(self, "struct {}", name);
284                 self.print_generic_params(generic_params);
285                 self.print_fields_and_where_clause(fields, generic_params);
286                 if matches!(fields, Fields::Record(_)) {
287                     wln!(self);
288                 } else {
289                     wln!(self, ";");
290                 }
291             }
292             ModItem::Union(it) => {
293                 let Union { name, visibility, fields, generic_params, ast_id: _ } = &self.tree[it];
294                 self.print_visibility(*visibility);
295                 w!(self, "union {}", name);
296                 self.print_generic_params(generic_params);
297                 self.print_fields_and_where_clause(fields, generic_params);
298                 if matches!(fields, Fields::Record(_)) {
299                     wln!(self);
300                 } else {
301                     wln!(self, ";");
302                 }
303             }
304             ModItem::Enum(it) => {
305                 let Enum { name, visibility, variants, generic_params, ast_id: _ } = &self.tree[it];
306                 self.print_visibility(*visibility);
307                 w!(self, "enum {}", name);
308                 self.print_generic_params(generic_params);
309                 self.print_where_clause_and_opening_brace(generic_params);
310                 self.indented(|this| {
311                     for variant in variants.clone() {
312                         let Variant { name, fields } = &this.tree[variant];
313                         this.print_attrs_of(variant);
314                         w!(this, "{}", name);
315                         this.print_fields(fields);
316                         wln!(this, ",");
317                     }
318                 });
319                 wln!(self, "}}");
320             }
321             ModItem::Const(it) => {
322                 let Const { name, visibility, type_ref, ast_id: _ } = &self.tree[it];
323                 self.print_visibility(*visibility);
324                 w!(self, "const ");
325                 match name {
326                     Some(name) => w!(self, "{}", name),
327                     None => w!(self, "_"),
328                 }
329                 w!(self, ": ");
330                 self.print_type_ref(type_ref);
331                 wln!(self, " = _;");
332             }
333             ModItem::Static(it) => {
334                 let Static { name, visibility, mutable, type_ref, ast_id: _ } = &self.tree[it];
335                 self.print_visibility(*visibility);
336                 w!(self, "static ");
337                 if *mutable {
338                     w!(self, "mut ");
339                 }
340                 w!(self, "{}: ", name);
341                 self.print_type_ref(type_ref);
342                 w!(self, " = _;");
343                 wln!(self);
344             }
345             ModItem::Trait(it) => {
346                 let Trait {
347                     name,
348                     visibility,
349                     is_auto,
350                     is_unsafe,
351                     items,
352                     generic_params,
353                     ast_id: _,
354                 } = &self.tree[it];
355                 self.print_visibility(*visibility);
356                 if *is_unsafe {
357                     w!(self, "unsafe ");
358                 }
359                 if *is_auto {
360                     w!(self, "auto ");
361                 }
362                 w!(self, "trait {}", name);
363                 self.print_generic_params(generic_params);
364                 self.print_where_clause_and_opening_brace(generic_params);
365                 self.indented(|this| {
366                     for item in &**items {
367                         this.print_mod_item((*item).into());
368                     }
369                 });
370                 wln!(self, "}}");
371             }
372             ModItem::Impl(it) => {
373                 let Impl { target_trait, self_ty, is_negative, items, generic_params, ast_id: _ } =
374                     &self.tree[it];
375                 w!(self, "impl");
376                 self.print_generic_params(generic_params);
377                 w!(self, " ");
378                 if *is_negative {
379                     w!(self, "!");
380                 }
381                 if let Some(tr) = target_trait {
382                     self.print_path(&tr.path);
383                     w!(self, " for ");
384                 }
385                 self.print_type_ref(self_ty);
386                 self.print_where_clause_and_opening_brace(generic_params);
387                 self.indented(|this| {
388                     for item in &**items {
389                         this.print_mod_item((*item).into());
390                     }
391                 });
392                 wln!(self, "}}");
393             }
394             ModItem::TypeAlias(it) => {
395                 let TypeAlias { name, visibility, bounds, type_ref, generic_params, ast_id: _ } =
396                     &self.tree[it];
397                 self.print_visibility(*visibility);
398                 w!(self, "type {}", name);
399                 self.print_generic_params(generic_params);
400                 if !bounds.is_empty() {
401                     w!(self, ": ");
402                     self.print_type_bounds(bounds);
403                 }
404                 if let Some(ty) = type_ref {
405                     w!(self, " = ");
406                     self.print_type_ref(ty);
407                 }
408                 self.print_where_clause(generic_params);
409                 w!(self, ";");
410                 wln!(self);
411             }
412             ModItem::Mod(it) => {
413                 let Mod { name, visibility, kind, ast_id: _ } = &self.tree[it];
414                 self.print_visibility(*visibility);
415                 w!(self, "mod {}", name);
416                 match kind {
417                     ModKind::Inline { items } => {
418                         w!(self, " {{");
419                         self.indented(|this| {
420                             for item in &**items {
421                                 this.print_mod_item(*item);
422                             }
423                         });
424                         wln!(self, "}}");
425                     }
426                     ModKind::Outline => {
427                         wln!(self, ";");
428                     }
429                 }
430             }
431             ModItem::MacroCall(it) => {
432                 let MacroCall { path, ast_id: _, expand_to: _ } = &self.tree[it];
433                 wln!(self, "{}!(...);", path);
434             }
435             ModItem::MacroRules(it) => {
436                 let MacroRules { name, ast_id: _ } = &self.tree[it];
437                 wln!(self, "macro_rules! {} {{ ... }}", name);
438             }
439             ModItem::MacroDef(it) => {
440                 let MacroDef { name, visibility, ast_id: _ } = &self.tree[it];
441                 self.print_visibility(*visibility);
442                 wln!(self, "macro {} {{ ... }}", name);
443             }
444         }
445
446         self.blank();
447     }
448
449     fn print_type_ref(&mut self, type_ref: &TypeRef) {
450         // FIXME: deduplicate with `HirDisplay` impl
451         match type_ref {
452             TypeRef::Never => w!(self, "!"),
453             TypeRef::Placeholder => w!(self, "_"),
454             TypeRef::Tuple(fields) => {
455                 w!(self, "(");
456                 for (i, field) in fields.iter().enumerate() {
457                     if i != 0 {
458                         w!(self, ", ");
459                     }
460                     self.print_type_ref(field);
461                 }
462                 w!(self, ")");
463             }
464             TypeRef::Path(path) => self.print_path(path),
465             TypeRef::RawPtr(pointee, mtbl) => {
466                 let mtbl = match mtbl {
467                     Mutability::Shared => "*const",
468                     Mutability::Mut => "*mut",
469                 };
470                 w!(self, "{} ", mtbl);
471                 self.print_type_ref(pointee);
472             }
473             TypeRef::Reference(pointee, lt, mtbl) => {
474                 let mtbl = match mtbl {
475                     Mutability::Shared => "",
476                     Mutability::Mut => "mut ",
477                 };
478                 w!(self, "&");
479                 if let Some(lt) = lt {
480                     w!(self, "{} ", lt.name);
481                 }
482                 w!(self, "{}", mtbl);
483                 self.print_type_ref(pointee);
484             }
485             TypeRef::Array(elem, len) => {
486                 w!(self, "[");
487                 self.print_type_ref(elem);
488                 w!(self, "; {}]", len);
489             }
490             TypeRef::Slice(elem) => {
491                 w!(self, "[");
492                 self.print_type_ref(elem);
493                 w!(self, "]");
494             }
495             TypeRef::Fn(args_and_ret, varargs) => {
496                 let ((_, return_type), args) =
497                     args_and_ret.split_last().expect("TypeRef::Fn is missing return type");
498                 w!(self, "fn(");
499                 for (i, (_, typeref)) in args.iter().enumerate() {
500                     if i != 0 {
501                         w!(self, ", ");
502                     }
503                     self.print_type_ref(typeref);
504                 }
505                 if *varargs {
506                     if !args.is_empty() {
507                         w!(self, ", ");
508                     }
509                     w!(self, "...");
510                 }
511                 w!(self, ") -> ");
512                 self.print_type_ref(return_type);
513             }
514             TypeRef::Macro(_ast_id) => {
515                 w!(self, "<macro>");
516             }
517             TypeRef::Error => w!(self, "{{unknown}}"),
518             TypeRef::ImplTrait(bounds) => {
519                 w!(self, "impl ");
520                 self.print_type_bounds(bounds);
521             }
522             TypeRef::DynTrait(bounds) => {
523                 w!(self, "dyn ");
524                 self.print_type_bounds(bounds);
525             }
526         }
527     }
528
529     fn print_type_bounds(&mut self, bounds: &[Interned<TypeBound>]) {
530         for (i, bound) in bounds.iter().enumerate() {
531             if i != 0 {
532                 w!(self, " + ");
533             }
534
535             match bound.as_ref() {
536                 TypeBound::Path(path, modifier) => {
537                     match modifier {
538                         TraitBoundModifier::None => (),
539                         TraitBoundModifier::Maybe => w!(self, "?"),
540                     }
541                     self.print_path(path)
542                 }
543                 TypeBound::ForLifetime(lifetimes, path) => {
544                     w!(self, "for<{}> ", lifetimes.iter().format(", "));
545                     self.print_path(path);
546                 }
547                 TypeBound::Lifetime(lt) => w!(self, "{}", lt.name),
548                 TypeBound::Error => w!(self, "{{unknown}}"),
549             }
550         }
551     }
552
553     fn print_path(&mut self, path: &Path) {
554         match path.type_anchor() {
555             Some(anchor) => {
556                 w!(self, "<");
557                 self.print_type_ref(anchor);
558                 w!(self, ">::");
559             }
560             None => match path.kind() {
561                 PathKind::Plain => {}
562                 PathKind::Super(0) => w!(self, "self::"),
563                 PathKind::Super(n) => {
564                     for _ in 0..*n {
565                         w!(self, "super::");
566                     }
567                 }
568                 PathKind::Crate => w!(self, "crate::"),
569                 PathKind::Abs => w!(self, "::"),
570                 PathKind::DollarCrate(_) => w!(self, "$crate::"),
571             },
572         }
573
574         for (i, segment) in path.segments().iter().enumerate() {
575             if i != 0 {
576                 w!(self, "::");
577             }
578
579             w!(self, "{}", segment.name);
580             if let Some(generics) = segment.args_and_bindings {
581                 // NB: these are all in type position, so `::<` turbofish syntax is not necessary
582                 w!(self, "<");
583                 let mut first = true;
584                 let args = if generics.has_self_type {
585                     let (self_ty, args) = generics.args.split_first().unwrap();
586                     w!(self, "Self=");
587                     self.print_generic_arg(self_ty);
588                     first = false;
589                     args
590                 } else {
591                     &generics.args
592                 };
593                 for arg in args {
594                     if !first {
595                         w!(self, ", ");
596                     }
597                     first = false;
598                     self.print_generic_arg(arg);
599                 }
600                 for binding in &generics.bindings {
601                     if !first {
602                         w!(self, ", ");
603                     }
604                     first = false;
605                     w!(self, "{}", binding.name);
606                     if !binding.bounds.is_empty() {
607                         w!(self, ": ");
608                         self.print_type_bounds(&binding.bounds);
609                     }
610                     if let Some(ty) = &binding.type_ref {
611                         w!(self, " = ");
612                         self.print_type_ref(ty);
613                     }
614                 }
615
616                 w!(self, ">");
617             }
618         }
619     }
620
621     fn print_generic_arg(&mut self, arg: &GenericArg) {
622         match arg {
623             GenericArg::Type(ty) => self.print_type_ref(ty),
624             GenericArg::Const(c) => w!(self, "{}", c),
625             GenericArg::Lifetime(lt) => w!(self, "{}", lt.name),
626         }
627     }
628
629     fn print_generic_params(&mut self, params: &GenericParams) {
630         if params.type_or_consts.is_empty() && params.lifetimes.is_empty() {
631             return;
632         }
633
634         w!(self, "<");
635         let mut first = true;
636         for (_, lt) in params.lifetimes.iter() {
637             if !first {
638                 w!(self, ", ");
639             }
640             first = false;
641             w!(self, "{}", lt.name);
642         }
643         for (idx, x) in params.type_or_consts.iter() {
644             if !first {
645                 w!(self, ", ");
646             }
647             first = false;
648             match x {
649                 TypeOrConstParamData::TypeParamData(ty) => match &ty.name {
650                     Some(name) => w!(self, "{}", name),
651                     None => w!(self, "_anon_{}", idx.into_raw()),
652                 },
653                 TypeOrConstParamData::ConstParamData(konst) => {
654                     w!(self, "const {}: ", konst.name);
655                     self.print_type_ref(&konst.ty);
656                 }
657             }
658         }
659         w!(self, ">");
660     }
661
662     fn print_where_clause_and_opening_brace(&mut self, params: &GenericParams) {
663         if self.print_where_clause(params) {
664             w!(self, "\n{{");
665         } else {
666             self.whitespace();
667             w!(self, "{{");
668         }
669     }
670
671     fn print_where_clause(&mut self, params: &GenericParams) -> bool {
672         if params.where_predicates.is_empty() {
673             return false;
674         }
675
676         w!(self, "\nwhere");
677         self.indented(|this| {
678             for (i, pred) in params.where_predicates.iter().enumerate() {
679                 if i != 0 {
680                     wln!(this, ",");
681                 }
682
683                 let (target, bound) = match pred {
684                     WherePredicate::TypeBound { target, bound } => (target, bound),
685                     WherePredicate::Lifetime { target, bound } => {
686                         wln!(this, "{}: {},", target.name, bound.name);
687                         continue;
688                     }
689                     WherePredicate::ForLifetime { lifetimes, target, bound } => {
690                         w!(this, "for<");
691                         for (i, lt) in lifetimes.iter().enumerate() {
692                             if i != 0 {
693                                 w!(this, ", ");
694                             }
695                             w!(this, "{}", lt);
696                         }
697                         w!(this, "> ");
698                         (target, bound)
699                     }
700                 };
701
702                 match target {
703                     WherePredicateTypeTarget::TypeRef(ty) => this.print_type_ref(ty),
704                     WherePredicateTypeTarget::TypeOrConstParam(id) => {
705                         match &params.type_or_consts[*id].name() {
706                             Some(name) => w!(this, "{}", name),
707                             None => w!(this, "_anon_{}", id.into_raw()),
708                         }
709                     }
710                 }
711                 w!(this, ": ");
712                 this.print_type_bounds(std::slice::from_ref(bound));
713             }
714         });
715         true
716     }
717 }
718
719 impl<'a> Write for Printer<'a> {
720     fn write_str(&mut self, s: &str) -> fmt::Result {
721         for line in s.split_inclusive('\n') {
722             if self.needs_indent {
723                 match self.buf.chars().last() {
724                     Some('\n') | None => {}
725                     _ => self.buf.push('\n'),
726                 }
727                 self.buf.push_str(&"    ".repeat(self.indent_level));
728                 self.needs_indent = false;
729             }
730
731             self.buf.push_str(line);
732             self.needs_indent = line.ends_with('\n');
733         }
734
735         Ok(())
736     }
737 }