Skip to content

Commit f1070b1

Browse files
Replace ToJson with serde
1 parent 15babed commit f1070b1

File tree

8 files changed

+51
-78
lines changed

8 files changed

+51
-78
lines changed

src/librustdoc/config.rs

+11-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::collections::BTreeMap;
2-
use std::ffi::OsStr;
32
use std::convert::TryFrom;
3+
use std::ffi::OsStr;
44
use std::fmt;
55
use std::path::PathBuf;
66

@@ -28,12 +28,12 @@ use crate::theme;
2828
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2929
pub enum OutputFormat {
3030
Json,
31-
HTML,
31+
Html,
3232
}
3333

3434
impl OutputFormat {
3535
pub fn is_json(&self) -> bool {
36-
match *self {
36+
match self {
3737
OutputFormat::Json => true,
3838
_ => false,
3939
}
@@ -46,7 +46,7 @@ impl TryFrom<&str> for OutputFormat {
4646
fn try_from(value: &str) -> Result<Self, Self::Error> {
4747
match value {
4848
"json" => Ok(OutputFormat::Json),
49-
"html" => Ok(OutputFormat::HTML),
49+
"html" => Ok(OutputFormat::Html),
5050
_ => Err(format!("unknown output format `{}`", value)),
5151
}
5252
}
@@ -498,14 +498,20 @@ impl Options {
498498
diag.struct_err("json output format isn't supported for doc generation")
499499
.emit();
500500
return Err(1);
501+
} else if !o.is_json() && show_coverage {
502+
diag.struct_err(
503+
"html output format isn't supported for the --show-coverage option",
504+
)
505+
.emit();
506+
return Err(1);
501507
}
502508
Some(o)
503509
}
504510
Err(e) => {
505511
diag.struct_err(&e).emit();
506512
return Err(1);
507513
}
508-
}
514+
},
509515
None => None,
510516
};
511517
let crate_name = matches.opt_str("crate-name");

src/librustdoc/passes/calculate_doc_coverage.rs

+26-64
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ use crate::passes::Pass;
77
use rustc_ast::attr;
88
use rustc_span::symbol::sym;
99
use rustc_span::FileName;
10-
use serialize::json::{ToJson, Json};
10+
use serde::Serialize;
11+
use serde_json;
1112

1213
use std::collections::BTreeMap;
1314
use std::ops;
@@ -18,16 +19,16 @@ pub const CALCULATE_DOC_COVERAGE: Pass = Pass {
1819
description: "counts the number of items with and without documentation",
1920
};
2021

21-
fn calculate_doc_coverage( krate: clean::Crate, ctx: &DocContext<'_>) -> clean::Crate {
22-
let mut calc = CoverageCalculator::new(ctx.renderinfo.borrow().output_format);
22+
fn calculate_doc_coverage(krate: clean::Crate, ctx: &DocContext<'_>) -> clean::Crate {
23+
let mut calc = CoverageCalculator::new();
2324
let krate = calc.fold_crate(krate);
2425

25-
calc.print_results();
26+
calc.print_results(ctx.renderinfo.borrow().output_format);
2627

2728
krate
2829
}
2930

30-
#[derive(Default, Copy, Clone)]
31+
#[derive(Default, Copy, Clone, Serialize)]
3132
struct ItemCount {
3233
total: u64,
3334
with_docs: u64,
@@ -68,68 +69,37 @@ impl ops::AddAssign for ItemCount {
6869

6970
struct CoverageCalculator {
7071
items: BTreeMap<FileName, ItemCount>,
71-
output_format: Option<OutputFormat>,
7272
}
7373

7474
fn limit_filename_len(filename: String) -> String {
75-
// if a filename is too long, shorten it so we don't blow out the table
76-
// FIXME(misdreavus): this needs to count graphemes, and probably also track
77-
// double-wide characters...
78-
if filename.len() > 35 {
79-
"...".to_string() + &filename[filename.len() - 32..]
75+
let nb_chars = filename.chars().count();
76+
if nb_chars > 35 {
77+
"...".to_string()
78+
+ &filename[filename.char_indices().nth(nb_chars - 32).map(|x| x.0).unwrap_or(0)..]
8079
} else {
8180
filename
8281
}
8382
}
8483

85-
impl ToJson for CoverageCalculator {
86-
fn to_json(&self) -> Json {
87-
let mut total = ItemCount::default();
88-
let mut entries = BTreeMap::default();
89-
90-
entries.insert("files".to_owned(), Json::Array(self.items
91-
.iter()
92-
.filter_map(|(file, &count)| {
93-
count.percentage().map(|percent| {
94-
(limit_filename_len(file.to_string()), count, percent)
95-
})
96-
})
97-
.map(|(name, count, percentage)| {
98-
let mut fields = BTreeMap::default();
99-
100-
fields.insert("documented".to_owned(), Json::U64(count.with_docs));
101-
fields.insert("total".to_owned(), Json::U64(count.total));
102-
fields.insert("percentage".to_owned(), Json::F64(percentage));
103-
104-
total += count;
105-
106-
let mut obj = BTreeMap::default();
107-
obj.insert(name, Json::Object(fields));
108-
109-
Json::Object(obj)
110-
})
111-
.collect::<Vec<_>>()));
112-
let mut fields = BTreeMap::default();
113-
fields.insert("documented".to_owned(), Json::U64(total.with_docs));
114-
fields.insert("total".to_owned(), Json::U64(total.total));
115-
fields.insert("percentage".to_owned(), Json::F64(total.percentage().unwrap_or(0.0)));
116-
117-
entries.insert("total".to_owned(), Json::Object(fields));
118-
Json::Object(entries)
84+
impl CoverageCalculator {
85+
fn new() -> CoverageCalculator {
86+
CoverageCalculator { items: Default::default() }
11987
}
120-
}
12188

122-
impl CoverageCalculator {
123-
fn new(output_format: Option<OutputFormat>) -> CoverageCalculator {
124-
CoverageCalculator {
125-
items: Default::default(),
126-
output_format,
127-
}
89+
fn to_json(&self) -> String {
90+
serde_json::to_string(
91+
&self
92+
.items
93+
.iter()
94+
.map(|(k, v)| (k.to_string(), v))
95+
.collect::<BTreeMap<String, &ItemCount>>(),
96+
)
97+
.expect("failed to convert JSON data to string")
12898
}
12999

130-
fn print_results(&self) {
131-
if self.output_format.map(|o| o.is_json()).unwrap_or_else(|| false) {
132-
println!("{}", self.to_json().pretty());
100+
fn print_results(&self, output_format: Option<OutputFormat>) {
101+
if output_format.map(|o| o.is_json()).unwrap_or_else(|| false) {
102+
println!("{}", self.to_json());
133103
return;
134104
}
135105
let mut total = ItemCount::default();
@@ -154,15 +124,7 @@ impl CoverageCalculator {
154124

155125
for (file, &count) in &self.items {
156126
if let Some(percentage) = count.percentage() {
157-
let mut name = file.to_string();
158-
// if a filename is too long, shorten it so we don't blow out the table
159-
// FIXME(misdreavus): this needs to count graphemes, and probably also track
160-
// double-wide characters...
161-
if name.len() > 35 {
162-
name = "...".to_string() + &name[name.len() - 32..];
163-
}
164-
165-
print_table_record(&name, count, percentage);
127+
print_table_record(&limit_filename_len(file.to_string()), count, percentage);
166128

167129
total += count;
168130
}

src/test/rustdoc-ui/coverage/html.rs

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// compile-flags:-Z unstable-options --output-format html --show-coverage
2+
3+
/// Foo
4+
pub struct Xo;
+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
error: html output format isn't supported for the --show-coverage option
2+

src/test/rustdoc-ui/coverage/json.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// build-pass
2-
// compile-flags:-Z unstable-options --show-coverage
2+
// compile-flags:-Z unstable-options --output-format json --show-coverage
33

44
pub mod foo {
55
/// Hello!
+1-7
Original file line numberDiff line numberDiff line change
@@ -1,7 +1 @@
1-
+-------------------------------------+------------+------------+------------+
2-
| File | Documented | Total | Percentage |
3-
+-------------------------------------+------------+------------+------------+
4-
| ...test/rustdoc-ui/coverage/json.rs | 7 | 13 | 53.8% |
5-
+-------------------------------------+------------+------------+------------+
6-
| Total | 7 | 13 | 53.8% |
7-
+-------------------------------------+------------+------------+------------+
1+
{"$DIR/json.rs":{"total":13,"with_docs":7}}
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
// compile-flags:-Z unstable-options --output-format
2-
// should-fail
32

43
/// toudoum!
54
pub struct SomeStruct;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
warning: the 'output-format' flag is considered deprecated
2+
|
3+
= warning: see issue #44136 <https://github.com/rust-lang/rust/issues/44136> for more information
4+
5+
error: too many file operands
6+

0 commit comments

Comments
 (0)