Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
4b3f82a
Add updated support for example-analyzer
willcrichton May 9, 2021
7831fee
Fix check issue
willcrichton May 30, 2021
2855bf0
Factor scraping and rendering into separate calls to rustdoc
willcrichton Jun 1, 2021
b6338e7
Generate example source files with corresponding links
willcrichton Jun 3, 2021
eea8f0a
Sort examples by size
willcrichton Aug 26, 2021
55bb517
Move highlighting logic from JS to Rust
willcrichton Aug 26, 2021
18edcf8
Reduce blur size, fix example width bug, add better error handling fo…
willcrichton Sep 14, 2021
a1cb194
Add styles for non-white themes
willcrichton Sep 14, 2021
829b1a9
Incorporate jyn's feedback
willcrichton Sep 17, 2021
5c05b3c
Add target crates as inputs to reduce size of intermediates
willcrichton Sep 20, 2021
df5e3a6
Change serialized format to use DefPathHash instead of custom String
willcrichton Sep 21, 2021
25323ec
Move JS into a standalone file
willcrichton Oct 1, 2021
55731bb
Fix lint error, change scrape-examples.js minify call
willcrichton Oct 1, 2021
ed8e12f
Unversioned -> InvocationSpecific
willcrichton Oct 1, 2021
5584c79
Update to latest rustc and rustdoc styles
willcrichton Oct 7, 2021
bb383ed
Move some expansion logic into generation-time, fix section header li…
willcrichton Oct 7, 2021
8b141a2
Add variance constraints for const params
voidc Oct 7, 2021
e22e858
Move more scrape-examples logic from JS to rust
willcrichton Oct 7, 2021
f10dcee
Change handling of spans in scrape examples, add test for highlight d…
willcrichton Oct 8, 2021
9e4958a
Add test for prev/back arrows + examples across multiple files
willcrichton Oct 9, 2021
b1616f3
Add test for ordering of examples, simplify with single scrape.mk file
willcrichton Oct 9, 2021
59b36bc
Add UI test for the variance of types appearing in consts
voidc Oct 12, 2021
a400f10
Bless tests
voidc Oct 12, 2021
24a71cb
Fix local crate not being scraped
willcrichton Oct 13, 2021
02e4d0b
Make all proc-macro back-compat lints deny-by-default
Aaron1011 Aug 15, 2021
a836676
Update the minimum external LLVM to 11
cuviper Oct 19, 2021
5a87d1a
llvm-dwp-11 fails on absolute paths
cuviper Oct 19, 2021
8f80d86
Small scrape-example fixes
willcrichton Oct 20, 2021
d1c29c6
Revert def_id addition from clean::Function, add test for
willcrichton Oct 22, 2021
fd5d614
Move def_id logic into render_call_locations
willcrichton Oct 22, 2021
e4aeeca
Reset qualifs when a storage of a local ends
tmiasko Oct 22, 2021
fd25491
Add caveat about changing parallelism and function call overhead
the8472 Oct 23, 2021
a7f2bc1
Rollup merge of #85833 - willcrichton:example-analyzer, r=jyn514
matthiaskrgr Oct 23, 2021
0c85cd4
Rollup merge of #88041 - Aaron1011:deny-proc-macro-hack, r=wesleywiser
matthiaskrgr Oct 23, 2021
809e5c8
Rollup merge of #89829 - voidc:assoc-const-variance, r=lcnr
matthiaskrgr Oct 23, 2021
684402e
Rollup merge of #90062 - cuviper:min-llvm-11, r=nikic
matthiaskrgr Oct 23, 2021
6584391
Rollup merge of #90168 - tmiasko:const-qualif-storage, r=matthewjasper
matthiaskrgr Oct 23, 2021
f99f296
Rollup merge of #90198 - the8472:available-parallelism-runtime, r=jos…
matthiaskrgr Oct 23, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Generate example source files with corresponding links
Add display name

Fix remaining merge conflicts

Only embed code for items containing examples
  • Loading branch information
willcrichton committed Oct 7, 2021
commit b6338e7792fab06e015cdf3a3d1c30ff9797673e
8 changes: 0 additions & 8 deletions src/librustdoc/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,12 +161,9 @@ crate struct Options {
/// Whether to skip capturing stdout and stderr of tests.
crate nocapture: bool,

// Options for scraping call sites from examples/ directory
/// Path to output file to write JSON of call sites. If this option is Some(..) then
/// the compiler will scrape examples and not generate documentation.
crate scrape_examples: Option<PathBuf>,
/// Path to the root of the workspace, used to generate workspace-relative file paths.
crate workspace_root: Option<PathBuf>,
}

impl fmt::Debug for Options {
Expand Down Expand Up @@ -290,7 +287,6 @@ crate struct RenderOptions {
/// If `true`, HTML source pages will generate links for items to their definition.
crate generate_link_to_definition: bool,
crate call_locations: Option<AllCallLocations>,
crate repository_url: Option<String>,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
Expand Down Expand Up @@ -682,9 +678,7 @@ impl Options {
return Err(1);
}

let repository_url = matches.opt_str("repository-url");
let scrape_examples = matches.opt_str("scrape-examples").map(PathBuf::from);
let workspace_root = matches.opt_str("workspace-root").map(PathBuf::from);
let with_examples = matches.opt_strs("with-examples");
let each_call_locations = with_examples
.into_iter()
Expand Down Expand Up @@ -777,13 +771,11 @@ impl Options {
emit,
generate_link_to_definition,
call_locations,
repository_url,
},
crate_name,
output_format,
json_unused_externs,
scrape_examples,
workspace_root,
})
}

Expand Down
1 change: 1 addition & 0 deletions src/librustdoc/html/render/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,7 @@ impl<'tcx> Context<'tcx> {
let hiline = span.hi(self.sess()).line;
let lines =
if loline == hiline { loline.to_string() } else { format!("{}-{}", loline, hiline) };

Some(format!(
"{root}src/{krate}/{path}#{lines}",
root = Escape(&root),
Expand Down
91 changes: 50 additions & 41 deletions src/librustdoc/html/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ use crate::html::format::{
};
use crate::html::markdown::{HeadingOffset, Markdown, MarkdownHtml, MarkdownSummaryLine};
use crate::html::sources;
use crate::scrape_examples::FnCallLocations;
use crate::scrape_examples::{CallData, FnCallLocations};

/// A pair of name and its optional document.
crate type NameDoc = (String, Option<String>);
Expand Down Expand Up @@ -2451,6 +2451,8 @@ fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
out
}

const MAX_FULL_EXAMPLES: usize = 5;

fn render_call_locations(
w: &mut Buffer,
cx: &Context<'_>,
Expand All @@ -2463,29 +2465,7 @@ fn render_call_locations(
}
};

let filtered_locations: Vec<_> = call_locations
.iter()
.filter_map(|(file, locs)| {
// FIXME(wcrichto): file I/O should be cached
let mut contents = match fs::read_to_string(&file) {
Ok(contents) => contents,
Err(e) => {
eprintln!("Failed to read file {}", e);
return None;
}
};

// Remove the utf-8 BOM if any
if contents.starts_with('\u{feff}') {
contents.drain(..3);
}

Some((file, contents, locs))
})
.collect();

let n_examples = filtered_locations.len();
if n_examples == 0 {
if call_locations.len() == 0 {
return;
}

Expand All @@ -2499,35 +2479,55 @@ fn render_call_locations(
id
);

let write_example = |w: &mut Buffer, (file, contents, locs): (&String, String, _)| {
let ex_title = match cx.shared.repository_url.as_ref() {
Some(url) => format!(
r#"<a href="{url}/{file}" target="_blank">{file}</a>"#,
file = file,
url = url
),
None => file.clone(),
};
let example_url = |call_data: &CallData| -> String {
format!(
r#"<a href="{root}{url}" target="_blank">{name}</a>"#,
root = cx.root_path(),
url = call_data.url,
name = call_data.display_name
)
};

let write_example = |w: &mut Buffer, (path, call_data): (&PathBuf, &CallData)| {
let mut contents =
fs::read_to_string(&path).expect(&format!("Failed to read file: {}", path.display()));

let min_loc =
call_data.locations.iter().min_by_key(|loc| loc.enclosing_item_span.0).unwrap();
let min_byte = min_loc.enclosing_item_span.0;
let min_line = min_loc.enclosing_item_lines.0;
let max_byte =
call_data.locations.iter().map(|loc| loc.enclosing_item_span.1).max().unwrap();
contents = contents[min_byte..max_byte].to_string();

let locations = call_data
.locations
.iter()
.map(|loc| (loc.call_span.0 - min_byte, loc.call_span.1 - min_byte))
.collect::<Vec<_>>();

let edition = cx.shared.edition();
write!(
w,
r#"<div class="scraped-example" data-code="{code}" data-locs="{locations}">
<strong>{title}</strong>
<div class="code-wrapper">"#,
<strong>{title}</strong>
<div class="code-wrapper">"#,
code = contents.replace("\"", "&quot;"),
locations = serde_json::to_string(&locs).unwrap(),
title = ex_title,
locations = serde_json::to_string(&locations).unwrap(),
title = example_url(call_data),
);
write!(w, r#"<span class="prev">&pr;</span> <span class="next">&sc;</span>"#);
write!(w, r#"<span class="expand">&varr;</span>"#);
sources::print_src(w, &contents, edition);
let file_span = rustc_span::DUMMY_SP;
let root_path = "".to_string();
sources::print_src(w, &contents, edition, file_span, cx, &root_path, Some(min_line));
write!(w, "</div></div>");
};

let mut it = filtered_locations.into_iter();
let mut it = call_locations.into_iter().peekable();
write_example(w, it.next().unwrap());

if n_examples > 1 {
if it.peek().is_some() {
write!(
w,
r#"<details class="rustdoc-toggle more-examples-toggle">
Expand All @@ -2536,7 +2536,16 @@ fn render_call_locations(
</summary>
<div class="more-scraped-examples">"#
);
it.for_each(|ex| write_example(w, ex));
(&mut it).take(MAX_FULL_EXAMPLES).for_each(|ex| write_example(w, ex));

if it.peek().is_some() {
write!(w, "Additional examples can be found in:<br /><ul>");
it.for_each(|(_, call_data)| {
write!(w, "<li>{}</li>", example_url(call_data));
});
write!(w, "</ul>");
}

write!(w, "</div></details>");
}

Expand Down
14 changes: 12 additions & 2 deletions src/librustdoc/html/sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,15 @@ impl SourceCollector<'_, 'tcx> {
&page,
"",
|buf: &mut _| {
print_src(buf, contents, self.cx.shared.edition(), file_span, &self.cx, &root_path)
print_src(
buf,
contents,
self.cx.shared.edition(),
file_span,
&self.cx,
&root_path,
None,
)
},
&self.cx.shared.style_files,
);
Expand Down Expand Up @@ -250,6 +258,7 @@ crate fn print_src(
file_span: rustc_span::Span,
context: &Context<'_>,
root_path: &str,
offset: Option<usize>,
) {
let lines = s.lines().count();
let mut line_numbers = Buffer::empty_from(buf);
Expand All @@ -260,8 +269,9 @@ crate fn print_src(
tmp /= 10;
}
line_numbers.write_str("<pre class=\"line-numbers\">");
let offset = offset.unwrap_or(0);
for i in 1..=lines {
writeln!(line_numbers, "<span id=\"{0}\">{0:1$}</span>", i, cols);
writeln!(line_numbers, "<span id=\"{0}\">{0:1$}</span>", i + offset, cols);
}
line_numbers.write_str("</pre>");
highlight::render_with_highlighting(
Expand Down
2 changes: 1 addition & 1 deletion src/librustdoc/html/static/css/rustdoc.css
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ nav.sub {
text-decoration: underline;
}

.rustdoc:not(.source) .example-wrap > pre:not(.line-number) {
.rustdoc:not(.source) .example-wrap > pre:not(.line-numbers) {
width: 100%;
overflow-x: auto;
}
Expand Down
18 changes: 10 additions & 8 deletions src/librustdoc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -620,8 +620,6 @@ fn opts() -> Vec<RustcOptGroup> {
)
}),
unstable("scrape-examples", |o| o.optopt("", "scrape-examples", "", "")),
unstable("workspace-root", |o| o.optopt("", "workspace-root", "", "")),
unstable("repository-url", |o| o.optopt("", "repository-url", "", "")),
unstable("with-examples", |o| o.optmulti("", "with-examples", "", "")),
]
}
Expand Down Expand Up @@ -705,17 +703,16 @@ fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
fn main_options(options: config::Options) -> MainResult {
let diag = core::new_handler(options.error_format, None, &options.debugging_opts);

match (options.should_test, options.markdown_input(), options.scrape_examples.is_some()) {
(_, _, true) => return scrape_examples::run(options),
(true, true, false) => return wrap_return(&diag, markdown::test(options)),
(true, false, false) => return doctest::run(options),
(false, true, false) => {
match (options.should_test, options.markdown_input()) {
(true, true) => return wrap_return(&diag, markdown::test(options)),
(true, false) => return doctest::run(options),
(false, true) => {
return wrap_return(
&diag,
markdown::render(&options.input, options.render_options, options.edition),
);
}
(false, false, false) => {}
(false, false) => {}
}

// need to move these items separately because we lose them by the time the closure is called,
Expand All @@ -737,6 +734,7 @@ fn main_options(options: config::Options) -> MainResult {
// FIXME: fix this clone (especially render_options)
let manual_passes = options.manual_passes.clone();
let render_options = options.render_options.clone();
let scrape_examples = options.scrape_examples.clone();
let config = core::create_config(options);

interface::create_compiler_and_run(config, |compiler| {
Expand Down Expand Up @@ -773,6 +771,10 @@ fn main_options(options: config::Options) -> MainResult {
});
info!("finished with rustc");

if let Some(example_path) = scrape_examples {
return scrape_examples::run(krate, render_opts, cache, tcx, example_path);
}

cache.crate_version = crate_version;

if show_coverage {
Expand Down
Loading