深度理解之三:ctx.ctx.tcx.sess.source_map()

·

1 min read

You want to print the source code of the expression given its Span. The Span object defines a range in the source code, so you can retrieve the source code that it covers. The following will show you how to print the source code of the expression in addition to the existing information:

https://doc.rust-lang.org/stable/nightly-rustc/rustc_middle/dep_graph/trait.DepContext.html#tymethod.sess

Returns the source snippet as String corresponding to the given Span.

let span = arg.span;
let lo = ctx.ctx.tcx.sess.source_map().lookup_char_pos(span.lo());
let hi = ctx.ctx.tcx.sess.source_map().lookup_char_pos(span.hi());

// Extract the source code given the span.
let source_code = ctx.ctx.tcx.sess.source_map().span_to_snippet(span).unwrap_or("<source code extraction failed>".to_string());