Skip to content

Commit

Permalink
Auto merge of rust-lang#86545 - JohnTitor:rollup-7sqdhpa, r=JohnTitor
Browse files Browse the repository at this point in the history
Rollup of 6 pull requests

Successful merges:

 - rust-lang#86393 (Add regression test for issue rust-lang#52025)
 - rust-lang#86402 (rustdoc: add optional woff2 versions of Source Serif and Source Code)
 - rust-lang#86451 (Resolve intra-doc links in summary desc)
 - rust-lang#86501 (Cleanup handling of `crate_name` for doctests)
 - rust-lang#86517 (Fix `unused_unsafe` around `await`)
 - rust-lang#86537 (Mark some edition tests as check-pass)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
  • Loading branch information
bors committed Jun 22, 2021
2 parents 75ed342 + 00a7d5c commit 3487be1
Show file tree
Hide file tree
Showing 40 changed files with 279 additions and 100 deletions.
2 changes: 2 additions & 0 deletions compiler/rustc_middle/src/mir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,8 @@ impl<'tcx> Body<'tcx> {
#[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
pub enum Safety {
Safe,
/// Unsafe because of compiler-generated unsafe code, like `await` desugaring
BuiltinUnsafe,
/// Unsafe because of an unsafe fn
FnUnsafe,
/// Unsafe because of an `unsafe` block
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_middle/src/thir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ pub struct Adt<'tcx> {
#[derive(Copy, Clone, Debug, HashStable)]
pub enum BlockSafety {
Safe,
BuiltinUnsafe,
ExplicitUnsafe(hir::HirId),
}

Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_mir/src/transform/check_unsafety.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,7 @@ impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
}
false
}
Safety::BuiltinUnsafe => true,
Safety::ExplicitUnsafe(hir_id) => {
// mark unsafe block as used if there are any unsafe operations inside
if !violations.is_empty() {
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_mir_build/src/build/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
debug!("update_source_scope_for({:?}, {:?})", span, safety_mode);
let new_unsafety = match safety_mode {
BlockSafety::Safe => None,
BlockSafety::BuiltinUnsafe => Some(Safety::BuiltinUnsafe),
BlockSafety::ExplicitUnsafe(hir_id) => {
match self.in_scope_unsafe {
Safety::Safe => {}
Expand Down
33 changes: 20 additions & 13 deletions compiler/rustc_mir_build/src/check_unsafety.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,7 @@ struct UnsafetyVisitor<'a, 'tcx> {
}

impl<'tcx> UnsafetyVisitor<'_, 'tcx> {
fn in_safety_context<R>(
&mut self,
safety_context: SafetyContext,
f: impl FnOnce(&mut Self) -> R,
) {
fn in_safety_context(&mut self, safety_context: SafetyContext, f: impl FnOnce(&mut Self)) {
if let (
SafetyContext::UnsafeBlock { span: enclosing_span, .. },
SafetyContext::UnsafeBlock { span: block_span, hir_id, .. },
Expand Down Expand Up @@ -63,14 +59,14 @@ impl<'tcx> UnsafetyVisitor<'_, 'tcx> {
);
}
self.safety_context = prev_context;
return;
}
}

fn requires_unsafe(&mut self, span: Span, kind: UnsafeOpKind) {
let (description, note) = kind.description_and_note();
let unsafe_op_in_unsafe_fn_allowed = self.unsafe_op_in_unsafe_fn_allowed();
match self.safety_context {
SafetyContext::BuiltinUnsafeBlock => {}
SafetyContext::UnsafeBlock { ref mut used, .. } => {
if !self.body_unsafety.is_unsafe() || !unsafe_op_in_unsafe_fn_allowed {
// Mark this block as useful
Expand Down Expand Up @@ -142,13 +138,23 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
}

fn visit_block(&mut self, block: &Block) {
if let BlockSafety::ExplicitUnsafe(hir_id) = block.safety_mode {
self.in_safety_context(
SafetyContext::UnsafeBlock { span: block.span, hir_id, used: false },
|this| visit::walk_block(this, block),
);
} else {
visit::walk_block(self, block);
match block.safety_mode {
// compiler-generated unsafe code should not count towards the usefulness of
// an outer unsafe block
BlockSafety::BuiltinUnsafe => {
self.in_safety_context(SafetyContext::BuiltinUnsafeBlock, |this| {
visit::walk_block(this, block)
});
}
BlockSafety::ExplicitUnsafe(hir_id) => {
self.in_safety_context(
SafetyContext::UnsafeBlock { span: block.span, hir_id, used: false },
|this| visit::walk_block(this, block),
);
}
BlockSafety::Safe => {
visit::walk_block(self, block);
}
}
}

Expand Down Expand Up @@ -250,6 +256,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
#[derive(Clone, Copy)]
enum SafetyContext {
Safe,
BuiltinUnsafeBlock,
UnsafeFn,
UnsafeBlock { span: Span, hir_id: hir::HirId, used: bool },
}
Expand Down
7 changes: 6 additions & 1 deletion compiler/rustc_mir_build/src/thir/cx/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@ impl<'tcx> Cx<'tcx> {
expr: block.expr.map(|expr| self.mirror_expr(expr)),
safety_mode: match block.rules {
hir::BlockCheckMode::DefaultBlock => BlockSafety::Safe,
hir::BlockCheckMode::UnsafeBlock(..) => BlockSafety::ExplicitUnsafe(block.hir_id),
hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated) => {
BlockSafety::BuiltinUnsafe
}
hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) => {
BlockSafety::ExplicitUnsafe(block.hir_id)
}
},
}
}
Expand Down
27 changes: 27 additions & 0 deletions src/librustdoc/clean/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,33 @@ impl Item {
.collect()
}

/// Find a list of all link names, without finding their href.
///
/// This is used for generating summary text, which does not include
/// the link text, but does need to know which `[]`-bracketed names
/// are actually links.
crate fn link_names(&self, cache: &Cache) -> Vec<RenderedLink> {
cache
.intra_doc_links
.get(&self.def_id)
.map_or(&[][..], |v| v.as_slice())
.iter()
.filter_map(|ItemLink { link: s, link_text, did, fragment }| {
// FIXME(83083): using fragments as a side-channel for
// primitive names is very unfortunate
if did.is_some() || fragment.is_some() {
Some(RenderedLink {
original_text: s.clone(),
new_text: link_text.clone(),
href: String::new(),
})
} else {
None
}
})
.collect()
}

crate fn is_crate(&self) -> bool {
self.is_mod() && self.def_id.as_real().map_or(false, |did| did.index == CRATE_DEF_INDEX)
}
Expand Down
40 changes: 20 additions & 20 deletions src/librustdoc/doctest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::sync::Lrc;
use rustc_errors::{ColorConfig, ErrorReported};
use rustc_hir as hir;
use rustc_hir::def_id::LOCAL_CRATE;
use rustc_hir::intravisit;
use rustc_hir::{HirId, CRATE_HIR_ID};
use rustc_interface::interface;
Expand All @@ -13,6 +14,7 @@ use rustc_session::{lint, DiagnosticOutput, Session};
use rustc_span::edition::Edition;
use rustc_span::source_map::SourceMap;
use rustc_span::symbol::sym;
use rustc_span::Symbol;
use rustc_span::{BytePos, FileName, Pos, Span, DUMMY_SP};
use rustc_target::spec::TargetTriple;
use tempfile::Builder as TempFileBuilder;
Expand Down Expand Up @@ -111,8 +113,6 @@ crate fn run(options: Options) -> Result<(), ErrorReported> {
let res = interface::run_compiler(config, |compiler| {
compiler.enter(|queries| {
let _lower_to_hir = queries.lower_to_hir()?;

let crate_name = queries.crate_name()?.peek().to_string();
let mut global_ctxt = queries.global_ctxt()?.take();

let collector = global_ctxt.enter(|tcx| {
Expand All @@ -123,7 +123,7 @@ crate fn run(options: Options) -> Result<(), ErrorReported> {
opts.display_warnings |= options.display_warnings;
let enable_per_target_ignores = options.enable_per_target_ignores;
let mut collector = Collector::new(
crate_name,
tcx.crate_name(LOCAL_CRATE),
options,
false,
opts,
Expand Down Expand Up @@ -293,7 +293,7 @@ struct UnusedExterns {

fn run_test(
test: &str,
cratename: &str,
crate_name: &str,
line: usize,
options: Options,
should_panic: bool,
Expand All @@ -312,7 +312,7 @@ fn run_test(
report_unused_externs: impl Fn(UnusedExterns),
) -> Result<(), TestFailure> {
let (test, line_offset, supports_color) =
make_test(test, Some(cratename), as_test_harness, opts, edition, Some(test_id));
make_test(test, Some(crate_name), as_test_harness, opts, edition, Some(test_id));

let output_file = outdir.path().join("rust_out");

Expand Down Expand Up @@ -479,7 +479,7 @@ fn run_test(
/// lines before the test code begins as well as if the output stream supports colors or not.
crate fn make_test(
s: &str,
cratename: Option<&str>,
crate_name: Option<&str>,
dont_insert_main: bool,
opts: &TestOptions,
edition: Edition,
Expand Down Expand Up @@ -540,7 +540,7 @@ crate fn make_test(
let sess = ParseSess::with_span_handler(handler, sm);

let mut found_main = false;
let mut found_extern_crate = cratename.is_none();
let mut found_extern_crate = crate_name.is_none();
let mut found_macro = false;

let mut parser = match maybe_new_parser_from_source_str(&sess, filename, source) {
Expand All @@ -567,13 +567,13 @@ crate fn make_test(

if !found_extern_crate {
if let ast::ItemKind::ExternCrate(original) = item.kind {
// This code will never be reached if `cratename` is none because
// This code will never be reached if `crate_name` is none because
// `found_extern_crate` is initialized to `true` if it is none.
let cratename = cratename.unwrap();
let crate_name = crate_name.unwrap();

match original {
Some(name) => found_extern_crate = name.as_str() == cratename,
None => found_extern_crate = item.ident.as_str() == cratename,
Some(name) => found_extern_crate = name.as_str() == crate_name,
None => found_extern_crate = item.ident.as_str() == crate_name,
}
}
}
Expand Down Expand Up @@ -631,14 +631,14 @@ crate fn make_test(

// Don't inject `extern crate std` because it's already injected by the
// compiler.
if !already_has_extern_crate && !opts.no_crate_inject && cratename != Some("std") {
if let Some(cratename) = cratename {
if !already_has_extern_crate && !opts.no_crate_inject && crate_name != Some("std") {
if let Some(crate_name) = crate_name {
// Don't inject `extern crate` if the crate is never used.
// NOTE: this is terribly inaccurate because it doesn't actually
// parse the source, but only has false positives, not false
// negatives.
if s.contains(cratename) {
prog.push_str(&format!("extern crate r#{};\n", cratename));
if s.contains(crate_name) {
prog.push_str(&format!("extern crate r#{};\n", crate_name));
line_offset += 1;
}
}
Expand Down Expand Up @@ -797,7 +797,7 @@ crate struct Collector {
options: Options,
use_headers: bool,
enable_per_target_ignores: bool,
cratename: String,
crate_name: Symbol,
opts: TestOptions,
position: Span,
source_map: Option<Lrc<SourceMap>>,
Expand All @@ -809,7 +809,7 @@ crate struct Collector {

impl Collector {
crate fn new(
cratename: String,
crate_name: Symbol,
options: Options,
use_headers: bool,
opts: TestOptions,
Expand All @@ -823,7 +823,7 @@ impl Collector {
options,
use_headers,
enable_per_target_ignores,
cratename,
crate_name,
opts,
position: DUMMY_SP,
source_map,
Expand Down Expand Up @@ -871,7 +871,7 @@ impl Tester for Collector {
fn add_test(&mut self, test: String, config: LangString, line: usize) {
let filename = self.get_filename();
let name = self.generate_name(line, &filename);
let cratename = self.cratename.to_string();
let crate_name = self.crate_name.to_string();
let opts = self.opts.clone();
let edition = config.edition.unwrap_or(self.options.edition);
let options = self.options.clone();
Expand Down Expand Up @@ -954,7 +954,7 @@ impl Tester for Collector {
};
let res = run_test(
&test,
&cratename,
&crate_name,
line,
options,
config.should_panic,
Expand Down
7 changes: 4 additions & 3 deletions src/librustdoc/formats/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,13 +292,14 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> {
// which should not be indexed. The crate-item itself is
// inserted later on when serializing the search-index.
if item.def_id.index().map_or(false, |idx| idx != CRATE_DEF_INDEX) {
let desc = item.doc_value().map_or_else(String::new, |x| {
short_markdown_summary(&x.as_str(), &item.link_names(&self.cache))
});
self.cache.search_index.push(IndexItem {
ty: item.type_(),
name: s.to_string(),
path: path.join("::"),
desc: item
.doc_value()
.map_or_else(String::new, |x| short_markdown_summary(&x.as_str())),
desc,
parent,
parent_idx: None,
search_type: get_index_search_type(&item, &self.empty_cache, self.tcx),
Expand Down
25 changes: 21 additions & 4 deletions src/librustdoc/html/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1051,7 +1051,11 @@ impl MarkdownSummaryLine<'_> {
///
/// Returns a tuple of the rendered HTML string and whether the output was shortened
/// due to the provided `length_limit`.
fn markdown_summary_with_limit(md: &str, length_limit: usize) -> (String, bool) {
fn markdown_summary_with_limit(
md: &str,
link_names: &[RenderedLink],
length_limit: usize,
) -> (String, bool) {
if md.is_empty() {
return (String::new(), false);
}
Expand All @@ -1065,7 +1069,20 @@ fn markdown_summary_with_limit(md: &str, length_limit: usize) -> (String, bool)
*text_length += text.len();
}

'outer: for event in Parser::new_ext(md, summary_opts()) {
let mut replacer = |broken_link: BrokenLink<'_>| {
if let Some(link) =
link_names.iter().find(|link| &*link.original_text == broken_link.reference)
{
Some((link.href.as_str().into(), link.new_text.as_str().into()))
} else {
None
}
};

let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut replacer));
let p = LinkReplacer::new(p, link_names);

'outer: for event in p {
match &event {
Event::Text(text) => {
for word in text.split_inclusive(char::is_whitespace) {
Expand Down Expand Up @@ -1121,8 +1138,8 @@ fn markdown_summary_with_limit(md: &str, length_limit: usize) -> (String, bool)
/// Will shorten to 59 or 60 characters, including an ellipsis (…) if it was shortened.
///
/// See [`markdown_summary_with_limit`] for details about what is rendered and what is not.
crate fn short_markdown_summary(markdown: &str) -> String {
let (mut s, was_shortened) = markdown_summary_with_limit(markdown, 59);
crate fn short_markdown_summary(markdown: &str, link_names: &[RenderedLink]) -> String {
let (mut s, was_shortened) = markdown_summary_with_limit(markdown, link_names, 59);

if was_shortened {
s.push('…');
Expand Down
4 changes: 3 additions & 1 deletion src/librustdoc/html/markdown/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ fn test_header_ids_multiple_blocks() {
#[test]
fn test_short_markdown_summary() {
fn t(input: &str, expect: &str) {
let output = short_markdown_summary(input);
let output = short_markdown_summary(input, &[][..]);
assert_eq!(output, expect, "original: {}", input);
}

Expand All @@ -232,6 +232,7 @@ fn test_short_markdown_summary() {
t("Hard-break \nsummary", "Hard-break summary");
t("hello [Rust] :)\n\n[Rust]: https://www.rust-lang.org", "hello Rust :)");
t("hello [Rust](https://www.rust-lang.org \"Rust\") :)", "hello Rust :)");
t("dud [link]", "dud [link]");
t("code `let x = i32;` ...", "code <code>let x = i32;</code> …");
t("type `Type<'static>` ...", "type <code>Type<'static></code> …");
t("# top header", "top header");
Expand Down Expand Up @@ -259,6 +260,7 @@ fn test_plain_text_summary() {
t("Hard-break \nsummary", "Hard-break summary");
t("hello [Rust] :)\n\n[Rust]: https://www.rust-lang.org", "hello Rust :)");
t("hello [Rust](https://www.rust-lang.org \"Rust\") :)", "hello Rust :)");
t("dud [link]", "dud [link]");
t("code `let x = i32;` ...", "code `let x = i32;` …");
t("type `Type<'static>` ...", "type `Type<'static>` …");
t("# top header", "top header");
Expand Down
Loading

0 comments on commit 3487be1

Please sign in to comment.