forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpprust.rs
2422 lines (2238 loc) · 86.3 KB
/
pprust.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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012 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.
use abi;
use ast::{P, RegionTyParamBound, TraitTyParamBound, Required, Provided};
use ast;
use ast_util;
use owned_slice::OwnedSlice;
use attr::{AttrMetaMethods, AttributeMethods};
use codemap::{CodeMap, BytePos};
use codemap;
use diagnostic;
use parse::classify::expr_is_simple_block;
use parse::token::IdentInterner;
use parse::{comments, token};
use parse;
use print::pp::{break_offset, word, space, zerobreak, hardbreak};
use print::pp::{Breaks, Consistent, Inconsistent, eof};
use print::pp;
use std::cast;
use std::char;
use std::io::{IoResult, MemWriter};
use std::io;
use std::rc::Rc;
use std::str;
use std::strbuf::StrBuf;
pub enum AnnNode<'a> {
NodeBlock(&'a ast::Block),
NodeItem(&'a ast::Item),
NodeExpr(&'a ast::Expr),
NodePat(&'a ast::Pat),
}
pub trait PpAnn {
fn pre(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
fn post(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
}
pub struct NoAnn;
impl PpAnn for NoAnn {}
pub struct CurrentCommentAndLiteral {
cur_cmnt: uint,
cur_lit: uint,
}
pub struct State<'a> {
pub s: pp::Printer,
cm: Option<&'a CodeMap>,
intr: Rc<token::IdentInterner>,
comments: Option<Vec<comments::Comment> >,
literals: Option<Vec<comments::Literal> >,
cur_cmnt_and_lit: CurrentCommentAndLiteral,
boxes: Vec<pp::Breaks>,
ann: &'a PpAnn
}
pub fn rust_printer(writer: ~io::Writer) -> State<'static> {
static NO_ANN: NoAnn = NoAnn;
rust_printer_annotated(writer, &NO_ANN)
}
pub fn rust_printer_annotated<'a>(writer: ~io::Writer,
ann: &'a PpAnn) -> State<'a> {
State {
s: pp::mk_printer(writer, default_columns),
cm: None,
intr: token::get_ident_interner(),
comments: None,
literals: None,
cur_cmnt_and_lit: CurrentCommentAndLiteral {
cur_cmnt: 0,
cur_lit: 0
},
boxes: Vec::new(),
ann: ann
}
}
pub static indent_unit: uint = 4u;
pub static default_columns: uint = 78u;
// Requires you to pass an input filename and reader so that
// it can scan the input text for comments and literals to
// copy forward.
pub fn print_crate<'a>(cm: &'a CodeMap,
span_diagnostic: &diagnostic::SpanHandler,
krate: &ast::Crate,
filename: ~str,
input: &mut io::Reader,
out: ~io::Writer,
ann: &'a PpAnn,
is_expanded: bool) -> IoResult<()> {
let (cmnts, lits) = comments::gather_comments_and_literals(
span_diagnostic,
filename,
input
);
let mut s = State {
s: pp::mk_printer(out, default_columns),
cm: Some(cm),
intr: token::get_ident_interner(),
comments: Some(cmnts),
// If the code is post expansion, don't use the table of
// literals, since it doesn't correspond with the literals
// in the AST anymore.
literals: if is_expanded {
None
} else {
Some(lits)
},
cur_cmnt_and_lit: CurrentCommentAndLiteral {
cur_cmnt: 0,
cur_lit: 0
},
boxes: Vec::new(),
ann: ann
};
try!(s.print_mod(&krate.module, krate.attrs.as_slice()));
try!(s.print_remaining_comments());
eof(&mut s.s)
}
pub fn to_str(f: |&mut State| -> IoResult<()>) -> ~str {
let mut s = rust_printer(~MemWriter::new());
f(&mut s).unwrap();
eof(&mut s.s).unwrap();
unsafe {
// FIXME(pcwalton): A nasty function to extract the string from an `io::Writer`
// that we "know" to be a `MemWriter` that works around the lack of checked
// downcasts.
let (_, wr): (uint, ~MemWriter) = cast::transmute_copy(&s.s.out);
let result = str::from_utf8_owned(wr.get_ref().to_owned()).unwrap();
cast::forget(wr);
result
}
}
pub fn ty_to_str(ty: &ast::Ty) -> ~str {
to_str(|s| s.print_type(ty))
}
pub fn pat_to_str(pat: &ast::Pat) -> ~str {
to_str(|s| s.print_pat(pat))
}
pub fn expr_to_str(e: &ast::Expr) -> ~str {
to_str(|s| s.print_expr(e))
}
pub fn lifetime_to_str(e: &ast::Lifetime) -> ~str {
to_str(|s| s.print_lifetime(e))
}
pub fn tt_to_str(tt: &ast::TokenTree) -> ~str {
to_str(|s| s.print_tt(tt))
}
pub fn tts_to_str(tts: &[ast::TokenTree]) -> ~str {
to_str(|s| s.print_tts(&tts))
}
pub fn stmt_to_str(stmt: &ast::Stmt) -> ~str {
to_str(|s| s.print_stmt(stmt))
}
pub fn item_to_str(i: &ast::Item) -> ~str {
to_str(|s| s.print_item(i))
}
pub fn generics_to_str(generics: &ast::Generics) -> ~str {
to_str(|s| s.print_generics(generics))
}
pub fn path_to_str(p: &ast::Path) -> ~str {
to_str(|s| s.print_path(p, false))
}
pub fn fun_to_str(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident,
opt_explicit_self: Option<ast::ExplicitSelf_>,
generics: &ast::Generics) -> ~str {
to_str(|s| {
try!(s.print_fn(decl, Some(fn_style), abi::Rust,
name, generics, opt_explicit_self, ast::Inherited));
try!(s.end()); // Close the head box
s.end() // Close the outer box
})
}
pub fn block_to_str(blk: &ast::Block) -> ~str {
to_str(|s| {
// containing cbox, will be closed by print-block at }
try!(s.cbox(indent_unit));
// head-ibox, will be closed by print-block after {
try!(s.ibox(0u));
s.print_block(blk)
})
}
pub fn meta_item_to_str(mi: &ast::MetaItem) -> ~str {
to_str(|s| s.print_meta_item(mi))
}
pub fn attribute_to_str(attr: &ast::Attribute) -> ~str {
to_str(|s| s.print_attribute(attr))
}
pub fn lit_to_str(l: &ast::Lit) -> ~str {
to_str(|s| s.print_literal(l))
}
pub fn explicit_self_to_str(explicit_self: ast::ExplicitSelf_) -> ~str {
to_str(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
}
pub fn variant_to_str(var: &ast::Variant) -> ~str {
to_str(|s| s.print_variant(var))
}
pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> ~str {
match vis {
ast::Private => format!("priv {}", s),
ast::Public => format!("pub {}", s),
ast::Inherited => s.to_owned()
}
}
impl<'a> State<'a> {
pub fn ibox(&mut self, u: uint) -> IoResult<()> {
self.boxes.push(pp::Inconsistent);
pp::ibox(&mut self.s, u)
}
pub fn end(&mut self) -> IoResult<()> {
self.boxes.pop().unwrap();
pp::end(&mut self.s)
}
pub fn cbox(&mut self, u: uint) -> IoResult<()> {
self.boxes.push(pp::Consistent);
pp::cbox(&mut self.s, u)
}
// "raw box"
pub fn rbox(&mut self, u: uint, b: pp::Breaks) -> IoResult<()> {
self.boxes.push(b);
pp::rbox(&mut self.s, u, b)
}
pub fn nbsp(&mut self) -> IoResult<()> { word(&mut self.s, " ") }
pub fn word_nbsp(&mut self, w: &str) -> IoResult<()> {
try!(word(&mut self.s, w));
self.nbsp()
}
pub fn word_space(&mut self, w: &str) -> IoResult<()> {
try!(word(&mut self.s, w));
space(&mut self.s)
}
pub fn popen(&mut self) -> IoResult<()> { word(&mut self.s, "(") }
pub fn pclose(&mut self) -> IoResult<()> { word(&mut self.s, ")") }
pub fn head(&mut self, w: &str) -> IoResult<()> {
// outer-box is consistent
try!(self.cbox(indent_unit));
// head-box is inconsistent
try!(self.ibox(w.len() + 1));
// keyword that starts the head
if !w.is_empty() {
try!(self.word_nbsp(w));
}
Ok(())
}
pub fn bopen(&mut self) -> IoResult<()> {
try!(word(&mut self.s, "{"));
self.end() // close the head-box
}
pub fn bclose_(&mut self, span: codemap::Span,
indented: uint) -> IoResult<()> {
self.bclose_maybe_open(span, indented, true)
}
pub fn bclose_maybe_open (&mut self, span: codemap::Span,
indented: uint, close_box: bool) -> IoResult<()> {
try!(self.maybe_print_comment(span.hi));
try!(self.break_offset_if_not_bol(1u, -(indented as int)));
try!(word(&mut self.s, "}"));
if close_box {
try!(self.end()); // close the outer-box
}
Ok(())
}
pub fn bclose(&mut self, span: codemap::Span) -> IoResult<()> {
self.bclose_(span, indent_unit)
}
pub fn is_begin(&mut self) -> bool {
match self.s.last_token() { pp::Begin(_) => true, _ => false }
}
pub fn is_end(&mut self) -> bool {
match self.s.last_token() { pp::End => true, _ => false }
}
pub fn is_bol(&mut self) -> bool {
self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok()
}
pub fn in_cbox(&self) -> bool {
match self.boxes.last() {
Some(&last_box) => last_box == pp::Consistent,
None => false
}
}
pub fn hardbreak_if_not_bol(&mut self) -> IoResult<()> {
if !self.is_bol() {
try!(hardbreak(&mut self.s))
}
Ok(())
}
pub fn space_if_not_bol(&mut self) -> IoResult<()> {
if !self.is_bol() { try!(space(&mut self.s)); }
Ok(())
}
pub fn break_offset_if_not_bol(&mut self, n: uint,
off: int) -> IoResult<()> {
if !self.is_bol() {
break_offset(&mut self.s, n, off)
} else {
if off != 0 && self.s.last_token().is_hardbreak_tok() {
// We do something pretty sketchy here: tuck the nonzero
// offset-adjustment we were going to deposit along with the
// break into the previous hardbreak.
self.s.replace_last_token(pp::hardbreak_tok_offset(off));
}
Ok(())
}
}
// Synthesizes a comment that was not textually present in the original source
// file.
pub fn synth_comment(&mut self, text: ~str) -> IoResult<()> {
try!(word(&mut self.s, "/*"));
try!(space(&mut self.s));
try!(word(&mut self.s, text));
try!(space(&mut self.s));
word(&mut self.s, "*/")
}
pub fn commasep<T>(&mut self, b: Breaks, elts: &[T],
op: |&mut State, &T| -> IoResult<()>)
-> IoResult<()> {
try!(self.rbox(0u, b));
let mut first = true;
for elt in elts.iter() {
if first { first = false; } else { try!(self.word_space(",")); }
try!(op(self, elt));
}
self.end()
}
pub fn commasep_cmnt<T>(
&mut self,
b: Breaks,
elts: &[T],
op: |&mut State, &T| -> IoResult<()>,
get_span: |&T| -> codemap::Span) -> IoResult<()> {
try!(self.rbox(0u, b));
let len = elts.len();
let mut i = 0u;
for elt in elts.iter() {
try!(self.maybe_print_comment(get_span(elt).hi));
try!(op(self, elt));
i += 1u;
if i < len {
try!(word(&mut self.s, ","));
try!(self.maybe_print_trailing_comment(get_span(elt),
Some(get_span(&elts[i]).hi)));
try!(self.space_if_not_bol());
}
}
self.end()
}
pub fn commasep_exprs(&mut self, b: Breaks,
exprs: &[@ast::Expr]) -> IoResult<()> {
self.commasep_cmnt(b, exprs, |s, &e| s.print_expr(e), |e| e.span)
}
pub fn print_mod(&mut self, _mod: &ast::Mod,
attrs: &[ast::Attribute]) -> IoResult<()> {
try!(self.print_inner_attributes(attrs));
for vitem in _mod.view_items.iter() {
try!(self.print_view_item(vitem));
}
for item in _mod.items.iter() {
try!(self.print_item(*item));
}
Ok(())
}
pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
attrs: &[ast::Attribute]) -> IoResult<()> {
try!(self.print_inner_attributes(attrs));
for vitem in nmod.view_items.iter() {
try!(self.print_view_item(vitem));
}
for item in nmod.items.iter() {
try!(self.print_foreign_item(*item));
}
Ok(())
}
pub fn print_opt_lifetime(&mut self,
lifetime: &Option<ast::Lifetime>) -> IoResult<()> {
for l in lifetime.iter() {
try!(self.print_lifetime(l));
try!(self.nbsp());
}
Ok(())
}
pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> {
try!(self.maybe_print_comment(ty.span.lo));
try!(self.ibox(0u));
match ty.node {
ast::TyNil => try!(word(&mut self.s, "()")),
ast::TyBot => try!(word(&mut self.s, "!")),
ast::TyBox(ty) => {
try!(word(&mut self.s, "@"));
try!(self.print_type(ty));
}
ast::TyUniq(ty) => {
try!(word(&mut self.s, "~"));
try!(self.print_type(ty));
}
ast::TyVec(ty) => {
try!(word(&mut self.s, "["));
try!(self.print_type(ty));
try!(word(&mut self.s, "]"));
}
ast::TyPtr(ref mt) => {
try!(word(&mut self.s, "*"));
try!(self.print_mt(mt));
}
ast::TyRptr(ref lifetime, ref mt) => {
try!(word(&mut self.s, "&"));
try!(self.print_opt_lifetime(lifetime));
try!(self.print_mt(mt));
}
ast::TyTup(ref elts) => {
try!(self.popen());
try!(self.commasep(Inconsistent, elts.as_slice(),
|s, ty| s.print_type_ref(ty)));
if elts.len() == 1 {
try!(word(&mut self.s, ","));
}
try!(self.pclose());
}
ast::TyBareFn(f) => {
let generics = ast::Generics {
lifetimes: f.lifetimes.clone(),
ty_params: OwnedSlice::empty()
};
try!(self.print_ty_fn(Some(f.abi), None, &None,
f.fn_style, ast::Many, f.decl, None, &None,
Some(&generics), None));
}
ast::TyClosure(f, ref region) => {
let generics = ast::Generics {
lifetimes: f.lifetimes.clone(),
ty_params: OwnedSlice::empty()
};
try!(self.print_ty_fn(None, Some('&'), region, f.fn_style,
f.onceness, f.decl, None, &f.bounds,
Some(&generics), None));
}
ast::TyProc(f) => {
let generics = ast::Generics {
lifetimes: f.lifetimes.clone(),
ty_params: OwnedSlice::empty()
};
try!(self.print_ty_fn(None, Some('~'), &None, f.fn_style,
f.onceness, f.decl, None, &f.bounds,
Some(&generics), None));
}
ast::TyPath(ref path, ref bounds, _) => {
try!(self.print_bounded_path(path, bounds));
}
ast::TyFixedLengthVec(ty, v) => {
try!(word(&mut self.s, "["));
try!(self.print_type(ty));
try!(word(&mut self.s, ", .."));
try!(self.print_expr(v));
try!(word(&mut self.s, "]"));
}
ast::TyTypeof(e) => {
try!(word(&mut self.s, "typeof("));
try!(self.print_expr(e));
try!(word(&mut self.s, ")"));
}
ast::TyInfer => {
try!(word(&mut self.s, "_"));
}
}
self.end()
}
pub fn print_type_ref(&mut self, ty: &P<ast::Ty>) -> IoResult<()> {
self.print_type(*ty)
}
pub fn print_foreign_item(&mut self,
item: &ast::ForeignItem) -> IoResult<()> {
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(item.span.lo));
try!(self.print_outer_attributes(item.attrs.as_slice()));
match item.node {
ast::ForeignItemFn(decl, ref generics) => {
try!(self.print_fn(decl, None, abi::Rust, item.ident, generics,
None, item.vis));
try!(self.end()); // end head-ibox
try!(word(&mut self.s, ";"));
self.end() // end the outer fn box
}
ast::ForeignItemStatic(t, m) => {
try!(self.head(visibility_qualified(item.vis, "static")));
if m {
try!(self.word_space("mut"));
}
try!(self.print_ident(item.ident));
try!(self.word_space(":"));
try!(self.print_type(t));
try!(word(&mut self.s, ";"));
try!(self.end()); // end the head-ibox
self.end() // end the outer cbox
}
}
}
pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> {
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(item.span.lo));
try!(self.print_outer_attributes(item.attrs.as_slice()));
try!(self.ann.pre(self, NodeItem(item)));
match item.node {
ast::ItemStatic(ty, m, expr) => {
try!(self.head(visibility_qualified(item.vis, "static")));
if m == ast::MutMutable {
try!(self.word_space("mut"));
}
try!(self.print_ident(item.ident));
try!(self.word_space(":"));
try!(self.print_type(ty));
try!(space(&mut self.s));
try!(self.end()); // end the head-ibox
try!(self.word_space("="));
try!(self.print_expr(expr));
try!(word(&mut self.s, ";"));
try!(self.end()); // end the outer cbox
}
ast::ItemFn(decl, fn_style, abi, ref typarams, body) => {
try!(self.print_fn(
decl,
Some(fn_style),
abi,
item.ident,
typarams,
None,
item.vis
));
try!(word(&mut self.s, " "));
try!(self.print_block_with_attrs(body, item.attrs.as_slice()));
}
ast::ItemMod(ref _mod) => {
try!(self.head(visibility_qualified(item.vis, "mod")));
try!(self.print_ident(item.ident));
try!(self.nbsp());
try!(self.bopen());
try!(self.print_mod(_mod, item.attrs.as_slice()));
try!(self.bclose(item.span));
}
ast::ItemForeignMod(ref nmod) => {
try!(self.head("extern"));
try!(self.word_nbsp(nmod.abi.to_str()));
try!(self.bopen());
try!(self.print_foreign_mod(nmod, item.attrs.as_slice()));
try!(self.bclose(item.span));
}
ast::ItemTy(ty, ref params) => {
try!(self.ibox(indent_unit));
try!(self.ibox(0u));
try!(self.word_nbsp(visibility_qualified(item.vis, "type")));
try!(self.print_ident(item.ident));
try!(self.print_generics(params));
try!(self.end()); // end the inner ibox
try!(space(&mut self.s));
try!(self.word_space("="));
try!(self.print_type(ty));
try!(word(&mut self.s, ";"));
try!(self.end()); // end the outer ibox
}
ast::ItemEnum(ref enum_definition, ref params) => {
try!(self.print_enum_def(
enum_definition,
params,
item.ident,
item.span,
item.vis
));
}
ast::ItemStruct(struct_def, ref generics) => {
try!(self.head(visibility_qualified(item.vis, "struct")));
try!(self.print_struct(struct_def, generics, item.ident, item.span));
}
ast::ItemImpl(ref generics, ref opt_trait, ty, ref methods) => {
try!(self.head(visibility_qualified(item.vis, "impl")));
if generics.is_parameterized() {
try!(self.print_generics(generics));
try!(space(&mut self.s));
}
match opt_trait {
&Some(ref t) => {
try!(self.print_trait_ref(t));
try!(space(&mut self.s));
try!(self.word_space("for"));
}
&None => {}
}
try!(self.print_type(ty));
try!(space(&mut self.s));
try!(self.bopen());
try!(self.print_inner_attributes(item.attrs.as_slice()));
for meth in methods.iter() {
try!(self.print_method(*meth));
}
try!(self.bclose(item.span));
}
ast::ItemTrait(ref generics, ref traits, ref methods) => {
try!(self.head(visibility_qualified(item.vis, "trait")));
try!(self.print_ident(item.ident));
try!(self.print_generics(generics));
if traits.len() != 0u {
try!(word(&mut self.s, ":"));
for (i, trait_) in traits.iter().enumerate() {
try!(self.nbsp());
if i != 0 {
try!(self.word_space("+"));
}
try!(self.print_path(&trait_.path, false));
}
}
try!(word(&mut self.s, " "));
try!(self.bopen());
for meth in methods.iter() {
try!(self.print_trait_method(meth));
}
try!(self.bclose(item.span));
}
// I think it's reasonable to hide the context here:
ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
..}) => {
try!(self.print_visibility(item.vis));
try!(self.print_path(pth, false));
try!(word(&mut self.s, "! "));
try!(self.print_ident(item.ident));
try!(self.cbox(indent_unit));
try!(self.popen());
try!(self.print_tts(&(tts.as_slice())));
try!(self.pclose());
try!(self.end());
}
}
self.ann.post(self, NodeItem(item))
}
fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
self.print_path(&t.path, false)
}
pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
generics: &ast::Generics, ident: ast::Ident,
span: codemap::Span,
visibility: ast::Visibility) -> IoResult<()> {
try!(self.head(visibility_qualified(visibility, "enum")));
try!(self.print_ident(ident));
try!(self.print_generics(generics));
try!(space(&mut self.s));
self.print_variants(enum_definition.variants.as_slice(), span)
}
pub fn print_variants(&mut self,
variants: &[P<ast::Variant>],
span: codemap::Span) -> IoResult<()> {
try!(self.bopen());
for &v in variants.iter() {
try!(self.space_if_not_bol());
try!(self.maybe_print_comment(v.span.lo));
try!(self.print_outer_attributes(v.node.attrs.as_slice()));
try!(self.ibox(indent_unit));
try!(self.print_variant(v));
try!(word(&mut self.s, ","));
try!(self.end());
try!(self.maybe_print_trailing_comment(v.span, None));
}
self.bclose(span)
}
pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
match vis {
ast::Private => self.word_nbsp("priv"),
ast::Public => self.word_nbsp("pub"),
ast::Inherited => Ok(())
}
}
pub fn print_struct(&mut self,
struct_def: &ast::StructDef,
generics: &ast::Generics,
ident: ast::Ident,
span: codemap::Span) -> IoResult<()> {
try!(self.print_ident(ident));
try!(self.print_generics(generics));
if ast_util::struct_def_is_tuple_like(struct_def) {
if !struct_def.fields.is_empty() {
try!(self.popen());
try!(self.commasep(
Inconsistent, struct_def.fields.as_slice(),
|s, field| {
match field.node.kind {
ast::NamedField(..) => fail!("unexpected named field"),
ast::UnnamedField(vis) => {
try!(s.print_visibility(vis));
try!(s.maybe_print_comment(field.span.lo));
s.print_type(field.node.ty)
}
}
}
));
try!(self.pclose());
}
try!(word(&mut self.s, ";"));
try!(self.end());
self.end() // close the outer-box
} else {
try!(self.nbsp());
try!(self.bopen());
try!(self.hardbreak_if_not_bol());
for field in struct_def.fields.iter() {
match field.node.kind {
ast::UnnamedField(..) => fail!("unexpected unnamed field"),
ast::NamedField(ident, visibility) => {
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(field.span.lo));
try!(self.print_outer_attributes(field.node.attrs.as_slice()));
try!(self.print_visibility(visibility));
try!(self.print_ident(ident));
try!(self.word_nbsp(":"));
try!(self.print_type(field.node.ty));
try!(word(&mut self.s, ","));
}
}
}
self.bclose(span)
}
}
/// This doesn't deserve to be called "pretty" printing, but it should be
/// meaning-preserving. A quick hack that might help would be to look at the
/// spans embedded in the TTs to decide where to put spaces and newlines.
/// But it'd be better to parse these according to the grammar of the
/// appropriate macro, transcribe back into the grammar we just parsed from,
/// and then pretty-print the resulting AST nodes (so, e.g., we print
/// expression arguments as expressions). It can be done! I think.
pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
match *tt {
ast::TTDelim(ref tts) => self.print_tts(&(tts.as_slice())),
ast::TTTok(_, ref tk) => {
word(&mut self.s, parse::token::to_str(tk))
}
ast::TTSeq(_, ref tts, ref sep, zerok) => {
try!(word(&mut self.s, "$("));
for tt_elt in (*tts).iter() {
try!(self.print_tt(tt_elt));
}
try!(word(&mut self.s, ")"));
match *sep {
Some(ref tk) => {
try!(word(&mut self.s, parse::token::to_str(tk)));
}
None => ()
}
word(&mut self.s, if zerok { "*" } else { "+" })
}
ast::TTNonterminal(_, name) => {
try!(word(&mut self.s, "$"));
self.print_ident(name)
}
}
}
pub fn print_tts(&mut self, tts: & &[ast::TokenTree]) -> IoResult<()> {
try!(self.ibox(0));
for (i, tt) in tts.iter().enumerate() {
if i != 0 {
try!(space(&mut self.s));
}
try!(self.print_tt(tt));
}
self.end()
}
pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
try!(self.print_visibility(v.node.vis));
match v.node.kind {
ast::TupleVariantKind(ref args) => {
try!(self.print_ident(v.node.name));
if !args.is_empty() {
try!(self.popen());
try!(self.commasep(Consistent,
args.as_slice(),
|s, arg| s.print_type(arg.ty)));
try!(self.pclose());
}
}
ast::StructVariantKind(struct_def) => {
try!(self.head(""));
let generics = ast_util::empty_generics();
try!(self.print_struct(struct_def, &generics, v.node.name, v.span));
}
}
match v.node.disr_expr {
Some(d) => {
try!(space(&mut self.s));
try!(self.word_space("="));
self.print_expr(d)
}
_ => Ok(())
}
}
pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(m.span.lo));
try!(self.print_outer_attributes(m.attrs.as_slice()));
try!(self.print_ty_fn(None,
None,
&None,
m.fn_style,
ast::Many,
m.decl,
Some(m.ident),
&None,
Some(&m.generics),
Some(m.explicit_self.node)));
word(&mut self.s, ";")
}
pub fn print_trait_method(&mut self,
m: &ast::TraitMethod) -> IoResult<()> {
match *m {
Required(ref ty_m) => self.print_ty_method(ty_m),
Provided(m) => self.print_method(m)
}
}
pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(meth.span.lo));
try!(self.print_outer_attributes(meth.attrs.as_slice()));
try!(self.print_fn(meth.decl, Some(meth.fn_style), abi::Rust,
meth.ident, &meth.generics, Some(meth.explicit_self.node),
meth.vis));
try!(word(&mut self.s, " "));
self.print_block_with_attrs(meth.body, meth.attrs.as_slice())
}
pub fn print_outer_attributes(&mut self,
attrs: &[ast::Attribute]) -> IoResult<()> {
let mut count = 0;
for attr in attrs.iter() {
match attr.node.style {
ast::AttrOuter => {
try!(self.print_attribute(attr));
count += 1;
}
_ => {/* fallthrough */ }
}
}
if count > 0 {
try!(self.hardbreak_if_not_bol());
}
Ok(())
}
pub fn print_inner_attributes(&mut self,
attrs: &[ast::Attribute]) -> IoResult<()> {
let mut count = 0;
for attr in attrs.iter() {
match attr.node.style {
ast::AttrInner => {
try!(self.print_attribute(attr));
count += 1;
}
_ => {/* fallthrough */ }
}
}
if count > 0 {
try!(self.hardbreak_if_not_bol());
}
Ok(())
}
pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(attr.span.lo));
if attr.node.is_sugared_doc {
word(&mut self.s, attr.value_str().unwrap().get())
} else {
match attr.node.style {
ast::AttrInner => try!(word(&mut self.s, "#![")),
ast::AttrOuter => try!(word(&mut self.s, "#[")),
}
try!(self.print_meta_item(attr.meta()));
word(&mut self.s, "]")
}
}
pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
try!(self.maybe_print_comment(st.span.lo));
match st.node {
ast::StmtDecl(decl, _) => {
try!(self.print_decl(decl));
}
ast::StmtExpr(expr, _) => {
try!(self.space_if_not_bol());
try!(self.print_expr(expr));
}
ast::StmtSemi(expr, _) => {
try!(self.space_if_not_bol());
try!(self.print_expr(expr));
try!(word(&mut self.s, ";"));
}
ast::StmtMac(ref mac, semi) => {
try!(self.space_if_not_bol());
try!(self.print_mac(mac));
if semi {
try!(word(&mut self.s, ";"));
}
}
}
if parse::classify::stmt_ends_with_semi(st) {
try!(word(&mut self.s, ";"));
}
self.maybe_print_trailing_comment(st.span, None)
}
pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
self.print_block_with_attrs(blk, &[])
}
pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
self.print_block_unclosed_indent(blk, indent_unit)
}
pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
indented: uint) -> IoResult<()> {
self.print_block_maybe_unclosed(blk, indented, &[], false)
}
pub fn print_block_with_attrs(&mut self,
blk: &ast::Block,
attrs: &[ast::Attribute]) -> IoResult<()> {
self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)