]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/item_path.rs
Fixes issue #43205: ICE in Rvalue::Len evaluation.
[rust.git] / src / librustc / ty / item_path.rs
1 // Copyright 2012-2015 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::map::DefPathData;
12 use hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
13 use ty::{self, Ty, TyCtxt};
14 use syntax::ast;
15 use syntax::symbol::Symbol;
16 use syntax_pos::DUMMY_SP;
17
18 use std::cell::Cell;
19
20 thread_local! {
21     static FORCE_ABSOLUTE: Cell<bool> = Cell::new(false);
22     static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
23 }
24
25 /// Enforces that item_path_str always returns an absolute path and
26 /// also enables "type-based" impl paths. This is used when building
27 /// symbols that contain types, where we want the crate name to be
28 /// part of the symbol.
29 pub fn with_forced_absolute_paths<F: FnOnce() -> R, R>(f: F) -> R {
30     FORCE_ABSOLUTE.with(|force| {
31         let old = force.get();
32         force.set(true);
33         let result = f();
34         force.set(old);
35         result
36     })
37 }
38
39 /// Force us to name impls with just the filename/line number. We
40 /// normally try to use types. But at some points, notably while printing
41 /// cycle errors, this can result in extra or suboptimal error output,
42 /// so this variable disables that check.
43 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
44     FORCE_IMPL_FILENAME_LINE.with(|force| {
45         let old = force.get();
46         force.set(true);
47         let result = f();
48         force.set(old);
49         result
50     })
51 }
52
53 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
54     /// Returns a string identifying this def-id. This string is
55     /// suitable for user output. It is relative to the current crate
56     /// root, unless with_forced_absolute_paths was used.
57     pub fn item_path_str(self, def_id: DefId) -> String {
58         let mode = FORCE_ABSOLUTE.with(|force| {
59             if force.get() {
60                 RootMode::Absolute
61             } else {
62                 RootMode::Local
63             }
64         });
65         let mut buffer = LocalPathBuffer::new(mode);
66         self.push_item_path(&mut buffer, def_id);
67         buffer.into_string()
68     }
69
70     /// Returns a string identifying this local node-id.
71     pub fn node_path_str(self, id: ast::NodeId) -> String {
72         self.item_path_str(self.hir.local_def_id(id))
73     }
74
75     /// Returns a string identifying this def-id. This string is
76     /// suitable for user output. It always begins with a crate identifier.
77     pub fn absolute_item_path_str(self, def_id: DefId) -> String {
78         let mut buffer = LocalPathBuffer::new(RootMode::Absolute);
79         self.push_item_path(&mut buffer, def_id);
80         buffer.into_string()
81     }
82
83     /// Returns the "path" to a particular crate. This can proceed in
84     /// various ways, depending on the `root_mode` of the `buffer`.
85     /// (See `RootMode` enum for more details.)
86     pub fn push_krate_path<T>(self, buffer: &mut T, cnum: CrateNum)
87         where T: ItemPathBuffer
88     {
89         match *buffer.root_mode() {
90             RootMode::Local => {
91                 // In local mode, when we encounter a crate other than
92                 // LOCAL_CRATE, execution proceeds in one of two ways:
93                 //
94                 // 1. for a direct dependency, where user added an
95                 //    `extern crate` manually, we put the `extern
96                 //    crate` as the parent. So you wind up with
97                 //    something relative to the current crate.
98                 // 2. for an indirect crate, where there is no extern
99                 //    crate, we just prepend the crate name.
100                 //
101                 // Returns `None` for the local crate.
102                 if cnum != LOCAL_CRATE {
103                     let opt_extern_crate = self.extern_crate(cnum.as_def_id());
104                     let opt_extern_crate = opt_extern_crate.and_then(|extern_crate| {
105                         if extern_crate.direct {
106                             Some(extern_crate.def_id)
107                         } else {
108                             None
109                         }
110                     });
111                     if let Some(extern_crate_def_id) = opt_extern_crate {
112                         self.push_item_path(buffer, extern_crate_def_id);
113                     } else {
114                         buffer.push(&self.crate_name(cnum).as_str());
115                     }
116                 }
117             }
118             RootMode::Absolute => {
119                 // In absolute mode, just write the crate name
120                 // unconditionally.
121                 buffer.push(&self.original_crate_name(cnum).as_str());
122             }
123         }
124     }
125
126     /// If possible, this pushes a global path resolving to `external_def_id` that is visible
127     /// from at least one local module and returns true. If the crate defining `external_def_id` is
128     /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
129     pub fn try_push_visible_item_path<T>(self, buffer: &mut T, external_def_id: DefId) -> bool
130         where T: ItemPathBuffer
131     {
132         let visible_parent_map = self.sess.cstore.visible_parent_map(self.sess);
133
134         let (mut cur_def, mut cur_path) = (external_def_id, Vec::<ast::Name>::new());
135         loop {
136             // If `cur_def` is a direct or injected extern crate, push the path to the crate
137             // followed by the path to the item within the crate and return.
138             if cur_def.index == CRATE_DEF_INDEX {
139                 match *self.extern_crate(cur_def) {
140                     Some(ref extern_crate) if extern_crate.direct => {
141                         self.push_item_path(buffer, extern_crate.def_id);
142                         cur_path.iter().rev().map(|segment| buffer.push(&segment.as_str())).count();
143                         return true;
144                     }
145                     None => {
146                         buffer.push(&self.crate_name(cur_def.krate).as_str());
147                         cur_path.iter().rev().map(|segment| buffer.push(&segment.as_str())).count();
148                         return true;
149                     }
150                     _ => {},
151                 }
152             }
153
154             cur_path.push(self.sess.cstore.def_key(cur_def)
155                               .disambiguated_data.data.get_opt_name().unwrap_or_else(||
156                 Symbol::intern("<unnamed>")));
157             match visible_parent_map.get(&cur_def) {
158                 Some(&def) => cur_def = def,
159                 None => return false,
160             };
161         }
162     }
163
164     pub fn push_item_path<T>(self, buffer: &mut T, def_id: DefId)
165         where T: ItemPathBuffer
166     {
167         match *buffer.root_mode() {
168             RootMode::Local if !def_id.is_local() =>
169                 if self.try_push_visible_item_path(buffer, def_id) { return },
170             _ => {}
171         }
172
173         let key = self.def_key(def_id);
174         match key.disambiguated_data.data {
175             DefPathData::CrateRoot => {
176                 assert!(key.parent.is_none());
177                 self.push_krate_path(buffer, def_id.krate);
178             }
179
180             DefPathData::Impl => {
181                 self.push_impl_path(buffer, def_id);
182             }
183
184             // Unclear if there is any value in distinguishing these.
185             // Probably eventually (and maybe we would even want
186             // finer-grained distinctions, e.g. between enum/struct).
187             data @ DefPathData::Misc |
188             data @ DefPathData::TypeNs(..) |
189             data @ DefPathData::ValueNs(..) |
190             data @ DefPathData::Module(..) |
191             data @ DefPathData::TypeParam(..) |
192             data @ DefPathData::LifetimeDef(..) |
193             data @ DefPathData::EnumVariant(..) |
194             data @ DefPathData::Field(..) |
195             data @ DefPathData::Initializer |
196             data @ DefPathData::MacroDef(..) |
197             data @ DefPathData::ClosureExpr |
198             data @ DefPathData::Binding(..) |
199             data @ DefPathData::ImplTrait |
200             data @ DefPathData::Typeof |
201             data @ DefPathData::GlobalMetaData(..) => {
202                 let parent_def_id = self.parent_def_id(def_id).unwrap();
203                 self.push_item_path(buffer, parent_def_id);
204                 buffer.push(&data.as_interned_str());
205             }
206             DefPathData::StructCtor => { // present `X` instead of `X::{{constructor}}`
207                 let parent_def_id = self.parent_def_id(def_id).unwrap();
208                 self.push_item_path(buffer, parent_def_id);
209             }
210         }
211     }
212
213     fn push_impl_path<T>(self,
214                          buffer: &mut T,
215                          impl_def_id: DefId)
216         where T: ItemPathBuffer
217     {
218         let parent_def_id = self.parent_def_id(impl_def_id).unwrap();
219
220         // Always use types for non-local impls, where types are always
221         // available, and filename/line-number is mostly uninteresting.
222         let use_types = !self.is_default_impl(impl_def_id) && (!impl_def_id.is_local() || {
223             // Otherwise, use filename/line-number if forced.
224             let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
225             !force_no_types && {
226                 // Otherwise, use types if we can query them without inducing a cycle.
227                 ty::queries::impl_trait_ref::try_get(self, DUMMY_SP, impl_def_id).is_ok() &&
228                     ty::queries::type_of::try_get(self, DUMMY_SP, impl_def_id).is_ok()
229             }
230         });
231
232         if !use_types {
233             return self.push_impl_path_fallback(buffer, impl_def_id);
234         }
235
236         // Decide whether to print the parent path for the impl.
237         // Logically, since impls are global, it's never needed, but
238         // users may find it useful. Currently, we omit the parent if
239         // the impl is either in the same module as the self-type or
240         // as the trait.
241         let self_ty = self.type_of(impl_def_id);
242         let in_self_mod = match characteristic_def_id_of_type(self_ty) {
243             None => false,
244             Some(ty_def_id) => self.parent_def_id(ty_def_id) == Some(parent_def_id),
245         };
246
247         let impl_trait_ref = self.impl_trait_ref(impl_def_id);
248         let in_trait_mod = match impl_trait_ref {
249             None => false,
250             Some(trait_ref) => self.parent_def_id(trait_ref.def_id) == Some(parent_def_id),
251         };
252
253         if !in_self_mod && !in_trait_mod {
254             // If the impl is not co-located with either self-type or
255             // trait-type, then fallback to a format that identifies
256             // the module more clearly.
257             self.push_item_path(buffer, parent_def_id);
258             if let Some(trait_ref) = impl_trait_ref {
259                 buffer.push(&format!("<impl {} for {}>", trait_ref, self_ty));
260             } else {
261                 buffer.push(&format!("<impl {}>", self_ty));
262             }
263             return;
264         }
265
266         // Otherwise, try to give a good form that would be valid language
267         // syntax. Preferably using associated item notation.
268
269         if let Some(trait_ref) = impl_trait_ref {
270             // Trait impls.
271             buffer.push(&format!("<{} as {}>",
272                                  self_ty,
273                                  trait_ref));
274             return;
275         }
276
277         // Inherent impls. Try to print `Foo::bar` for an inherent
278         // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
279         // anything other than a simple path.
280         match self_ty.sty {
281             ty::TyAdt(adt_def, substs) => {
282                 if substs.types().next().is_none() { // ignore regions
283                     self.push_item_path(buffer, adt_def.did);
284                 } else {
285                     buffer.push(&format!("<{}>", self_ty));
286                 }
287             }
288
289             ty::TyBool |
290             ty::TyChar |
291             ty::TyInt(_) |
292             ty::TyUint(_) |
293             ty::TyFloat(_) |
294             ty::TyStr => {
295                 buffer.push(&format!("{}", self_ty));
296             }
297
298             _ => {
299                 buffer.push(&format!("<{}>", self_ty));
300             }
301         }
302     }
303
304     fn push_impl_path_fallback<T>(self,
305                                   buffer: &mut T,
306                                   impl_def_id: DefId)
307         where T: ItemPathBuffer
308     {
309         // If no type info is available, fall back to
310         // pretty printing some span information. This should
311         // only occur very early in the compiler pipeline.
312         let parent_def_id = self.parent_def_id(impl_def_id).unwrap();
313         self.push_item_path(buffer, parent_def_id);
314         let node_id = self.hir.as_local_node_id(impl_def_id).unwrap();
315         let item = self.hir.expect_item(node_id);
316         let span_str = self.sess.codemap().span_to_string(item.span);
317         buffer.push(&format!("<impl at {}>", span_str));
318     }
319
320     /// Returns the def-id of `def_id`'s parent in the def tree. If
321     /// this returns `None`, then `def_id` represents a crate root or
322     /// inlined root.
323     pub fn parent_def_id(self, def_id: DefId) -> Option<DefId> {
324         let key = self.def_key(def_id);
325         key.parent.map(|index| DefId { krate: def_id.krate, index: index })
326     }
327 }
328
329 /// As a heuristic, when we see an impl, if we see that the
330 /// 'self-type' is a type defined in the same module as the impl,
331 /// we can omit including the path to the impl itself. This
332 /// function tries to find a "characteristic def-id" for a
333 /// type. It's just a heuristic so it makes some questionable
334 /// decisions and we may want to adjust it later.
335 pub fn characteristic_def_id_of_type(ty: Ty) -> Option<DefId> {
336     match ty.sty {
337         ty::TyAdt(adt_def, _) => Some(adt_def.did),
338
339         ty::TyDynamic(data, ..) => data.principal().map(|p| p.def_id()),
340
341         ty::TyArray(subty, _) |
342         ty::TySlice(subty) => characteristic_def_id_of_type(subty),
343
344         ty::TyRawPtr(mt) |
345         ty::TyRef(_, mt) => characteristic_def_id_of_type(mt.ty),
346
347         ty::TyTuple(ref tys, _) => tys.iter()
348                                       .filter_map(|ty| characteristic_def_id_of_type(ty))
349                                       .next(),
350
351         ty::TyFnDef(def_id, _) |
352         ty::TyClosure(def_id, _) => Some(def_id),
353
354         ty::TyBool |
355         ty::TyChar |
356         ty::TyInt(_) |
357         ty::TyUint(_) |
358         ty::TyStr |
359         ty::TyFnPtr(_) |
360         ty::TyProjection(_) |
361         ty::TyParam(_) |
362         ty::TyAnon(..) |
363         ty::TyInfer(_) |
364         ty::TyError |
365         ty::TyNever |
366         ty::TyFloat(_) => None,
367     }
368 }
369
370 /// Unifying Trait for different kinds of item paths we might
371 /// construct. The basic interface is that components get pushed: the
372 /// instance can also customize how we handle the root of a crate.
373 pub trait ItemPathBuffer {
374     fn root_mode(&self) -> &RootMode;
375     fn push(&mut self, text: &str);
376 }
377
378 #[derive(Debug)]
379 pub enum RootMode {
380     /// Try to make a path relative to the local crate.  In
381     /// particular, local paths have no prefix, and if the path comes
382     /// from an extern crate, start with the path to the `extern
383     /// crate` declaration.
384     Local,
385
386     /// Always prepend the crate name to the path, forming an absolute
387     /// path from within a given set of crates.
388     Absolute,
389 }
390
391 #[derive(Debug)]
392 struct LocalPathBuffer {
393     root_mode: RootMode,
394     str: String,
395 }
396
397 impl LocalPathBuffer {
398     fn new(root_mode: RootMode) -> LocalPathBuffer {
399         LocalPathBuffer {
400             root_mode,
401             str: String::new(),
402         }
403     }
404
405     fn into_string(self) -> String {
406         self.str
407     }
408 }
409
410 impl ItemPathBuffer for LocalPathBuffer {
411     fn root_mode(&self) -> &RootMode {
412         &self.root_mode
413     }
414
415     fn push(&mut self, text: &str) {
416         if !self.str.is_empty() {
417             self.str.push_str("::");
418         }
419         self.str.push_str(text);
420     }
421 }