1 // Copyright 2012-2014 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.
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.
11 use rustc::session::Session;
20 use syntax::parse::lexer::{self, StringReader};
21 use syntax::parse::token::{self, Token};
22 use syntax::symbol::keywords;
23 use syntax::tokenstream::TokenTree;
27 pub struct SpanUtils<'a> {
28 pub sess: &'a Session,
29 // FIXME given that we clone SpanUtils all over the place, this err_count is
30 // probably useless and any logic relying on it is bogus.
31 pub err_count: Cell<isize>,
34 impl<'a> SpanUtils<'a> {
35 pub fn new(sess: &'a Session) -> SpanUtils<'a> {
38 err_count: Cell::new(0),
42 pub fn make_path_string(file_name: &str) -> String {
43 let path = Path::new(file_name);
44 if path.is_absolute() {
45 path.clone().display().to_string()
47 env::current_dir().unwrap().join(&path).display().to_string()
51 pub fn snippet(&self, span: Span) -> String {
52 match self.sess.codemap().span_to_snippet(span) {
54 Err(_) => String::new(),
58 pub fn retokenise_span(&self, span: Span) -> StringReader<'a> {
59 lexer::StringReader::retokenize(&self.sess.parse_sess, span)
62 // Re-parses a path and returns the span for the last identifier in the path
63 pub fn span_for_last_ident(&self, span: Span) -> Option<Span> {
64 let mut result = None;
66 let mut toks = self.retokenise_span(span);
67 let mut bracket_count = 0;
69 let ts = toks.real_token();
70 if ts.tok == token::Eof {
73 if bracket_count == 0 && (ts.tok.is_ident() || ts.tok.is_keyword(keywords::SelfValue)) {
77 bracket_count += match ts.tok {
80 token::BinOp(token::Shr) => -2,
86 // Return the span for the first identifier in the path.
87 pub fn span_for_first_ident(&self, span: Span) -> Option<Span> {
88 let mut toks = self.retokenise_span(span);
89 let mut bracket_count = 0;
91 let ts = toks.real_token();
92 if ts.tok == token::Eof {
95 if bracket_count == 0 && (ts.tok.is_ident() || ts.tok.is_keyword(keywords::SelfValue)) {
99 bracket_count += match ts.tok {
102 token::BinOp(token::Shr) => -2,
108 // Return the span for the last ident before a `(` or `<` or '::<' and outside any
109 // any brackets, or the last span.
110 pub fn sub_span_for_meth_name(&self, span: Span) -> Option<Span> {
111 let mut toks = self.retokenise_span(span);
112 let mut prev = toks.real_token();
113 let mut result = None;
114 let mut bracket_count = 0;
115 let mut prev_span = None;
116 while prev.tok != token::Eof {
118 let mut next = toks.real_token();
120 if (next.tok == token::OpenDelim(token::Paren) || next.tok == token::Lt) &&
121 bracket_count == 0 && prev.tok.is_ident() {
122 result = Some(prev.sp);
125 if bracket_count == 0 && next.tok == token::ModSep {
128 next = toks.real_token();
129 if next.tok == token::Lt && old.tok.is_ident() {
130 result = Some(old.sp);
134 bracket_count += match prev.tok {
135 token::OpenDelim(token::Paren) | token::Lt => 1,
136 token::CloseDelim(token::Paren) | token::Gt => -1,
137 token::BinOp(token::Shr) => -2,
141 if prev.tok.is_ident() && bracket_count == 0 {
142 prev_span = Some(prev.sp);
149 // Return the span for the last ident before a `<` and outside any
150 // angle brackets, or the last span.
151 pub fn sub_span_for_type_name(&self, span: Span) -> Option<Span> {
152 let mut toks = self.retokenise_span(span);
153 let mut prev = toks.real_token();
154 let mut result = None;
156 // We keep track of the following two counts - the depth of nesting of
157 // angle brackets, and the depth of nesting of square brackets. For the
158 // angle bracket count, we only count tokens which occur outside of any
159 // square brackets (i.e. bracket_count == 0). The intutition here is
160 // that we want to count angle brackets in the type, but not any which
161 // could be in expression context (because these could mean 'less than',
163 let mut angle_count = 0;
164 let mut bracket_count = 0;
166 let next = toks.real_token();
168 if (next.tok == token::Lt || next.tok == token::Colon) &&
170 bracket_count == 0 &&
171 prev.tok.is_ident() {
172 result = Some(prev.sp);
175 if bracket_count == 0 {
176 angle_count += match prev.tok {
179 token::BinOp(token::Shl) => 2,
180 token::BinOp(token::Shr) => -2,
185 bracket_count += match prev.tok {
186 token::OpenDelim(token::Bracket) => 1,
187 token::CloseDelim(token::Bracket) => -1,
191 if next.tok == token::Eof {
196 if angle_count != 0 || bracket_count != 0 {
197 let loc = self.sess.codemap().lookup_char_pos(span.lo);
199 "Mis-counted brackets when breaking path? Parsing '{}' \
205 if result.is_none() && prev.tok.is_ident() && angle_count == 0 {
206 return Some(prev.sp);
211 // Reparse span and return an owned vector of sub spans of the first limit
212 // identifier tokens in the given nesting level.
213 // example with Foo<Bar<T,V>, Bar<T,V>>
214 // Nesting = 0: all idents outside of angle brackets: [Foo]
215 // Nesting = 1: idents within one level of angle brackets: [Bar, Bar]
216 pub fn spans_with_brackets(&self, span: Span, nesting: isize, limit: isize) -> Vec<Span> {
217 let mut result: Vec<Span> = vec![];
219 let mut toks = self.retokenise_span(span);
220 // We keep track of how many brackets we're nested in
221 let mut angle_count: isize = 0;
222 let mut bracket_count: isize = 0;
223 let mut found_ufcs_sep = false;
225 let ts = toks.real_token();
226 if ts.tok == token::Eof {
227 if angle_count != 0 || bracket_count != 0 {
228 if generated_code(span) {
231 let loc = self.sess.codemap().lookup_char_pos(span.lo);
233 "Mis-counted brackets when breaking path? \
234 Parsing '{}' in {}, line {}",
241 if (result.len() as isize) == limit {
244 bracket_count += match ts.tok {
245 token::OpenDelim(token::Bracket) => 1,
246 token::CloseDelim(token::Bracket) => -1,
249 if bracket_count > 0 {
252 angle_count += match ts.tok {
255 token::BinOp(token::Shl) => 2,
256 token::BinOp(token::Shr) => -2,
260 // Ignore the `>::` in `<Type as Trait>::AssocTy`.
262 // The root cause of this hack is that the AST representation of
263 // qpaths is horrible. It treats <A as B>::C as a path with two
264 // segments, B and C and notes that there is also a self type A at
265 // position 0. Because we don't have spans for individual idents,
266 // only the whole path, we have to iterate over the tokens in the
267 // path, trying to pull out the non-nested idents (e.g., avoiding 'a
268 // in `<A as B<'a>>::C`). So we end up with a span for `B>::C` from
269 // the start of the first ident to the end of the path.
270 if !found_ufcs_sep && angle_count == -1 {
271 found_ufcs_sep = true;
274 if ts.tok.is_ident() && angle_count == nesting {
280 /// `span` must be the span for an item such as a function or struct. This
281 /// function returns the program text from the start of the span until the
282 /// end of the 'signature' part, that is up to, but not including an opening
283 /// brace or semicolon.
284 pub fn signature_string_for_span(&self, span: Span) -> String {
285 let mut toks = self.retokenise_span(span);
287 let mut toks = toks.parse_all_token_trees().unwrap().trees();
288 let mut prev = toks.next().unwrap();
290 let first_span = prev.span();
291 let mut angle_count = 0;
293 if let TokenTree::Token(_, ref tok) = prev {
294 angle_count += match *tok {
295 token::Eof => { break; }
298 token::BinOp(token::Shl) => 2,
299 token::BinOp(token::Shr) => -2,
307 if let TokenTree::Token(_, token::Semi) = tok {
308 return self.snippet(first_span.to(prev.span()));
309 } else if let TokenTree::Delimited(_, ref d) = tok {
310 if d.delim == token::Brace {
311 return self.snippet(first_span.to(prev.span()));
319 pub fn sub_span_before_token(&self, span: Span, tok: Token) -> Option<Span> {
320 let mut toks = self.retokenise_span(span);
321 let mut prev = toks.real_token();
323 if prev.tok == token::Eof {
326 let next = toks.real_token();
328 return Some(prev.sp);
334 pub fn sub_span_of_token(&self, span: Span, tok: Token) -> Option<Span> {
335 let mut toks = self.retokenise_span(span);
337 let next = toks.real_token();
338 if next.tok == token::Eof {
342 return Some(next.sp);
347 pub fn sub_span_after_keyword(&self, span: Span, keyword: keywords::Keyword) -> Option<Span> {
348 self.sub_span_after(span, |t| t.is_keyword(keyword))
351 pub fn sub_span_after_token(&self, span: Span, tok: Token) -> Option<Span> {
352 self.sub_span_after(span, |t| t == tok)
355 fn sub_span_after<F: Fn(Token) -> bool>(&self, span: Span, f: F) -> Option<Span> {
356 let mut toks = self.retokenise_span(span);
358 let ts = toks.real_token();
359 if ts.tok == token::Eof {
363 let ts = toks.real_token();
364 if ts.tok == token::Eof {
374 // Returns a list of the spans of idents in a path.
375 // E.g., For foo::bar<x,t>::baz, we return [foo, bar, baz] (well, their spans)
376 pub fn spans_for_path_segments(&self, path: &ast::Path) -> Vec<Span> {
377 self.spans_with_brackets(path.span, 0, -1)
380 // Return an owned vector of the subspans of the param identifier
381 // tokens found in span.
382 pub fn spans_for_ty_params(&self, span: Span, number: isize) -> Vec<Span> {
383 // Type params are nested within one level of brackets:
384 // i.e. we want Vec<A, B> from Foo<A, B<T,U>>
385 self.spans_with_brackets(span, 1, number)
388 pub fn report_span_err(&self, kind: &str, span: Span) {
389 let loc = self.sess.codemap().lookup_char_pos(span.lo);
390 info!("({}) Could not find sub_span in `{}` in {}, line {}",
395 self.err_count.set(self.err_count.get() + 1);
396 if self.err_count.get() > 1000 {
397 bug!("span errors reached 1000, giving up");
401 // Return the name for a macro definition (identifier after first `!`)
402 pub fn span_for_macro_def_name(&self, span: Span) -> Option<Span> {
403 let mut toks = self.retokenise_span(span);
405 let ts = toks.real_token();
406 if ts.tok == token::Eof {
409 if ts.tok == token::Not {
410 let ts = toks.real_token();
411 if ts.tok.is_ident() {
420 // Return the name for a macro use (identifier before first `!`).
421 pub fn span_for_macro_use_name(&self, span:Span) -> Option<Span> {
422 let mut toks = self.retokenise_span(span);
423 let mut prev = toks.real_token();
425 if prev.tok == token::Eof {
428 let ts = toks.real_token();
429 if ts.tok == token::Not {
430 if prev.tok.is_ident() {
431 return Some(prev.sp);
440 /// Return true if the span is generated code, and
441 /// it is not a subspan of the root callsite.
443 /// Used to filter out spans of minimal value,
444 /// such as references to macro internal variables.
445 pub fn filter_generated(&self, sub_span: Option<Span>, parent: Span) -> bool {
446 if !generated_code(parent) {
447 if sub_span.is_none() {
448 // Edge case - this occurs on generated code with incorrect expansion info.
453 // If sub_span is none, filter out generated code.
454 if sub_span.is_none() {
458 //If the span comes from a fake filemap, filter it.
459 if !self.sess.codemap().lookup_char_pos(parent.lo).file.is_real_file() {
463 // Otherwise, a generated span is deemed invalid if it is not a sub-span of the root
464 // callsite. This filters out macro internal variables and most malformed spans.
465 !parent.source_callsite().contains(parent)
469 macro_rules! filter {
470 ($util: expr, $span: ident, $parent: expr, None) => {
471 if $util.filter_generated($span, $parent) {
475 ($util: expr, $span: ident, $parent: expr) => {
476 if $util.filter_generated($span, $parent) {