Skip to content

Commit

Permalink
rustfmt
Browse files Browse the repository at this point in the history
  • Loading branch information
wfraser committed Nov 25, 2023
1 parent b71e15f commit c9a6fb1
Show file tree
Hide file tree
Showing 8 changed files with 230 additions and 184 deletions.
68 changes: 43 additions & 25 deletions src/analysis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,14 @@ impl Analysis {
.arg("--target-dir")
.arg(Path::new("target").join(SUBDIR))
.arg("--workspace")
.env("RUSTDOCFLAGS", "-Zunstable-options \
.env(
"RUSTDOCFLAGS",
"-Zunstable-options \
--output-format=json \
--document-private-items \
--document-hidden-items \
")
",
)
.current_dir(workspace_path)
.status()
.context("failed to run 'cargo rustdoc'")?;
Expand All @@ -44,32 +47,39 @@ impl Analysis {
}

pub fn load(workspace_path: impl Into<PathBuf>) -> anyhow::Result<Self> {
let root: PathBuf = workspace_path.into().join("target").join(SUBDIR).join("doc");
let root: PathBuf = workspace_path
.into()
.join("target")
.join(SUBDIR)
.join("doc");
let mut paths = vec![];
for res in fs::read_dir(root)? {
let entry = res?;
if entry.file_name().as_encoded_bytes().ends_with(b".json") {
let path = entry.path();
let crate_name = path.file_stem().unwrap().to_str()
let crate_name = path
.file_stem()
.unwrap()
.to_str()
.ok_or_else(|| anyhow::anyhow!("{path:?} isn't utf-8"))?
.to_owned();
paths.push((crate_name, path));
}
}

let crates = paths.into_par_iter()
let crates = paths
.into_par_iter()
.map(|(crate_name, path)| {
println!("reading {path:?}");
let data: rustdoc_types::Crate = parse_json(&path)
.with_context(|| path.display().to_string())?;
let data = parse_json(&path).with_context(|| path.display().to_string())?;
Ok((crate_name, data))
})
.collect::<anyhow::Result<HashMap<_, _>>>()?;

Ok(Self { crates })
}

pub fn crate_ids(&self) -> impl Iterator<Item=CrateId> + '_ {
pub fn crate_ids(&self) -> impl Iterator<Item = CrateId> + '_ {
/*let mut ids = vec![];
for c in self.crates.values() {
Expand All @@ -87,24 +97,25 @@ impl Analysis {
ids.push(CrateId { name });
}*/

self.crates.values()
self.crates
.values()
.flat_map(|crate_| &crate_.index)
.filter_map(|(_id, item)| {
match &item.inner {
rustdoc_types::ItemEnum::Module(m) if m.is_crate && item.crate_id == 0 => {
let name = item.name.clone().expect("crate module should have a name");
Some(CrateId { name })
}
_ => None
.filter_map(|(_id, item)| match &item.inner {
rustdoc_types::ItemEnum::Module(m) if m.is_crate && item.crate_id == 0 => {
let name = item.name.clone().expect("crate module should have a name");
Some(CrateId { name })
}
_ => None,
})

//ids.into_iter()
}

pub fn items<'a>(&'a self, crate_id: &'a CrateId, parent_id: Option<Id>)
-> impl Iterator<Item = &'a rustdoc_types::Item> + 'a
{
pub fn items<'a>(
&'a self,
crate_id: &'a CrateId,
parent_id: Option<Id>,
) -> impl Iterator<Item = &'a rustdoc_types::Item> + 'a {
let parent_id = parent_id.unwrap_or(self.crates[&crate_id.name].root.clone());
let parent = &self.crates[&crate_id.name].index[&parent_id];

Expand All @@ -117,7 +128,9 @@ impl Analysis {
Struct(s) => {
let fields = match &s.kind {
rustdoc_types::StructKind::Unit => vec![],
rustdoc_types::StructKind::Tuple(t) => t.iter().filter_map(|x| x.as_ref()).cloned().collect(),
rustdoc_types::StructKind::Tuple(t) => {
t.iter().filter_map(|x| x.as_ref()).cloned().collect()
}
rustdoc_types::StructKind::Plain { fields, .. } => fields.clone(),
};
[&fields[..], &s.impls[..]].concat()
Expand All @@ -128,7 +141,7 @@ impl Analysis {
rustdoc_types::VariantKind::Plain => vec![],
rustdoc_types::VariantKind::Tuple(t) => {
t.iter().filter_map(|id| id.clone()).collect()
},
}
rustdoc_types::VariantKind::Struct { fields, .. } => fields.clone(),
},
Function(_) => vec![],
Expand All @@ -144,7 +157,7 @@ impl Analysis {
items.push(trait_.id.clone());
}
items
},
}
TypeAlias(_) => vec![],
OpaqueTy(_) => vec![],
Constant(_) => vec![],
Expand All @@ -157,7 +170,9 @@ impl Analysis {
AssocType { .. } => vec![],
};

self.crates[&crate_id.name].index.iter()
self.crates[&crate_id.name]
.index
.iter()
.filter_map(move |(id, item)| {
if children.contains(id) {
Some(item)
Expand Down Expand Up @@ -185,7 +200,8 @@ fn type_ids(ty: &rustdoc_types::Type) -> Vec<Id> {
Tuple(types) => types.iter().map(type_ids).flatten().collect(),
Slice(ty) => type_ids(ty),
Array { type_, .. } => type_ids(type_),
ImplTrait(generics) => generics.iter()
ImplTrait(generics) => generics
.iter()
.filter_map(|g| match g {
rustdoc_types::GenericBound::TraitBound { trait_, .. } => Some(trait_.id.clone()),
rustdoc_types::GenericBound::Outlives(_) => None,
Expand All @@ -194,7 +210,9 @@ fn type_ids(ty: &rustdoc_types::Type) -> Vec<Id> {
Infer => vec![],
RawPointer { type_, .. } => type_ids(type_),
BorrowedRef { type_, .. } => type_ids(type_),
QualifiedPath { self_type, trait_, .. } => {
QualifiedPath {
self_type, trait_, ..
} => {
let from_self = type_ids(&self_type);
if let Some(t) = trait_ {
[&from_self[..], &[t.id.clone()]].concat()
Expand Down
89 changes: 56 additions & 33 deletions src/browser_rustdoc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ pub struct RustdocBrowser {

impl RustdocBrowser {
pub fn new(analysis: Analysis) -> Self {
Self {
analysis,
}
Self { analysis }
}
}

Expand All @@ -19,7 +17,9 @@ impl Browser for RustdocBrowser {
type Item = Item;

fn list_crates(&self) -> Vec<(String, CrateId)> {
let mut crates = self.analysis.crate_ids()
let mut crates = self
.analysis
.crate_ids()
//.filter(|c| !self.analysis.stdlib_crates.contains(c))
.map(|c| (crate_label(&c), c))
.collect::<Vec<_>>();
Expand All @@ -34,14 +34,14 @@ impl Browser for RustdocBrowser {
Item::Item(item) => Some(item.id.clone()),
_ => None,
};

let mut items = self.analysis.items(crate_id, parent_id)

let mut items = self
.analysis
.items(crate_id, parent_id)
.filter(|item| {
// Remove the clutter of automatically derived, blanket, and synthetic trait impls.
use rustdoc_types::ItemEnum::*;
if item.attrs.iter()
.any(|a| a == "#[automatically_derived]")
{
if item.attrs.iter().any(|a| a == "#[automatically_derived]") {
return false;
}
match &item.inner {
Expand All @@ -65,9 +65,12 @@ impl Browser for RustdocBrowser {
txt.push('\n');
}
if let Some(span) = &item.span {
write!(txt, "defined in {:?}\nstarting on line {}",
span.filename,
span.begin.0).unwrap();
write!(
txt,
"defined in {:?}\nstarting on line {}",
span.filename, span.begin.0
)
.unwrap();
}
}
Item::Root => {
Expand Down Expand Up @@ -101,20 +104,15 @@ fn get_source_for_item(item: &rustdoc_types::Item) -> (String, usize) {
match File::open(&span.filename) {
Ok(f) => {
let mut txt = String::new();
for (i, line) in BufReader::new(f)
.lines()
.enumerate()
{
for (i, line) in BufReader::new(f).lines().enumerate() {
write!(txt, "{}: ", i + 1).unwrap();
txt += &line.unwrap_or_else(|e| format!("<Read Error: {e}>"));
txt.push('\n');
}
let line = span.begin.0 - 1;
(txt, line)
}
Err(e) => {
(format!("Error opening source: {e}"), 0)
}
Err(e) => (format!("Error opening source: {e}"), 0),
}
}

Expand Down Expand Up @@ -193,12 +191,23 @@ fn type_label(ty: &rustdoc_types::Type) -> String {
// TODO: needs to also include the generic params, otherwise
// something like Option<Box<dyn Error>> gets shown as just "Option".
p.name.clone()
},
DynTrait(dt) => "dyn ".to_owned() + &dt.traits.iter().map(|t| t.trait_.name.clone()).collect::<Vec<_>>().join(" + "),
}
DynTrait(dt) => {
"dyn ".to_owned()
+ &dt
.traits
.iter()
.map(|t| t.trait_.name.clone())
.collect::<Vec<_>>()
.join(" + ")
}
Generic(g) => g.to_owned(),
Primitive(p) => p.to_owned(),
FunctionPointer(fp) => {
let args = fp.decl.inputs.iter()
let args = fp
.decl
.inputs
.iter()
.map(|(name, ty)| format!("{name}: {}", type_label(ty)))
.collect::<Vec<_>>()
.join(", ");
Expand All @@ -207,14 +216,17 @@ fn type_label(ty: &rustdoc_types::Type) -> String {
None => String::new(),
};
format!("fn({args}){ret}")
},
Tuple(types) => format!("({})",
types.iter().map(type_label).collect::<Vec<_>>().join(", ")),
}
Tuple(types) => format!(
"({})",
types.iter().map(type_label).collect::<Vec<_>>().join(", ")
),
Slice(ty) => format!("&[{}]", type_label(ty)),
Array { type_, len } => format!("[{}; {len}]", type_label(type_)),
ImplTrait(t) => {
use rustdoc_types::GenericBound::*;
format!("impl {}",
format!(
"impl {}",
t.iter()
.map(|g| match g {
TraitBound { trait_, .. } => trait_.name.as_str(),
Expand All @@ -226,25 +238,36 @@ fn type_label(ty: &rustdoc_types::Type) -> String {
}
Infer => "_".to_owned(),
RawPointer { mutable, type_ } => {
format!("*{} {}",
format!(
"*{} {}",
if *mutable { "mut" } else { "const" },
type_label(type_),
)
},
BorrowedRef { lifetime, mutable, type_ } => {
format!("&{}{} {}",
}
BorrowedRef {
lifetime,
mutable,
type_,
} => {
format!(
"&{}{} {}",
lifetime.as_deref().unwrap_or_default(),
if *mutable { "mut" } else { "" },
type_label(type_),
)
},
QualifiedPath { name, args:_ , self_type, trait_ } => {
}
QualifiedPath {
name,
args: _,
self_type,
trait_,
} => {
if let Some(trait_) = trait_ {
format!("<{} as {}>::{name}", type_label(self_type), trait_.name)
} else {
format!("{}::{name}", type_label(self_type))
}
},
}
}
}

Expand Down
6 changes: 5 additions & 1 deletion src/browser_trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ pub trait Browser {
type CrateId: Clone;
type Item: Item + Clone;
fn list_crates(&self) -> Vec<(String, Self::CrateId)>;
fn list_items(&self, crate_id: &Self::CrateId, parent: &Self::Item) -> Vec<(String, Self::Item)>;
fn list_items(
&self,
crate_id: &Self::CrateId,
parent: &Self::Item,
) -> Vec<(String, Self::Item)>;
fn get_info(&self, crate_id: &Self::CrateId, item: &Self::Item) -> String;
fn get_debug_info(&self, crate_id: &Self::CrateId, item: &Self::Item) -> String;
fn get_source(&self, item: &Self::Item) -> (String, Option<usize>);
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
pub mod analysis;
pub mod browser_trait;
pub mod browser_rustdoc;
pub mod browser_trait;
pub mod scroll_pad;
pub mod ui;
14 changes: 8 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ struct Arguments {
}

fn usage() {
eprintln!("usage: {} <cargo workspace path>", std::env::args().next().unwrap());
eprintln!(
"usage: {} <cargo workspace path>",
std::env::args().next().unwrap()
);
}

fn parse_args() -> Option<Arguments> {
Expand Down Expand Up @@ -41,11 +44,10 @@ fn parse_args() -> Option<Arguments> {
}

fn main() {
let args = parse_args()
.unwrap_or_else(|| {
usage();
std::process::exit(1);
});
let args = parse_args().unwrap_or_else(|| {
usage();
std::process::exit(1);
});

eprintln!("Running Cargo to generate analysis data...");
Analysis::generate(&args.workspace_path, &args.compiler).unwrap();
Expand Down
2 changes: 1 addition & 1 deletion src/scroll_pad.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use cursive::Vec2;
use cursive::view::{View, ViewWrapper};
use cursive::Vec2;

/// Adds one unit of padding to the right side of any view that doesn't require scrolling.
/// This is used to prevent views from having text immediately adjacent to each other (which is
Expand Down
Loading

0 comments on commit c9a6fb1

Please sign in to comment.