]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/debuginfo/mod.rs
Use Names in HIR Items
[rust.git] / src / librustc_trans / trans / debuginfo / mod.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 // See doc.rs for documentation.
12 mod doc;
13
14 use self::VariableAccess::*;
15 use self::VariableKind::*;
16
17 use self::utils::{DIB, span_start, assert_type_for_node_id, contains_nodebug_attribute,
18                   create_DIArray, is_node_local_to_unit};
19 use self::namespace::{namespace_for_item, NamespaceTreeNode};
20 use self::type_names::compute_debuginfo_type_name;
21 use self::metadata::{type_metadata, diverging_type_metadata};
22 use self::metadata::{file_metadata, scope_metadata, TypeMap, compile_unit_metadata};
23 use self::source_loc::InternalDebugLocation;
24
25 use llvm;
26 use llvm::{ModuleRef, ContextRef, ValueRef};
27 use llvm::debuginfo::{DIFile, DIType, DIScope, DIBuilderRef, DISubprogram, DIArray,
28                       DIDescriptor, FlagPrototyped};
29 use middle::def_id::DefId;
30 use middle::infer::normalize_associated_type;
31 use middle::subst::{self, Substs};
32 use rustc_front;
33 use rustc_front::hir;
34
35 use trans::common::{NodeIdAndSpan, CrateContext, FunctionContext, Block};
36 use trans;
37 use trans::{monomorphize, type_of};
38 use middle::ty::{self, Ty};
39 use session::config::{self, FullDebugInfo, LimitedDebugInfo, NoDebugInfo};
40 use util::nodemap::{NodeMap, FnvHashMap, FnvHashSet};
41 use rustc::front::map as hir_map;
42
43 use libc::c_uint;
44 use std::cell::{Cell, RefCell};
45 use std::ffi::CString;
46 use std::ptr;
47 use std::rc::Rc;
48
49 use syntax::codemap::{Span, Pos};
50 use syntax::{abi, ast, codemap};
51 use syntax::attr::IntType;
52 use syntax::parse::token::{self, special_idents};
53
54 pub mod gdb;
55 mod utils;
56 mod namespace;
57 mod type_names;
58 mod metadata;
59 mod create_scope_map;
60 mod source_loc;
61
62 pub use self::source_loc::set_source_location;
63 pub use self::source_loc::clear_source_location;
64 pub use self::source_loc::start_emitting_source_locations;
65 pub use self::source_loc::get_cleanup_debug_loc_for_ast_node;
66 pub use self::source_loc::with_source_location_override;
67 pub use self::metadata::create_match_binding_metadata;
68 pub use self::metadata::create_argument_metadata;
69 pub use self::metadata::create_captured_var_metadata;
70 pub use self::metadata::create_global_var_metadata;
71 pub use self::metadata::create_local_var_metadata;
72
73 #[allow(non_upper_case_globals)]
74 const DW_TAG_auto_variable: c_uint = 0x100;
75 #[allow(non_upper_case_globals)]
76 const DW_TAG_arg_variable: c_uint = 0x101;
77
78 /// A context object for maintaining all state needed by the debuginfo module.
79 pub struct CrateDebugContext<'tcx> {
80     llcontext: ContextRef,
81     builder: DIBuilderRef,
82     current_debug_location: Cell<InternalDebugLocation>,
83     created_files: RefCell<FnvHashMap<String, DIFile>>,
84     created_enum_disr_types: RefCell<FnvHashMap<(DefId, IntType), DIType>>,
85
86     type_map: RefCell<TypeMap<'tcx>>,
87     namespace_map: RefCell<FnvHashMap<Vec<ast::Name>, Rc<NamespaceTreeNode>>>,
88
89     // This collection is used to assert that composite types (structs, enums,
90     // ...) have their members only set once:
91     composite_types_completed: RefCell<FnvHashSet<DIType>>,
92 }
93
94 impl<'tcx> CrateDebugContext<'tcx> {
95     pub fn new(llmod: ModuleRef) -> CrateDebugContext<'tcx> {
96         debug!("CrateDebugContext::new");
97         let builder = unsafe { llvm::LLVMDIBuilderCreate(llmod) };
98         // DIBuilder inherits context from the module, so we'd better use the same one
99         let llcontext = unsafe { llvm::LLVMGetModuleContext(llmod) };
100         return CrateDebugContext {
101             llcontext: llcontext,
102             builder: builder,
103             current_debug_location: Cell::new(InternalDebugLocation::UnknownLocation),
104             created_files: RefCell::new(FnvHashMap()),
105             created_enum_disr_types: RefCell::new(FnvHashMap()),
106             type_map: RefCell::new(TypeMap::new()),
107             namespace_map: RefCell::new(FnvHashMap()),
108             composite_types_completed: RefCell::new(FnvHashSet()),
109         };
110     }
111 }
112
113 pub enum FunctionDebugContext {
114     RegularContext(Box<FunctionDebugContextData>),
115     DebugInfoDisabled,
116     FunctionWithoutDebugInfo,
117 }
118
119 impl FunctionDebugContext {
120     fn get_ref<'a>(&'a self,
121                    cx: &CrateContext,
122                    span: Span)
123                    -> &'a FunctionDebugContextData {
124         match *self {
125             FunctionDebugContext::RegularContext(box ref data) => data,
126             FunctionDebugContext::DebugInfoDisabled => {
127                 cx.sess().span_bug(span,
128                                    FunctionDebugContext::debuginfo_disabled_message());
129             }
130             FunctionDebugContext::FunctionWithoutDebugInfo => {
131                 cx.sess().span_bug(span,
132                                    FunctionDebugContext::should_be_ignored_message());
133             }
134         }
135     }
136
137     fn debuginfo_disabled_message() -> &'static str {
138         "debuginfo: Error trying to access FunctionDebugContext although debug info is disabled!"
139     }
140
141     fn should_be_ignored_message() -> &'static str {
142         "debuginfo: Error trying to access FunctionDebugContext for function that should be \
143          ignored by debug info!"
144     }
145 }
146
147 struct FunctionDebugContextData {
148     scope_map: RefCell<NodeMap<DIScope>>,
149     fn_metadata: DISubprogram,
150     argument_counter: Cell<usize>,
151     source_locations_enabled: Cell<bool>,
152     source_location_override: Cell<bool>,
153 }
154
155 pub enum VariableAccess<'a> {
156     // The llptr given is an alloca containing the variable's value
157     DirectVariable { alloca: ValueRef },
158     // The llptr given is an alloca containing the start of some pointer chain
159     // leading to the variable's content.
160     IndirectVariable { alloca: ValueRef, address_operations: &'a [i64] }
161 }
162
163 pub enum VariableKind {
164     ArgumentVariable(usize /*index*/),
165     LocalVariable,
166     CapturedVariable,
167 }
168
169 /// Create any deferred debug metadata nodes
170 pub fn finalize(cx: &CrateContext) {
171     if cx.dbg_cx().is_none() {
172         return;
173     }
174
175     debug!("finalize");
176     let _ = compile_unit_metadata(cx);
177
178     if gdb::needs_gdb_debug_scripts_section(cx) {
179         // Add a .debug_gdb_scripts section to this compile-unit. This will
180         // cause GDB to try and load the gdb_load_rust_pretty_printers.py file,
181         // which activates the Rust pretty printers for binary this section is
182         // contained in.
183         gdb::get_or_insert_gdb_debug_scripts_section_global(cx);
184     }
185
186     unsafe {
187         llvm::LLVMDIBuilderFinalize(DIB(cx));
188         llvm::LLVMDIBuilderDispose(DIB(cx));
189         // Debuginfo generation in LLVM by default uses a higher
190         // version of dwarf than OS X currently understands. We can
191         // instruct LLVM to emit an older version of dwarf, however,
192         // for OS X to understand. For more info see #11352
193         // This can be overridden using --llvm-opts -dwarf-version,N.
194         // Android has the same issue (#22398)
195         if cx.sess().target.target.options.is_like_osx ||
196            cx.sess().target.target.options.is_like_android {
197             llvm::LLVMRustAddModuleFlag(cx.llmod(),
198                                         "Dwarf Version\0".as_ptr() as *const _,
199                                         2)
200         }
201
202         // Prevent bitcode readers from deleting the debug info.
203         let ptr = "Debug Info Version\0".as_ptr();
204         llvm::LLVMRustAddModuleFlag(cx.llmod(), ptr as *const _,
205                                     llvm::LLVMRustDebugMetadataVersion());
206     };
207 }
208
209 /// Creates the function-specific debug context.
210 ///
211 /// Returns the FunctionDebugContext for the function which holds state needed
212 /// for debug info creation. The function may also return another variant of the
213 /// FunctionDebugContext enum which indicates why no debuginfo should be created
214 /// for the function.
215 pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
216                                                fn_ast_id: ast::NodeId,
217                                                param_substs: &Substs<'tcx>,
218                                                llfn: ValueRef) -> FunctionDebugContext {
219     if cx.sess().opts.debuginfo == NoDebugInfo {
220         return FunctionDebugContext::DebugInfoDisabled;
221     }
222
223     // Clear the debug location so we don't assign them in the function prelude.
224     // Do this here already, in case we do an early exit from this function.
225     source_loc::set_debug_location(cx, InternalDebugLocation::UnknownLocation);
226
227     if fn_ast_id == ast::DUMMY_NODE_ID {
228         // This is a function not linked to any source location, so don't
229         // generate debuginfo for it.
230         return FunctionDebugContext::FunctionWithoutDebugInfo;
231     }
232
233     let empty_generics = rustc_front::util::empty_generics();
234
235     let fnitem = cx.tcx().map.get(fn_ast_id);
236
237     let (name, fn_decl, generics, top_level_block, span, has_path) = match fnitem {
238         hir_map::NodeItem(ref item) => {
239             if contains_nodebug_attribute(&item.attrs) {
240                 return FunctionDebugContext::FunctionWithoutDebugInfo;
241             }
242
243             match item.node {
244                 hir::ItemFn(ref fn_decl, _, _, _, ref generics, ref top_level_block) => {
245                     (item.name, fn_decl, generics, top_level_block, item.span, true)
246                 }
247                 _ => {
248                     cx.sess().span_bug(item.span,
249                         "create_function_debug_context: item bound to non-function");
250                 }
251             }
252         }
253         hir_map::NodeImplItem(impl_item) => {
254             match impl_item.node {
255                 hir::MethodImplItem(ref sig, ref body) => {
256                     if contains_nodebug_attribute(&impl_item.attrs) {
257                         return FunctionDebugContext::FunctionWithoutDebugInfo;
258                     }
259
260                     (impl_item.name,
261                      &sig.decl,
262                      &sig.generics,
263                      body,
264                      impl_item.span,
265                      true)
266                 }
267                 _ => {
268                     cx.sess().span_bug(impl_item.span,
269                                        "create_function_debug_context() \
270                                         called on non-method impl item?!")
271                 }
272             }
273         }
274         hir_map::NodeExpr(ref expr) => {
275             match expr.node {
276                 hir::ExprClosure(_, ref fn_decl, ref top_level_block) => {
277                     let name = format!("fn{}", token::gensym("fn"));
278                     let name = token::intern(&name[..]);
279                     (name, fn_decl,
280                         // This is not quite right. It should actually inherit
281                         // the generics of the enclosing function.
282                         &empty_generics,
283                         top_level_block,
284                         expr.span,
285                         // Don't try to lookup the item path:
286                         false)
287                 }
288                 _ => cx.sess().span_bug(expr.span,
289                         "create_function_debug_context: expected an expr_fn_block here")
290             }
291         }
292         hir_map::NodeTraitItem(trait_item) => {
293             match trait_item.node {
294                 hir::MethodTraitItem(ref sig, Some(ref body)) => {
295                     if contains_nodebug_attribute(&trait_item.attrs) {
296                         return FunctionDebugContext::FunctionWithoutDebugInfo;
297                     }
298
299                     (trait_item.name,
300                      &sig.decl,
301                      &sig.generics,
302                      body,
303                      trait_item.span,
304                      true)
305                 }
306                 _ => {
307                     cx.sess()
308                       .bug(&format!("create_function_debug_context: \
309                                     unexpected sort of node: {:?}",
310                                     fnitem))
311                 }
312             }
313         }
314         hir_map::NodeForeignItem(..) |
315         hir_map::NodeVariant(..) |
316         hir_map::NodeStructCtor(..) => {
317             return FunctionDebugContext::FunctionWithoutDebugInfo;
318         }
319         _ => cx.sess().bug(&format!("create_function_debug_context: \
320                                     unexpected sort of node: {:?}",
321                                    fnitem))
322     };
323
324     // This can be the case for functions inlined from another crate
325     if span == codemap::DUMMY_SP {
326         return FunctionDebugContext::FunctionWithoutDebugInfo;
327     }
328
329     let loc = span_start(cx, span);
330     let file_metadata = file_metadata(cx, &loc.file.name);
331
332     let function_type_metadata = unsafe {
333         let fn_signature = get_function_signature(cx,
334                                                   fn_ast_id,
335                                                   param_substs,
336                                                   span);
337         llvm::LLVMDIBuilderCreateSubroutineType(DIB(cx), file_metadata, fn_signature)
338     };
339
340     // Get_template_parameters() will append a `<...>` clause to the function
341     // name if necessary.
342     let mut function_name = name.to_string();
343     let template_parameters = get_template_parameters(cx,
344                                                       generics,
345                                                       param_substs,
346                                                       file_metadata,
347                                                       &mut function_name);
348
349     // There is no hir_map::Path for hir::ExprClosure-type functions. For now,
350     // just don't put them into a namespace. In the future this could be improved
351     // somehow (storing a path in the hir_map, or construct a path using the
352     // enclosing function).
353     let (linkage_name, containing_scope) = if has_path {
354         let namespace_node = namespace_for_item(cx, DefId::local(fn_ast_id));
355         let linkage_name = namespace_node.mangled_name_of_contained_item(
356             &function_name[..]);
357         let containing_scope = namespace_node.scope;
358         (linkage_name, containing_scope)
359     } else {
360         (function_name.clone(), file_metadata)
361     };
362
363     // Clang sets this parameter to the opening brace of the function's block,
364     // so let's do this too.
365     let scope_line = span_start(cx, top_level_block.span).line;
366
367     let is_local_to_unit = is_node_local_to_unit(cx, fn_ast_id);
368
369     let function_name = CString::new(function_name).unwrap();
370     let linkage_name = CString::new(linkage_name).unwrap();
371     let fn_metadata = unsafe {
372         llvm::LLVMDIBuilderCreateFunction(
373             DIB(cx),
374             containing_scope,
375             function_name.as_ptr(),
376             linkage_name.as_ptr(),
377             file_metadata,
378             loc.line as c_uint,
379             function_type_metadata,
380             is_local_to_unit,
381             true,
382             scope_line as c_uint,
383             FlagPrototyped as c_uint,
384             cx.sess().opts.optimize != config::No,
385             llfn,
386             template_parameters,
387             ptr::null_mut())
388     };
389
390     let scope_map = create_scope_map::create_scope_map(cx,
391                                                        &fn_decl.inputs,
392                                                        &*top_level_block,
393                                                        fn_metadata,
394                                                        fn_ast_id);
395
396     // Initialize fn debug context (including scope map and namespace map)
397     let fn_debug_context = box FunctionDebugContextData {
398         scope_map: RefCell::new(scope_map),
399         fn_metadata: fn_metadata,
400         argument_counter: Cell::new(1),
401         source_locations_enabled: Cell::new(false),
402         source_location_override: Cell::new(false),
403     };
404
405
406
407     return FunctionDebugContext::RegularContext(fn_debug_context);
408
409     fn get_function_signature<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
410                                         fn_ast_id: ast::NodeId,
411                                         param_substs: &Substs<'tcx>,
412                                         error_reporting_span: Span) -> DIArray {
413         if cx.sess().opts.debuginfo == LimitedDebugInfo {
414             return create_DIArray(DIB(cx), &[]);
415         }
416
417         // Return type -- llvm::DIBuilder wants this at index 0
418         assert_type_for_node_id(cx, fn_ast_id, error_reporting_span);
419         let fn_type = cx.tcx().node_id_to_type(fn_ast_id);
420
421         let (sig, abi) = match fn_type.sty {
422             ty::TyBareFn(_, ref barefnty) => {
423                 (cx.tcx().erase_late_bound_regions(&barefnty.sig), barefnty.abi)
424             }
425             ty::TyClosure(def_id, ref substs) => {
426                 let closure_type = cx.tcx().closure_type(def_id, substs);
427                 (cx.tcx().erase_late_bound_regions(&closure_type.sig), closure_type.abi)
428             }
429
430             _ => cx.sess().bug("get_function_metdata: Expected a function type!")
431         };
432         let sig = monomorphize::apply_param_substs(cx.tcx(), param_substs, &sig);
433
434         let mut signature = Vec::with_capacity(sig.inputs.len() + 1);
435
436         // Return type -- llvm::DIBuilder wants this at index 0
437         signature.push(match sig.output {
438             ty::FnConverging(ret_ty) => match ret_ty.sty {
439                 ty::TyTuple(ref tys) if tys.is_empty() => ptr::null_mut(),
440                 _ => type_metadata(cx, ret_ty, codemap::DUMMY_SP)
441             },
442             ty::FnDiverging => diverging_type_metadata(cx)
443         });
444
445         let inputs = &if abi == abi::RustCall {
446             type_of::untuple_arguments(cx, &sig.inputs)
447         } else {
448             sig.inputs
449         };
450
451         // Arguments types
452         for &argument_type in inputs {
453             signature.push(type_metadata(cx, argument_type, codemap::DUMMY_SP));
454         }
455
456         return create_DIArray(DIB(cx), &signature[..]);
457     }
458
459     fn get_template_parameters<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
460                                          generics: &hir::Generics,
461                                          param_substs: &Substs<'tcx>,
462                                          file_metadata: DIFile,
463                                          name_to_append_suffix_to: &mut String)
464                                          -> DIArray
465     {
466         let self_type = param_substs.self_ty();
467         let self_type = normalize_associated_type(cx.tcx(), &self_type);
468
469         // Only true for static default methods:
470         let has_self_type = self_type.is_some();
471
472         if !generics.is_type_parameterized() && !has_self_type {
473             return create_DIArray(DIB(cx), &[]);
474         }
475
476         name_to_append_suffix_to.push('<');
477
478         // The list to be filled with template parameters:
479         let mut template_params: Vec<DIDescriptor> =
480             Vec::with_capacity(generics.ty_params.len() + 1);
481
482         // Handle self type
483         if has_self_type {
484             let actual_self_type = self_type.unwrap();
485             // Add self type name to <...> clause of function name
486             let actual_self_type_name = compute_debuginfo_type_name(
487                 cx,
488                 actual_self_type,
489                 true);
490
491             name_to_append_suffix_to.push_str(&actual_self_type_name[..]);
492
493             if generics.is_type_parameterized() {
494                 name_to_append_suffix_to.push_str(",");
495             }
496
497             // Only create type information if full debuginfo is enabled
498             if cx.sess().opts.debuginfo == FullDebugInfo {
499                 let actual_self_type_metadata = type_metadata(cx,
500                                                               actual_self_type,
501                                                               codemap::DUMMY_SP);
502
503                 let name = special_idents::type_self.name.as_str();
504
505                 let name = CString::new(name.as_bytes()).unwrap();
506                 let param_metadata = unsafe {
507                     llvm::LLVMDIBuilderCreateTemplateTypeParameter(
508                         DIB(cx),
509                         ptr::null_mut(),
510                         name.as_ptr(),
511                         actual_self_type_metadata,
512                         file_metadata,
513                         0,
514                         0)
515                 };
516
517                 template_params.push(param_metadata);
518             }
519         }
520
521         // Handle other generic parameters
522         let actual_types = param_substs.types.get_slice(subst::FnSpace);
523         for (index, &hir::TyParam{ ident, .. }) in generics.ty_params.iter().enumerate() {
524             let actual_type = actual_types[index];
525             // Add actual type name to <...> clause of function name
526             let actual_type_name = compute_debuginfo_type_name(cx,
527                                                                actual_type,
528                                                                true);
529             name_to_append_suffix_to.push_str(&actual_type_name[..]);
530
531             if index != generics.ty_params.len() - 1 {
532                 name_to_append_suffix_to.push_str(",");
533             }
534
535             // Again, only create type information if full debuginfo is enabled
536             if cx.sess().opts.debuginfo == FullDebugInfo {
537                 let actual_type_metadata = type_metadata(cx, actual_type, codemap::DUMMY_SP);
538                 let name = CString::new(ident.name.as_str().as_bytes()).unwrap();
539                 let param_metadata = unsafe {
540                     llvm::LLVMDIBuilderCreateTemplateTypeParameter(
541                         DIB(cx),
542                         ptr::null_mut(),
543                         name.as_ptr(),
544                         actual_type_metadata,
545                         file_metadata,
546                         0,
547                         0)
548                 };
549                 template_params.push(param_metadata);
550             }
551         }
552
553         name_to_append_suffix_to.push('>');
554
555         return create_DIArray(DIB(cx), &template_params[..]);
556     }
557 }
558
559 fn declare_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
560                              variable_name: ast::Name,
561                              variable_type: Ty<'tcx>,
562                              scope_metadata: DIScope,
563                              variable_access: VariableAccess,
564                              variable_kind: VariableKind,
565                              span: Span) {
566     let cx: &CrateContext = bcx.ccx();
567
568     let filename = span_start(cx, span).file.name.clone();
569     let file_metadata = file_metadata(cx, &filename[..]);
570
571     let loc = span_start(cx, span);
572     let type_metadata = type_metadata(cx, variable_type, span);
573
574     let (argument_index, dwarf_tag) = match variable_kind {
575         ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
576         LocalVariable    |
577         CapturedVariable => (0, DW_TAG_auto_variable)
578     };
579
580     let name = CString::new(variable_name.as_str().as_bytes()).unwrap();
581     match (variable_access, &[][..]) {
582         (DirectVariable { alloca }, address_operations) |
583         (IndirectVariable {alloca, address_operations}, _) => {
584             let metadata = unsafe {
585                 llvm::LLVMDIBuilderCreateVariable(
586                     DIB(cx),
587                     dwarf_tag,
588                     scope_metadata,
589                     name.as_ptr(),
590                     file_metadata,
591                     loc.line as c_uint,
592                     type_metadata,
593                     cx.sess().opts.optimize != config::No,
594                     0,
595                     address_operations.as_ptr(),
596                     address_operations.len() as c_uint,
597                     argument_index)
598             };
599             source_loc::set_debug_location(cx, InternalDebugLocation::new(scope_metadata,
600                                                                           loc.line,
601                                                                           loc.col.to_usize()));
602             unsafe {
603                 let debug_loc = llvm::LLVMGetCurrentDebugLocation(cx.raw_builder());
604                 let instr = llvm::LLVMDIBuilderInsertDeclareAtEnd(
605                     DIB(cx),
606                     alloca,
607                     metadata,
608                     address_operations.as_ptr(),
609                     address_operations.len() as c_uint,
610                     debug_loc,
611                     bcx.llbb);
612
613                 llvm::LLVMSetInstDebugLocation(trans::build::B(bcx).llbuilder, instr);
614             }
615         }
616     }
617
618     match variable_kind {
619         ArgumentVariable(_) | CapturedVariable => {
620             assert!(!bcx.fcx
621                         .debug_context
622                         .get_ref(cx, span)
623                         .source_locations_enabled
624                         .get());
625             source_loc::set_debug_location(cx, InternalDebugLocation::UnknownLocation);
626         }
627         _ => { /* nothing to do */ }
628     }
629 }
630
631 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
632 pub enum DebugLoc {
633     At(ast::NodeId, Span),
634     None
635 }
636
637 impl DebugLoc {
638     pub fn apply(&self, fcx: &FunctionContext) {
639         match *self {
640             DebugLoc::At(node_id, span) => {
641                 source_loc::set_source_location(fcx, node_id, span);
642             }
643             DebugLoc::None => {
644                 source_loc::clear_source_location(fcx);
645             }
646         }
647     }
648 }
649
650 pub trait ToDebugLoc {
651     fn debug_loc(&self) -> DebugLoc;
652 }
653
654 impl ToDebugLoc for hir::Expr {
655     fn debug_loc(&self) -> DebugLoc {
656         DebugLoc::At(self.id, self.span)
657     }
658 }
659
660 impl ToDebugLoc for NodeIdAndSpan {
661     fn debug_loc(&self) -> DebugLoc {
662         DebugLoc::At(self.id, self.span)
663     }
664 }
665
666 impl ToDebugLoc for Option<NodeIdAndSpan> {
667     fn debug_loc(&self) -> DebugLoc {
668         match *self {
669             Some(NodeIdAndSpan { id, span }) => DebugLoc::At(id, span),
670             None => DebugLoc::None
671         }
672     }
673 }