]> git.proxmox.com Git - rustc.git/blob - src/librustc/util/ppaux.rs
New upstream version 1.14.0+dfsg1
[rustc.git] / src / librustc / util / ppaux.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use hir::def_id::DefId;
12 use hir::map::definitions::DefPathData;
13 use ty::subst::{self, Subst};
14 use ty::{BrAnon, BrEnv, BrFresh, BrNamed};
15 use ty::{TyBool, TyChar, TyAdt};
16 use ty::{TyError, TyStr, TyArray, TySlice, TyFloat, TyFnDef, TyFnPtr};
17 use ty::{TyParam, TyRawPtr, TyRef, TyNever, TyTuple};
18 use ty::{TyClosure, TyProjection, TyAnon};
19 use ty::{TyBox, TyTrait, TyInt, TyUint, TyInfer};
20 use ty::{self, Ty, TyCtxt, TypeFoldable};
21 use ty::fold::{TypeFolder, TypeVisitor};
22
23 use std::cell::Cell;
24 use std::fmt;
25 use std::usize;
26
27 use syntax::abi::Abi;
28 use syntax::parse::token;
29 use syntax::ast::CRATE_NODE_ID;
30 use hir;
31
32 pub fn verbose() -> bool {
33 ty::tls::with(|tcx| tcx.sess.verbose())
34 }
35
36 fn fn_sig(f: &mut fmt::Formatter,
37 inputs: &[Ty],
38 variadic: bool,
39 output: Ty)
40 -> fmt::Result {
41 write!(f, "(")?;
42 let mut inputs = inputs.iter();
43 if let Some(&ty) = inputs.next() {
44 write!(f, "{}", ty)?;
45 for &ty in inputs {
46 write!(f, ", {}", ty)?;
47 }
48 if variadic {
49 write!(f, ", ...")?;
50 }
51 }
52 write!(f, ")")?;
53 if !output.is_nil() {
54 write!(f, " -> {}", output)?;
55 }
56
57 Ok(())
58 }
59
60 pub fn parameterized(f: &mut fmt::Formatter,
61 substs: &subst::Substs,
62 mut did: DefId,
63 projections: &[ty::ProjectionPredicate])
64 -> fmt::Result {
65 let key = ty::tls::with(|tcx| tcx.def_key(did));
66 let mut item_name = if let Some(name) = key.disambiguated_data.data.get_opt_name() {
67 Some(name)
68 } else {
69 did.index = key.parent.unwrap_or_else(
70 || bug!("finding type for {:?}, encountered def-id {:?} with no parent",
71 did, did));
72 parameterized(f, substs, did, projections)?;
73 return write!(f, "::{}", key.disambiguated_data.data.as_interned_str());
74 };
75
76 let mut verbose = false;
77 let mut num_supplied_defaults = 0;
78 let mut has_self = false;
79 let mut num_regions = 0;
80 let mut num_types = 0;
81 let mut is_value_path = false;
82 let fn_trait_kind = ty::tls::with(|tcx| {
83 // Unfortunately, some kinds of items (e.g., closures) don't have
84 // generics. So walk back up the find the closest parent that DOES
85 // have them.
86 let mut item_def_id = did;
87 loop {
88 let key = tcx.def_key(item_def_id);
89 match key.disambiguated_data.data {
90 DefPathData::TypeNs(_) => {
91 break;
92 }
93 DefPathData::ValueNs(_) | DefPathData::EnumVariant(_) => {
94 is_value_path = true;
95 break;
96 }
97 _ => {
98 // if we're making a symbol for something, there ought
99 // to be a value or type-def or something in there
100 // *somewhere*
101 item_def_id.index = key.parent.unwrap_or_else(|| {
102 bug!("finding type for {:?}, encountered def-id {:?} with no \
103 parent", did, item_def_id);
104 });
105 }
106 }
107 }
108 let mut generics = tcx.lookup_generics(item_def_id);
109 let mut path_def_id = did;
110 verbose = tcx.sess.verbose();
111 has_self = generics.has_self;
112
113 let mut child_types = 0;
114 if let Some(def_id) = generics.parent {
115 // Methods.
116 assert!(is_value_path);
117 child_types = generics.types.len();
118 generics = tcx.lookup_generics(def_id);
119 num_regions = generics.regions.len();
120 num_types = generics.types.len();
121
122 if has_self {
123 write!(f, "<{} as ", substs.type_at(0))?;
124 }
125
126 path_def_id = def_id;
127 } else {
128 item_name = None;
129
130 if is_value_path {
131 // Functions.
132 assert_eq!(has_self, false);
133 } else {
134 // Types and traits.
135 num_regions = generics.regions.len();
136 num_types = generics.types.len();
137 }
138 }
139
140 if !verbose {
141 if generics.types.last().map_or(false, |def| def.default.is_some()) {
142 if let Some(substs) = tcx.lift(&substs) {
143 let tps = substs.types().rev().skip(child_types);
144 for (def, actual) in generics.types.iter().rev().zip(tps) {
145 if def.default.subst(tcx, substs) != Some(actual) {
146 break;
147 }
148 num_supplied_defaults += 1;
149 }
150 }
151 }
152 }
153
154 write!(f, "{}", tcx.item_path_str(path_def_id))?;
155 Ok(tcx.lang_items.fn_trait_kind(path_def_id))
156 })?;
157
158 if !verbose && fn_trait_kind.is_some() && projections.len() == 1 {
159 let projection_ty = projections[0].ty;
160 if let TyTuple(ref args) = substs.type_at(1).sty {
161 return fn_sig(f, args, false, projection_ty);
162 }
163 }
164
165 let empty = Cell::new(true);
166 let start_or_continue = |f: &mut fmt::Formatter, start: &str, cont: &str| {
167 if empty.get() {
168 empty.set(false);
169 write!(f, "{}", start)
170 } else {
171 write!(f, "{}", cont)
172 }
173 };
174
175 let print_regions = |f: &mut fmt::Formatter, start: &str, skip, count| {
176 // Don't print any regions if they're all erased.
177 let regions = || substs.regions().skip(skip).take(count);
178 if regions().all(|r: &ty::Region| *r == ty::ReErased) {
179 return Ok(());
180 }
181
182 for region in regions() {
183 let region: &ty::Region = region;
184 start_or_continue(f, start, ", ")?;
185 if verbose {
186 write!(f, "{:?}", region)?;
187 } else {
188 let s = region.to_string();
189 if s.is_empty() {
190 // This happens when the value of the region
191 // parameter is not easily serialized. This may be
192 // because the user omitted it in the first place,
193 // or because it refers to some block in the code,
194 // etc. I'm not sure how best to serialize this.
195 write!(f, "'_")?;
196 } else {
197 write!(f, "{}", s)?;
198 }
199 }
200 }
201
202 Ok(())
203 };
204
205 print_regions(f, "<", 0, num_regions)?;
206
207 let tps = substs.types().take(num_types - num_supplied_defaults)
208 .skip(has_self as usize);
209
210 for ty in tps {
211 start_or_continue(f, "<", ", ")?;
212 write!(f, "{}", ty)?;
213 }
214
215 for projection in projections {
216 start_or_continue(f, "<", ", ")?;
217 write!(f, "{}={}",
218 projection.projection_ty.item_name,
219 projection.ty)?;
220 }
221
222 start_or_continue(f, "", ">")?;
223
224 // For values, also print their name and type parameters.
225 if is_value_path {
226 empty.set(true);
227
228 if has_self {
229 write!(f, ">")?;
230 }
231
232 if let Some(item_name) = item_name {
233 write!(f, "::{}", item_name)?;
234 }
235
236 print_regions(f, "::<", num_regions, usize::MAX)?;
237
238 // FIXME: consider being smart with defaults here too
239 for ty in substs.types().skip(num_types) {
240 start_or_continue(f, "::<", ", ")?;
241 write!(f, "{}", ty)?;
242 }
243
244 start_or_continue(f, "", ">")?;
245 }
246
247 Ok(())
248 }
249
250 fn in_binder<'a, 'gcx, 'tcx, T, U>(f: &mut fmt::Formatter,
251 tcx: TyCtxt<'a, 'gcx, 'tcx>,
252 original: &ty::Binder<T>,
253 lifted: Option<ty::Binder<U>>) -> fmt::Result
254 where T: fmt::Display, U: fmt::Display + TypeFoldable<'tcx>
255 {
256 // Replace any anonymous late-bound regions with named
257 // variants, using gensym'd identifiers, so that we can
258 // clearly differentiate between named and unnamed regions in
259 // the output. We'll probably want to tweak this over time to
260 // decide just how much information to give.
261 let value = if let Some(v) = lifted {
262 v
263 } else {
264 return write!(f, "{}", original.0);
265 };
266
267 let mut empty = true;
268 let mut start_or_continue = |f: &mut fmt::Formatter, start: &str, cont: &str| {
269 if empty {
270 empty = false;
271 write!(f, "{}", start)
272 } else {
273 write!(f, "{}", cont)
274 }
275 };
276
277 let new_value = tcx.replace_late_bound_regions(&value, |br| {
278 let _ = start_or_continue(f, "for<", ", ");
279 let br = match br {
280 ty::BrNamed(_, name, _) => {
281 let _ = write!(f, "{}", name);
282 br
283 }
284 ty::BrAnon(_) |
285 ty::BrFresh(_) |
286 ty::BrEnv => {
287 let name = token::intern("'r");
288 let _ = write!(f, "{}", name);
289 ty::BrNamed(tcx.map.local_def_id(CRATE_NODE_ID),
290 name,
291 ty::Issue32330::WontChange)
292 }
293 };
294 tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1), br))
295 }).0;
296
297 start_or_continue(f, "", "> ")?;
298 write!(f, "{}", new_value)
299 }
300
301 /// This curious type is here to help pretty-print trait objects. In
302 /// a trait object, the projections are stored separately from the
303 /// main trait bound, but in fact we want to package them together
304 /// when printing out; they also have separate binders, but we want
305 /// them to share a binder when we print them out. (And the binder
306 /// pretty-printing logic is kind of clever and we don't want to
307 /// reproduce it.) So we just repackage up the structure somewhat.
308 ///
309 /// Right now there is only one trait in an object that can have
310 /// projection bounds, so we just stuff them altogether. But in
311 /// reality we should eventually sort things out better.
312 #[derive(Clone, Debug)]
313 struct TraitAndProjections<'tcx>(ty::TraitRef<'tcx>,
314 Vec<ty::ProjectionPredicate<'tcx>>);
315
316 impl<'tcx> TypeFoldable<'tcx> for TraitAndProjections<'tcx> {
317 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
318 TraitAndProjections(self.0.fold_with(folder), self.1.fold_with(folder))
319 }
320
321 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
322 self.0.visit_with(visitor) || self.1.visit_with(visitor)
323 }
324 }
325
326 impl<'tcx> fmt::Display for TraitAndProjections<'tcx> {
327 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
328 let TraitAndProjections(ref trait_ref, ref projection_bounds) = *self;
329 parameterized(f, trait_ref.substs,
330 trait_ref.def_id,
331 projection_bounds)
332 }
333 }
334
335 impl<'tcx> fmt::Display for ty::TraitObject<'tcx> {
336 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
337 // Generate the main trait ref, including associated types.
338 ty::tls::with(|tcx| {
339 // Use a type that can't appear in defaults of type parameters.
340 let dummy_self = tcx.mk_infer(ty::FreshTy(0));
341
342 let principal = tcx.lift(&self.principal)
343 .expect("could not lift TraitRef for printing")
344 .with_self_ty(tcx, dummy_self).0;
345 let projections = self.projection_bounds.iter().map(|p| {
346 tcx.lift(p)
347 .expect("could not lift projection for printing")
348 .with_self_ty(tcx, dummy_self).0
349 }).collect();
350
351 let tap = ty::Binder(TraitAndProjections(principal, projections));
352 in_binder(f, tcx, &ty::Binder(""), Some(tap))
353 })?;
354
355 // Builtin bounds.
356 for bound in &self.builtin_bounds {
357 write!(f, " + {:?}", bound)?;
358 }
359
360 // FIXME: It'd be nice to compute from context when this bound
361 // is implied, but that's non-trivial -- we'd perhaps have to
362 // use thread-local data of some kind? There are also
363 // advantages to just showing the region, since it makes
364 // people aware that it's there.
365 let bound = self.region_bound.to_string();
366 if !bound.is_empty() {
367 write!(f, " + {}", bound)?;
368 }
369
370 Ok(())
371 }
372 }
373
374 impl<'tcx> fmt::Debug for ty::TypeParameterDef<'tcx> {
375 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
376 write!(f, "TypeParameterDef({}, {:?}, {})",
377 self.name,
378 self.def_id,
379 self.index)
380 }
381 }
382
383 impl<'tcx> fmt::Debug for ty::RegionParameterDef<'tcx> {
384 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
385 write!(f, "RegionParameterDef({}, {:?}, {}, {:?})",
386 self.name,
387 self.def_id,
388 self.index,
389 self.bounds)
390 }
391 }
392
393 impl<'tcx> fmt::Debug for ty::TyS<'tcx> {
394 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
395 write!(f, "{}", *self)
396 }
397 }
398
399 impl<'tcx> fmt::Display for ty::TypeAndMut<'tcx> {
400 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
401 write!(f, "{}{}",
402 if self.mutbl == hir::MutMutable { "mut " } else { "" },
403 self.ty)
404 }
405 }
406
407 impl<'tcx> fmt::Debug for ty::ItemSubsts<'tcx> {
408 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
409 write!(f, "ItemSubsts({:?})", self.substs)
410 }
411 }
412
413 impl<'tcx> fmt::Debug for ty::TraitRef<'tcx> {
414 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
415 // when printing out the debug representation, we don't need
416 // to enumerate the `for<...>` etc because the debruijn index
417 // tells you everything you need to know.
418 write!(f, "<{:?} as {}>", self.self_ty(), *self)
419 }
420 }
421
422 impl<'tcx> fmt::Debug for ty::ExistentialTraitRef<'tcx> {
423 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
424 ty::tls::with(|tcx| {
425 let dummy_self = tcx.mk_infer(ty::FreshTy(0));
426
427 let trait_ref = tcx.lift(&ty::Binder(*self))
428 .expect("could not lift TraitRef for printing")
429 .with_self_ty(tcx, dummy_self).0;
430 parameterized(f, trait_ref.substs, trait_ref.def_id, &[])
431 })
432 }
433 }
434
435 impl<'tcx> fmt::Debug for ty::TraitDef<'tcx> {
436 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
437 write!(f, "TraitDef(generics={:?}, trait_ref={:?})",
438 self.generics, self.trait_ref)
439 }
440 }
441
442 impl<'tcx, 'container> fmt::Debug for ty::AdtDefData<'tcx, 'container> {
443 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
444 ty::tls::with(|tcx| {
445 write!(f, "{}", tcx.item_path_str(self.did))
446 })
447 }
448 }
449
450 impl<'tcx> fmt::Debug for ty::adjustment::Adjustment<'tcx> {
451 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
452 write!(f, "{:?} -> {}", self.kind, self.target)
453 }
454 }
455
456 impl<'tcx> fmt::Debug for ty::TraitObject<'tcx> {
457 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
458 let mut empty = true;
459 let mut maybe_continue = |f: &mut fmt::Formatter| {
460 if empty {
461 empty = false;
462 Ok(())
463 } else {
464 write!(f, " + ")
465 }
466 };
467
468 maybe_continue(f)?;
469 write!(f, "{:?}", self.principal)?;
470
471 let region_str = format!("{:?}", self.region_bound);
472 if !region_str.is_empty() {
473 maybe_continue(f)?;
474 write!(f, "{}", region_str)?;
475 }
476
477 for bound in &self.builtin_bounds {
478 maybe_continue(f)?;
479 write!(f, "{:?}", bound)?;
480 }
481
482 for projection_bound in &self.projection_bounds {
483 maybe_continue(f)?;
484 write!(f, "{:?}", projection_bound)?;
485 }
486
487 Ok(())
488 }
489 }
490
491 impl<'tcx> fmt::Debug for ty::Predicate<'tcx> {
492 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
493 match *self {
494 ty::Predicate::Trait(ref a) => write!(f, "{:?}", a),
495 ty::Predicate::Equate(ref pair) => write!(f, "{:?}", pair),
496 ty::Predicate::RegionOutlives(ref pair) => write!(f, "{:?}", pair),
497 ty::Predicate::TypeOutlives(ref pair) => write!(f, "{:?}", pair),
498 ty::Predicate::Projection(ref pair) => write!(f, "{:?}", pair),
499 ty::Predicate::WellFormed(ty) => write!(f, "WF({:?})", ty),
500 ty::Predicate::ObjectSafe(trait_def_id) => {
501 write!(f, "ObjectSafe({:?})", trait_def_id)
502 }
503 ty::Predicate::ClosureKind(closure_def_id, kind) => {
504 write!(f, "ClosureKind({:?}, {:?})", closure_def_id, kind)
505 }
506 }
507 }
508 }
509
510 impl fmt::Display for ty::BoundRegion {
511 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
512 if verbose() {
513 return write!(f, "{:?}", *self);
514 }
515
516 match *self {
517 BrNamed(_, name, _) => write!(f, "{}", name),
518 BrAnon(_) | BrFresh(_) | BrEnv => Ok(())
519 }
520 }
521 }
522
523 impl fmt::Debug for ty::BoundRegion {
524 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
525 match *self {
526 BrAnon(n) => write!(f, "BrAnon({:?})", n),
527 BrFresh(n) => write!(f, "BrFresh({:?})", n),
528 BrNamed(did, name, issue32330) => {
529 write!(f, "BrNamed({:?}:{:?}, {:?}, {:?})",
530 did.krate, did.index, name, issue32330)
531 }
532 BrEnv => "BrEnv".fmt(f),
533 }
534 }
535 }
536
537 impl fmt::Debug for ty::Region {
538 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
539 match *self {
540 ty::ReEarlyBound(ref data) => {
541 write!(f, "ReEarlyBound({}, {})",
542 data.index,
543 data.name)
544 }
545
546 ty::ReLateBound(binder_id, ref bound_region) => {
547 write!(f, "ReLateBound({:?}, {:?})",
548 binder_id,
549 bound_region)
550 }
551
552 ty::ReFree(ref fr) => write!(f, "{:?}", fr),
553
554 ty::ReScope(id) => {
555 write!(f, "ReScope({:?})", id)
556 }
557
558 ty::ReStatic => write!(f, "ReStatic"),
559
560 ty::ReVar(ref vid) => {
561 write!(f, "{:?}", vid)
562 }
563
564 ty::ReSkolemized(id, ref bound_region) => {
565 write!(f, "ReSkolemized({}, {:?})", id.index, bound_region)
566 }
567
568 ty::ReEmpty => write!(f, "ReEmpty"),
569
570 ty::ReErased => write!(f, "ReErased")
571 }
572 }
573 }
574
575 impl<'tcx> fmt::Debug for ty::ClosureTy<'tcx> {
576 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
577 write!(f, "ClosureTy({},{:?},{})",
578 self.unsafety,
579 self.sig,
580 self.abi)
581 }
582 }
583
584 impl<'tcx> fmt::Debug for ty::ClosureUpvar<'tcx> {
585 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
586 write!(f, "ClosureUpvar({:?},{:?})",
587 self.def,
588 self.ty)
589 }
590 }
591
592 impl<'tcx> fmt::Debug for ty::ParameterEnvironment<'tcx> {
593 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
594 write!(f, "ParameterEnvironment(\
595 free_substs={:?}, \
596 implicit_region_bound={:?}, \
597 caller_bounds={:?})",
598 self.free_substs,
599 self.implicit_region_bound,
600 self.caller_bounds)
601 }
602 }
603
604 impl<'tcx> fmt::Debug for ty::ObjectLifetimeDefault<'tcx> {
605 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
606 match *self {
607 ty::ObjectLifetimeDefault::Ambiguous => write!(f, "Ambiguous"),
608 ty::ObjectLifetimeDefault::BaseDefault => write!(f, "BaseDefault"),
609 ty::ObjectLifetimeDefault::Specific(ref r) => write!(f, "{:?}", r),
610 }
611 }
612 }
613
614 impl fmt::Display for ty::Region {
615 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
616 if verbose() {
617 return write!(f, "{:?}", *self);
618 }
619
620 // These printouts are concise. They do not contain all the information
621 // the user might want to diagnose an error, but there is basically no way
622 // to fit that into a short string. Hence the recommendation to use
623 // `explain_region()` or `note_and_explain_region()`.
624 match *self {
625 ty::ReEarlyBound(ref data) => {
626 write!(f, "{}", data.name)
627 }
628 ty::ReLateBound(_, br) |
629 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
630 ty::ReSkolemized(_, br) => {
631 write!(f, "{}", br)
632 }
633 ty::ReScope(_) |
634 ty::ReVar(_) |
635 ty::ReErased => Ok(()),
636 ty::ReStatic => write!(f, "'static"),
637 ty::ReEmpty => write!(f, "'<empty>"),
638 }
639 }
640 }
641
642 impl fmt::Debug for ty::FreeRegion {
643 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
644 write!(f, "ReFree({:?}, {:?})",
645 self.scope, self.bound_region)
646 }
647 }
648
649 impl fmt::Debug for ty::Variance {
650 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
651 f.write_str(match *self {
652 ty::Covariant => "+",
653 ty::Contravariant => "-",
654 ty::Invariant => "o",
655 ty::Bivariant => "*",
656 })
657 }
658 }
659
660 impl<'tcx> fmt::Debug for ty::GenericPredicates<'tcx> {
661 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
662 write!(f, "GenericPredicates({:?})", self.predicates)
663 }
664 }
665
666 impl<'tcx> fmt::Debug for ty::InstantiatedPredicates<'tcx> {
667 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
668 write!(f, "InstantiatedPredicates({:?})",
669 self.predicates)
670 }
671 }
672
673 impl<'tcx> fmt::Debug for ty::ImplOrTraitItem<'tcx> {
674 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
675 write!(f, "ImplOrTraitItem(")?;
676 match *self {
677 ty::ImplOrTraitItem::MethodTraitItem(ref i) => write!(f, "{:?}", i),
678 ty::ImplOrTraitItem::ConstTraitItem(ref i) => write!(f, "{:?}", i),
679 ty::ImplOrTraitItem::TypeTraitItem(ref i) => write!(f, "{:?}", i),
680 }?;
681 write!(f, ")")
682 }
683 }
684
685 impl<'tcx> fmt::Display for ty::FnSig<'tcx> {
686 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
687 write!(f, "fn")?;
688 fn_sig(f, &self.inputs, self.variadic, self.output)
689 }
690 }
691
692 impl fmt::Display for ty::BuiltinBounds {
693 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
694 let mut bounds = self.iter();
695 if let Some(bound) = bounds.next() {
696 write!(f, "{:?}", bound)?;
697 for bound in bounds {
698 write!(f, " + {:?}", bound)?;
699 }
700 }
701 Ok(())
702 }
703 }
704
705 impl fmt::Debug for ty::TyVid {
706 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
707 write!(f, "_#{}t", self.index)
708 }
709 }
710
711 impl fmt::Debug for ty::IntVid {
712 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
713 write!(f, "_#{}i", self.index)
714 }
715 }
716
717 impl fmt::Debug for ty::FloatVid {
718 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
719 write!(f, "_#{}f", self.index)
720 }
721 }
722
723 impl fmt::Debug for ty::RegionVid {
724 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
725 write!(f, "'_#{}r", self.index)
726 }
727 }
728
729 impl<'tcx> fmt::Debug for ty::FnSig<'tcx> {
730 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
731 write!(f, "({:?}; variadic: {})->{:?}", self.inputs, self.variadic, self.output)
732 }
733 }
734
735 impl fmt::Debug for ty::InferTy {
736 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
737 match *self {
738 ty::TyVar(ref v) => v.fmt(f),
739 ty::IntVar(ref v) => v.fmt(f),
740 ty::FloatVar(ref v) => v.fmt(f),
741 ty::FreshTy(v) => write!(f, "FreshTy({:?})", v),
742 ty::FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v),
743 ty::FreshFloatTy(v) => write!(f, "FreshFloatTy({:?})", v)
744 }
745 }
746 }
747
748 impl fmt::Debug for ty::IntVarValue {
749 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
750 match *self {
751 ty::IntType(ref v) => v.fmt(f),
752 ty::UintType(ref v) => v.fmt(f),
753 }
754 }
755 }
756
757 // The generic impl doesn't work yet because projections are not
758 // normalized under HRTB.
759 /*impl<T> fmt::Display for ty::Binder<T>
760 where T: fmt::Display + for<'a> ty::Lift<'a>,
761 for<'a> <T as ty::Lift<'a>>::Lifted: fmt::Display + TypeFoldable<'a>
762 {
763 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
764 ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
765 }
766 }*/
767
768 impl<'tcx> fmt::Display for ty::Binder<ty::TraitRef<'tcx>> {
769 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
770 ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
771 }
772 }
773
774 impl<'tcx> fmt::Display for ty::Binder<ty::TraitPredicate<'tcx>> {
775 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
776 ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
777 }
778 }
779
780 impl<'tcx> fmt::Display for ty::Binder<ty::EquatePredicate<'tcx>> {
781 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
782 ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
783 }
784 }
785
786 impl<'tcx> fmt::Display for ty::Binder<ty::ProjectionPredicate<'tcx>> {
787 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
788 ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
789 }
790 }
791
792 impl<'tcx> fmt::Display for ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, &'tcx ty::Region>> {
793 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
794 ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
795 }
796 }
797
798 impl<'tcx> fmt::Display for ty::Binder<ty::OutlivesPredicate<&'tcx ty::Region,
799 &'tcx ty::Region>> {
800 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
801 ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
802 }
803 }
804
805 impl<'tcx> fmt::Display for ty::TraitRef<'tcx> {
806 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
807 parameterized(f, self.substs, self.def_id, &[])
808 }
809 }
810
811 impl<'tcx> fmt::Display for ty::TypeVariants<'tcx> {
812 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
813 match *self {
814 TyBool => write!(f, "bool"),
815 TyChar => write!(f, "char"),
816 TyInt(t) => write!(f, "{}", t.ty_to_string()),
817 TyUint(t) => write!(f, "{}", t.ty_to_string()),
818 TyFloat(t) => write!(f, "{}", t.ty_to_string()),
819 TyBox(typ) => write!(f, "Box<{}>", typ),
820 TyRawPtr(ref tm) => {
821 write!(f, "*{} {}", match tm.mutbl {
822 hir::MutMutable => "mut",
823 hir::MutImmutable => "const",
824 }, tm.ty)
825 }
826 TyRef(r, ref tm) => {
827 write!(f, "&")?;
828 let s = r.to_string();
829 write!(f, "{}", s)?;
830 if !s.is_empty() {
831 write!(f, " ")?;
832 }
833 write!(f, "{}", tm)
834 }
835 TyNever => write!(f, "!"),
836 TyTuple(ref tys) => {
837 write!(f, "(")?;
838 let mut tys = tys.iter();
839 if let Some(&ty) = tys.next() {
840 write!(f, "{},", ty)?;
841 if let Some(&ty) = tys.next() {
842 write!(f, " {}", ty)?;
843 for &ty in tys {
844 write!(f, ", {}", ty)?;
845 }
846 }
847 }
848 write!(f, ")")
849 }
850 TyFnDef(def_id, substs, ref bare_fn) => {
851 if bare_fn.unsafety == hir::Unsafety::Unsafe {
852 write!(f, "unsafe ")?;
853 }
854
855 if bare_fn.abi != Abi::Rust {
856 write!(f, "extern {} ", bare_fn.abi)?;
857 }
858
859 write!(f, "{} {{", bare_fn.sig.0)?;
860 parameterized(f, substs, def_id, &[])?;
861 write!(f, "}}")
862 }
863 TyFnPtr(ref bare_fn) => {
864 if bare_fn.unsafety == hir::Unsafety::Unsafe {
865 write!(f, "unsafe ")?;
866 }
867
868 if bare_fn.abi != Abi::Rust {
869 write!(f, "extern {} ", bare_fn.abi)?;
870 }
871
872 write!(f, "{}", bare_fn.sig.0)
873 }
874 TyInfer(infer_ty) => write!(f, "{}", infer_ty),
875 TyError => write!(f, "[type error]"),
876 TyParam(ref param_ty) => write!(f, "{}", param_ty),
877 TyAdt(def, substs) => {
878 ty::tls::with(|tcx| {
879 if def.did.is_local() &&
880 !tcx.tcache.borrow().contains_key(&def.did) {
881 write!(f, "{}<..>", tcx.item_path_str(def.did))
882 } else {
883 parameterized(f, substs, def.did, &[])
884 }
885 })
886 }
887 TyTrait(ref data) => write!(f, "{}", data),
888 TyProjection(ref data) => write!(f, "{}", data),
889 TyAnon(def_id, substs) => {
890 ty::tls::with(|tcx| {
891 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
892 // by looking up the projections associated with the def_id.
893 let item_predicates = tcx.lookup_predicates(def_id);
894 let substs = tcx.lift(&substs).unwrap_or_else(|| {
895 tcx.intern_substs(&[])
896 });
897 let bounds = item_predicates.instantiate(tcx, substs);
898
899 let mut first = true;
900 let mut is_sized = false;
901 write!(f, "impl")?;
902 for predicate in bounds.predicates {
903 if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
904 // Don't print +Sized, but rather +?Sized if absent.
905 if Some(trait_ref.def_id()) == tcx.lang_items.sized_trait() {
906 is_sized = true;
907 continue;
908 }
909
910 write!(f, "{}{}", if first { " " } else { "+" }, trait_ref)?;
911 first = false;
912 }
913 }
914 if !is_sized {
915 write!(f, "{}?Sized", if first { " " } else { "+" })?;
916 }
917 Ok(())
918 })
919 }
920 TyStr => write!(f, "str"),
921 TyClosure(did, substs) => ty::tls::with(|tcx| {
922 write!(f, "[closure")?;
923
924 if let Some(node_id) = tcx.map.as_local_node_id(did) {
925 write!(f, "@{:?}", tcx.map.span(node_id))?;
926 let mut sep = " ";
927 tcx.with_freevars(node_id, |freevars| {
928 for (freevar, upvar_ty) in freevars.iter().zip(substs.upvar_tys) {
929 let def_id = freevar.def.def_id();
930 let node_id = tcx.map.as_local_node_id(def_id).unwrap();
931 write!(f,
932 "{}{}:{}",
933 sep,
934 tcx.local_var_name_str(node_id),
935 upvar_ty)?;
936 sep = ", ";
937 }
938 Ok(())
939 })?
940 } else {
941 // cross-crate closure types should only be
942 // visible in trans bug reports, I imagine.
943 write!(f, "@{:?}", did)?;
944 let mut sep = " ";
945 for (index, upvar_ty) in substs.upvar_tys.iter().enumerate() {
946 write!(f, "{}{}:{}", sep, index, upvar_ty)?;
947 sep = ", ";
948 }
949 }
950
951 write!(f, "]")
952 }),
953 TyArray(ty, sz) => write!(f, "[{}; {}]", ty, sz),
954 TySlice(ty) => write!(f, "[{}]", ty)
955 }
956 }
957 }
958
959 impl<'tcx> fmt::Display for ty::TyS<'tcx> {
960 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
961 write!(f, "{}", self.sty)
962 }
963 }
964
965 impl fmt::Debug for ty::UpvarId {
966 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
967 write!(f, "UpvarId({};`{}`;{})",
968 self.var_id,
969 ty::tls::with(|tcx| tcx.local_var_name_str(self.var_id)),
970 self.closure_expr_id)
971 }
972 }
973
974 impl<'tcx> fmt::Debug for ty::UpvarBorrow<'tcx> {
975 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
976 write!(f, "UpvarBorrow({:?}, {:?})",
977 self.kind, self.region)
978 }
979 }
980
981 impl fmt::Display for ty::InferTy {
982 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
983 let print_var_ids = verbose();
984 match *self {
985 ty::TyVar(ref vid) if print_var_ids => write!(f, "{:?}", vid),
986 ty::IntVar(ref vid) if print_var_ids => write!(f, "{:?}", vid),
987 ty::FloatVar(ref vid) if print_var_ids => write!(f, "{:?}", vid),
988 ty::TyVar(_) => write!(f, "_"),
989 ty::IntVar(_) => write!(f, "{}", "{integer}"),
990 ty::FloatVar(_) => write!(f, "{}", "{float}"),
991 ty::FreshTy(v) => write!(f, "FreshTy({})", v),
992 ty::FreshIntTy(v) => write!(f, "FreshIntTy({})", v),
993 ty::FreshFloatTy(v) => write!(f, "FreshFloatTy({})", v)
994 }
995 }
996 }
997
998 impl<'tcx> fmt::Display for ty::ExplicitSelfCategory<'tcx> {
999 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1000 f.write_str(match *self {
1001 ty::ExplicitSelfCategory::Static => "static",
1002 ty::ExplicitSelfCategory::ByValue => "self",
1003 ty::ExplicitSelfCategory::ByReference(_, hir::MutMutable) => {
1004 "&mut self"
1005 }
1006 ty::ExplicitSelfCategory::ByReference(_, hir::MutImmutable) => "&self",
1007 ty::ExplicitSelfCategory::ByBox => "Box<self>",
1008 })
1009 }
1010 }
1011
1012 impl fmt::Display for ty::ParamTy {
1013 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1014 write!(f, "{}", self.name)
1015 }
1016 }
1017
1018 impl fmt::Debug for ty::ParamTy {
1019 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1020 write!(f, "{}/#{}", self, self.idx)
1021 }
1022 }
1023
1024 impl<'tcx, T, U> fmt::Display for ty::OutlivesPredicate<T,U>
1025 where T: fmt::Display, U: fmt::Display
1026 {
1027 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1028 write!(f, "{} : {}", self.0, self.1)
1029 }
1030 }
1031
1032 impl<'tcx> fmt::Display for ty::EquatePredicate<'tcx> {
1033 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1034 write!(f, "{} == {}", self.0, self.1)
1035 }
1036 }
1037
1038 impl<'tcx> fmt::Debug for ty::TraitPredicate<'tcx> {
1039 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1040 write!(f, "TraitPredicate({:?})",
1041 self.trait_ref)
1042 }
1043 }
1044
1045 impl<'tcx> fmt::Display for ty::TraitPredicate<'tcx> {
1046 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1047 write!(f, "{}: {}", self.trait_ref.self_ty(), self.trait_ref)
1048 }
1049 }
1050
1051 impl<'tcx> fmt::Debug for ty::ProjectionPredicate<'tcx> {
1052 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1053 write!(f, "ProjectionPredicate({:?}, {:?})",
1054 self.projection_ty,
1055 self.ty)
1056 }
1057 }
1058
1059 impl<'tcx> fmt::Display for ty::ProjectionPredicate<'tcx> {
1060 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1061 write!(f, "{} == {}",
1062 self.projection_ty,
1063 self.ty)
1064 }
1065 }
1066
1067 impl<'tcx> fmt::Display for ty::ProjectionTy<'tcx> {
1068 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1069 write!(f, "{:?}::{}",
1070 self.trait_ref,
1071 self.item_name)
1072 }
1073 }
1074
1075 impl fmt::Display for ty::ClosureKind {
1076 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1077 match *self {
1078 ty::ClosureKind::Fn => write!(f, "Fn"),
1079 ty::ClosureKind::FnMut => write!(f, "FnMut"),
1080 ty::ClosureKind::FnOnce => write!(f, "FnOnce"),
1081 }
1082 }
1083 }
1084
1085 impl<'tcx> fmt::Display for ty::Predicate<'tcx> {
1086 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1087 match *self {
1088 ty::Predicate::Trait(ref data) => write!(f, "{}", data),
1089 ty::Predicate::Equate(ref predicate) => write!(f, "{}", predicate),
1090 ty::Predicate::RegionOutlives(ref predicate) => write!(f, "{}", predicate),
1091 ty::Predicate::TypeOutlives(ref predicate) => write!(f, "{}", predicate),
1092 ty::Predicate::Projection(ref predicate) => write!(f, "{}", predicate),
1093 ty::Predicate::WellFormed(ty) => write!(f, "{} well-formed", ty),
1094 ty::Predicate::ObjectSafe(trait_def_id) =>
1095 ty::tls::with(|tcx| {
1096 write!(f, "the trait `{}` is object-safe", tcx.item_path_str(trait_def_id))
1097 }),
1098 ty::Predicate::ClosureKind(closure_def_id, kind) =>
1099 ty::tls::with(|tcx| {
1100 write!(f, "the closure `{}` implements the trait `{}`",
1101 tcx.item_path_str(closure_def_id), kind)
1102 }),
1103 }
1104 }
1105 }