Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rustdoc: Add ItemTemplate trait and related functions to avoid repetitively wrapping existing functions #111946

Merged
merged 1 commit into from
May 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
95 changes: 57 additions & 38 deletions src/librustdoc/html/render/print_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ use rustc_middle::middle::stability;
use rustc_middle::ty::{self, TyCtxt};
use rustc_span::hygiene::MacroKind;
use rustc_span::symbol::{kw, sym, Symbol};
use std::borrow::Borrow;
use std::cell::{RefCell, RefMut};
use std::cmp::Ordering;
use std::fmt;
use std::rc::Rc;
Expand Down Expand Up @@ -216,6 +218,53 @@ fn toggle_close(mut w: impl fmt::Write) {
w.write_str("</details>").unwrap();
}

trait ItemTemplate<'a, 'cx: 'a>: askama::Template + fmt::Display {
fn item_and_mut_cx(&self) -> (&'a clean::Item, RefMut<'_, &'a mut Context<'cx>>);
}

fn item_template_document<'a: 'b, 'b, 'cx: 'a>(
templ: &'b impl ItemTemplate<'a, 'cx>,
) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
display_fn(move |f| {
let (item, mut cx) = templ.item_and_mut_cx();
let v = document(*cx, item, None, HeadingOffset::H2);
write!(f, "{v}")
})
}

fn item_template_document_type_layout<'a: 'b, 'b, 'cx: 'a>(
templ: &'b impl ItemTemplate<'a, 'cx>,
) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
display_fn(move |f| {
let (item, cx) = templ.item_and_mut_cx();
let def_id = item.item_id.expect_def_id();
let v = document_type_layout(*cx, def_id);
write!(f, "{v}")
})
}

fn item_template_render_attributes_in_pre<'a: 'b, 'b, 'cx: 'a>(
templ: &'b impl ItemTemplate<'a, 'cx>,
) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
display_fn(move |f| {
let (item, cx) = templ.item_and_mut_cx();
let tcx = cx.tcx();
let v = render_attributes_in_pre(item, "", tcx);
write!(f, "{v}")
})
}

fn item_template_render_assoc_items<'a: 'b, 'b, 'cx: 'a>(
templ: &'b impl ItemTemplate<'a, 'cx>,
) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
display_fn(move |f| {
let (item, mut cx) = templ.item_and_mut_cx();
let def_id = item.item_id.expect_def_id();
let v = render_assoc_items(*cx, item, def_id, AssocItemRender::All);
write!(f, "{v}")
})
}

fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items: &[clean::Item]) {
write!(w, "{}", document(cx, item, None, HeadingOffset::H2));

Expand Down Expand Up @@ -1131,55 +1180,25 @@ fn item_union(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean:
#[derive(Template)]
#[template(path = "item_union.html")]
struct ItemUnion<'a, 'cx> {
cx: std::cell::RefCell<&'a mut Context<'cx>>,
cx: RefCell<&'a mut Context<'cx>>,
it: &'a clean::Item,
s: &'a clean::Union,
}

impl<'a, 'cx: 'a> ItemUnion<'a, 'cx> {
fn render_assoc_items<'b>(
&'b self,
) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
display_fn(move |f| {
let def_id = self.it.item_id.expect_def_id();
let mut cx = self.cx.borrow_mut();
let v = render_assoc_items(*cx, self.it, def_id, AssocItemRender::All);
write!(f, "{v}")
})
}
fn document_type_layout<'b>(
&'b self,
) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
display_fn(move |f| {
let def_id = self.it.item_id.expect_def_id();
let cx = self.cx.borrow_mut();
let v = document_type_layout(*cx, def_id);
write!(f, "{v}")
})
impl<'a, 'cx: 'a> ItemTemplate<'a, 'cx> for ItemUnion<'a, 'cx> {
fn item_and_mut_cx(&self) -> (&'a clean::Item, RefMut<'_, &'a mut Context<'cx>>) {
(self.it, self.cx.borrow_mut())
}
}

impl<'a, 'cx: 'a> ItemUnion<'a, 'cx> {
fn render_union<'b>(&'b self) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
display_fn(move |f| {
let cx = self.cx.borrow_mut();
let v = render_union(self.it, Some(&self.s.generics), &self.s.fields, *cx);
write!(f, "{v}")
})
}
fn render_attributes_in_pre<'b>(
&'b self,
) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
display_fn(move |f| {
let tcx = self.cx.borrow().tcx();
let v = render_attributes_in_pre(self.it, "", tcx);
write!(f, "{v}")
})
}
fn document<'b>(&'b self) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
display_fn(move |f| {
let mut cx = self.cx.borrow_mut();
let v = document(*cx, self.it, None, HeadingOffset::H2);
write!(f, "{v}")
})
}
fn document_field<'b>(
&'b self,
field: &'a clean::Item,
Expand Down Expand Up @@ -1219,7 +1238,7 @@ fn item_union(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean:
}
}

ItemUnion { cx: std::cell::RefCell::new(cx), it, s }.render_into(w).unwrap();
ItemUnion { cx: RefCell::new(cx), it, s }.render_into(w).unwrap();
}

fn print_tuple_struct_fields<'a, 'cx: 'a>(
Expand Down
8 changes: 4 additions & 4 deletions src/librustdoc/html/templates/item_union.html
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<pre class="rust item-decl"><code>
{{ self.render_attributes_in_pre() | safe }}
{{ self::item_template_render_attributes_in_pre(self.borrow()) | safe }}
{{ self.render_union() | safe }}
</code></pre>
{{ self.document() | safe }}
{{ self::item_template_document(self.borrow()) | safe }}
{% if self.fields_iter().peek().is_some() %}
<h2 id="fields" class="fields small-section-header">
Fields<a href="#fields" class="anchor">§</a>
Expand All @@ -19,5 +19,5 @@ <h2 id="fields" class="fields small-section-header">
{{ self.document_field(field) | safe }}
{% endfor %}
{% endif %}
{{ self.render_assoc_items() | safe }}
{{ self.document_type_layout() | safe }}
{{ self::item_template_render_assoc_items(self.borrow()) | safe }}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just thought about something: could we instead of calling .borrow() change the API of item_template_render_assoc_items to take a &RefCell<T> where T: ItemTemplate or something equivalent to not have to write .borrow() every time? I'm not sure if it's possible though. If you could confirm it, it'd be awesome!

Copy link
Contributor Author

@nicklimmm nicklimmm May 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

self::item_template_render_attributes_in_pre(self) | safe expands to

  • Without .borrow(): &::askama::filters::safe(::askama::Html, self::item_template_render_attributes_in_pre(&(self)))?
  • With .borrow(): &::askama::filters::safe(::askama::Html, self::item_template_render_attributes_in_pre({self.borrow()}))?

I'm not sure why the function didn't catch &(self) as &impl ItemTemplate, but self.borrow() does here (self.borrow() returns &ItemUnion) ...

Copy link
Contributor Author

@nicklimmm nicklimmm May 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found out that we can remove .borrow() calls by:

  • Implementing ItemTemplate trait for &ItemUnion
    • The compiler suggested this after I removed .borrow()
    • We should use blanket impls to prevent writing the same impl blocks multiple times
  • Implementing askama::Template trait for &ItemUnion
    • Due to the derive macro doesn't implement askama::Template for &T
    • Can't apply blanket impls here since Template is from an external crate (not sure if we should make a feature request for this to be available)
    • Implication: we need to copy over the associated types and wrap methods from T
    • Possible to use macros here

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm pretty much stuck at this point, what do you think? @GuillaumeGomez

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really like the first suggestion which also seems to be the simplest to be implemented (but maybe I'm wrong there). Thanks for taking a look! So what do you prefer: making the changes here directly or opening an issue and fixing it in a follow-up PR?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, I laid them out wrongly, they should be implemented together.

Doing only the 1st item will cause errors, and the compiler suggested to do the 2nd item to fix it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh I see. Well, that still seems doable. Then same question for how you prefer things to roll out. :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really like the first suggestion which also seems to be the simplest to be implemented (but maybe I'm wrong there). Thanks for taking a look! So what do you prefer: making the changes here directly or opening an issue and fixing it in a follow-up PR?

Nevertheless, I'd prefer to do a follow-up PR and open up a new issue. I would like to see opinions from others (in case there exists something simpler).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's go this way then! I r+ this PR. Please open an issue. ;)

{{ self::item_template_document_type_layout(self.borrow()) | safe }}