forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 2
/
pretty.rs
3127 lines (2785 loc) · 115 KB
/
pretty.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::mir::interpret::{AllocRange, GlobalAlloc, Pointer, Provenance, Scalar};
use crate::query::IntoQueryParam;
use crate::query::Providers;
use crate::ty::{
self, ConstInt, ParamConst, ScalarInt, Term, TermKind, Ty, TyCtxt, TypeFoldable,
TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt,
};
use crate::ty::{GenericArg, GenericArgKind};
use rustc_apfloat::ieee::{Double, Single};
use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
use rustc_data_structures::sso::SsoHashSet;
use rustc_hir as hir;
use rustc_hir::def::{self, CtorKind, DefKind, Namespace};
use rustc_hir::def_id::{DefId, DefIdSet, ModDefId, CRATE_DEF_ID, LOCAL_CRATE};
use rustc_hir::definitions::{DefKey, DefPathData, DefPathDataName, DisambiguatedDefPathData};
use rustc_hir::LangItem;
use rustc_session::config::TrimmedDefPaths;
use rustc_session::cstore::{ExternCrate, ExternCrateSource};
use rustc_session::Limit;
use rustc_span::sym;
use rustc_span::symbol::{kw, Ident, Symbol};
use rustc_span::FileNameDisplayPreference;
use rustc_target::abi::Size;
use rustc_target::spec::abi::Abi;
use smallvec::SmallVec;
use std::cell::Cell;
use std::collections::BTreeMap;
use std::fmt::{self, Write as _};
use std::iter;
use std::ops::{ControlFlow, Deref, DerefMut};
// `pretty` is a separate module only for organization.
use super::*;
macro_rules! p {
(@$lit:literal) => {
write!(scoped_cx!(), $lit)?
};
(@write($($data:expr),+)) => {
write!(scoped_cx!(), $($data),+)?
};
(@print($x:expr)) => {
scoped_cx!() = $x.print(scoped_cx!())?
};
(@$method:ident($($arg:expr),*)) => {
scoped_cx!() = scoped_cx!().$method($($arg),*)?
};
($($elem:tt $(($($args:tt)*))?),+) => {{
$(p!(@ $elem $(($($args)*))?);)+
}};
}
macro_rules! define_scoped_cx {
($cx:ident) => {
#[allow(unused_macros)]
macro_rules! scoped_cx {
() => {
$cx
};
}
};
}
thread_local! {
static FORCE_IMPL_FILENAME_LINE: Cell<bool> = const { Cell::new(false) };
static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = const { Cell::new(false) };
static NO_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
static FORCE_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
static NO_QUERIES: Cell<bool> = const { Cell::new(false) };
static NO_VISIBLE_PATH: Cell<bool> = const { Cell::new(false) };
}
macro_rules! define_helper {
($($(#[$a:meta])* fn $name:ident($helper:ident, $tl:ident);)+) => {
$(
#[must_use]
pub struct $helper(bool);
impl $helper {
pub fn new() -> $helper {
$helper($tl.with(|c| c.replace(true)))
}
}
$(#[$a])*
pub macro $name($e:expr) {
{
let _guard = $helper::new();
$e
}
}
impl Drop for $helper {
fn drop(&mut self) {
$tl.with(|c| c.set(self.0))
}
}
pub fn $name() -> bool {
$tl.with(|c| c.get())
}
)+
}
}
define_helper!(
/// Avoids running any queries during any prints that occur
/// during the closure. This may alter the appearance of some
/// types (e.g. forcing verbose printing for opaque types).
/// This method is used during some queries (e.g. `explicit_item_bounds`
/// for opaque types), to ensure that any debug printing that
/// occurs during the query computation does not end up recursively
/// calling the same query.
fn with_no_queries(NoQueriesGuard, NO_QUERIES);
/// Force us to name impls with just the filename/line number. We
/// normally try to use types. But at some points, notably while printing
/// cycle errors, this can result in extra or suboptimal error output,
/// so this variable disables that check.
fn with_forced_impl_filename_line(ForcedImplGuard, FORCE_IMPL_FILENAME_LINE);
/// Adds the `crate::` prefix to paths where appropriate.
fn with_crate_prefix(CratePrefixGuard, SHOULD_PREFIX_WITH_CRATE);
/// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
/// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
/// if no other `Vec` is found.
fn with_no_trimmed_paths(NoTrimmedGuard, NO_TRIMMED_PATH);
fn with_forced_trimmed_paths(ForceTrimmedGuard, FORCE_TRIMMED_PATH);
/// Prevent selection of visible paths. `Display` impl of DefId will prefer
/// visible (public) reexports of types as paths.
fn with_no_visible_paths(NoVisibleGuard, NO_VISIBLE_PATH);
);
/// The "region highlights" are used to control region printing during
/// specific error messages. When a "region highlight" is enabled, it
/// gives an alternate way to print specific regions. For now, we
/// always print those regions using a number, so something like "`'0`".
///
/// Regions not selected by the region highlight mode are presently
/// unaffected.
#[derive(Copy, Clone, Default)]
pub struct RegionHighlightMode<'tcx> {
/// If enabled, when we see the selected region, use "`'N`"
/// instead of the ordinary behavior.
highlight_regions: [Option<(ty::Region<'tcx>, usize)>; 3],
/// If enabled, when printing a "free region" that originated from
/// the given `ty::BoundRegionKind`, print it as "`'1`". Free regions that would ordinarily
/// have names print as normal.
///
/// This is used when you have a signature like `fn foo(x: &u32,
/// y: &'a u32)` and we want to give a name to the region of the
/// reference `x`.
highlight_bound_region: Option<(ty::BoundRegionKind, usize)>,
}
impl<'tcx> RegionHighlightMode<'tcx> {
/// If `region` and `number` are both `Some`, invokes
/// `highlighting_region`.
pub fn maybe_highlighting_region(
&mut self,
region: Option<ty::Region<'tcx>>,
number: Option<usize>,
) {
if let Some(k) = region {
if let Some(n) = number {
self.highlighting_region(k, n);
}
}
}
/// Highlights the region inference variable `vid` as `'N`.
pub fn highlighting_region(&mut self, region: ty::Region<'tcx>, number: usize) {
let num_slots = self.highlight_regions.len();
let first_avail_slot =
self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
bug!("can only highlight {} placeholders at a time", num_slots,)
});
*first_avail_slot = Some((region, number));
}
/// Convenience wrapper for `highlighting_region`.
pub fn highlighting_region_vid(
&mut self,
tcx: TyCtxt<'tcx>,
vid: ty::RegionVid,
number: usize,
) {
self.highlighting_region(ty::Region::new_var(tcx, vid), number)
}
/// Returns `Some(n)` with the number to use for the given region, if any.
fn region_highlighted(&self, region: ty::Region<'tcx>) -> Option<usize> {
self.highlight_regions.iter().find_map(|h| match h {
Some((r, n)) if *r == region => Some(*n),
_ => None,
})
}
/// Highlight the given bound region.
/// We can only highlight one bound region at a time. See
/// the field `highlight_bound_region` for more detailed notes.
pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind, number: usize) {
assert!(self.highlight_bound_region.is_none());
self.highlight_bound_region = Some((br, number));
}
}
/// Trait for printers that pretty-print using `fmt::Write` to the printer.
pub trait PrettyPrinter<'tcx>:
Printer<
'tcx,
Error = fmt::Error,
Path = Self,
Region = Self,
Type = Self,
DynExistential = Self,
Const = Self,
> + fmt::Write
{
/// Like `print_def_path` but for value paths.
fn print_value_path(
self,
def_id: DefId,
args: &'tcx [GenericArg<'tcx>],
) -> Result<Self::Path, Self::Error> {
self.print_def_path(def_id, args)
}
fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
where
T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<TyCtxt<'tcx>>,
{
value.as_ref().skip_binder().print(self)
}
fn wrap_binder<T, F: FnOnce(&T, Self) -> Result<Self, fmt::Error>>(
self,
value: &ty::Binder<'tcx, T>,
f: F,
) -> Result<Self, Self::Error>
where
T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<TyCtxt<'tcx>>,
{
f(value.as_ref().skip_binder(), self)
}
/// Prints comma-separated elements.
fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
where
T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
{
if let Some(first) = elems.next() {
self = first.print(self)?;
for elem in elems {
self.write_str(", ")?;
self = elem.print(self)?;
}
}
Ok(self)
}
/// Prints `{f: t}` or `{f as t}` depending on the `cast` argument
fn typed_value(
mut self,
f: impl FnOnce(Self) -> Result<Self, Self::Error>,
t: impl FnOnce(Self) -> Result<Self, Self::Error>,
conversion: &str,
) -> Result<Self::Const, Self::Error> {
self.write_str("{")?;
self = f(self)?;
self.write_str(conversion)?;
self = t(self)?;
self.write_str("}")?;
Ok(self)
}
/// Prints `<...>` around what `f` prints.
fn generic_delimiters(
self,
f: impl FnOnce(Self) -> Result<Self, Self::Error>,
) -> Result<Self, Self::Error>;
/// Returns `true` if the region should be printed in
/// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
/// This is typically the case for all non-`'_` regions.
fn should_print_region(&self, region: ty::Region<'tcx>) -> bool;
fn reset_type_limit(&mut self) {}
// Defaults (should not be overridden):
/// If possible, this returns a global path resolving to `def_id` that is visible
/// from at least one local module, and returns `true`. If the crate defining `def_id` is
/// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
if NO_VISIBLE_PATH.with(|flag| flag.get()) {
return Ok((self, false));
}
let mut callers = Vec::new();
self.try_print_visible_def_path_recur(def_id, &mut callers)
}
// Given a `DefId`, produce a short name. For types and traits, it prints *only* its name,
// For associated items on traits it prints out the trait's name and the associated item's name.
// For enum variants, if they have an unique name, then we only print the name, otherwise we
// print the enum name and the variant name. Otherwise, we do not print anything and let the
// caller use the `print_def_path` fallback.
fn force_print_trimmed_def_path(
mut self,
def_id: DefId,
) -> Result<(Self::Path, bool), Self::Error> {
let key = self.tcx().def_key(def_id);
let visible_parent_map = self.tcx().visible_parent_map(());
let kind = self.tcx().def_kind(def_id);
let get_local_name = |this: &Self, name, def_id, key: DefKey| {
if let Some(visible_parent) = visible_parent_map.get(&def_id)
&& let actual_parent = this.tcx().opt_parent(def_id)
&& let DefPathData::TypeNs(_) = key.disambiguated_data.data
&& Some(*visible_parent) != actual_parent
{
this.tcx()
// FIXME(typed_def_id): Further propagate ModDefId
.module_children(ModDefId::new_unchecked(*visible_parent))
.iter()
.filter(|child| child.res.opt_def_id() == Some(def_id))
.find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
.map(|child| child.ident.name)
.unwrap_or(name)
} else {
name
}
};
if let DefKind::Variant = kind
&& let Some(symbol) = self.tcx().trimmed_def_paths(()).get(&def_id)
{
// If `Assoc` is unique, we don't want to talk about `Trait::Assoc`.
self.write_str(get_local_name(&self, *symbol, def_id, key).as_str())?;
return Ok((self, true));
}
if let Some(symbol) = key.get_opt_name() {
if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = kind
&& let Some(parent) = self.tcx().opt_parent(def_id)
&& let parent_key = self.tcx().def_key(parent)
&& let Some(symbol) = parent_key.get_opt_name()
{
// Trait
self.write_str(get_local_name(&self, symbol, parent, parent_key).as_str())?;
self.write_str("::")?;
} else if let DefKind::Variant = kind
&& let Some(parent) = self.tcx().opt_parent(def_id)
&& let parent_key = self.tcx().def_key(parent)
&& let Some(symbol) = parent_key.get_opt_name()
{
// Enum
// For associated items and variants, we want the "full" path, namely, include
// the parent type in the path. For example, `Iterator::Item`.
self.write_str(get_local_name(&self, symbol, parent, parent_key).as_str())?;
self.write_str("::")?;
} else if let DefKind::Struct
| DefKind::Union
| DefKind::Enum
| DefKind::Trait
| DefKind::TyAlias
| DefKind::Fn
| DefKind::Const
| DefKind::Static(_) = kind
{
} else {
// If not covered above, like for example items out of `impl` blocks, fallback.
return Ok((self, false));
}
self.write_str(get_local_name(&self, symbol, def_id, key).as_str())?;
return Ok((self, true));
}
Ok((self, false))
}
/// Try to see if this path can be trimmed to a unique symbol name.
fn try_print_trimmed_def_path(
mut self,
def_id: DefId,
) -> Result<(Self::Path, bool), Self::Error> {
if FORCE_TRIMMED_PATH.with(|flag| flag.get()) {
let (s, trimmed) = self.force_print_trimmed_def_path(def_id)?;
if trimmed {
return Ok((s, true));
}
self = s;
}
if !self.tcx().sess.opts.unstable_opts.trim_diagnostic_paths
|| matches!(self.tcx().sess.opts.trimmed_def_paths, TrimmedDefPaths::Never)
|| NO_TRIMMED_PATH.with(|flag| flag.get())
|| SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get())
{
return Ok((self, false));
}
match self.tcx().trimmed_def_paths(()).get(&def_id) {
None => Ok((self, false)),
Some(symbol) => {
write!(self, "{}", Ident::with_dummy_span(*symbol))?;
Ok((self, true))
}
}
}
/// Does the work of `try_print_visible_def_path`, building the
/// full definition path recursively before attempting to
/// post-process it into the valid and visible version that
/// accounts for re-exports.
///
/// This method should only be called by itself or
/// `try_print_visible_def_path`.
///
/// `callers` is a chain of visible_parent's leading to `def_id`,
/// to support cycle detection during recursion.
///
/// This method returns false if we can't print the visible path, so
/// `print_def_path` can fall back on the item's real definition path.
fn try_print_visible_def_path_recur(
mut self,
def_id: DefId,
callers: &mut Vec<DefId>,
) -> Result<(Self, bool), Self::Error> {
define_scoped_cx!(self);
debug!("try_print_visible_def_path: def_id={:?}", def_id);
// If `def_id` is a direct or injected extern crate, return the
// path to the crate followed by the path to the item within the crate.
if let Some(cnum) = def_id.as_crate_root() {
if cnum == LOCAL_CRATE {
return Ok((self.path_crate(cnum)?, true));
}
// In local mode, when we encounter a crate other than
// LOCAL_CRATE, execution proceeds in one of two ways:
//
// 1. For a direct dependency, where user added an
// `extern crate` manually, we put the `extern
// crate` as the parent. So you wind up with
// something relative to the current crate.
// 2. For an extern inferred from a path or an indirect crate,
// where there is no explicit `extern crate`, we just prepend
// the crate name.
match self.tcx().extern_crate(def_id) {
Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
(ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
// NOTE(eddyb) the only reason `span` might be dummy,
// that we're aware of, is that it's the `std`/`core`
// `extern crate` injected by default.
// FIXME(eddyb) find something better to key this on,
// or avoid ending up with `ExternCrateSource::Extern`,
// for the injected `std`/`core`.
if span.is_dummy() {
return Ok((self.path_crate(cnum)?, true));
}
// Disable `try_print_trimmed_def_path` behavior within
// the `print_def_path` call, to avoid infinite recursion
// in cases where the `extern crate foo` has non-trivial
// parents, e.g. it's nested in `impl foo::Trait for Bar`
// (see also issues #55779 and #87932).
self = with_no_visible_paths!(self.print_def_path(def_id, &[])?);
return Ok((self, true));
}
(ExternCrateSource::Path, LOCAL_CRATE) => {
return Ok((self.path_crate(cnum)?, true));
}
_ => {}
},
None => {
return Ok((self.path_crate(cnum)?, true));
}
}
}
if def_id.is_local() {
return Ok((self, false));
}
let visible_parent_map = self.tcx().visible_parent_map(());
let mut cur_def_key = self.tcx().def_key(def_id);
debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
// For a constructor, we want the name of its parent rather than <unnamed>.
if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
let parent = DefId {
krate: def_id.krate,
index: cur_def_key
.parent
.expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
};
cur_def_key = self.tcx().def_key(parent);
}
let Some(visible_parent) = visible_parent_map.get(&def_id).cloned() else {
return Ok((self, false));
};
let actual_parent = self.tcx().opt_parent(def_id);
debug!(
"try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
visible_parent, actual_parent,
);
let mut data = cur_def_key.disambiguated_data.data;
debug!(
"try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
data, visible_parent, actual_parent,
);
match data {
// In order to output a path that could actually be imported (valid and visible),
// we need to handle re-exports correctly.
//
// For example, take `std::os::unix::process::CommandExt`, this trait is actually
// defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
//
// `std::os::unix` reexports the contents of `std::sys::unix::ext`. `std::sys` is
// private so the "true" path to `CommandExt` isn't accessible.
//
// In this case, the `visible_parent_map` will look something like this:
//
// (child) -> (parent)
// `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
// `std::sys::unix::ext::process` -> `std::sys::unix::ext`
// `std::sys::unix::ext` -> `std::os`
//
// This is correct, as the visible parent of `std::sys::unix::ext` is in fact
// `std::os`.
//
// When printing the path to `CommandExt` and looking at the `cur_def_key` that
// corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
// to the parent - resulting in a mangled path like
// `std::os::ext::process::CommandExt`.
//
// Instead, we must detect that there was a re-export and instead print `unix`
// (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
// do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
// the visible parent (`std::os`). If these do not match, then we iterate over
// the children of the visible parent (as was done when computing
// `visible_parent_map`), looking for the specific child we currently have and then
// have access to the re-exported name.
DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
// Item might be re-exported several times, but filter for the one
// that's public and whose identifier isn't `_`.
let reexport = self
.tcx()
// FIXME(typed_def_id): Further propagate ModDefId
.module_children(ModDefId::new_unchecked(visible_parent))
.iter()
.filter(|child| child.res.opt_def_id() == Some(def_id))
.find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
.map(|child| child.ident.name);
if let Some(new_name) = reexport {
*name = new_name;
} else {
// There is no name that is public and isn't `_`, so bail.
return Ok((self, false));
}
}
// Re-exported `extern crate` (#43189).
DefPathData::CrateRoot => {
data = DefPathData::TypeNs(self.tcx().crate_name(def_id.krate));
}
_ => {}
}
debug!("try_print_visible_def_path: data={:?}", data);
if callers.contains(&visible_parent) {
return Ok((self, false));
}
callers.push(visible_parent);
// HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
// knowing ahead of time whether the entire path will succeed or not.
// To support printers that do not implement `PrettyPrinter`, a `Vec` or
// linked list on the stack would need to be built, before any printing.
match self.try_print_visible_def_path_recur(visible_parent, callers)? {
(cx, false) => return Ok((cx, false)),
(cx, true) => self = cx,
}
callers.pop();
Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
}
fn pretty_path_qualified(
self,
self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<Self::Path, Self::Error> {
if trait_ref.is_none() {
// Inherent impls. Try to print `Foo::bar` for an inherent
// impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
// anything other than a simple path.
match self_ty.kind() {
ty::Adt(..)
| ty::Foreign(_)
| ty::Bool
| ty::Char
| ty::Str
| ty::Int(_)
| ty::Uint(_)
| ty::Float(_) => {
return self_ty.print(self);
}
_ => {}
}
}
self.generic_delimiters(|mut cx| {
define_scoped_cx!(cx);
p!(print(self_ty));
if let Some(trait_ref) = trait_ref {
p!(" as ", print(trait_ref.print_only_trait_path()));
}
Ok(cx)
})
}
fn pretty_path_append_impl(
mut self,
print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<Self::Path, Self::Error> {
self = print_prefix(self)?;
self.generic_delimiters(|mut cx| {
define_scoped_cx!(cx);
p!("impl ");
if let Some(trait_ref) = trait_ref {
p!(print(trait_ref.print_only_trait_path()), " for ");
}
p!(print(self_ty));
Ok(cx)
})
}
fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
define_scoped_cx!(self);
match *ty.kind() {
ty::Bool => p!("bool"),
ty::Char => p!("char"),
ty::Int(t) => p!(write("{}", t.name_str())),
ty::Uint(t) => p!(write("{}", t.name_str())),
ty::Float(t) => p!(write("{}", t.name_str())),
ty::RawPtr(ref tm) => {
p!(write(
"*{} ",
match tm.mutbl {
hir::Mutability::Mut => "mut",
hir::Mutability::Not => "const",
}
));
p!(print(tm.ty))
}
ty::Ref(r, ty, mutbl) => {
p!("&");
if self.should_print_region(r) {
p!(print(r), " ");
}
p!(print(ty::TypeAndMut { ty, mutbl }))
}
ty::Never => p!("!"),
ty::Tuple(ref tys) => {
p!("(", comma_sep(tys.iter()));
if tys.len() == 1 {
p!(",");
}
p!(")")
}
ty::FnDef(def_id, args) => {
if with_no_queries() {
p!(print_def_path(def_id, args));
} else {
let sig = self.tcx().fn_sig(def_id).instantiate(self.tcx(), args);
p!(print(sig), " {{", print_value_path(def_id, args), "}}");
}
}
ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
ty::Infer(infer_ty) => {
if self.should_print_verbose() {
p!(write("{:?}", ty.kind()));
return Ok(self);
}
if let ty::TyVar(ty_vid) = infer_ty {
if let Some(name) = self.ty_infer_name(ty_vid) {
p!(write("{}", name))
} else {
p!(write("{}", infer_ty))
}
} else {
p!(write("{}", infer_ty))
}
}
ty::Error(_) => p!("{{type error}}"),
ty::Param(ref param_ty) => p!(print(param_ty)),
ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
ty::BoundTyKind::Anon => {
rustc_type_ir::debug_bound_var(&mut self, debruijn, bound_ty.var)?
}
ty::BoundTyKind::Param(_, s) => match self.should_print_verbose() {
true => p!(write("{:?}", ty.kind())),
false => p!(write("{s}")),
},
},
ty::Adt(def, args) => {
p!(print_def_path(def.did(), args));
}
ty::Dynamic(data, r, repr) => {
let print_r = self.should_print_region(r);
if print_r {
p!("(");
}
match repr {
ty::Dyn => p!("dyn "),
ty::DynStar => p!("dyn* "),
}
p!(print(data));
if print_r {
p!(" + ", print(r), ")");
}
}
ty::Foreign(def_id) => {
p!(print_def_path(def_id, &[]));
}
ty::Alias(ty::Projection | ty::Inherent | ty::Weak, ref data) => {
if !(self.should_print_verbose() || with_no_queries())
&& self.tcx().is_impl_trait_in_trait(data.def_id)
{
return self.pretty_print_opaque_impl_type(data.def_id, data.args);
} else {
p!(print(data))
}
}
ty::Placeholder(placeholder) => match placeholder.bound.kind {
ty::BoundTyKind::Anon => p!(write("{placeholder:?}")),
ty::BoundTyKind::Param(_, name) => match self.should_print_verbose() {
true => p!(write("{:?}", ty.kind())),
false => p!(write("{name}")),
},
},
ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
// We use verbose printing in 'NO_QUERIES' mode, to
// avoid needing to call `predicates_of`. This should
// only affect certain debug messages (e.g. messages printed
// from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
// and should have no effect on any compiler output.
// [Unless `-Zverbose` is used, e.g. in the output of
// `tests/ui/nll/ty-outlives/impl-trait-captures.rs`, for
// example.]
if self.should_print_verbose() {
// FIXME(eddyb) print this with `print_def_path`.
p!(write("Opaque({:?}, {})", def_id, args.print_as_list()));
return Ok(self);
}
let parent = self.tcx().parent(def_id);
match self.tcx().def_kind(parent) {
DefKind::TyAlias | DefKind::AssocTy => {
// NOTE: I know we should check for NO_QUERIES here, but it's alright.
// `type_of` on a type alias or assoc type should never cause a cycle.
if let ty::Alias(ty::Opaque, ty::AliasTy { def_id: d, .. }) =
*self.tcx().type_of(parent).instantiate_identity().kind()
{
if d == def_id {
// If the type alias directly starts with the `impl` of the
// opaque type we're printing, then skip the `::{opaque#1}`.
p!(print_def_path(parent, args));
return Ok(self);
}
}
// Complex opaque type, e.g. `type Foo = (i32, impl Debug);`
p!(print_def_path(def_id, args));
return Ok(self);
}
_ => {
if with_no_queries() {
p!(print_def_path(def_id, &[]));
return Ok(self);
} else {
return self.pretty_print_opaque_impl_type(def_id, args);
}
}
}
}
ty::Str => p!("str"),
ty::Generator(did, args, movability) => {
p!(write("{{"));
let generator_kind = self.tcx().generator_kind(did).unwrap();
let should_print_movability =
self.should_print_verbose() || generator_kind == hir::GeneratorKind::Gen;
if should_print_movability {
match movability {
hir::Movability::Movable => {}
hir::Movability::Static => p!("static "),
}
}
if !self.should_print_verbose() {
p!(write("{}", generator_kind));
// FIXME(eddyb) should use `def_span`.
if let Some(did) = did.as_local() {
let span = self.tcx().def_span(did);
p!(write(
"@{}",
// This may end up in stderr diagnostics but it may also be emitted
// into MIR. Hence we use the remapped path if available
self.tcx().sess.source_map().span_to_embeddable_string(span)
));
} else {
p!(write("@"), print_def_path(did, args));
}
} else {
p!(print_def_path(did, args));
p!(" upvar_tys=(");
if !args.as_generator().is_valid() {
p!("unavailable");
} else {
self = self.comma_sep(args.as_generator().upvar_tys().iter())?;
}
p!(")");
if args.as_generator().is_valid() {
p!(" ", print(args.as_generator().witness()));
}
}
p!("}}")
}
ty::GeneratorWitness(did, args) => {
p!(write("{{"));
if !self.tcx().sess.verbose() {
p!("generator witness");
// FIXME(eddyb) should use `def_span`.
if let Some(did) = did.as_local() {
let span = self.tcx().def_span(did);
p!(write(
"@{}",
// This may end up in stderr diagnostics but it may also be emitted
// into MIR. Hence we use the remapped path if available
self.tcx().sess.source_map().span_to_embeddable_string(span)
));
} else {
p!(write("@"), print_def_path(did, args));
}
} else {
p!(print_def_path(did, args));
}
p!("}}")
}
ty::Closure(did, args) => {
p!(write("{{"));
if !self.should_print_verbose() {
p!(write("closure"));
// FIXME(eddyb) should use `def_span`.
if let Some(did) = did.as_local() {
if self.tcx().sess.opts.unstable_opts.span_free_formats {
p!("@", print_def_path(did.to_def_id(), args));
} else {
let span = self.tcx().def_span(did);
let preference = if FORCE_TRIMMED_PATH.with(|flag| flag.get()) {
FileNameDisplayPreference::Short
} else {
FileNameDisplayPreference::Remapped
};
p!(write(
"@{}",
// This may end up in stderr diagnostics but it may also be emitted
// into MIR. Hence we use the remapped path if available
self.tcx().sess.source_map().span_to_string(span, preference)
));
}
} else {
p!(write("@"), print_def_path(did, args));
}
} else {
p!(print_def_path(did, args));
if !args.as_closure().is_valid() {
p!(" closure_args=(unavailable)");
p!(write(" args={}", args.print_as_list()));
} else {
p!(" closure_kind_ty=", print(args.as_closure().kind_ty()));
p!(
" closure_sig_as_fn_ptr_ty=",
print(args.as_closure().sig_as_fn_ptr_ty())
);
p!(" upvar_tys=(");
self = self.comma_sep(args.as_closure().upvar_tys().iter())?;
p!(")");
}
}
p!("}}");
}
ty::Array(ty, sz) => p!("[", print(ty), "; ", print(sz), "]"),
ty::Slice(ty) => p!("[", print(ty), "]"),
}
Ok(self)
}
fn pretty_print_opaque_impl_type(
mut self,
def_id: DefId,
args: &'tcx ty::List<ty::GenericArg<'tcx>>,
) -> Result<Self::Type, Self::Error> {
let tcx = self.tcx();
// Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
// by looking up the projections associated with the def_id.
let bounds = tcx.explicit_item_bounds(def_id);
let mut traits = FxIndexMap::default();
let mut fn_traits = FxIndexMap::default();
let mut is_sized = false;
let mut lifetimes = SmallVec::<[ty::Region<'tcx>; 1]>::new();
for (predicate, _) in bounds.iter_instantiated_copied(tcx, args) {
let bound_predicate = predicate.kind();
match bound_predicate.skip_binder() {
ty::ClauseKind::Trait(pred) => {
let trait_ref = bound_predicate.rebind(pred.trait_ref);
// Don't print + Sized, but rather + ?Sized if absent.
if Some(trait_ref.def_id()) == tcx.lang_items().sized_trait() {
is_sized = true;
continue;
}
self.insert_trait_and_projection(trait_ref, None, &mut traits, &mut fn_traits);
}
ty::ClauseKind::Projection(pred) => {
let proj_ref = bound_predicate.rebind(pred);
let trait_ref = proj_ref.required_poly_trait_ref(tcx);
// Projection type entry -- the def-id for naming, and the ty.
let proj_ty = (proj_ref.projection_def_id(), proj_ref.term());
self.insert_trait_and_projection(
trait_ref,
Some(proj_ty),
&mut traits,
&mut fn_traits,
);
}
ty::ClauseKind::TypeOutlives(outlives) => {
lifetimes.push(outlives.1);
}
_ => {}
}
}
write!(self, "impl ")?;
let mut first = true;
// Insert parenthesis around (Fn(A, B) -> C) if the opaque ty has more than one other trait
let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !is_sized;
for (fn_once_trait_ref, entry) in fn_traits {
write!(self, "{}", if first { "" } else { " + " })?;
write!(self, "{}", if paren_needed { "(" } else { "" })?;
self = self.wrap_binder(&fn_once_trait_ref, |trait_ref, mut cx| {
define_scoped_cx!(cx);
// Get the (single) generic ty (the args) of this FnOnce trait ref.
let generics = tcx.generics_of(trait_ref.def_id);
let own_args = generics.own_args_no_defaults(tcx, trait_ref.args);
match (entry.return_ty, own_args[0].expect_ty()) {
// We can only print `impl Fn() -> ()` if we have a tuple of args and we recorded
// a return type.
(Some(return_ty), arg_tys) if matches!(arg_tys.kind(), ty::Tuple(_)) => {
let name = if entry.fn_trait_ref.is_some() {
"Fn"
} else if entry.fn_mut_trait_ref.is_some() {
"FnMut"
} else {
"FnOnce"
};
p!(write("{}(", name));
for (idx, ty) in arg_tys.tuple_fields().iter().enumerate() {