-
Notifications
You must be signed in to change notification settings - Fork 12.7k
/
format.rs
820 lines (766 loc) · 28.4 KB
/
format.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! HTML formatting module
//!
//! This module contains a large number of `fmt::Display` implementations for
//! various types in `rustdoc::clean`. These implementations all currently
//! assume that HTML output is desired, although it may be possible to redesign
//! them in the future to instead emit any format desired.
use std::fmt;
use std::iter::repeat;
use syntax::ast;
use syntax::ast_util;
use clean;
use stability_summary::ModuleSummary;
use html::item_type::ItemType;
use html::render;
use html::escape::Escape;
use html::render::{cache, CURRENT_LOCATION_KEY};
/// Helper to render an optional visibility with a space after it (if the
/// visibility is preset)
#[derive(Copy)]
pub struct VisSpace(pub Option<ast::Visibility>);
/// Similarly to VisSpace, this structure is used to render a function style with a
/// space after it.
#[derive(Copy)]
pub struct UnsafetySpace(pub ast::Unsafety);
/// Wrapper struct for properly emitting a method declaration.
pub struct Method<'a>(pub &'a clean::SelfTy, pub &'a clean::FnDecl);
/// Similar to VisSpace, but used for mutability
#[derive(Copy)]
pub struct MutableSpace(pub clean::Mutability);
/// Similar to VisSpace, but used for mutability
#[derive(Copy)]
pub struct RawMutableSpace(pub clean::Mutability);
/// Wrapper struct for properly emitting the stability level.
pub struct Stability<'a>(pub &'a Option<clean::Stability>);
/// Wrapper struct for emitting the stability level concisely.
pub struct ConciseStability<'a>(pub &'a Option<clean::Stability>);
/// Wrapper struct for emitting a where clause from Generics.
pub struct WhereClause<'a>(pub &'a clean::Generics);
/// Wrapper struct for emitting type parameter bounds.
pub struct TyParamBounds<'a>(pub &'a [clean::TyParamBound]);
/// Wrapper struct for emitting a comma-separated list of items
pub struct CommaSep<'a, T: 'a>(pub &'a [T]);
impl VisSpace {
pub fn get(&self) -> Option<ast::Visibility> {
let VisSpace(v) = *self; v
}
}
impl UnsafetySpace {
pub fn get(&self) -> ast::Unsafety {
let UnsafetySpace(v) = *self; v
}
}
impl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, item) in self.0.iter().enumerate() {
if i != 0 { try!(write!(f, ", ")); }
try!(write!(f, "{}", item));
}
Ok(())
}
}
impl<'a> fmt::Display for TyParamBounds<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let &TyParamBounds(bounds) = self;
for (i, bound) in bounds.iter().enumerate() {
if i > 0 {
try!(f.write_str(" + "));
}
try!(write!(f, "{}", *bound));
}
Ok(())
}
}
impl fmt::Display for clean::Generics {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.lifetimes.len() == 0 && self.type_params.len() == 0 { return Ok(()) }
try!(f.write_str("<"));
for (i, life) in self.lifetimes.iter().enumerate() {
if i > 0 {
try!(f.write_str(", "));
}
try!(write!(f, "{}", *life));
}
if self.type_params.len() > 0 {
if self.lifetimes.len() > 0 {
try!(f.write_str(", "));
}
for (i, tp) in self.type_params.iter().enumerate() {
if i > 0 {
try!(f.write_str(", "))
}
try!(f.write_str(&tp.name));
if tp.bounds.len() > 0 {
try!(write!(f, ": {}", TyParamBounds(&tp.bounds)));
}
match tp.default {
Some(ref ty) => { try!(write!(f, " = {}", ty)); },
None => {}
};
}
}
try!(f.write_str(">"));
Ok(())
}
}
impl<'a> fmt::Display for WhereClause<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let &WhereClause(gens) = self;
if gens.where_predicates.len() == 0 {
return Ok(());
}
try!(f.write_str(" <span class='where'>where "));
for (i, pred) in gens.where_predicates.iter().enumerate() {
if i > 0 {
try!(f.write_str(", "));
}
match pred {
&clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
let bounds = bounds;
try!(write!(f, "{}: {}", ty, TyParamBounds(bounds)));
}
&clean::WherePredicate::RegionPredicate { ref lifetime,
ref bounds } => {
try!(write!(f, "{}: ", lifetime));
for (i, lifetime) in bounds.iter().enumerate() {
if i > 0 {
try!(f.write_str(" + "));
}
try!(write!(f, "{}", lifetime));
}
}
&clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
try!(write!(f, "{} == {}", lhs, rhs));
}
}
}
try!(f.write_str("</span>"));
Ok(())
}
}
impl fmt::Display for clean::Lifetime {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(f.write_str(self.get_ref()));
Ok(())
}
}
impl fmt::Display for clean::PolyTrait {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.lifetimes.len() > 0 {
try!(f.write_str("for<"));
for (i, lt) in self.lifetimes.iter().enumerate() {
if i > 0 {
try!(f.write_str(", "));
}
try!(write!(f, "{}", lt));
}
try!(f.write_str("> "));
}
write!(f, "{}", self.trait_)
}
}
impl fmt::Display for clean::TyParamBound {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
clean::RegionBound(ref lt) => {
write!(f, "{}", *lt)
}
clean::TraitBound(ref ty, modifier) => {
let modifier_str = match modifier {
ast::TraitBoundModifier::None => "",
ast::TraitBoundModifier::Maybe => "?",
};
write!(f, "{}{}", modifier_str, *ty)
}
}
}
}
impl fmt::Display for clean::PathParameters {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
clean::PathParameters::AngleBracketed {
ref lifetimes, ref types, ref bindings
} => {
if lifetimes.len() > 0 || types.len() > 0 || bindings.len() > 0 {
try!(f.write_str("<"));
let mut comma = false;
for lifetime in lifetimes {
if comma {
try!(f.write_str(", "));
}
comma = true;
try!(write!(f, "{}", *lifetime));
}
for ty in types {
if comma {
try!(f.write_str(", "));
}
comma = true;
try!(write!(f, "{}", *ty));
}
for binding in bindings {
if comma {
try!(f.write_str(", "));
}
comma = true;
try!(write!(f, "{}", *binding));
}
try!(f.write_str(">"));
}
}
clean::PathParameters::Parenthesized { ref inputs, ref output } => {
try!(f.write_str("("));
let mut comma = false;
for ty in inputs {
if comma {
try!(f.write_str(", "));
}
comma = true;
try!(write!(f, "{}", *ty));
}
try!(f.write_str(")"));
if let Some(ref ty) = *output {
try!(f.write_str(" -> "));
try!(write!(f, "{}", ty));
}
}
}
Ok(())
}
}
impl fmt::Display for clean::PathSegment {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(f.write_str(&self.name));
write!(f, "{}", self.params)
}
}
impl fmt::Display for clean::Path {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.global {
try!(f.write_str("::"))
}
for (i, seg) in self.segments.iter().enumerate() {
if i > 0 {
try!(f.write_str("::"))
}
try!(write!(f, "{}", seg));
}
Ok(())
}
}
/// Used when rendering a `ResolvedPath` structure. This invokes the `path`
/// rendering function with the necessary arguments for linking to a local path.
fn resolved_path(w: &mut fmt::Formatter, did: ast::DefId, p: &clean::Path,
print_all: bool) -> fmt::Result {
path(w, p, print_all,
|cache, loc| {
if ast_util::is_local(did) || cache.inlined.contains(&did) {
Some(repeat("../").take(loc.len()).collect::<String>())
} else {
match cache.extern_locations[&did.krate] {
render::Remote(ref s) => Some(s.to_string()),
render::Local => {
Some(repeat("../").take(loc.len()).collect::<String>())
}
render::Unknown => None,
}
}
},
|cache| {
match cache.paths.get(&did) {
None => None,
Some(&(ref fqp, shortty)) => Some((fqp.clone(), shortty))
}
})
}
fn path<F, G>(w: &mut fmt::Formatter,
path: &clean::Path,
print_all: bool,
root: F,
info: G)
-> fmt::Result where
F: FnOnce(&render::Cache, &[String]) -> Option<String>,
G: FnOnce(&render::Cache) -> Option<(Vec<String>, ItemType)>,
{
// The generics will get written to both the title and link
let last = path.segments.last().unwrap();
let generics = format!("{}", last.params);
let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
let cache = cache();
let abs_root = root(&*cache, &loc);
let rel_root = match &*path.segments[0].name {
"self" => Some("./".to_string()),
_ => None,
};
if print_all {
let amt = path.segments.len() - 1;
match rel_root {
Some(root) => {
let mut root = String::from_str(&root);
for seg in &path.segments[..amt] {
if "super" == seg.name ||
"self" == seg.name {
try!(write!(w, "{}::", seg.name));
} else {
root.push_str(&seg.name);
root.push_str("/");
try!(write!(w, "<a class='mod'
href='{}index.html'>{}</a>::",
root,
seg.name));
}
}
}
None => {
for seg in &path.segments[..amt] {
try!(write!(w, "{}::", seg.name));
}
}
}
}
match info(&*cache) {
// This is a documented path, link to it!
Some((ref fqp, shortty)) if abs_root.is_some() => {
let mut url = String::from_str(&abs_root.unwrap());
let to_link = &fqp[..fqp.len() - 1];
for component in to_link {
url.push_str(component);
url.push_str("/");
}
match shortty {
ItemType::Module => {
url.push_str(fqp.last().unwrap());
url.push_str("/index.html");
}
_ => {
url.push_str(shortty.to_static_str());
url.push_str(".");
url.push_str(fqp.last().unwrap());
url.push_str(".html");
}
}
try!(write!(w, "<a class='{}' href='{}' title='{}'>{}</a>",
shortty, url, fqp.connect("::"), last.name));
}
_ => {
try!(write!(w, "{}", last.name));
}
}
try!(write!(w, "{}", generics));
Ok(())
}
fn primitive_link(f: &mut fmt::Formatter,
prim: clean::PrimitiveType,
name: &str) -> fmt::Result {
let m = cache();
let mut needs_termination = false;
match m.primitive_locations.get(&prim) {
Some(&ast::LOCAL_CRATE) => {
let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
let len = if len == 0 {0} else {len - 1};
try!(write!(f, "<a href='{}primitive.{}.html'>",
repeat("../").take(len).collect::<String>(),
prim.to_url_str()));
needs_termination = true;
}
Some(&cnum) => {
let path = &m.paths[&ast::DefId {
krate: cnum,
node: ast::CRATE_NODE_ID,
}];
let loc = match m.extern_locations[&cnum] {
render::Remote(ref s) => Some(s.to_string()),
render::Local => {
let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
Some(repeat("../").take(len).collect::<String>())
}
render::Unknown => None,
};
match loc {
Some(root) => {
try!(write!(f, "<a href='{}{}/primitive.{}.html'>",
root,
path.0.first().unwrap(),
prim.to_url_str()));
needs_termination = true;
}
None => {}
}
}
None => {}
}
try!(write!(f, "{}", name));
if needs_termination {
try!(write!(f, "</a>"));
}
Ok(())
}
/// Helper to render type parameters
fn tybounds(w: &mut fmt::Formatter,
typarams: &Option<Vec<clean::TyParamBound> >) -> fmt::Result {
match *typarams {
Some(ref params) => {
for param in params {
try!(write!(w, " + "));
try!(write!(w, "{}", *param));
}
Ok(())
}
None => Ok(())
}
}
impl fmt::Display for clean::Type {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
clean::Generic(ref name) => {
f.write_str(name)
}
clean::ResolvedPath{ did, ref typarams, ref path } => {
// Paths like Self::Output should be rendered with all segments
try!(resolved_path(f, did, path, path.segments[0].name == "Self"));
tybounds(f, typarams)
}
clean::Infer => write!(f, "_"),
clean::Primitive(prim) => primitive_link(f, prim, prim.to_string()),
clean::BareFunction(ref decl) => {
write!(f, "{}{}fn{}{}",
UnsafetySpace(decl.unsafety),
match &*decl.abi {
"" => " extern ".to_string(),
"\"Rust\"" => "".to_string(),
s => format!(" extern {} ", s)
},
decl.generics,
decl.decl)
}
clean::Tuple(ref typs) => {
primitive_link(f, clean::PrimitiveTuple,
&*match &**typs {
[ref one] => format!("({},)", one),
many => format!("({})", CommaSep(&many)),
})
}
clean::Vector(ref t) => {
primitive_link(f, clean::Slice, &format!("[{}]", **t))
}
clean::FixedVector(ref t, ref s) => {
primitive_link(f, clean::PrimitiveType::Array,
&format!("[{}; {}]", **t, *s))
}
clean::Bottom => f.write_str("!"),
clean::RawPointer(m, ref t) => {
write!(f, "*{}{}", RawMutableSpace(m), **t)
}
clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
let lt = match *l {
Some(ref l) => format!("{} ", *l),
_ => "".to_string(),
};
let m = MutableSpace(mutability);
match **ty {
clean::Vector(ref bt) => { // BorrowedRef{ ... Vector(T) } is &[T]
match **bt {
clean::Generic(_) =>
primitive_link(f, clean::Slice,
&format!("&{}{}[{}]", lt, m, **bt)),
_ => {
try!(primitive_link(f, clean::Slice,
&format!("&{}{}[", lt, m)));
try!(write!(f, "{}", **bt));
primitive_link(f, clean::Slice, "]")
}
}
}
_ => {
write!(f, "&{}{}{}", lt, m, **ty)
}
}
}
clean::PolyTraitRef(ref bounds) => {
for (i, bound) in bounds.iter().enumerate() {
if i != 0 {
try!(write!(f, " + "));
}
try!(write!(f, "{}", *bound));
}
Ok(())
}
clean::QPath { ref name, ref self_type, ref trait_ } => {
write!(f, "<{} as {}>::{}", self_type, trait_, name)
}
clean::Unique(..) => {
panic!("should have been cleaned")
}
}
}
}
impl fmt::Display for clean::Arguments {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, input) in self.values.iter().enumerate() {
if i > 0 { try!(write!(f, ", ")); }
if input.name.len() > 0 {
try!(write!(f, "{}: ", input.name));
}
try!(write!(f, "{}", input.type_));
}
Ok(())
}
}
impl fmt::Display for clean::FunctionRetTy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()),
clean::Return(ref ty) => write!(f, " -> {}", ty),
clean::DefaultReturn => Ok(()),
clean::NoReturn => write!(f, " -> !")
}
}
}
impl fmt::Display for clean::FnDecl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output)
}
}
impl<'a> fmt::Display for Method<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Method(selfty, d) = *self;
let mut args = String::new();
match *selfty {
clean::SelfStatic => {},
clean::SelfValue => args.push_str("self"),
clean::SelfBorrowed(Some(ref lt), mtbl) => {
args.push_str(&format!("&{} {}self", *lt, MutableSpace(mtbl)));
}
clean::SelfBorrowed(None, mtbl) => {
args.push_str(&format!("&{}self", MutableSpace(mtbl)));
}
clean::SelfExplicit(ref typ) => {
args.push_str(&format!("self: {}", *typ));
}
}
for (i, input) in d.inputs.values.iter().enumerate() {
if i > 0 || args.len() > 0 { args.push_str(", "); }
if input.name.len() > 0 {
args.push_str(&format!("{}: ", input.name));
}
args.push_str(&format!("{}", input.type_));
}
write!(f, "({args}){arrow}", args = args, arrow = d.output)
}
}
impl fmt::Display for VisSpace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.get() {
Some(ast::Public) => write!(f, "pub "),
Some(ast::Inherited) | None => Ok(())
}
}
}
impl fmt::Display for UnsafetySpace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.get() {
ast::Unsafety::Unsafe => write!(f, "unsafe "),
ast::Unsafety::Normal => Ok(())
}
}
}
impl fmt::Display for clean::Import {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
clean::SimpleImport(ref name, ref src) => {
if *name == src.path.segments.last().unwrap().name {
write!(f, "use {};", *src)
} else {
write!(f, "use {} as {};", *src, *name)
}
}
clean::GlobImport(ref src) => {
write!(f, "use {}::*;", *src)
}
clean::ImportList(ref src, ref names) => {
try!(write!(f, "use {}::{{", *src));
for (i, n) in names.iter().enumerate() {
if i > 0 {
try!(write!(f, ", "));
}
try!(write!(f, "{}", *n));
}
write!(f, "}};")
}
}
}
}
impl fmt::Display for clean::ImportSource {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.did {
Some(did) => resolved_path(f, did, &self.path, true),
_ => {
for (i, seg) in self.path.segments.iter().enumerate() {
if i > 0 {
try!(write!(f, "::"))
}
try!(write!(f, "{}", seg.name));
}
Ok(())
}
}
}
}
impl fmt::Display for clean::ViewListIdent {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.source {
Some(did) => {
let path = clean::Path {
global: false,
segments: vec!(clean::PathSegment {
name: self.name.clone(),
params: clean::PathParameters::AngleBracketed {
lifetimes: Vec::new(),
types: Vec::new(),
bindings: Vec::new()
}
})
};
resolved_path(f, did, &path, false)
}
_ => write!(f, "{}", self.name),
}
}
}
impl fmt::Display for clean::TypeBinding {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}={}", self.name, self.ty)
}
}
impl fmt::Display for MutableSpace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
MutableSpace(clean::Immutable) => Ok(()),
MutableSpace(clean::Mutable) => write!(f, "mut "),
}
}
}
impl fmt::Display for RawMutableSpace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
RawMutableSpace(clean::Immutable) => write!(f, "const "),
RawMutableSpace(clean::Mutable) => write!(f, "mut "),
}
}
}
impl<'a> fmt::Display for Stability<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Stability(stab) = *self;
match *stab {
Some(ref stability) => {
let lvl = if stability.deprecated_since.is_empty() {
format!("{}", stability.level)
} else {
"Deprecated".to_string()
};
write!(f, "<a class='stability {lvl}' title='{reason}'>{lvl}</a>",
lvl = Escape(&*lvl),
reason = Escape(&*stability.reason))
}
None => Ok(())
}
}
}
impl<'a> fmt::Display for ConciseStability<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let ConciseStability(stab) = *self;
match *stab {
Some(ref stability) => {
let lvl = if stability.deprecated_since.is_empty() {
format!("{}", stability.level)
} else {
"Deprecated".to_string()
};
write!(f, "<a class='stability {lvl}' title='{lvl}{colon}{reason}'></a>",
lvl = Escape(&*lvl),
colon = if stability.reason.len() > 0 { ": " } else { "" },
reason = Escape(&*stability.reason))
}
None => {
write!(f, "<a class='stability Unmarked' title='No stability level'></a>")
}
}
}
}
impl fmt::Display for ModuleSummary {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fn fmt_inner<'a>(f: &mut fmt::Formatter,
context: &mut Vec<&'a str>,
m: &'a ModuleSummary)
-> fmt::Result {
let cnt = m.counts;
let tot = cnt.total();
if tot == 0 { return Ok(()) }
context.push(&m.name);
let path = context.connect("::");
try!(write!(f, "<tr>"));
try!(write!(f, "<td><a href='{}'>{}</a></td>", {
let mut url = context[1..].to_vec();
url.push("index.html");
url.connect("/")
},
path));
try!(write!(f, "<td class='summary-column'>"));
try!(write!(f, "<span class='summary Stable' \
style='width: {:.4}%; display: inline-block'> </span>",
(100 * cnt.stable) as f64/tot as f64));
try!(write!(f, "<span class='summary Unstable' \
style='width: {:.4}%; display: inline-block'> </span>",
(100 * cnt.unstable) as f64/tot as f64));
try!(write!(f, "<span class='summary Deprecated' \
style='width: {:.4}%; display: inline-block'> </span>",
(100 * cnt.deprecated) as f64/tot as f64));
try!(write!(f, "<span class='summary Unmarked' \
style='width: {:.4}%; display: inline-block'> </span>",
(100 * cnt.unmarked) as f64/tot as f64));
try!(write!(f, "</td></tr>"));
for submodule in &m.submodules {
try!(fmt_inner(f, context, submodule));
}
context.pop();
Ok(())
}
let mut context = Vec::new();
let tot = self.counts.total();
let (stable, unstable, deprecated, unmarked) = if tot == 0 {
(0, 0, 0, 0)
} else {
((100 * self.counts.stable)/tot,
(100 * self.counts.unstable)/tot,
(100 * self.counts.deprecated)/tot,
(100 * self.counts.unmarked)/tot)
};
try!(write!(f,
r"<h1 class='fqn'>Stability dashboard: crate <a class='mod' href='index.html'>{name}</a></h1>
This dashboard summarizes the stability levels for all of the public modules of
the crate, according to the total number of items at each level in the module and
its children (percentages total for {name}):
<blockquote>
<a class='stability Stable'></a> stable ({}%),<br/>
<a class='stability Unstable'></a> unstable ({}%),<br/>
<a class='stability Deprecated'></a> deprecated ({}%),<br/>
<a class='stability Unmarked'></a> unmarked ({}%)
</blockquote>
The counts do not include methods or trait
implementations that are visible only through a re-exported type.",
stable, unstable, deprecated, unmarked,
name=self.name));
try!(write!(f, "<table>"));
try!(fmt_inner(f, &mut context, self));
write!(f, "</table>")
}
}