Skip to content

Commit 703c82e

Browse files
committed
Auto merge of #62359 - euclio:remove-serialize, r=Dylan-DPC
replace serialize with serde in rustdoc This is a slightly less aggressive version of #61028. r? @GuillaumeGomez
2 parents 3964a55 + 94630d4 commit 703c82e

File tree

6 files changed

+125
-69
lines changed

6 files changed

+125
-69
lines changed

Cargo.lock

+2
Original file line numberDiff line numberDiff line change
@@ -3946,6 +3946,8 @@ dependencies = [
39463946
"minifier",
39473947
"pulldown-cmark 0.5.3",
39483948
"rustc-rayon",
3949+
"serde",
3950+
"serde_json",
39493951
"tempfile",
39503952
]
39513953

src/librustdoc/Cargo.toml

+2
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,6 @@ path = "lib.rs"
1212
pulldown-cmark = { version = "0.5.3", default-features = false }
1313
minifier = "0.0.33"
1414
rayon = { version = "0.3.0", package = "rustc-rayon" }
15+
serde = { version = "1.0", features = ["derive"] }
16+
serde_json = "1.0"
1517
tempfile = "3"

src/librustdoc/html/item_type.rs

+12
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
//! Item types.
22
33
use std::fmt;
4+
5+
use serde::{Serialize, Serializer};
6+
47
use syntax_pos::hygiene::MacroKind;
8+
59
use crate::clean;
610

711
/// Item type. Corresponds to `clean::ItemEnum` variants.
@@ -45,6 +49,14 @@ pub enum ItemType {
4549
TraitAlias = 25,
4650
}
4751

52+
impl Serialize for ItemType {
53+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
54+
where
55+
S: Serializer,
56+
{
57+
(*self as u8).serialize(serializer)
58+
}
59+
}
4860

4961
impl<'a> From<&'a clean::Item> for ItemType {
5062
fn from(item: &'a clean::Item) -> ItemType {

src/librustdoc/html/render.rs

+86-57
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ use std::cmp::Ordering;
3131
use std::collections::{BTreeMap, VecDeque};
3232
use std::default::Default;
3333
use std::error;
34-
use std::fmt::{self, Formatter, Write as FmtWrite};
34+
35+
use std::fmt::{self, Formatter, Write};
3536
use std::ffi::OsStr;
3637
use std::fs::{self, File};
3738
use std::io::prelude::*;
@@ -42,7 +43,8 @@ use std::sync::Arc;
4243
use std::rc::Rc;
4344

4445
use errors;
45-
use serialize::json::{ToJson, Json, as_json};
46+
use serde::{Serialize, Serializer};
47+
use serde::ser::SerializeSeq;
4648
use syntax::ast;
4749
use syntax::edition::Edition;
4850
use syntax::print::pprust;
@@ -303,19 +305,22 @@ struct IndexItem {
303305
search_type: Option<IndexItemFunctionType>,
304306
}
305307

306-
impl ToJson for IndexItem {
307-
fn to_json(&self) -> Json {
308+
impl Serialize for IndexItem {
309+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
310+
where
311+
S: Serializer,
312+
{
308313
assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
309314

310-
let mut data = Vec::with_capacity(6);
311-
data.push((self.ty as usize).to_json());
312-
data.push(self.name.to_json());
313-
data.push(self.path.to_json());
314-
data.push(self.desc.to_json());
315-
data.push(self.parent_idx.to_json());
316-
data.push(self.search_type.to_json());
317-
318-
Json::Array(data)
315+
(
316+
self.ty,
317+
&self.name,
318+
&self.path,
319+
&self.desc,
320+
self.parent_idx,
321+
&self.search_type,
322+
)
323+
.serialize(serializer)
319324
}
320325
}
321326

@@ -326,18 +331,20 @@ struct Type {
326331
generics: Option<Vec<String>>,
327332
}
328333

329-
impl ToJson for Type {
330-
fn to_json(&self) -> Json {
331-
match self.name {
332-
Some(ref name) => {
333-
let mut data = Vec::with_capacity(2);
334-
data.push(name.to_json());
335-
if let Some(ref generics) = self.generics {
336-
data.push(generics.to_json());
337-
}
338-
Json::Array(data)
334+
impl Serialize for Type {
335+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
336+
where
337+
S: Serializer,
338+
{
339+
if let Some(name) = &self.name {
340+
let mut seq = serializer.serialize_seq(None)?;
341+
seq.serialize_element(&name)?;
342+
if let Some(generics) = &self.generics {
343+
seq.serialize_element(&generics)?;
339344
}
340-
None => Json::Null,
345+
seq.end()
346+
} else {
347+
serializer.serialize_none()
341348
}
342349
}
343350
}
@@ -349,26 +356,29 @@ struct IndexItemFunctionType {
349356
output: Option<Vec<Type>>,
350357
}
351358

352-
impl ToJson for IndexItemFunctionType {
353-
fn to_json(&self) -> Json {
359+
impl Serialize for IndexItemFunctionType {
360+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
361+
where
362+
S: Serializer,
363+
{
354364
// If we couldn't figure out a type, just write `null`.
355365
let mut iter = self.inputs.iter();
356366
if match self.output {
357367
Some(ref output) => iter.chain(output.iter()).any(|ref i| i.name.is_none()),
358368
None => iter.any(|ref i| i.name.is_none()),
359369
} {
360-
Json::Null
370+
serializer.serialize_none()
361371
} else {
362-
let mut data = Vec::with_capacity(2);
363-
data.push(self.inputs.to_json());
364-
if let Some(ref output) = self.output {
372+
let mut seq = serializer.serialize_seq(None)?;
373+
seq.serialize_element(&self.inputs)?;
374+
if let Some(output) = &self.output {
365375
if output.len() > 1 {
366-
data.push(output.to_json());
376+
seq.serialize_element(&output)?;
367377
} else {
368-
data.push(output[0].to_json());
378+
seq.serialize_element(&output[0])?;
369379
}
370380
}
371-
Json::Array(data)
381+
seq.end()
372382
}
373383
}
374384
}
@@ -596,7 +606,7 @@ fn write_shared(
596606
// To avoid theme switch latencies as much as possible, we put everything theme related
597607
// at the beginning of the html files into another js file.
598608
let theme_js = format!(
599-
r#"var themes = document.getElementById("theme-choices");
609+
r#"var themes = document.getElementById("theme-choices");
600610
var themePicker = document.getElementById("theme-picker");
601611
602612
function showThemeButtonState() {{
@@ -642,8 +652,8 @@ themePicker.onblur = handleThemeButtonsBlur;
642652
}};
643653
but.onblur = handleThemeButtonsBlur;
644654
themes.appendChild(but);
645-
}});"#,
646-
as_json(&themes));
655+
}});"#, serde_json::to_string(&themes).unwrap());
656+
647657
write_minify(&cx.shared.fs, cx.path("theme.js"),
648658
&theme_js,
649659
options.enable_minification)?;
@@ -932,32 +942,48 @@ themePicker.onblur = handleThemeButtonsBlur;
932942
}
933943
};
934944

935-
let mut have_impls = false;
936-
let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
937-
for imp in imps {
938-
// If the trait and implementation are in the same crate, then
939-
// there's no need to emit information about it (there's inlining
940-
// going on). If they're in different crates then the crate defining
941-
// the trait will be interested in our implementation.
942-
if imp.impl_item.def_id.krate == did.krate { continue }
943-
// If the implementation is from another crate then that crate
944-
// should add it.
945-
if !imp.impl_item.def_id.is_local() { continue }
946-
have_impls = true;
947-
write!(implementors, "{{text:{},synthetic:{},types:{}}},",
948-
as_json(&imp.inner_impl().print().to_string()),
949-
imp.inner_impl().synthetic,
950-
as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
945+
#[derive(Serialize)]
946+
struct Implementor {
947+
text: String,
948+
synthetic: bool,
949+
types: Vec<String>,
951950
}
952-
implementors.push_str("];");
951+
952+
let implementors = imps
953+
.iter()
954+
.filter_map(|imp| {
955+
// If the trait and implementation are in the same crate, then
956+
// there's no need to emit information about it (there's inlining
957+
// going on). If they're in different crates then the crate defining
958+
// the trait will be interested in our implementation.
959+
//
960+
// If the implementation is from another crate then that crate
961+
// should add it.
962+
if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
963+
None
964+
} else {
965+
Some(Implementor {
966+
text: imp.inner_impl().print().to_string(),
967+
synthetic: imp.inner_impl().synthetic,
968+
types: collect_paths_for_type(imp.inner_impl().for_.clone()),
969+
})
970+
}
971+
})
972+
.collect::<Vec<_>>();
953973

954974
// Only create a js file if we have impls to add to it. If the trait is
955975
// documented locally though we always create the file to avoid dead
956976
// links.
957-
if !have_impls && !cx.cache.paths.contains_key(&did) {
977+
if implementors.is_empty() && !cx.cache.paths.contains_key(&did) {
958978
continue;
959979
}
960980

981+
let implementors = format!(
982+
r#"implementors["{}"] = {};"#,
983+
krate.name,
984+
serde_json::to_string(&implementors).unwrap()
985+
);
986+
961987
let mut mydst = dst.clone();
962988
for part in &remote_path[..remote_path.len() - 1] {
963989
mydst.push(part);
@@ -1456,7 +1482,7 @@ impl Context {
14561482
if !self.render_redirect_pages {
14571483
let items = self.build_sidebar_items(&m);
14581484
let js_dst = self.dst.join("sidebar-items.js");
1459-
let v = format!("initSidebarItems({});", as_json(&items));
1485+
let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
14601486
scx.fs.write(&js_dst, &v)?;
14611487
}
14621488

@@ -2558,8 +2584,11 @@ fn item_trait(
25582584
write_loading_content(w, "</div>");
25592585
}
25602586
}
2561-
write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2562-
as_json(&synthetic_types));
2587+
write!(
2588+
w,
2589+
r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2590+
serde_json::to_string(&synthetic_types).unwrap(),
2591+
);
25632592

25642593
write!(w, r#"<script type="text/javascript" async
25652594
src="{root_path}/implementors/{path}/{ty}.{name}.js">

src/librustdoc/html/render/cache.rs

+23-11
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ use std::path::{Path, PathBuf};
88
use std::collections::BTreeMap;
99
use syntax::source_map::FileName;
1010
use syntax::symbol::sym;
11-
use serialize::json::{ToJson, Json, as_json};
11+
12+
use serde::Serialize;
1213

1314
use super::{ItemType, IndexItem, IndexItemFunctionType, Impl, shorten, plain_summary_line};
1415
use super::{Type, RenderInfo};
@@ -544,7 +545,7 @@ fn extern_location(e: &clean::ExternalCrate, extern_url: Option<&str>, dst: &Pat
544545
fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
545546
let mut nodeid_to_pathid = FxHashMap::default();
546547
let mut crate_items = Vec::with_capacity(cache.search_index.len());
547-
let mut crate_paths = Vec::<Json>::new();
548+
let mut crate_paths = vec![];
548549

549550
let Cache { ref mut search_index,
550551
ref orphan_impl_items,
@@ -581,7 +582,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
581582
lastpathid += 1;
582583

583584
let &(ref fqp, short) = paths.get(&nodeid).unwrap();
584-
crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
585+
crate_paths.push((short, fqp.last().unwrap().clone()));
585586
pathid
586587
}
587588
});
@@ -592,22 +593,33 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
592593
} else {
593594
lastpath = item.path.clone();
594595
}
595-
crate_items.push(item.to_json());
596+
crate_items.push(&*item);
596597
}
597598

598599
let crate_doc = krate.module.as_ref().map(|module| {
599600
shorten(plain_summary_line(module.doc_value()))
600601
}).unwrap_or(String::new());
601602

602-
let mut crate_data = BTreeMap::new();
603-
crate_data.insert("doc".to_owned(), Json::String(crate_doc));
604-
crate_data.insert("i".to_owned(), Json::Array(crate_items));
605-
crate_data.insert("p".to_owned(), Json::Array(crate_paths));
603+
#[derive(Serialize)]
604+
struct CrateData<'a> {
605+
doc: String,
606+
#[serde(rename = "i")]
607+
items: Vec<&'a IndexItem>,
608+
#[serde(rename = "p")]
609+
paths: Vec<(ItemType, String)>,
610+
}
606611

607612
// Collect the index into a string
608-
format!("searchIndex[{}] = {};",
609-
as_json(&krate.name),
610-
Json::Object(crate_data))
613+
format!(
614+
r#"searchIndex["{}"] = {};"#,
615+
krate.name,
616+
serde_json::to_string(&CrateData {
617+
doc: crate_doc,
618+
items: crate_items,
619+
paths: crate_paths,
620+
})
621+
.unwrap()
622+
)
611623
}
612624

613625
fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {

src/librustdoc/lib.rs

-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ extern crate rustc_parse;
3535
extern crate rustc_target;
3636
extern crate rustc_typeck;
3737
extern crate rustc_lexer;
38-
extern crate serialize;
3938
extern crate syntax;
4039
extern crate syntax_expand;
4140
extern crate syntax_pos;

0 commit comments

Comments
 (0)