Skip to content

Commit

Permalink
Code quality pass on forc doc (#5962)
Browse files Browse the repository at this point in the history
  • Loading branch information
JoshuaBatty authored May 6, 2024
1 parent 7c926d2 commit b7a87f3
Show file tree
Hide file tree
Showing 15 changed files with 150 additions and 157 deletions.
7 changes: 5 additions & 2 deletions forc-plugins/forc-doc/src/doc/descriptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
use crate::{
doc::{module::ModuleInfo, Document},
render::{
item::{components::*, context::*},
item::{
components::*,
context::{Context, ContextType, ItemContext},
},
util::format::{code_block::trim_fn_body, docstring::DocStrings},
},
};
Expand Down Expand Up @@ -129,7 +132,7 @@ impl Descriptor {
trait_decl
.interface_surface
.into_iter()
.flat_map(|item| match item {
.filter_map(|item| match item {
TyTraitInterfaceItem::TraitFn(fn_decl) => Some(fn_decl),
_ => None,
})
Expand Down
52 changes: 34 additions & 18 deletions forc-plugins/forc-doc/src/doc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@ use crate::{
render::{
item::{components::*, context::DocImplTrait},
link::DocLink,
util::format::docstring::*,
util::format::docstring::{create_preview, DocStrings},
},
};
use anyhow::Result;
use std::{collections::HashMap, option::Option};
use std::{
collections::HashMap,
ops::{Deref, DerefMut},
option::Option,
};
use sway_core::{
decl_engine::DeclEngine,
language::ty::{TyAstNodeContent, TyDecl, TyImplTrait, TyModule, TyProgram, TySubmodule},
Expand All @@ -21,6 +25,7 @@ pub mod module;

#[derive(Default, Clone)]
pub(crate) struct Documentation(pub(crate) Vec<Document>);

impl Documentation {
/// Gather [Documentation] from the [TyProgram].
pub(crate) fn from_ty_program(
Expand All @@ -30,14 +35,12 @@ impl Documentation {
document_private_items: bool,
) -> Result<Documentation> {
// the first module prefix will always be the project name
let namespace = &typed_program.root.namespace;
let decl_engine = engines.de();
let mut docs: Documentation = Default::default();
let mut docs = Documentation::default();
let mut impl_traits: Vec<(TyImplTrait, ModuleInfo)> = Vec::new();
let module_info = ModuleInfo::from_ty_module(vec![project_name.to_owned()], None);
Documentation::from_ty_module(
decl_engine,
module_info,
engines.de(),
&module_info,
&typed_program.root,
&mut docs,
&mut impl_traits,
Expand All @@ -51,7 +54,7 @@ impl Documentation {
let module_prefix =
ModuleInfo::from_ty_module(vec![project_name.to_owned()], attributes);
Documentation::from_ty_submodule(
decl_engine,
engines.de(),
typed_submodule,
&mut docs,
&mut impl_traits,
Expand All @@ -60,7 +63,6 @@ impl Documentation {
)?;
}
let trait_decls = docs
.0
.iter()
.filter_map(|d| {
(d.item_header.friendly_name == "trait").then_some((
Expand All @@ -73,24 +75,25 @@ impl Documentation {
// match for the spans to add the impl_traits to their corresponding doc:
// currently this compares the spans as str, but this needs to change
// to compare the actual types
for doc in &mut docs.0 {
for doc in docs.iter_mut() {
let mut impl_vec: Vec<DocImplTrait> = Vec::new();

match doc.item_body.ty_decl {
TyDecl::StructDecl(ref decl) => {
for (impl_trait, module_info) in impl_traits.iter_mut() {
let struct_decl = decl_engine.get_struct(&decl.decl_id);
let struct_decl = engines.de().get_struct(&decl.decl_id);
if struct_decl.name().as_str() == impl_trait.implementing_for.span.as_str()
&& struct_decl.name().as_str()
!= impl_trait.trait_name.suffix.span().as_str()
{
let module_info_override = if let Some(decl_module_info) =
trait_decls.get(&impl_trait.trait_name.suffix)
{
Some(decl_module_info.module_prefixes.to_owned())
Some(decl_module_info.module_prefixes.clone())
} else {
impl_trait.trait_name =
impl_trait.trait_name.to_fullpath(engines, namespace);
impl_trait.trait_name = impl_trait
.trait_name
.to_fullpath(engines, &typed_program.root.namespace);
None
};

Expand All @@ -114,7 +117,7 @@ impl Documentation {
}
fn from_ty_module(
decl_engine: &DeclEngine,
module_info: ModuleInfo,
module_info: &ModuleInfo,
ty_module: &TyModule,
docs: &mut Documentation,
impl_traits: &mut Vec<(TyImplTrait, ModuleInfo)>,
Expand All @@ -126,7 +129,7 @@ impl Documentation {
impl_traits.push((
(*decl_engine.get_impl_trait(&impl_trait.decl_id)).clone(),
module_info.clone(),
))
));
} else {
let desc = Descriptor::from_typed_decl(
decl_engine,
Expand All @@ -136,7 +139,7 @@ impl Documentation {
)?;

if let Descriptor::Documentable(doc) = desc {
docs.0.push(doc)
docs.push(doc);
}
}
}
Expand All @@ -158,7 +161,7 @@ impl Documentation {
.push(typed_submodule.mod_name_span.as_str().to_owned());
Documentation::from_ty_module(
decl_engine,
module_info.clone(),
&module_info.clone(),
&typed_submodule.module,
docs,
impl_traits,
Expand Down Expand Up @@ -220,3 +223,16 @@ impl Document {
create_preview(self.raw_attributes.clone())
}
}

impl Deref for Documentation {
type Target = Vec<Document>;
fn deref(&self) -> &Self::Target {
&self.0
}
}

impl DerefMut for Documentation {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
17 changes: 8 additions & 9 deletions forc-plugins/forc-doc/src/doc/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,12 @@ impl ModuleInfo {
///
/// Returns `None` if there is no parent.
pub(crate) fn parent(&self) -> Option<&String> {
match self.has_parent() {
true => {
let mut iter = self.module_prefixes.iter();
iter.next_back();
iter.next_back()
}
false => None,
if self.has_parent() {
let mut iter = self.module_prefixes.iter();
iter.next_back();
iter.next_back()
} else {
None
}
}
/// Determines if the current module has a parent module.
Expand Down Expand Up @@ -79,14 +78,14 @@ impl ModuleInfo {
break;
}
}
iter.map(|s| s.as_str()).collect::<Vec<&str>>().join("::")
iter.map(String::as_str).collect::<Vec<&str>>().join("::")
}
/// Renders the [ModuleInfo] into a [CallPath] with anchors. We return this as a `Result<Vec<String>>`
/// since the `box_html!` macro returns a closure and no two closures are considered the same type.
pub(crate) fn get_anchors(&self) -> Result<Vec<String>> {
let mut count = self.depth();
let mut rendered_module_anchors = Vec::with_capacity(self.depth());
for prefix in self.module_prefixes.iter() {
for prefix in &self.module_prefixes {
let mut href = (1..count).map(|_| "../").collect::<String>();
href.push_str(INDEX_FILENAME);
rendered_module_anchors.push(
Expand Down
61 changes: 27 additions & 34 deletions forc-plugins/forc-doc/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ fn build_docs(
raw_docs.clone(),
RenderPlan::new(no_deps, document_private_items, engines),
root_attributes,
ty_program.kind,
&ty_program.kind,
forc_version,
)?;

Expand All @@ -161,14 +161,12 @@ fn write_content(rendered_docs: RenderedDocumentation, doc_path: &Path) -> Resul
for doc in rendered_docs.0 {
let mut doc_path = doc_path.to_path_buf();
for prefix in doc.module_info.module_prefixes {
doc_path.push(prefix)
doc_path.push(prefix);
}

fs::create_dir_all(&doc_path)?;
doc_path.push(doc.html_filename);
fs::write(&doc_path, doc.file_contents.0.as_bytes())?;
}

Ok(())
}

Expand All @@ -184,9 +182,7 @@ pub fn compile_html(
std::env::current_dir()?
};
let manifest = ManifestFile::from_dir(dir)?;
let pkg_manifest = if let ManifestFile::Package(pkg_manifest) = &manifest {
pkg_manifest
} else {
let ManifestFile::Package(pkg_manifest) = &manifest else {
bail!("forc-doc does not support workspaces.")
};

Expand Down Expand Up @@ -231,58 +227,55 @@ pub fn compile_html(
experimental,
)?;

let raw_docs = if !build_instructions.no_deps {
let raw_docs = if build_instructions.no_deps {
let Some(ty_program) = compile_results
.pop()
.and_then(|(programs, _handler)| programs)
.and_then(|p| p.typed.ok())
else {
bail! {
"documentation could not be built from manifest located at '{}'",
pkg_manifest.path().display()
}
};
let program_info = ProgramInfo {
ty_program,
engines: &engines,
manifest: &manifest,
pkg_manifest,
};
build_docs(program_info, &doc_path, build_instructions)?
} else {
let order = plan.compilation_order();
let graph = plan.graph();
let manifest_map = plan.manifest_map();
let mut raw_docs = Documentation(Vec::new());

for (node, (compile_result, _handler)) in order.iter().zip(compile_results) {
let id = &graph[*node].id();

if let Some(pkg_manifest_file) = manifest_map.get(id) {
let manifest_file = ManifestFile::from_dir(pkg_manifest_file.path())?;
let ty_program = match compile_result.and_then(|programs| programs.typed.ok()) {
Some(ty_program) => ty_program,
_ => bail!(
let Some(ty_program) = compile_result.and_then(|programs| programs.typed.ok())
else {
bail!(
"documentation could not be built from manifest located at '{}'",
pkg_manifest_file.path().display()
),
)
};
let program_info = ProgramInfo {
ty_program,
engines: &engines,
manifest: &manifest_file,
pkg_manifest: pkg_manifest_file,
};

raw_docs
.0
.extend(build_docs(program_info, &doc_path, build_instructions)?.0);
}
}
raw_docs
} else {
let ty_program = match compile_results
.pop()
.and_then(|(programs, _handler)| programs)
.and_then(|p| p.typed.ok())
{
Some(ty_program) => ty_program,
_ => bail!(
"documentation could not be built from manifest located at '{}'",
pkg_manifest.path().display()
),
};
let program_info = ProgramInfo {
ty_program,
engines: &engines,
manifest: &manifest,
pkg_manifest,
};
build_docs(program_info, &doc_path, build_instructions)?
};
write_search_index(&doc_path, raw_docs)?;
write_search_index(&doc_path, &raw_docs)?;

Ok((doc_path, pkg_manifest.to_owned()))
}
Expand Down
11 changes: 6 additions & 5 deletions forc-plugins/forc-doc/src/render/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ impl Renderable for AllDocIndex {
: sidebar;
main {
div(class="width-limiter") {
: generate_searchbar(self.project_name.clone());
: generate_searchbar(&self.project_name);
section(id="main-content", class="content") {
h1(class="fqn") {
span(class="in-band") { : "List of all items" }
Expand Down Expand Up @@ -102,9 +102,10 @@ impl ModuleIndex {
}
impl SidebarNav for ModuleIndex {
fn sidebar(&self) -> Sidebar {
let style = match self.module_info.is_root_module() {
true => self.module_docs.style.clone(),
false => DocStyle::ModuleIndex,
let style = if self.module_info.is_root_module() {
self.module_docs.style.clone()
} else {
DocStyle::ModuleIndex
};
Sidebar::new(
self.version_opt.clone(),
Expand Down Expand Up @@ -169,7 +170,7 @@ impl Renderable for ModuleIndex {
: sidebar;
main {
div(class="width-limiter") {
: generate_searchbar(self.module_info.clone());
: generate_searchbar(&self.module_info);
section(id="main-content", class="content") {
div(class="main-heading") {
h1(class="fqn") {
Expand Down
10 changes: 7 additions & 3 deletions forc-plugins/forc-doc/src/render/item/components.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@
use crate::{
doc::module::ModuleInfo,
render::{
constant::IDENTITY, item::context::ItemContext, search::generate_searchbar, sidebar::*,
title::DocBlockTitle, DocStyle, Renderable,
constant::IDENTITY,
item::context::ItemContext,
search::generate_searchbar,
sidebar::{Sidebar, SidebarNav},
title::DocBlockTitle,
DocStyle, Renderable,
},
RenderPlan, ASSETS_DIR_NAME,
};
Expand Down Expand Up @@ -122,7 +126,7 @@ impl Renderable for ItemBody {
// this is the main code block
main {
div(class="width-limiter") {
: generate_searchbar(module_info.clone());
: generate_searchbar(&module_info);
section(id="main-content", class="content") {
div(class="main-heading") {
h1(class="fqn") {
Expand Down
Loading

0 comments on commit b7a87f3

Please sign in to comment.