-
Notifications
You must be signed in to change notification settings - Fork 12.7k
/
print.rs
2297 lines (2113 loc) · 80.5 KB
/
print.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
use rustc_target::spec::abi::Abi;
use syntax::ast;
use syntax::source_map::{SourceMap, Spanned};
use syntax::print::pp::{self, Breaks};
use syntax::print::pp::Breaks::{Consistent, Inconsistent};
use syntax::print::pprust::{self, Comments, PrintState};
use syntax::sess::ParseSess;
use syntax::symbol::kw;
use syntax::util::parser::{self, AssocOp, Fixity};
use syntax_pos::{self, BytePos, FileName};
use crate::hir;
use crate::hir::{PatKind, GenericBound, TraitBoundModifier, RangeEnd};
use crate::hir::{GenericParam, GenericParamKind, GenericArg};
use crate::hir::ptr::P;
use std::borrow::Cow;
use std::cell::Cell;
use std::vec;
pub enum AnnNode<'a> {
Name(&'a ast::Name),
Block(&'a hir::Block),
Item(&'a hir::Item),
SubItem(hir::HirId),
Expr(&'a hir::Expr),
Pat(&'a hir::Pat),
Arm(&'a hir::Arm),
}
pub enum Nested {
Item(hir::ItemId),
TraitItem(hir::TraitItemId),
ImplItem(hir::ImplItemId),
Body(hir::BodyId),
BodyParamPat(hir::BodyId, usize)
}
pub trait PpAnn {
fn nested(&self, _state: &mut State<'_>, _nested: Nested) {
}
fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {
}
fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {
}
fn try_fetch_item(&self, _: hir::HirId) -> Option<&hir::Item> {
None
}
}
pub struct NoAnn;
impl PpAnn for NoAnn {}
pub const NO_ANN: &dyn PpAnn = &NoAnn;
impl PpAnn for hir::Crate {
fn try_fetch_item(&self, item: hir::HirId) -> Option<&hir::Item> {
Some(self.item(item))
}
fn nested(&self, state: &mut State<'_>, nested: Nested) {
match nested {
Nested::Item(id) => state.print_item(self.item(id.id)),
Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
Nested::Body(id) => state.print_expr(&self.body(id).value),
Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat)
}
}
}
pub struct State<'a> {
pub s: pp::Printer,
comments: Option<Comments<'a>>,
ann: &'a (dyn PpAnn + 'a),
}
impl std::ops::Deref for State<'_> {
type Target = pp::Printer;
fn deref(&self) -> &Self::Target {
&self.s
}
}
impl std::ops::DerefMut for State<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.s
}
}
impl<'a> PrintState<'a> for State<'a> {
fn comments(&mut self) -> &mut Option<Comments<'a>> {
&mut self.comments
}
fn print_ident(&mut self, ident: ast::Ident) {
self.s.word(pprust::ast_ident_to_string(ident, ident.is_raw_guess()));
self.ann.post(self, AnnNode::Name(&ident.name))
}
fn print_generic_args(&mut self, args: &ast::GenericArgs, _colons_before_params: bool) {
span_bug!(args.span(), "AST generic args printed by HIR pretty-printer");
}
}
pub const INDENT_UNIT: usize = 4;
/// Requires you to pass an input filename and reader so that
/// it can scan the input text for comments to copy forward.
pub fn print_crate<'a>(cm: &'a SourceMap,
sess: &ParseSess,
krate: &hir::Crate,
filename: FileName,
input: String,
ann: &'a dyn PpAnn) -> String {
let mut s = State::new_from_input(cm, sess, filename, input, ann);
// When printing the AST, we sometimes need to inject `#[no_std]` here.
// Since you can't compile the HIR, it's not necessary.
s.print_mod(&krate.module, &krate.attrs);
s.print_remaining_comments();
s.s.eof()
}
impl<'a> State<'a> {
pub fn new_from_input(cm: &'a SourceMap,
sess: &ParseSess,
filename: FileName,
input: String,
ann: &'a dyn PpAnn)
-> State<'a> {
State {
s: pp::mk_printer(),
comments: Some(Comments::new(cm, sess, filename, input)),
ann,
}
}
}
pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
where F: FnOnce(&mut State<'_>)
{
let mut printer = State {
s: pp::mk_printer(),
comments: None,
ann,
};
f(&mut printer);
printer.s.eof()
}
pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility, w: S) -> String {
to_string(NO_ANN, |s| {
s.print_visibility(vis);
s.s.word(w)
})
}
impl<'a> State<'a> {
pub fn cbox(&mut self, u: usize) {
self.s.cbox(u);
}
pub fn nbsp(&mut self) {
self.s.word(" ")
}
pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
self.s.word(w);
self.nbsp()
}
pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
let w = w.into();
// outer-box is consistent
self.cbox(INDENT_UNIT);
// head-box is inconsistent
self.ibox(w.len() + 1);
// keyword that starts the head
if !w.is_empty() {
self.word_nbsp(w);
}
}
pub fn bopen(&mut self) {
self.s.word("{");
self.end(); // close the head-box
}
pub fn bclose_maybe_open(&mut self,
span: syntax_pos::Span,
close_box: bool)
{
self.maybe_print_comment(span.hi());
self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
self.s.word("}");
if close_box {
self.end(); // close the outer-box
}
}
pub fn bclose(&mut self, span: syntax_pos::Span) {
self.bclose_maybe_open(span, true)
}
pub fn space_if_not_bol(&mut self) {
if !self.s.is_beginning_of_line() {
self.s.space();
}
}
pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
if !self.s.is_beginning_of_line() {
self.s.break_offset(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::Printer::hardbreak_tok_offset(off));
}
}
}
// Synthesizes a comment that was not textually present in the original source
// file.
pub fn synth_comment(&mut self, text: String) {
self.s.word("/*");
self.s.space();
self.s.word(text);
self.s.space();
self.s.word("*/")
}
pub fn commasep_cmnt<T, F, G>(&mut self,
b: Breaks,
elts: &[T],
mut op: F,
mut get_span: G)
where F: FnMut(&mut State<'_>, &T),
G: FnMut(&T) -> syntax_pos::Span
{
self.rbox(0, b);
let len = elts.len();
let mut i = 0;
for elt in elts {
self.maybe_print_comment(get_span(elt).hi());
op(self, elt);
i += 1;
if i < len {
self.s.word(",");
self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
self.space_if_not_bol();
}
}
self.end();
}
pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr]) {
self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
}
pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) {
self.print_inner_attributes(attrs);
for &item_id in &_mod.item_ids {
self.ann.nested(self, Nested::Item(item_id));
}
}
pub fn print_foreign_mod(&mut self,
nmod: &hir::ForeignMod,
attrs: &[ast::Attribute])
{
self.print_inner_attributes(attrs);
for item in &nmod.items {
self.print_foreign_item(item);
}
}
pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
if !lifetime.is_elided() {
self.print_lifetime(lifetime);
self.nbsp();
}
}
pub fn print_type(&mut self, ty: &hir::Ty) {
self.maybe_print_comment(ty.span.lo());
self.ibox(0);
match ty.kind {
hir::TyKind::Slice(ref ty) => {
self.s.word("[");
self.print_type(&ty);
self.s.word("]");
}
hir::TyKind::Ptr(ref mt) => {
self.s.word("*");
match mt.mutbl {
hir::MutMutable => self.word_nbsp("mut"),
hir::MutImmutable => self.word_nbsp("const"),
}
self.print_type(&mt.ty);
}
hir::TyKind::Rptr(ref lifetime, ref mt) => {
self.s.word("&");
self.print_opt_lifetime(lifetime);
self.print_mt(mt);
}
hir::TyKind::Never => {
self.s.word("!");
},
hir::TyKind::Tup(ref elts) => {
self.popen();
self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
if elts.len() == 1 {
self.s.word(",");
}
self.pclose();
}
hir::TyKind::BareFn(ref f) => {
self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &f.generic_params,
&f.param_names[..]);
}
hir::TyKind::Def(..) => {},
hir::TyKind::Path(ref qpath) => {
self.print_qpath(qpath, false)
}
hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
let mut first = true;
for bound in bounds {
if first {
first = false;
} else {
self.nbsp();
self.word_space("+");
}
self.print_poly_trait_ref(bound);
}
if !lifetime.is_elided() {
self.nbsp();
self.word_space("+");
self.print_lifetime(lifetime);
}
}
hir::TyKind::Array(ref ty, ref length) => {
self.s.word("[");
self.print_type(&ty);
self.s.word("; ");
self.print_anon_const(length);
self.s.word("]");
}
hir::TyKind::Typeof(ref e) => {
self.s.word("typeof(");
self.print_anon_const(e);
self.s.word(")");
}
hir::TyKind::Infer => {
self.s.word("_");
}
hir::TyKind::Err => {
self.popen();
self.s.word("/*ERROR*/");
self.pclose();
}
}
self.end()
}
pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) {
self.hardbreak_if_not_bol();
self.maybe_print_comment(item.span.lo());
self.print_outer_attributes(&item.attrs);
match item.kind {
hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
self.head("");
self.print_fn(decl,
hir::FnHeader {
unsafety: hir::Unsafety::Normal,
constness: hir::Constness::NotConst,
abi: Abi::Rust,
asyncness: hir::IsAsync::NotAsync,
},
Some(item.ident.name),
generics,
&item.vis,
arg_names,
None);
self.end(); // end head-ibox
self.s.word(";");
self.end() // end the outer fn box
}
hir::ForeignItemKind::Static(ref t, m) => {
self.head(visibility_qualified(&item.vis, "static"));
if m == hir::MutMutable {
self.word_space("mut");
}
self.print_ident(item.ident);
self.word_space(":");
self.print_type(&t);
self.s.word(";");
self.end(); // end the head-ibox
self.end() // end the outer cbox
}
hir::ForeignItemKind::Type => {
self.head(visibility_qualified(&item.vis, "type"));
self.print_ident(item.ident);
self.s.word(";");
self.end(); // end the head-ibox
self.end() // end the outer cbox
}
}
}
fn print_associated_const(&mut self,
ident: ast::Ident,
ty: &hir::Ty,
default: Option<hir::BodyId>,
vis: &hir::Visibility)
{
self.s.word(visibility_qualified(vis, ""));
self.word_space("const");
self.print_ident(ident);
self.word_space(":");
self.print_type(ty);
if let Some(expr) = default {
self.s.space();
self.word_space("=");
self.ann.nested(self, Nested::Body(expr));
}
self.s.word(";")
}
fn print_associated_type(&mut self,
ident: ast::Ident,
bounds: Option<&hir::GenericBounds>,
ty: Option<&hir::Ty>)
{
self.word_space("type");
self.print_ident(ident);
if let Some(bounds) = bounds {
self.print_bounds(":", bounds);
}
if let Some(ty) = ty {
self.s.space();
self.word_space("=");
self.print_type(ty);
}
self.s.word(";")
}
fn print_item_type(
&mut self,
item: &hir::Item,
generics: &hir::Generics,
inner: impl Fn(&mut Self),
) {
self.head(visibility_qualified(&item.vis, "type"));
self.print_ident(item.ident);
self.print_generic_params(&generics.params);
self.end(); // end the inner ibox
self.print_where_clause(&generics.where_clause);
self.s.space();
inner(self);
self.s.word(";");
self.end(); // end the outer ibox
}
/// Pretty-print an item
pub fn print_item(&mut self, item: &hir::Item) {
self.hardbreak_if_not_bol();
self.maybe_print_comment(item.span.lo());
self.print_outer_attributes(&item.attrs);
self.ann.pre(self, AnnNode::Item(item));
match item.kind {
hir::ItemKind::ExternCrate(orig_name) => {
self.head(visibility_qualified(&item.vis, "extern crate"));
if let Some(orig_name) = orig_name {
self.print_name(orig_name);
self.s.space();
self.s.word("as");
self.s.space();
}
self.print_ident(item.ident);
self.s.word(";");
self.end(); // end inner head-block
self.end(); // end outer head-block
}
hir::ItemKind::Use(ref path, kind) => {
self.head(visibility_qualified(&item.vis, "use"));
self.print_path(path, false);
match kind {
hir::UseKind::Single => {
if path.segments.last().unwrap().ident != item.ident {
self.s.space();
self.word_space("as");
self.print_ident(item.ident);
}
self.s.word(";");
}
hir::UseKind::Glob => self.s.word("::*;"),
hir::UseKind::ListStem => self.s.word("::{};")
}
self.end(); // end inner head-block
self.end(); // end outer head-block
}
hir::ItemKind::Static(ref ty, m, expr) => {
self.head(visibility_qualified(&item.vis, "static"));
if m == hir::MutMutable {
self.word_space("mut");
}
self.print_ident(item.ident);
self.word_space(":");
self.print_type(&ty);
self.s.space();
self.end(); // end the head-ibox
self.word_space("=");
self.ann.nested(self, Nested::Body(expr));
self.s.word(";");
self.end(); // end the outer cbox
}
hir::ItemKind::Const(ref ty, expr) => {
self.head(visibility_qualified(&item.vis, "const"));
self.print_ident(item.ident);
self.word_space(":");
self.print_type(&ty);
self.s.space();
self.end(); // end the head-ibox
self.word_space("=");
self.ann.nested(self, Nested::Body(expr));
self.s.word(";");
self.end(); // end the outer cbox
}
hir::ItemKind::Fn(ref decl, header, ref param_names, body) => {
self.head("");
self.print_fn(decl,
header,
Some(item.ident.name),
param_names,
&item.vis,
&[],
Some(body));
self.s.word(" ");
self.end(); // need to close a box
self.end(); // need to close a box
self.ann.nested(self, Nested::Body(body));
}
hir::ItemKind::Mod(ref _mod) => {
self.head(visibility_qualified(&item.vis, "mod"));
self.print_ident(item.ident);
self.nbsp();
self.bopen();
self.print_mod(_mod, &item.attrs);
self.bclose(item.span);
}
hir::ItemKind::ForeignMod(ref nmod) => {
self.head("extern");
self.word_nbsp(nmod.abi.to_string());
self.bopen();
self.print_foreign_mod(nmod, &item.attrs);
self.bclose(item.span);
}
hir::ItemKind::GlobalAsm(ref ga) => {
self.head(visibility_qualified(&item.vis, "global asm"));
self.s.word(ga.asm.as_str().to_string());
self.end()
}
hir::ItemKind::TyAlias(ref ty, ref generics) => {
self.print_item_type(item, &generics, |state| {
state.word_space("=");
state.print_type(&ty);
});
}
hir::ItemKind::OpaqueTy(ref opaque_ty) => {
self.print_item_type(item, &opaque_ty.generics, |state| {
let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
for b in opaque_ty.bounds.iter() {
if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
state.s.space();
state.word_space("for ?");
state.print_trait_ref(&ptr.trait_ref);
} else {
real_bounds.push(b);
}
}
state.print_bounds("= impl", real_bounds);
});
}
hir::ItemKind::Enum(ref enum_definition, ref params) => {
self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis);
}
hir::ItemKind::Struct(ref struct_def, ref generics) => {
self.head(visibility_qualified(&item.vis, "struct"));
self.print_struct(struct_def, generics, item.ident.name, item.span, true);
}
hir::ItemKind::Union(ref struct_def, ref generics) => {
self.head(visibility_qualified(&item.vis, "union"));
self.print_struct(struct_def, generics, item.ident.name, item.span, true);
}
hir::ItemKind::Impl(unsafety,
polarity,
defaultness,
ref generics,
ref opt_trait,
ref ty,
ref impl_items) => {
self.head("");
self.print_visibility(&item.vis);
self.print_defaultness(defaultness);
self.print_unsafety(unsafety);
self.word_nbsp("impl");
if !generics.params.is_empty() {
self.print_generic_params(&generics.params);
self.s.space();
}
if let hir::ImplPolarity::Negative = polarity {
self.s.word("!");
}
if let Some(ref t) = opt_trait {
self.print_trait_ref(t);
self.s.space();
self.word_space("for");
}
self.print_type(&ty);
self.print_where_clause(&generics.where_clause);
self.s.space();
self.bopen();
self.print_inner_attributes(&item.attrs);
for impl_item in impl_items {
self.ann.nested(self, Nested::ImplItem(impl_item.id));
}
self.bclose(item.span);
}
hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
self.head("");
self.print_visibility(&item.vis);
self.print_is_auto(is_auto);
self.print_unsafety(unsafety);
self.word_nbsp("trait");
self.print_ident(item.ident);
self.print_generic_params(&generics.params);
let mut real_bounds = Vec::with_capacity(bounds.len());
for b in bounds.iter() {
if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
self.s.space();
self.word_space("for ?");
self.print_trait_ref(&ptr.trait_ref);
} else {
real_bounds.push(b);
}
}
self.print_bounds(":", real_bounds);
self.print_where_clause(&generics.where_clause);
self.s.word(" ");
self.bopen();
for trait_item in trait_items {
self.ann.nested(self, Nested::TraitItem(trait_item.id));
}
self.bclose(item.span);
}
hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
self.head("");
self.print_visibility(&item.vis);
self.word_nbsp("trait");
self.print_ident(item.ident);
self.print_generic_params(&generics.params);
let mut real_bounds = Vec::with_capacity(bounds.len());
// FIXME(durka) this seems to be some quite outdated syntax
for b in bounds.iter() {
if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
self.s.space();
self.word_space("for ?");
self.print_trait_ref(&ptr.trait_ref);
} else {
real_bounds.push(b);
}
}
self.nbsp();
self.print_bounds("=", real_bounds);
self.print_where_clause(&generics.where_clause);
self.s.word(";");
}
}
self.ann.post(self, AnnNode::Item(item))
}
pub fn print_trait_ref(&mut self, t: &hir::TraitRef) {
self.print_path(&t.path, false)
}
fn print_formal_generic_params(
&mut self,
generic_params: &[hir::GenericParam]
) {
if !generic_params.is_empty() {
self.s.word("for");
self.print_generic_params(generic_params);
self.nbsp();
}
}
fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) {
self.print_formal_generic_params(&t.bound_generic_params);
self.print_trait_ref(&t.trait_ref)
}
pub fn print_enum_def(&mut self,
enum_definition: &hir::EnumDef,
generics: &hir::Generics,
name: ast::Name,
span: syntax_pos::Span,
visibility: &hir::Visibility)
{
self.head(visibility_qualified(visibility, "enum"));
self.print_name(name);
self.print_generic_params(&generics.params);
self.print_where_clause(&generics.where_clause);
self.s.space();
self.print_variants(&enum_definition.variants, span)
}
pub fn print_variants(&mut self,
variants: &[hir::Variant],
span: syntax_pos::Span)
{
self.bopen();
for v in variants {
self.space_if_not_bol();
self.maybe_print_comment(v.span.lo());
self.print_outer_attributes(&v.attrs);
self.ibox(INDENT_UNIT);
self.print_variant(v);
self.s.word(",");
self.end();
self.maybe_print_trailing_comment(v.span, None);
}
self.bclose(span)
}
pub fn print_visibility(&mut self, vis: &hir::Visibility) {
match vis.node {
hir::VisibilityKind::Public => self.word_nbsp("pub"),
hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate"),
hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)"),
hir::VisibilityKind::Restricted { ref path, .. } => {
self.s.word("pub(");
if path.segments.len() == 1 &&
path.segments[0].ident.name == kw::Super {
// Special case: `super` can print like `pub(super)`.
self.s.word("super");
} else {
// Everything else requires `in` at present.
self.word_nbsp("in");
self.print_path(path, false);
}
self.word_nbsp(")");
}
hir::VisibilityKind::Inherited => ()
}
}
pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
match defaultness {
hir::Defaultness::Default { .. } => self.word_nbsp("default"),
hir::Defaultness::Final => (),
}
}
pub fn print_struct(&mut self,
struct_def: &hir::VariantData,
generics: &hir::Generics,
name: ast::Name,
span: syntax_pos::Span,
print_finalizer: bool)
{
self.print_name(name);
self.print_generic_params(&generics.params);
match struct_def {
hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
if let hir::VariantData::Tuple(..) = struct_def {
self.popen();
self.commasep(Inconsistent, struct_def.fields(), |s, field| {
s.maybe_print_comment(field.span.lo());
s.print_outer_attributes(&field.attrs);
s.print_visibility(&field.vis);
s.print_type(&field.ty)
});
self.pclose();
}
self.print_where_clause(&generics.where_clause);
if print_finalizer {
self.s.word(";");
}
self.end();
self.end() // close the outer-box
}
hir::VariantData::Struct(..) => {
self.print_where_clause(&generics.where_clause);
self.nbsp();
self.bopen();
self.hardbreak_if_not_bol();
for field in struct_def.fields() {
self.hardbreak_if_not_bol();
self.maybe_print_comment(field.span.lo());
self.print_outer_attributes(&field.attrs);
self.print_visibility(&field.vis);
self.print_ident(field.ident);
self.word_nbsp(":");
self.print_type(&field.ty);
self.s.word(",");
}
self.bclose(span)
}
}
}
pub fn print_variant(&mut self, v: &hir::Variant) {
self.head("");
let generics = hir::Generics::empty();
self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
if let Some(ref d) = v.disr_expr {
self.s.space();
self.word_space("=");
self.print_anon_const(d);
}
}
pub fn print_method_sig(&mut self,
ident: ast::Ident,
m: &hir::MethodSig,
generics: &hir::Generics,
vis: &hir::Visibility,
arg_names: &[ast::Ident],
body_id: Option<hir::BodyId>)
{
self.print_fn(&m.decl,
m.header,
Some(ident.name),
generics,
vis,
arg_names,
body_id)
}
pub fn print_trait_item(&mut self, ti: &hir::TraitItem) {
self.ann.pre(self, AnnNode::SubItem(ti.hir_id));
self.hardbreak_if_not_bol();
self.maybe_print_comment(ti.span.lo());
self.print_outer_attributes(&ti.attrs);
match ti.kind {
hir::TraitItemKind::Const(ref ty, default) => {
let vis = Spanned { span: syntax_pos::DUMMY_SP,
node: hir::VisibilityKind::Inherited };
self.print_associated_const(ti.ident, &ty, default, &vis);
}
hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
let vis = Spanned { span: syntax_pos::DUMMY_SP,
node: hir::VisibilityKind::Inherited };
self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None);
self.s.word(";");
}
hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
let vis = Spanned { span: syntax_pos::DUMMY_SP,
node: hir::VisibilityKind::Inherited };
self.head("");
self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body));
self.nbsp();
self.end(); // need to close a box
self.end(); // need to close a box
self.ann.nested(self, Nested::Body(body));
}
hir::TraitItemKind::Type(ref bounds, ref default) => {
self.print_associated_type(ti.ident,
Some(bounds),
default.as_ref().map(|ty| &**ty));
}
}
self.ann.post(self, AnnNode::SubItem(ti.hir_id))
}
pub fn print_impl_item(&mut self, ii: &hir::ImplItem) {
self.ann.pre(self, AnnNode::SubItem(ii.hir_id));
self.hardbreak_if_not_bol();
self.maybe_print_comment(ii.span.lo());
self.print_outer_attributes(&ii.attrs);
self.print_defaultness(ii.defaultness);
match ii.kind {
hir::ImplItemKind::Const(ref ty, expr) => {
self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
}
hir::ImplItemKind::Method(ref sig, body) => {
self.head("");
self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
self.nbsp();
self.end(); // need to close a box
self.end(); // need to close a box
self.ann.nested(self, Nested::Body(body));
}
hir::ImplItemKind::TyAlias(ref ty) => {
self.print_associated_type(ii.ident, None, Some(ty));
}
hir::ImplItemKind::OpaqueTy(ref bounds) => {
self.word_space("type");
self.print_ident(ii.ident);
self.print_bounds("= impl", bounds);
self.s.word(";");
}
}
self.ann.post(self, AnnNode::SubItem(ii.hir_id))
}
pub fn print_local(
&mut self,
init: Option<&hir::Expr>,
decl: impl Fn(&mut Self)
) {
self.space_if_not_bol();
self.ibox(INDENT_UNIT);
self.word_nbsp("let");
self.ibox(INDENT_UNIT);
decl(self);
self.end();
if let Some(ref init) = init {
self.nbsp();
self.word_space("=");
self.print_expr(&init);
}
self.end()
}
pub fn print_stmt(&mut self, st: &hir::Stmt) {
self.maybe_print_comment(st.span.lo());
match st.kind {
hir::StmtKind::Local(ref loc) => {
self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc));
}
hir::StmtKind::Item(item) => {
self.ann.nested(self, Nested::Item(item))
}
hir::StmtKind::Expr(ref expr) => {
self.space_if_not_bol();
self.print_expr(&expr);
}
hir::StmtKind::Semi(ref expr) => {
self.space_if_not_bol();
self.print_expr(&expr);
self.s.word(";");
}
}
if stmt_ends_with_semi(&st.kind) {
self.s.word(";");
}
self.maybe_print_trailing_comment(st.span, None)
}
pub fn print_block(&mut self, blk: &hir::Block) {
self.print_block_with_attrs(blk, &[])
}
pub fn print_block_unclosed(&mut self, blk: &hir::Block) {
self.print_block_maybe_unclosed(blk, &[], false)
}
pub fn print_block_with_attrs(&mut self,
blk: &hir::Block,
attrs: &[ast::Attribute])
{
self.print_block_maybe_unclosed(blk, attrs, true)
}
pub fn print_block_maybe_unclosed(&mut self,
blk: &hir::Block,
attrs: &[ast::Attribute],
close_box: bool)
{
match blk.rules {
hir::UnsafeBlock(..) => self.word_space("unsafe"),
hir::PushUnsafeBlock(..) => self.word_space("push_unsafe"),
hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe"),
hir::DefaultBlock => (),
}
self.maybe_print_comment(blk.span.lo());
self.ann.pre(self, AnnNode::Block(blk));
self.bopen();
self.print_inner_attributes(attrs);
for st in &blk.stmts {
self.print_stmt(st);