Skip to content

Commit 62fb7fc

Browse files
Switch logic to Span instead of HashMap
1 parent 409e8ba commit 62fb7fc

File tree

8 files changed

+54
-63
lines changed

8 files changed

+54
-63
lines changed

src/librustdoc/clean/mod.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -521,17 +521,22 @@ impl<'a, I: IntoIterator<Item=&'a ast::NestedMetaItem>> NestedAttributesExt for
521521
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug, Default)]
522522
pub struct Attributes {
523523
pub doc_strings: Vec<String>,
524-
pub other_attrs: Vec<ast::Attribute>
524+
pub other_attrs: Vec<ast::Attribute>,
525+
pub span: Option<syntax_pos::Span>,
525526
}
526527

527528
impl Attributes {
528529
pub fn from_ast(attrs: &[ast::Attribute]) -> Attributes {
529530
let mut doc_strings = vec![];
531+
let mut sp = None;
530532
let other_attrs = attrs.iter().filter_map(|attr| {
531533
attr.with_desugared_doc(|attr| {
532534
if let Some(value) = attr.value_str() {
533535
if attr.check_name("doc") {
534536
doc_strings.push(value.to_string());
537+
if sp.is_none() {
538+
sp = Some(attr.span);
539+
}
535540
return None;
536541
}
537542
}
@@ -541,7 +546,8 @@ impl Attributes {
541546
}).collect();
542547
Attributes {
543548
doc_strings: doc_strings,
544-
other_attrs: other_attrs
549+
other_attrs: other_attrs,
550+
span: sp,
545551
}
546552
}
547553

src/librustdoc/html/markdown.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -429,12 +429,12 @@ pub fn render(w: &mut fmt::Formatter,
429429
}
430430
}
431431

432-
pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {
432+
pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector, start_line: usize) {
433433
extern fn block(_ob: *mut hoedown_buffer,
434434
text: *const hoedown_buffer,
435435
lang: *const hoedown_buffer,
436436
data: *const hoedown_renderer_data,
437-
_: libc::size_t) {
437+
line: libc::size_t) {
438438
unsafe {
439439
if text.is_null() { return }
440440
let block_info = if lang.is_null() {
@@ -453,11 +453,12 @@ pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {
453453
stripped_filtered_line(l).unwrap_or(l)
454454
});
455455
let text = lines.collect::<Vec<&str>>().join("\n");
456+
let line = tests.get_line() + line;
456457
tests.add_test(text.to_owned(),
457458
block_info.should_panic, block_info.no_run,
458459
block_info.ignore, block_info.test_harness,
459460
block_info.compile_fail, block_info.error_codes,
460-
block_info.original);
461+
line);
461462
}
462463
}
463464

@@ -478,6 +479,7 @@ pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {
478479
}
479480
}
480481

482+
tests.set_line(start_line);
481483
unsafe {
482484
let ob = hoedown_buffer_new(DEF_OUNIT);
483485
let renderer = hoedown_html_renderer_new(0, 0);

src/librustdoc/markdown.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,8 +154,9 @@ pub fn test(input: &str, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
154154
let mut opts = TestOptions::default();
155155
opts.no_crate_inject = true;
156156
let mut collector = Collector::new(input.to_string(), cfgs, libs, externs,
157-
true, opts, maybe_sysroot, &input_str, "input".to_string());
158-
find_testable_code(&input_str, &mut collector);
157+
true, opts, maybe_sysroot, "input".to_string(),
158+
None);
159+
find_testable_code(&input_str, &mut collector, 0);
159160
test_args.insert(0, "rustdoctest".to_string());
160161
testing::test_main(&test_args, collector.tests);
161162
0

src/librustdoc/test.rs

Lines changed: 25 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,8 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11-
use std::collections::HashMap;
1211
use std::env;
1312
use std::ffi::OsString;
14-
use std::fs::File;
1513
use std::io::prelude::*;
1614
use std::io;
1715
use std::path::PathBuf;
@@ -39,6 +37,7 @@ use rustc_trans::back::link;
3937
use syntax::ast;
4038
use syntax::codemap::CodeMap;
4139
use syntax::feature_gate::UnstableFeatures;
40+
use syntax_pos::{BytePos, DUMMY_SP, Pos};
4241
use errors;
4342
use errors::emitter::ColorConfig;
4443

@@ -81,7 +80,7 @@ pub fn run(input: &str,
8180
let _ignore = dep_graph.in_ignore();
8281
let cstore = Rc::new(CStore::new(&dep_graph));
8382
let mut sess = session::build_session_(
84-
sessopts, &dep_graph, Some(input_path.clone()), handler, codemap, cstore.clone(),
83+
sessopts, &dep_graph, Some(input_path.clone()), handler, codemap.clone(), cstore.clone(),
8584
);
8685
rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
8786
sess.parse_sess.config =
@@ -99,23 +98,15 @@ pub fn run(input: &str,
9998
});
10099
let opts = scrape_test_config(hir_forest.krate());
101100
let filename = input_path.to_str().unwrap_or("").to_owned();
102-
let mut f = match File::open(input_path) {
103-
Ok(f) => f,
104-
_ => return 1,
105-
};
106-
let mut file_content = String::new();
107-
if let Err(_) = f.read_to_string(&mut file_content) {
108-
return 1;
109-
}
110101
let mut collector = Collector::new(crate_name,
111102
cfgs,
112103
libs,
113104
externs,
114105
false,
115106
opts,
116107
maybe_sysroot,
117-
&file_content,
118-
filename);
108+
filename,
109+
Some(codemap));
119110

120111
{
121112
let dep_graph = DepGraph::new(false);
@@ -399,27 +390,15 @@ pub struct Collector {
399390
cratename: String,
400391
opts: TestOptions,
401392
maybe_sysroot: Option<PathBuf>,
402-
code_blocks: HashMap<String, Vec<u32>>,
403393
filename: String,
394+
start_line: usize,
395+
codemap: Option<Rc<CodeMap>>,
404396
}
405397

406398
impl Collector {
407399
pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
408400
use_headers: bool, opts: TestOptions, maybe_sysroot: Option<PathBuf>,
409-
file_content: &str, filename: String) -> Collector {
410-
let mut line_number = 1;
411-
let mut block_lines = HashMap::new();
412-
for (pos, block) in file_content.split("```").enumerate() {
413-
if (pos & 1) != 0 {
414-
let key = format!("{}", block.replace("/// ", "").replace("//!", ""));
415-
if !block_lines.contains_key(&key) {
416-
block_lines.insert(key.clone(), Vec::new());
417-
}
418-
block_lines.get_mut(&key).unwrap().push(line_number);
419-
}
420-
line_number += block.lines().count() as u32 - 1;
421-
}
422-
401+
filename: String, codemap: Option<Rc<CodeMap>>) -> Collector {
423402
Collector {
424403
tests: Vec::new(),
425404
names: Vec::new(),
@@ -432,30 +411,17 @@ impl Collector {
432411
cratename: cratename,
433412
opts: opts,
434413
maybe_sysroot: maybe_sysroot,
435-
code_blocks: block_lines,
436414
filename: filename,
415+
start_line: 0,
416+
codemap: codemap,
437417
}
438418
}
439419

440-
fn get_line_from_key(&mut self, key: &String) -> u32 {
441-
let (line, need_removal) = if let Some(l) = self.code_blocks.get_mut(key) {
442-
let need_removal = l.len() > 1;
443-
(l.pop().unwrap_or(1), need_removal)
444-
} else {
445-
return 1;
446-
};
447-
if need_removal {
448-
self.code_blocks.remove(key);
449-
}
450-
line
451-
}
452-
453420
pub fn add_test(&mut self, test: String,
454421
should_panic: bool, no_run: bool, should_ignore: bool,
455422
as_test_harness: bool, compile_fail: bool, error_codes: Vec<String>,
456-
original: String) {
457-
let line_number = self.get_line_from_key(&format!("{}\n{}\n", original, test));
458-
let name = format!("{} - line {}", self.filename, line_number);
423+
line: usize) {
424+
let name = format!("{} - line {}", self.filename, line);
459425
self.cnt += 1;
460426
let cfgs = self.cfgs.clone();
461427
let libs = self.libs.clone();
@@ -499,6 +465,18 @@ impl Collector {
499465
});
500466
}
501467

468+
pub fn get_line(&self) -> usize {
469+
if let Some(ref codemap) = self.codemap{
470+
codemap.lookup_char_pos(BytePos(self.start_line as u32)).line - 1
471+
} else {
472+
self.start_line
473+
}
474+
}
475+
476+
pub fn set_line(&mut self, start_line: usize) {
477+
self.start_line = start_line;
478+
}
479+
502480
pub fn register_header(&mut self, name: &str, level: u32) {
503481
if self.use_headers && level == 1 {
504482
// we use these headings as test names, so it's good if
@@ -539,7 +517,8 @@ impl<'a, 'hir> HirCollector<'a, 'hir> {
539517
attrs.unindent_doc_comments();
540518
if let Some(doc) = attrs.doc_value() {
541519
self.collector.cnt = 0;
542-
markdown::find_testable_code(doc, self.collector);
520+
markdown::find_testable_code(doc, self.collector,
521+
attrs.span.unwrap_or(DUMMY_SP).lo.to_usize());
543522
}
544523

545524
nested(self);

src/libsyntax/attr.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -280,9 +280,9 @@ impl Attribute {
280280
Symbol::intern("doc"),
281281
Symbol::intern(&strip_doc_comment_decoration(&comment.as_str())));
282282
if self.style == ast::AttrStyle::Outer {
283-
f(&mk_attr_outer(self.id, meta))
283+
f(&mk_attr_outer(self.span, self.id, meta))
284284
} else {
285-
f(&mk_attr_inner(self.id, meta))
285+
f(&mk_attr_inner(self.span, self.id, meta))
286286
}
287287
} else {
288288
f(self)
@@ -339,8 +339,8 @@ pub fn mk_attr_id() -> AttrId {
339339
}
340340

341341
/// Returns an inner attribute with the given value.
342-
pub fn mk_attr_inner(id: AttrId, item: MetaItem) -> Attribute {
343-
mk_spanned_attr_inner(DUMMY_SP, id, item)
342+
pub fn mk_attr_inner(span: Span, id: AttrId, item: MetaItem) -> Attribute {
343+
mk_spanned_attr_inner(span, id, item)
344344
}
345345

346346
/// Returns an innter attribute with the given value and span.
@@ -356,8 +356,8 @@ pub fn mk_spanned_attr_inner(sp: Span, id: AttrId, item: MetaItem) -> Attribute
356356

357357

358358
/// Returns an outer attribute with the given value.
359-
pub fn mk_attr_outer(id: AttrId, item: MetaItem) -> Attribute {
360-
mk_spanned_attr_outer(DUMMY_SP, id, item)
359+
pub fn mk_attr_outer(span: Span, id: AttrId, item: MetaItem) -> Attribute {
360+
mk_spanned_attr_outer(span, id, item)
361361
}
362362

363363
/// Returns an outer attribute with the given value and span.

src/libsyntax/print/pprust.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ use print::pp::Breaks::{Consistent, Inconsistent};
2727
use ptr::P;
2828
use std_inject;
2929
use symbol::{Symbol, keywords};
30+
use syntax_pos::DUMMY_SP;
3031
use tokenstream::{self, TokenTree};
3132

3233
use rustc_i128::i128;
@@ -118,12 +119,12 @@ pub fn print_crate<'a>(cm: &'a CodeMap,
118119
// #![feature(prelude_import)]
119120
let prelude_import_meta = attr::mk_list_word_item(Symbol::intern("prelude_import"));
120121
let list = attr::mk_list_item(Symbol::intern("feature"), vec![prelude_import_meta]);
121-
let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), list);
122+
let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), list);
122123
s.print_attribute(&fake_attr)?;
123124

124125
// #![no_std]
125126
let no_std_meta = attr::mk_word_item(Symbol::intern("no_std"));
126-
let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), no_std_meta);
127+
let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), no_std_meta);
127128
s.print_attribute(&fake_attr)?;
128129
}
129130

src/libsyntax/std_inject.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,8 @@ pub fn maybe_inject_crates_ref(sess: &ParseSess,
5656
let crate_name = Symbol::intern(&alt_std_name.unwrap_or(name.to_string()));
5757

5858
krate.module.items.insert(0, P(ast::Item {
59-
attrs: vec![attr::mk_attr_outer(attr::mk_attr_id(),
59+
attrs: vec![attr::mk_attr_outer(DUMMY_SP,
60+
attr::mk_attr_id(),
6061
attr::mk_word_item(Symbol::intern("macro_use")))],
6162
vis: ast::Visibility::Inherited,
6263
node: ast::ItemKind::ExternCrate(Some(crate_name)),

src/libsyntax/test.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,8 @@ impl fold::Folder for EntryPointCleaner {
195195
let dead_code_str = Symbol::intern("dead_code");
196196
let word_vec = vec![attr::mk_list_word_item(dead_code_str)];
197197
let allow_dead_code_item = attr::mk_list_item(allow_str, word_vec);
198-
let allow_dead_code = attr::mk_attr_outer(attr::mk_attr_id(),
198+
let allow_dead_code = attr::mk_attr_outer(DUMMY_SP,
199+
attr::mk_attr_id(),
199200
allow_dead_code_item);
200201

201202
ast::Item {

0 commit comments

Comments
 (0)