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