diff options
| -rw-r--r-- | src/librustdoc/html/highlight.rs | 222 | ||||
| -rw-r--r-- | src/librustdoc/html/render/context.rs | 7 | ||||
| -rw-r--r-- | src/librustdoc/html/render/mod.rs | 2 | ||||
| -rw-r--r-- | src/librustdoc/html/render/span_map.rs | 114 | ||||
| -rw-r--r-- | src/librustdoc/html/static/css/rustdoc.css | 57 |
5 files changed, 339 insertions, 63 deletions
diff --git a/src/librustdoc/html/highlight.rs b/src/librustdoc/html/highlight.rs index 272180fb990..165b0c587b0 100644 --- a/src/librustdoc/html/highlight.rs +++ b/src/librustdoc/html/highlight.rs @@ -5,6 +5,7 @@ //! //! Use the `render_with_highlighting` to highlight some rust code. +use std::borrow::Cow; use std::collections::VecDeque; use std::fmt::{self, Display, Write}; @@ -17,7 +18,7 @@ use rustc_span::{BytePos, DUMMY_SP, Span}; use super::format::{self, write_str}; use crate::clean::PrimitiveType; use crate::html::escape::EscapeBodyText; -use crate::html::render::{Context, LinkFromSrc}; +use crate::html::render::{Context, ExpandedCode, LinkFromSrc}; /// This type is needed in case we want to render links on items to allow to go to their definition. pub(crate) struct HrefContext<'a, 'tcx> { @@ -163,7 +164,7 @@ struct TokenHandler<'a, 'tcx, F: Write> { current_class: Option<Class>, /// We need to keep the `Class` for each element because it could contain a `Span` which is /// used to generate links. - pending_elems: Vec<(&'a str, Option<Class>)>, + pending_elems: Vec<(Cow<'a, str>, Option<Class>)>, href_context: Option<HrefContext<'a, 'tcx>>, write_line_number: fn(&mut F, u32, &'static str), } @@ -271,6 +272,62 @@ fn empty_line_number(out: &mut impl Write, _: u32, extra: &'static str) { out.write_str(extra).unwrap(); } +fn get_expansion<'a, W: Write>( + token_handler: &mut TokenHandler<'_, '_, W>, + expanded_codes: Option<&'a Vec<ExpandedCode>>, + line: u32, +) -> Option<&'a ExpandedCode> { + if let Some(expanded_codes) = expanded_codes + && let Some(expanded_code) = expanded_codes.iter().find(|code| code.start_line == line) + { + let (closing, reopening) = if let Some(current_class) = token_handler.current_class + && let class = current_class.as_html() + && !class.is_empty() + { + ("</span>", format!("<span class=\"{class}\">")) + } else { + ("", String::new()) + }; + let id = format!("expand-{line}"); + token_handler.pending_elems.push(( + Cow::Owned(format!( + "{closing}\ +<span class=expansion>\ + <input id={id} type=checkbox>\ + <label for={id}>↕</label>{reopening}", + )), + Some(Class::Expansion), + )); + Some(expanded_code) + } else { + None + } +} + +fn start_expansion(out: &mut Vec<(Cow<'_, str>, Option<Class>)>, expanded_code: &ExpandedCode) { + out.push(( + Cow::Owned(format!( + "<span class=expanded>{}</span><span class=original>", + expanded_code.code, + )), + Some(Class::Expansion), + )); +} + +fn end_expansion<W: Write>(token_handler: &mut TokenHandler<'_, '_, W>, level: usize) { + if level == 0 { + token_handler.pending_elems.push((Cow::Borrowed("</span></span>"), Some(Class::Expansion))); + return; + } + let mut out = String::new(); + let mut end = String::new(); + for (tag, class) in token_handler.closing_tags.iter().skip(token_handler.closing_tags.len() - level) { + out.push_str(tag); + end.push_str(&format!("<span class=\"{}\">", class.as_html())); + } + token_handler.pending_elems.push((Cow::Owned(format!("</span></span>{out}{end}")), Some(Class::Expansion))); +} + #[derive(Clone, Copy)] pub(super) struct LineInfo { pub(super) start_line: u32, @@ -317,7 +374,7 @@ pub(super) fn write_code( closing_tags: Vec::new(), pending_exit_span: None, current_class: None, - pending_elems: Vec::new(), + pending_elems: Vec::with_capacity(20), href_context, write_line_number: match line_info { Some(line_info) => { @@ -338,12 +395,21 @@ pub(super) fn write_code( (0, u32::MAX) }; + let expanded_codes = token_handler + .href_context + .as_ref() + .and_then(|c| c.context.shared.expanded_codes.get(&c.file_span.lo())); + let mut current_expansion = + get_expansion(&mut token_handler, expanded_codes, line); + token_handler.write_pending_elems(None); + let mut level = 0; + Classifier::new( &src, token_handler.href_context.as_ref().map(|c| c.file_span).unwrap_or(DUMMY_SP), decoration_info, ) - .highlight(&mut |highlight| { + .highlight(&mut |span, highlight| { match highlight { Highlight::Token { text, class } => { // If we received a `ExitSpan` event and then have a non-compatible `Class`, we @@ -369,10 +435,32 @@ pub(super) fn write_code( if text == "\n" { line += 1; if line < max_lines { - token_handler.pending_elems.push((text, Some(Class::Backline(line)))); + token_handler + .pending_elems + .push((Cow::Borrowed(text), Some(Class::Backline(line)))); + } + if current_expansion.is_none() { + current_expansion = + get_expansion(&mut token_handler, expanded_codes, line); } } else { - token_handler.pending_elems.push((text, class)); + token_handler.pending_elems.push((Cow::Borrowed(text), class)); + + let mut need_end = false; + if let Some(ref current_expansion) = current_expansion { + if current_expansion.span.lo() == span.hi() { + start_expansion(&mut token_handler.pending_elems, current_expansion); + } else if current_expansion.end_line == line + && span.hi() >= current_expansion.span.hi() + { + need_end = true; + } + } + if need_end { + end_expansion(&mut token_handler, level); + current_expansion = None; + level = 0; + } } } Highlight::EnterSpan { class } => { @@ -392,6 +480,9 @@ pub(super) fn write_code( if should_add { let closing_tag = enter_span(token_handler.out, class, &token_handler.href_context); + if current_expansion.is_some() { + level += 1; + } token_handler.closing_tags.push((closing_tag, class)); } @@ -400,6 +491,9 @@ pub(super) fn write_code( } Highlight::ExitSpan => { token_handler.current_class = None; + if current_expansion.is_some() { + level -= 1; + } token_handler.pending_exit_span = Some( token_handler .closing_tags @@ -440,6 +534,8 @@ enum Class { QuestionMark, Decoration(&'static str), Backline(u32), + /// Macro expansion. + Expansion, } impl Class { @@ -489,6 +585,7 @@ impl Class { Class::QuestionMark => "question-mark", Class::Decoration(kind) => kind, Class::Backline(_) => "", + Class::Expansion => "", } } @@ -513,7 +610,8 @@ impl Class { | Self::Lifetime | Self::QuestionMark | Self::Decoration(_) - | Self::Backline(_) => None, + | Self::Backline(_) + | Self::Expansion => None, } } } @@ -628,6 +726,13 @@ impl Decorations { } } +/// Convenient wrapper to create a [`Span`] from a position in the file. +fn new_span(lo: u32, text: &str, file_span: Span) -> Span { + let hi = lo + text.len() as u32; + let file_lo = file_span.lo(); + file_span.with_lo(file_lo + BytePos(lo)).with_hi(file_lo + BytePos(hi)) +} + /// Processes program tokens, classifying strings of text by highlighting /// category (`Class`). struct Classifier<'src> { @@ -660,13 +765,6 @@ impl<'src> Classifier<'src> { } } - /// Convenient wrapper to create a [`Span`] from a position in the file. - fn new_span(&self, lo: u32, text: &str) -> Span { - let hi = lo + text.len() as u32; - let file_lo = self.file_span.lo(); - self.file_span.with_lo(file_lo + BytePos(lo)).with_hi(file_lo + BytePos(hi)) - } - /// Concatenate colons and idents as one when possible. fn get_full_ident_path(&mut self) -> Vec<(TokenKind, usize, usize)> { let start = self.byte_pos as usize; @@ -735,18 +833,18 @@ impl<'src> Classifier<'src> { /// The general structure for this method is to iterate over each token, /// possibly giving it an HTML span with a class specifying what flavor of /// token is used. - fn highlight(mut self, sink: &mut dyn FnMut(Highlight<'src>)) { + fn highlight(mut self, sink: &mut dyn FnMut(Span, Highlight<'src>)) { loop { if let Some(decs) = self.decorations.as_mut() { let byte_pos = self.byte_pos; let n_starts = decs.starts.iter().filter(|(i, _)| byte_pos >= *i).count(); for (_, kind) in decs.starts.drain(0..n_starts) { - sink(Highlight::EnterSpan { class: Class::Decoration(kind) }); + sink(DUMMY_SP, Highlight::EnterSpan { class: Class::Decoration(kind) }); } let n_ends = decs.ends.iter().filter(|i| byte_pos >= **i).count(); for _ in decs.ends.drain(0..n_ends) { - sink(Highlight::ExitSpan); + sink(DUMMY_SP, Highlight::ExitSpan); } } @@ -784,14 +882,20 @@ impl<'src> Classifier<'src> { &mut self, token: TokenKind, text: &'src str, - sink: &mut dyn FnMut(Highlight<'src>), + sink: &mut dyn FnMut(Span, Highlight<'src>), before: u32, ) { let lookahead = self.peek(); - let no_highlight = |sink: &mut dyn FnMut(_)| sink(Highlight::Token { text, class: None }); - let whitespace = |sink: &mut dyn FnMut(_)| { + let file_span = self.file_span; + let no_highlight = |sink: &mut dyn FnMut(_, _)| sink(new_span(before, text, file_span), Highlight::Token { text, class: None }); + let whitespace = |sink: &mut dyn FnMut(_, _)| { + let mut start = 0u32; for part in text.split('\n').intersperse("\n").filter(|s| !s.is_empty()) { - sink(Highlight::Token { text: part, class: None }); + sink( + new_span(before + start, part, file_span), + Highlight::Token { text: part, class: None }, + ); + start += part.len() as u32; } }; let class = match token { @@ -807,8 +911,8 @@ impl<'src> Classifier<'src> { // leading identifier. TokenKind::Bang if self.in_macro => { self.in_macro = false; - sink(Highlight::Token { text, class: None }); - sink(Highlight::ExitSpan); + sink(new_span(before, text, file_span), Highlight::Token { text, class: None }); + sink(DUMMY_SP, Highlight::ExitSpan); return; } @@ -819,12 +923,18 @@ impl<'src> Classifier<'src> { Some((TokenKind::Whitespace, _)) => return whitespace(sink), Some((TokenKind::Ident, "mut")) => { self.next(); - sink(Highlight::Token { text: "*mut", class: Some(Class::RefKeyWord) }); + sink( + DUMMY_SP, + Highlight::Token { text: "*mut", class: Some(Class::RefKeyWord) }, + ); return; } Some((TokenKind::Ident, "const")) => { self.next(); - sink(Highlight::Token { text: "*const", class: Some(Class::RefKeyWord) }); + sink( + DUMMY_SP, + Highlight::Token { text: "*const", class: Some(Class::RefKeyWord) }, + ); return; } _ => Class::RefKeyWord, @@ -832,18 +942,21 @@ impl<'src> Classifier<'src> { TokenKind::And => match self.tokens.peek() { Some((TokenKind::And, _)) => { self.next(); - sink(Highlight::Token { text: "&&", class: None }); + sink(DUMMY_SP, Highlight::Token { text: "&&", class: None }); return; } Some((TokenKind::Eq, _)) => { self.next(); - sink(Highlight::Token { text: "&=", class: None }); + sink(DUMMY_SP, Highlight::Token { text: "&=", class: None }); return; } Some((TokenKind::Whitespace, _)) => return whitespace(sink), Some((TokenKind::Ident, "mut")) => { self.next(); - sink(Highlight::Token { text: "&mut", class: Some(Class::RefKeyWord) }); + sink( + DUMMY_SP, + Highlight::Token { text: "&mut", class: Some(Class::RefKeyWord) }, + ); return; } _ => Class::RefKeyWord, @@ -853,19 +966,19 @@ impl<'src> Classifier<'src> { TokenKind::Eq => match lookahead { Some(TokenKind::Eq) => { self.next(); - sink(Highlight::Token { text: "==", class: None }); + sink(DUMMY_SP, Highlight::Token { text: "==", class: None }); return; } Some(TokenKind::Gt) => { self.next(); - sink(Highlight::Token { text: "=>", class: None }); + sink(DUMMY_SP, Highlight::Token { text: "=>", class: None }); return; } _ => return no_highlight(sink), }, TokenKind::Minus if lookahead == Some(TokenKind::Gt) => { self.next(); - sink(Highlight::Token { text: "->", class: None }); + sink(DUMMY_SP, Highlight::Token { text: "->", class: None }); return; } @@ -916,16 +1029,22 @@ impl<'src> Classifier<'src> { self.next(); if let Some(TokenKind::OpenBracket) = self.peek() { self.in_attribute = true; - sink(Highlight::EnterSpan { class: Class::Attribute }); + sink( + new_span(before, text, file_span), + Highlight::EnterSpan { class: Class::Attribute }, + ); } - sink(Highlight::Token { text: "#", class: None }); - sink(Highlight::Token { text: "!", class: None }); + sink(DUMMY_SP, Highlight::Token { text: "#", class: None }); + sink(DUMMY_SP, Highlight::Token { text: "!", class: None }); return; } // Case 2: #[outer_attribute] Some(TokenKind::OpenBracket) => { self.in_attribute = true; - sink(Highlight::EnterSpan { class: Class::Attribute }); + sink( + new_span(before, text, file_span), + Highlight::EnterSpan { class: Class::Attribute }, + ); } _ => (), } @@ -934,8 +1053,8 @@ impl<'src> Classifier<'src> { TokenKind::CloseBracket => { if self.in_attribute { self.in_attribute = false; - sink(Highlight::Token { text: "]", class: None }); - sink(Highlight::ExitSpan); + sink(new_span(before, text, file_span), Highlight::Token { text: "]", class: None }); + sink(DUMMY_SP, Highlight::ExitSpan); return; } return no_highlight(sink); @@ -956,15 +1075,16 @@ impl<'src> Classifier<'src> { TokenKind::GuardedStrPrefix => return no_highlight(sink), TokenKind::Ident | TokenKind::RawIdent if lookahead == Some(TokenKind::Bang) => { self.in_macro = true; - sink(Highlight::EnterSpan { class: Class::Macro(self.new_span(before, text)) }); - sink(Highlight::Token { text, class: None }); + let span = new_span(before, text, file_span); + sink(DUMMY_SP, Highlight::EnterSpan { class: Class::Macro(span) }); + sink(span, Highlight::Token { text, class: None }); return; } TokenKind::Ident => match get_real_ident_class(text, false) { None => match text { - "Option" | "Result" => Class::PreludeTy(self.new_span(before, text)), + "Option" | "Result" => Class::PreludeTy(new_span(before, text, file_span)), "Some" | "None" | "Ok" | "Err" => { - Class::PreludeVal(self.new_span(before, text)) + Class::PreludeVal(new_span(before, text, file_span)) } // "union" is a weak keyword and is only considered as a keyword when declaring // a union type. @@ -973,13 +1093,13 @@ impl<'src> Classifier<'src> { self.in_macro_nonterminal = false; Class::MacroNonTerminal } - "self" | "Self" => Class::Self_(self.new_span(before, text)), - _ => Class::Ident(self.new_span(before, text)), + "self" | "Self" => Class::Self_(new_span(before, text, file_span)), + _ => Class::Ident(new_span(before, text, file_span)), }, Some(c) => c, }, TokenKind::RawIdent | TokenKind::UnknownPrefix | TokenKind::InvalidIdent => { - Class::Ident(self.new_span(before, text)) + Class::Ident(new_span(before, text, file_span)) } TokenKind::Lifetime { .. } | TokenKind::RawLifetime @@ -988,8 +1108,13 @@ impl<'src> Classifier<'src> { }; // Anything that didn't return above is the simple case where we the // class just spans a single token, so we can use the `string` method. + let mut start = 0u32; for part in text.split('\n').intersperse("\n").filter(|s| !s.is_empty()) { - sink(Highlight::Token { text: part, class: Some(class) }); + sink( + new_span(before + start, part, file_span), + Highlight::Token { text: part, class: Some(class) }, + ); + start += part.len() as u32; } } @@ -1042,9 +1167,9 @@ fn exit_span(out: &mut impl Write, closing_tag: &str) { /// Note that if `context` is not `None` and that the given `klass` contains a `Span`, the function /// will then try to find this `span` in the `span_correspondence_map`. If found, it'll then /// generate a link for this element (which corresponds to where its definition is located). -fn string<T: Display, W: Write>( +fn string<W: Write>( out: &mut W, - text: T, + text: EscapeBodyText<'_>, klass: Option<Class>, href_context: &Option<HrefContext<'_, '_>>, open_tag: bool, @@ -1052,6 +1177,9 @@ fn string<T: Display, W: Write>( ) { if let Some(Class::Backline(line)) = klass { write_line_number_callback(out, line, "\n"); + } else if let Some(Class::Expansion) = klass { + // Nothing to escape here so we get the text to write it directly. + out.write_str(text.0).unwrap(); } else if let Some(closing_tag) = string_without_closing_tag(out, text, klass, href_context, open_tag) { diff --git a/src/librustdoc/html/render/context.rs b/src/librustdoc/html/render/context.rs index e4fca09d64f..33dec1c24e6 100644 --- a/src/librustdoc/html/render/context.rs +++ b/src/librustdoc/html/render/context.rs @@ -12,7 +12,7 @@ use rustc_hir::def_id::{DefIdMap, LOCAL_CRATE}; use rustc_middle::ty::TyCtxt; use rustc_session::Session; use rustc_span::edition::Edition; -use rustc_span::{FileName, Symbol, sym}; +use rustc_span::{BytePos, FileName, Symbol, sym}; use tracing::info; use super::print_item::{full_path, print_item, print_item_path}; @@ -29,6 +29,7 @@ use crate::formats::cache::Cache; use crate::formats::item_type::ItemType; use crate::html::escape::Escape; use crate::html::markdown::{self, ErrorCodes, IdMap, plain_text_summary}; +use crate::html::render::ExpandedCode; use crate::html::render::write_shared::write_shared; use crate::html::url_parts_builder::UrlPartsBuilder; use crate::html::{layout, sources, static_files}; @@ -139,6 +140,7 @@ pub(crate) struct SharedContext<'tcx> { /// Correspondence map used to link types used in the source code pages to allow to click on /// links to jump to the type's definition. pub(crate) span_correspondence_map: FxHashMap<rustc_span::Span, LinkFromSrc>, + pub(crate) expanded_codes: FxHashMap<BytePos, Vec<ExpandedCode>>, /// The [`Cache`] used during rendering. pub(crate) cache: Cache, pub(crate) call_locations: AllCallLocations, @@ -548,7 +550,7 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> { } } - let (local_sources, matches) = collect_spans_and_sources( + let (local_sources, matches, expanded_codes) = collect_spans_and_sources( tcx, &krate, &src_root, @@ -579,6 +581,7 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> { cache, call_locations, should_merge: options.should_merge, + expanded_codes, }; let dst = output; diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 8d7f0577506..0986b9ca47b 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -63,7 +63,7 @@ use serde::{Serialize, Serializer}; use tracing::{debug, info}; pub(crate) use self::context::*; -pub(crate) use self::span_map::{LinkFromSrc, collect_spans_and_sources}; +pub(crate) use self::span_map::{ExpandedCode, LinkFromSrc, collect_spans_and_sources}; pub(crate) use self::write_shared::*; use crate::clean::{self, ItemId, RenderedLink}; use crate::display::{Joined as _, MaybeDisplay as _}; diff --git a/src/librustdoc/html/render/span_map.rs b/src/librustdoc/html/render/span_map.rs index 846d3ad310c..842da838049 100644 --- a/src/librustdoc/html/render/span_map.rs +++ b/src/librustdoc/html/render/span_map.rs @@ -30,12 +30,26 @@ pub(crate) enum LinkFromSrc { Doc(DefId), } +/// Contains information about macro expansion in the source code pages. +#[derive(Debug)] +pub(crate) struct ExpandedCode { + /// The line where the macro expansion starts. + pub(crate) start_line: u32, + /// The line where the macro expansion ends. + pub(crate) end_line: u32, + /// The source code of the expanded macro. + pub(crate) code: String, + /// The span of macro callsite. + pub(crate) span: Span, +} + /// This function will do at most two things: /// /// 1. Generate a `span` correspondence map which links an item `span` to its definition `span`. /// 2. Collect the source code files. /// -/// It returns the `krate`, the source code files and the `span` correspondence map. +/// It returns the source code files, the `span` correspondence map and the expanded macros +/// correspondence map. /// /// Note about the `span` correspondence map: the keys are actually `(lo, hi)` of `span`s. We don't /// need the `span` context later on, only their position, so instead of keeping a whole `Span`, we @@ -46,17 +60,23 @@ pub(crate) fn collect_spans_and_sources( src_root: &Path, include_sources: bool, generate_link_to_definition: bool, -) -> (FxIndexMap<PathBuf, String>, FxHashMap<Span, LinkFromSrc>) { +) -> ( + FxIndexMap<PathBuf, String>, + FxHashMap<Span, LinkFromSrc>, + FxHashMap<BytePos, Vec<ExpandedCode>>, +) { if include_sources { let mut visitor = SpanMapVisitor { tcx, matches: FxHashMap::default() }; + let mut expanded_visitor = ExpandedCodeVisitor { tcx, expanded_codes: Vec::new() }; + tcx.hir_walk_toplevel_module(&mut expanded_visitor); if generate_link_to_definition { tcx.hir_walk_toplevel_module(&mut visitor); } let sources = sources::collect_local_sources(tcx, src_root, krate); - (sources, visitor.matches) + (sources, visitor.matches, expanded_visitor.compute_expanded()) } else { - (Default::default(), Default::default()) + (Default::default(), Default::default(), Default::default()) } } @@ -292,3 +312,89 @@ impl<'tcx> Visitor<'tcx> for SpanMapVisitor<'tcx> { intravisit::walk_item(self, item); } } + +/// Contains temporary information of macro expanded code. +/// +/// As we go through the HIR visitor, if any span overlaps with another, they will +/// both be merged. +struct ExpandedCodeInfo { + /// Callsite of the macro. + span: Span, + /// Expanded macro source code. + code: String, +} + +/// HIR visitor which retrieves expanded macro. +/// +/// Once done, the `expanded_codes` will be transformed into a vec of [`ExpandedCode`] +/// which contains more information needed when running the source code highlighter. +pub struct ExpandedCodeVisitor<'tcx> { + tcx: TyCtxt<'tcx>, + expanded_codes: Vec<ExpandedCodeInfo>, +} + +impl<'tcx> ExpandedCodeVisitor<'tcx> { + fn handle_new_span<F: Fn(TyCtxt<'_>) -> String>(&mut self, new_span: Span, f: F) { + if new_span.is_dummy() || !new_span.from_expansion() { + return; + } + let new_span = new_span.source_callsite(); + if let Some(index) = + self.expanded_codes.iter().position(|info| info.span.overlaps(new_span)) + { + if !self.expanded_codes[index].span.contains(new_span) { + // We replace the item. + let info = &mut self.expanded_codes[index]; + info.span = new_span; + info.code = f(self.tcx); + } + } else { + // We add a new item. + self.expanded_codes.push(ExpandedCodeInfo { + span: new_span, + code: f(self.tcx), + }); + } + } + + fn compute_expanded(mut self) -> FxHashMap<BytePos, Vec<ExpandedCode>> { + self.expanded_codes.sort_unstable_by(|item1, item2| item1.span.cmp(&item2.span)); + let source_map = self.tcx.sess.source_map(); + let mut expanded: FxHashMap<BytePos, Vec<ExpandedCode>> = FxHashMap::default(); + for ExpandedCodeInfo { span, code } in self.expanded_codes { + if let Ok(lines) = source_map.span_to_lines(span) + && !lines.lines.is_empty() + { + let mut out = String::new(); + super::highlight::write_code(&mut out, &code, None, None, None); + let first = lines.lines.first().unwrap(); + let end = lines.lines.last().unwrap(); + expanded.entry(lines.file.start_pos).or_default().push(ExpandedCode { + start_line: first.line_index as u32 + 1, + end_line: end.line_index as u32 + 1, + code: out, + span, + }); + } + } + expanded + } +} + +impl<'tcx> Visitor<'tcx> for ExpandedCodeVisitor<'tcx> { + type NestedFilter = nested_filter::All; + + fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt { + self.tcx + } + + fn visit_expr(&mut self, expr: &'tcx rustc_hir::Expr<'tcx>) { + self.handle_new_span(expr.span, |tcx| rustc_hir_pretty::expr_to_string(&tcx, expr)); + intravisit::walk_expr(self, expr); + } + + fn visit_item(&mut self, item: &'tcx rustc_hir::Item<'tcx>) { + self.handle_new_span(item.span, |tcx| rustc_hir_pretty::item_to_string(&tcx, item)); + intravisit::walk_item(self, item); + } +} diff --git a/src/librustdoc/html/static/css/rustdoc.css b/src/librustdoc/html/static/css/rustdoc.css index dc27d7943d9..9403701d454 100644 --- a/src/librustdoc/html/static/css/rustdoc.css +++ b/src/librustdoc/html/static/css/rustdoc.css @@ -956,14 +956,55 @@ rustdoc-topbar { .example-wrap.digits-8 { --example-wrap-digits-count: 8ch; } .example-wrap.digits-9 { --example-wrap-digits-count: 9ch; } -.example-wrap [data-nosnippet] { +.example-wrap .expansion { + position: relative; + display: inline; +} +.example-wrap .expansion > input { + display: none; +} +.example-wrap .expansion > label { + position: absolute; + left: -20px; + top: 0; + border: 1px solid var(--border-color); + border-radius: 4px; + cursor: pointer; + color: var(--main-color); + padding: 0 2px; + line-height: 20px; + -moz-user-select: none; + -webkit-user-select: none; + -ms-user-select: none; + user-select: none; + +} +.example-wrap .expansion .expanded { + display: none; + color: var(--main-color); +} +.example-wrap .expansion > input:checked ~ .expanded, +.example-wrap .expansion > input:checked ~ * .expanded { + display: inherit; +} +.example-wrap .expansion > input:checked ~ .original, +.example-wrap .expansion > input:checked ~ * .original { + display: none; +} + +.src .example-wrap [data-nosnippet] { width: calc(var(--example-wrap-digits-count) + var(--line-number-padding) * 2); } -.example-wrap pre > code { +.src .example-wrap pre > code { padding-left: calc( var(--example-wrap-digits-count) + var(--line-number-padding) * 2 + var(--line-number-right-margin)); } +.src .example-wrap .expansion [data-nosnippet] { + left: calc(( + var(--example-wrap-digits-count) + var(--line-number-padding) * 2 + + var(--line-number-right-margin)) * -1); +} .example-wrap [data-nosnippet] { color: var(--src-line-numbers-span-color); @@ -978,23 +1019,21 @@ rustdoc-topbar { position: absolute; left: 0; } -.example-wrap .line-highlighted[data-nosnippet] { - background-color: var(--src-line-number-highlighted-background-color); -} .example-wrap pre > code { position: relative; - display: block; -} -:root.word-wrap-source-code .example-wrap pre > code { word-break: break-all; + display: block; white-space: pre-wrap; } -:root.word-wrap-source-code .example-wrap pre > code * { +.example-wrap pre > code * { word-break: break-all; } .example-wrap [data-nosnippet]:target { border-right: none; } +.example-wrap .line-highlighted[data-nosnippet] { + background-color: var(--src-line-number-highlighted-background-color); +} .example-wrap.hide-lines [data-nosnippet] { display: none; } |
