1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::AnnNode::*;
15 use syntax::codemap::{CodeMap, Spanned};
16 use syntax::parse::ParseSess;
17 use syntax::parse::lexer::comments;
18 use syntax::print::pp::{self, break_offset, word, space, hardbreak};
19 use syntax::print::pp::{Breaks, eof};
20 use syntax::print::pp::Breaks::{Consistent, Inconsistent};
21 use syntax::print::pprust::{self as ast_pp, PrintState};
23 use syntax::symbol::keywords;
24 use syntax_pos::{self, BytePos};
27 use hir::{PatKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier, RangeEnd};
30 use std::io::{self, Write, Read};
32 pub enum AnnNode<'a> {
33 NodeName(&'a ast::Name),
34 NodeBlock(&'a hir::Block),
35 NodeItem(&'a hir::Item),
36 NodeSubItem(ast::NodeId),
37 NodeExpr(&'a hir::Expr),
38 NodePat(&'a hir::Pat),
43 TraitItem(hir::TraitItemId),
44 ImplItem(hir::ImplItemId),
46 BodyArgPat(hir::BodyId, usize)
50 fn nested(&self, _state: &mut State, _nested: Nested) -> io::Result<()> {
53 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
56 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
62 impl PpAnn for NoAnn {}
63 pub const NO_ANN: &'static PpAnn = &NoAnn;
65 impl PpAnn for hir::Crate {
66 fn nested(&self, state: &mut State, nested: Nested) -> io::Result<()> {
68 Nested::Item(id) => state.print_item(self.item(id.id)),
69 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
70 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
71 Nested::Body(id) => state.print_expr(&self.body(id).value),
72 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
77 pub struct State<'a> {
78 pub s: pp::Printer<'a>,
79 cm: Option<&'a CodeMap>,
80 comments: Option<Vec<comments::Comment>>,
81 literals: Option<Vec<comments::Literal>>,
82 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral,
83 boxes: Vec<pp::Breaks>,
84 ann: &'a (PpAnn + 'a),
87 impl<'a> PrintState<'a> for State<'a> {
88 fn writer(&mut self) -> &mut pp::Printer<'a> {
92 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
96 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
100 fn cur_cmnt_and_lit(&mut self) -> &mut ast_pp::CurrentCommentAndLiteral {
101 &mut self.cur_cmnt_and_lit
104 fn literals(&self) -> &Option<Vec<comments::Literal>> {
109 #[allow(non_upper_case_globals)]
110 pub const indent_unit: usize = 4;
112 #[allow(non_upper_case_globals)]
113 pub const default_columns: usize = 78;
116 /// Requires you to pass an input filename and reader so that
117 /// it can scan the input text for comments and literals to
119 pub fn print_crate<'a>(cm: &'a CodeMap,
124 out: Box<Write + 'a>,
128 let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
130 // When printing the AST, we sometimes need to inject `#[no_std]` here.
131 // Since you can't compile the HIR, it's not necessary.
133 s.print_mod(&krate.module, &krate.attrs)?;
134 s.print_remaining_comments()?;
139 pub fn new_from_input(cm: &'a CodeMap,
143 out: Box<Write + 'a>,
147 let (cmnts, lits) = comments::gather_comments_and_literals(sess, filename, input);
153 // If the code is post expansion, don't use the table of
154 // literals, since it doesn't correspond with the literals
155 // in the AST anymore.
163 pub fn new(cm: &'a CodeMap,
164 out: Box<Write + 'a>,
166 comments: Option<Vec<comments::Comment>>,
167 literals: Option<Vec<comments::Literal>>)
170 s: pp::mk_printer(out, default_columns),
172 comments: comments.clone(),
173 literals: literals.clone(),
174 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
184 pub fn to_string<F>(ann: &PpAnn, f: F) -> String
185 where F: FnOnce(&mut State) -> io::Result<()>
187 let mut wr = Vec::new();
189 let mut printer = State {
190 s: pp::mk_printer(Box::new(&mut wr), default_columns),
194 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
201 f(&mut printer).unwrap();
202 eof(&mut printer.s).unwrap();
204 String::from_utf8(wr).unwrap()
207 pub fn visibility_qualified(vis: &hir::Visibility, w: &str) -> String {
208 to_string(NO_ANN, |s| {
209 s.print_visibility(vis)?;
214 fn needs_parentheses(expr: &hir::Expr) -> bool {
216 hir::ExprAssign(..) |
217 hir::ExprBinary(..) |
218 hir::ExprClosure(..) |
219 hir::ExprAssignOp(..) |
221 hir::ExprType(..) => true,
227 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
228 self.boxes.push(pp::Breaks::Consistent);
229 pp::cbox(&mut self.s, u)
232 pub fn nbsp(&mut self) -> io::Result<()> {
233 word(&mut self.s, " ")
236 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
237 word(&mut self.s, w)?;
241 pub fn head(&mut self, w: &str) -> io::Result<()> {
242 // outer-box is consistent
243 self.cbox(indent_unit)?;
244 // head-box is inconsistent
245 self.ibox(w.len() + 1)?;
246 // keyword that starts the head
253 pub fn bopen(&mut self) -> io::Result<()> {
254 word(&mut self.s, "{")?;
255 self.end() // close the head-box
258 pub fn bclose_(&mut self, span: syntax_pos::Span, indented: usize) -> io::Result<()> {
259 self.bclose_maybe_open(span, indented, true)
261 pub fn bclose_maybe_open(&mut self,
262 span: syntax_pos::Span,
266 self.maybe_print_comment(span.hi)?;
267 self.break_offset_if_not_bol(1, -(indented as isize))?;
268 word(&mut self.s, "}")?;
270 self.end()?; // close the outer-box
274 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
275 self.bclose_(span, indent_unit)
278 pub fn in_cbox(&self) -> bool {
279 match self.boxes.last() {
280 Some(&last_box) => last_box == pp::Breaks::Consistent,
284 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
290 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
292 break_offset(&mut self.s, n, off)
294 if off != 0 && self.s.last_token().is_hardbreak_tok() {
295 // We do something pretty sketchy here: tuck the nonzero
296 // offset-adjustment we were going to deposit along with the
297 // break into the previous hardbreak.
298 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
304 // Synthesizes a comment that was not textually present in the original source
306 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
307 word(&mut self.s, "/*")?;
309 word(&mut self.s, &text[..])?;
311 word(&mut self.s, "*/")
315 pub fn commasep_cmnt<T, F, G>(&mut self,
321 where F: FnMut(&mut State, &T) -> io::Result<()>,
322 G: FnMut(&T) -> syntax_pos::Span
325 let len = elts.len();
328 self.maybe_print_comment(get_span(elt).hi)?;
332 word(&mut self.s, ",")?;
333 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi))?;
334 self.space_if_not_bol()?;
340 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr]) -> io::Result<()> {
341 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
344 pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
345 self.print_inner_attributes(attrs)?;
346 for &item_id in &_mod.item_ids {
347 self.ann.nested(self, Nested::Item(item_id))?;
352 pub fn print_foreign_mod(&mut self,
353 nmod: &hir::ForeignMod,
354 attrs: &[ast::Attribute])
356 self.print_inner_attributes(attrs)?;
357 for item in &nmod.items {
358 self.print_foreign_item(item)?;
363 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
364 if !lifetime.is_elided() {
365 self.print_lifetime(lifetime)?;
371 pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
372 self.maybe_print_comment(ty.span.lo)?;
375 hir::TySlice(ref ty) => {
376 word(&mut self.s, "[")?;
377 self.print_type(&ty)?;
378 word(&mut self.s, "]")?;
380 hir::TyPtr(ref mt) => {
381 word(&mut self.s, "*")?;
383 hir::MutMutable => self.word_nbsp("mut")?,
384 hir::MutImmutable => self.word_nbsp("const")?,
386 self.print_type(&mt.ty)?;
388 hir::TyRptr(ref lifetime, ref mt) => {
389 word(&mut self.s, "&")?;
390 self.print_opt_lifetime(lifetime)?;
394 word(&mut self.s, "!")?;
396 hir::TyTup(ref elts) => {
398 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty))?;
400 word(&mut self.s, ",")?;
404 hir::TyBareFn(ref f) => {
405 let generics = hir::Generics {
406 lifetimes: f.lifetimes.clone(),
407 ty_params: hir::HirVec::new(),
408 where_clause: hir::WhereClause {
409 id: ast::DUMMY_NODE_ID,
410 predicates: hir::HirVec::new(),
412 span: syntax_pos::DUMMY_SP,
414 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &generics)?;
416 hir::TyPath(ref qpath) => {
417 self.print_qpath(qpath, false)?
419 hir::TyTraitObject(ref bounds, ref lifetime) => {
420 let mut first = true;
421 for bound in bounds {
426 self.word_space("+")?;
428 self.print_poly_trait_ref(bound)?;
430 if !lifetime.is_elided() {
431 self.word_space("+")?;
432 self.print_lifetime(lifetime)?;
435 hir::TyImplTrait(ref bounds) => {
436 self.print_bounds("impl ", &bounds[..])?;
438 hir::TyArray(ref ty, v) => {
439 word(&mut self.s, "[")?;
440 self.print_type(&ty)?;
441 word(&mut self.s, "; ")?;
442 self.ann.nested(self, Nested::Body(v))?;
443 word(&mut self.s, "]")?;
445 hir::TyTypeof(e) => {
446 word(&mut self.s, "typeof(")?;
447 self.ann.nested(self, Nested::Body(e))?;
448 word(&mut self.s, ")")?;
451 word(&mut self.s, "_")?;
454 word(&mut self.s, "?")?;
460 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
461 self.hardbreak_if_not_bol()?;
462 self.maybe_print_comment(item.span.lo)?;
463 self.print_outer_attributes(&item.attrs)?;
465 hir::ForeignItemFn(ref decl, ref arg_names, ref generics) => {
468 hir::Unsafety::Normal,
469 hir::Constness::NotConst,
476 self.end()?; // end head-ibox
477 word(&mut self.s, ";")?;
478 self.end() // end the outer fn box
480 hir::ForeignItemStatic(ref t, m) => {
481 self.head(&visibility_qualified(&item.vis, "static"))?;
483 self.word_space("mut")?;
485 self.print_name(item.name)?;
486 self.word_space(":")?;
487 self.print_type(&t)?;
488 word(&mut self.s, ";")?;
489 self.end()?; // end the head-ibox
490 self.end() // end the outer cbox
495 fn print_associated_const(&mut self,
498 default: Option<hir::BodyId>,
499 vis: &hir::Visibility)
501 word(&mut self.s, &visibility_qualified(vis, ""))?;
502 self.word_space("const")?;
503 self.print_name(name)?;
504 self.word_space(":")?;
505 self.print_type(ty)?;
506 if let Some(expr) = default {
508 self.word_space("=")?;
509 self.ann.nested(self, Nested::Body(expr))?;
511 word(&mut self.s, ";")
514 fn print_associated_type(&mut self,
516 bounds: Option<&hir::TyParamBounds>,
517 ty: Option<&hir::Ty>)
519 self.word_space("type")?;
520 self.print_name(name)?;
521 if let Some(bounds) = bounds {
522 self.print_bounds(":", bounds)?;
524 if let Some(ty) = ty {
526 self.word_space("=")?;
527 self.print_type(ty)?;
529 word(&mut self.s, ";")
532 /// Pretty-print an item
533 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
534 self.hardbreak_if_not_bol()?;
535 self.maybe_print_comment(item.span.lo)?;
536 self.print_outer_attributes(&item.attrs)?;
537 self.ann.pre(self, NodeItem(item))?;
539 hir::ItemExternCrate(ref optional_path) => {
540 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
541 if let Some(p) = *optional_path {
542 let val = p.as_str();
543 if val.contains("-") {
544 self.print_string(&val, ast::StrStyle::Cooked)?;
549 word(&mut self.s, "as")?;
552 self.print_name(item.name)?;
553 word(&mut self.s, ";")?;
554 self.end()?; // end inner head-block
555 self.end()?; // end outer head-block
557 hir::ItemUse(ref path, kind) => {
558 self.head(&visibility_qualified(&item.vis, "use"))?;
559 self.print_path(path, false)?;
562 hir::UseKind::Single => {
563 if path.segments.last().unwrap().name != item.name {
565 self.word_space("as")?;
566 self.print_name(item.name)?;
568 word(&mut self.s, ";")?;
570 hir::UseKind::Glob => word(&mut self.s, "::*;")?,
571 hir::UseKind::ListStem => word(&mut self.s, "::{};")?
573 self.end()?; // end inner head-block
574 self.end()?; // end outer head-block
576 hir::ItemStatic(ref ty, m, expr) => {
577 self.head(&visibility_qualified(&item.vis, "static"))?;
578 if m == hir::MutMutable {
579 self.word_space("mut")?;
581 self.print_name(item.name)?;
582 self.word_space(":")?;
583 self.print_type(&ty)?;
585 self.end()?; // end the head-ibox
587 self.word_space("=")?;
588 self.ann.nested(self, Nested::Body(expr))?;
589 word(&mut self.s, ";")?;
590 self.end()?; // end the outer cbox
592 hir::ItemConst(ref ty, expr) => {
593 self.head(&visibility_qualified(&item.vis, "const"))?;
594 self.print_name(item.name)?;
595 self.word_space(":")?;
596 self.print_type(&ty)?;
598 self.end()?; // end the head-ibox
600 self.word_space("=")?;
601 self.ann.nested(self, Nested::Body(expr))?;
602 word(&mut self.s, ";")?;
603 self.end()?; // end the outer cbox
605 hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, body) => {
616 word(&mut self.s, " ")?;
617 self.end()?; // need to close a box
618 self.end()?; // need to close a box
619 self.ann.nested(self, Nested::Body(body))?;
621 hir::ItemMod(ref _mod) => {
622 self.head(&visibility_qualified(&item.vis, "mod"))?;
623 self.print_name(item.name)?;
626 self.print_mod(_mod, &item.attrs)?;
627 self.bclose(item.span)?;
629 hir::ItemForeignMod(ref nmod) => {
630 self.head("extern")?;
631 self.word_nbsp(&nmod.abi.to_string())?;
633 self.print_foreign_mod(nmod, &item.attrs)?;
634 self.bclose(item.span)?;
636 hir::ItemGlobalAsm(ref ga) => {
637 self.head(&visibility_qualified(&item.vis, "global asm"))?;
638 word(&mut self.s, &ga.asm.as_str())?;
641 hir::ItemTy(ref ty, ref params) => {
642 self.ibox(indent_unit)?;
644 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
645 self.print_name(item.name)?;
646 self.print_generics(params)?;
647 self.end()?; // end the inner ibox
649 self.print_where_clause(¶ms.where_clause)?;
651 self.word_space("=")?;
652 self.print_type(&ty)?;
653 word(&mut self.s, ";")?;
654 self.end()?; // end the outer ibox
656 hir::ItemEnum(ref enum_definition, ref params) => {
657 self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
659 hir::ItemStruct(ref struct_def, ref generics) => {
660 self.head(&visibility_qualified(&item.vis, "struct"))?;
661 self.print_struct(struct_def, generics, item.name, item.span, true)?;
663 hir::ItemUnion(ref struct_def, ref generics) => {
664 self.head(&visibility_qualified(&item.vis, "union"))?;
665 self.print_struct(struct_def, generics, item.name, item.span, true)?;
667 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
669 self.print_visibility(&item.vis)?;
670 self.print_unsafety(unsafety)?;
671 self.word_nbsp("impl")?;
672 self.print_trait_ref(trait_ref)?;
674 self.word_space("for")?;
675 self.word_space("..")?;
677 self.bclose(item.span)?;
679 hir::ItemImpl(unsafety,
686 self.print_visibility(&item.vis)?;
687 self.print_unsafety(unsafety)?;
688 self.word_nbsp("impl")?;
690 if generics.is_parameterized() {
691 self.print_generics(generics)?;
696 hir::ImplPolarity::Negative => {
697 word(&mut self.s, "!")?;
704 self.print_trait_ref(t)?;
706 self.word_space("for")?;
711 self.print_type(&ty)?;
712 self.print_where_clause(&generics.where_clause)?;
716 self.print_inner_attributes(&item.attrs)?;
717 for impl_item in impl_items {
718 self.ann.nested(self, Nested::ImplItem(impl_item.id))?;
720 self.bclose(item.span)?;
722 hir::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
724 self.print_visibility(&item.vis)?;
725 self.print_unsafety(unsafety)?;
726 self.word_nbsp("trait")?;
727 self.print_name(item.name)?;
728 self.print_generics(generics)?;
729 let mut real_bounds = Vec::with_capacity(bounds.len());
730 for b in bounds.iter() {
731 if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
733 self.word_space("for ?")?;
734 self.print_trait_ref(&ptr.trait_ref)?;
736 real_bounds.push(b.clone());
739 self.print_bounds(":", &real_bounds[..])?;
740 self.print_where_clause(&generics.where_clause)?;
741 word(&mut self.s, " ")?;
743 for trait_item in trait_items {
744 self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
746 self.bclose(item.span)?;
749 self.ann.post(self, NodeItem(item))
752 pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
753 self.print_path(&t.path, false)
756 fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
757 if !lifetimes.is_empty() {
758 word(&mut self.s, "for<")?;
759 let mut comma = false;
760 for lifetime_def in lifetimes {
762 self.word_space(",")?
764 self.print_lifetime_def(lifetime_def)?;
767 word(&mut self.s, ">")?;
772 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
773 self.print_formal_lifetime_list(&t.bound_lifetimes)?;
774 self.print_trait_ref(&t.trait_ref)
777 pub fn print_enum_def(&mut self,
778 enum_definition: &hir::EnumDef,
779 generics: &hir::Generics,
781 span: syntax_pos::Span,
782 visibility: &hir::Visibility)
784 self.head(&visibility_qualified(visibility, "enum"))?;
785 self.print_name(name)?;
786 self.print_generics(generics)?;
787 self.print_where_clause(&generics.where_clause)?;
789 self.print_variants(&enum_definition.variants, span)
792 pub fn print_variants(&mut self,
793 variants: &[hir::Variant],
794 span: syntax_pos::Span)
798 self.space_if_not_bol()?;
799 self.maybe_print_comment(v.span.lo)?;
800 self.print_outer_attributes(&v.node.attrs)?;
801 self.ibox(indent_unit)?;
802 self.print_variant(v)?;
803 word(&mut self.s, ",")?;
805 self.maybe_print_trailing_comment(v.span, None)?;
810 pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
812 hir::Public => self.word_nbsp("pub"),
813 hir::Visibility::Crate => self.word_nbsp("pub(crate)"),
814 hir::Visibility::Restricted { ref path, .. } => {
815 word(&mut self.s, "pub(")?;
816 self.print_path(path, false)?;
819 hir::Inherited => Ok(()),
823 pub fn print_struct(&mut self,
824 struct_def: &hir::VariantData,
825 generics: &hir::Generics,
827 span: syntax_pos::Span,
828 print_finalizer: bool)
830 self.print_name(name)?;
831 self.print_generics(generics)?;
832 if !struct_def.is_struct() {
833 if struct_def.is_tuple() {
835 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
836 s.maybe_print_comment(field.span.lo)?;
837 s.print_outer_attributes(&field.attrs)?;
838 s.print_visibility(&field.vis)?;
839 s.print_type(&field.ty)
843 self.print_where_clause(&generics.where_clause)?;
845 word(&mut self.s, ";")?;
848 self.end() // close the outer-box
850 self.print_where_clause(&generics.where_clause)?;
853 self.hardbreak_if_not_bol()?;
855 for field in struct_def.fields() {
856 self.hardbreak_if_not_bol()?;
857 self.maybe_print_comment(field.span.lo)?;
858 self.print_outer_attributes(&field.attrs)?;
859 self.print_visibility(&field.vis)?;
860 self.print_name(field.name)?;
861 self.word_nbsp(":")?;
862 self.print_type(&field.ty)?;
863 word(&mut self.s, ",")?;
870 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
872 let generics = hir::Generics::empty();
873 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
874 if let Some(d) = v.node.disr_expr {
876 self.word_space("=")?;
877 self.ann.nested(self, Nested::Body(d))?;
881 pub fn print_method_sig(&mut self,
884 vis: &hir::Visibility,
885 arg_names: &[Spanned<ast::Name>],
886 body_id: Option<hir::BodyId>)
888 self.print_fn(&m.decl,
899 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
900 self.ann.pre(self, NodeSubItem(ti.id))?;
901 self.hardbreak_if_not_bol()?;
902 self.maybe_print_comment(ti.span.lo)?;
903 self.print_outer_attributes(&ti.attrs)?;
905 hir::TraitItemKind::Const(ref ty, default) => {
906 self.print_associated_const(ti.name, &ty, default, &hir::Inherited)?;
908 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
909 self.print_method_sig(ti.name, sig, &hir::Inherited, arg_names, None)?;
910 word(&mut self.s, ";")?;
912 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
914 self.print_method_sig(ti.name, sig, &hir::Inherited, &[], Some(body))?;
916 self.end()?; // need to close a box
917 self.end()?; // need to close a box
918 self.ann.nested(self, Nested::Body(body))?;
920 hir::TraitItemKind::Type(ref bounds, ref default) => {
921 self.print_associated_type(ti.name,
923 default.as_ref().map(|ty| &**ty))?;
926 self.ann.post(self, NodeSubItem(ti.id))
929 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
930 self.ann.pre(self, NodeSubItem(ii.id))?;
931 self.hardbreak_if_not_bol()?;
932 self.maybe_print_comment(ii.span.lo)?;
933 self.print_outer_attributes(&ii.attrs)?;
935 match ii.defaultness {
936 hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
937 hir::Defaultness::Final => (),
941 hir::ImplItemKind::Const(ref ty, expr) => {
942 self.print_associated_const(ii.name, &ty, Some(expr), &ii.vis)?;
944 hir::ImplItemKind::Method(ref sig, body) => {
946 self.print_method_sig(ii.name, sig, &ii.vis, &[], Some(body))?;
948 self.end()?; // need to close a box
949 self.end()?; // need to close a box
950 self.ann.nested(self, Nested::Body(body))?;
952 hir::ImplItemKind::Type(ref ty) => {
953 self.print_associated_type(ii.name, None, Some(ty))?;
956 self.ann.post(self, NodeSubItem(ii.id))
959 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
960 self.maybe_print_comment(st.span.lo)?;
962 hir::StmtDecl(ref decl, _) => {
963 self.print_decl(&decl)?;
965 hir::StmtExpr(ref expr, _) => {
966 self.space_if_not_bol()?;
967 self.print_expr(&expr)?;
969 hir::StmtSemi(ref expr, _) => {
970 self.space_if_not_bol()?;
971 self.print_expr(&expr)?;
972 word(&mut self.s, ";")?;
975 if stmt_ends_with_semi(&st.node) {
976 word(&mut self.s, ";")?;
978 self.maybe_print_trailing_comment(st.span, None)
981 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
982 self.print_block_with_attrs(blk, &[])
985 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
986 self.print_block_unclosed_indent(blk, indent_unit)
989 pub fn print_block_unclosed_indent(&mut self,
993 self.print_block_maybe_unclosed(blk, indented, &[], false)
996 pub fn print_block_with_attrs(&mut self,
998 attrs: &[ast::Attribute])
1000 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1003 pub fn print_block_maybe_unclosed(&mut self,
1006 attrs: &[ast::Attribute],
1010 hir::UnsafeBlock(..) => self.word_space("unsafe")?,
1011 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
1012 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
1013 hir::DefaultBlock => (),
1015 self.maybe_print_comment(blk.span.lo)?;
1016 self.ann.pre(self, NodeBlock(blk))?;
1019 self.print_inner_attributes(attrs)?;
1021 for st in &blk.stmts {
1022 self.print_stmt(st)?;
1026 self.space_if_not_bol()?;
1027 self.print_expr(&expr)?;
1028 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
1032 self.bclose_maybe_open(blk.span, indented, close_box)?;
1033 self.ann.post(self, NodeBlock(blk))
1036 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1040 // "another else-if"
1041 hir::ExprIf(ref i, ref then, ref e) => {
1042 self.cbox(indent_unit - 1)?;
1044 word(&mut self.s, " else if ")?;
1045 self.print_expr(&i)?;
1046 space(&mut self.s)?;
1047 self.print_expr(&then)?;
1048 self.print_else(e.as_ref().map(|e| &**e))
1051 hir::ExprBlock(ref b) => {
1052 self.cbox(indent_unit - 1)?;
1054 word(&mut self.s, " else ")?;
1055 self.print_block(&b)
1057 // BLEAH, constraints would be great here
1059 panic!("print_if saw if with weird alternative");
1067 pub fn print_if(&mut self,
1070 elseopt: Option<&hir::Expr>)
1073 self.print_expr(test)?;
1074 space(&mut self.s)?;
1075 self.print_expr(blk)?;
1076 self.print_else(elseopt)
1079 pub fn print_if_let(&mut self,
1083 elseopt: Option<&hir::Expr>)
1085 self.head("if let")?;
1086 self.print_pat(pat)?;
1087 space(&mut self.s)?;
1088 self.word_space("=")?;
1089 self.print_expr(expr)?;
1090 space(&mut self.s)?;
1091 self.print_block(blk)?;
1092 self.print_else(elseopt)
1096 fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
1098 self.commasep_exprs(Inconsistent, args)?;
1102 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr) -> io::Result<()> {
1103 let needs_par = needs_parentheses(expr);
1107 self.print_expr(expr)?;
1114 fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1115 self.ibox(indent_unit)?;
1116 word(&mut self.s, "[")?;
1117 self.commasep_exprs(Inconsistent, exprs)?;
1118 word(&mut self.s, "]")?;
1122 fn print_expr_repeat(&mut self, element: &hir::Expr, count: hir::BodyId) -> io::Result<()> {
1123 self.ibox(indent_unit)?;
1124 word(&mut self.s, "[")?;
1125 self.print_expr(element)?;
1126 self.word_space(";")?;
1127 self.ann.nested(self, Nested::Body(count))?;
1128 word(&mut self.s, "]")?;
1132 fn print_expr_struct(&mut self,
1134 fields: &[hir::Field],
1135 wth: &Option<P<hir::Expr>>)
1137 self.print_qpath(qpath, true)?;
1138 word(&mut self.s, "{")?;
1139 self.commasep_cmnt(Consistent,
1142 s.ibox(indent_unit)?;
1143 if !field.is_shorthand {
1144 s.print_name(field.name.node)?;
1147 s.print_expr(&field.expr)?;
1153 self.ibox(indent_unit)?;
1154 if !fields.is_empty() {
1155 word(&mut self.s, ",")?;
1156 space(&mut self.s)?;
1158 word(&mut self.s, "..")?;
1159 self.print_expr(&expr)?;
1162 _ => if !fields.is_empty() {
1163 word(&mut self.s, ",")?
1166 word(&mut self.s, "}")?;
1170 fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1172 self.commasep_exprs(Inconsistent, exprs)?;
1173 if exprs.len() == 1 {
1174 word(&mut self.s, ",")?;
1179 fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1180 self.print_expr_maybe_paren(func)?;
1181 self.print_call_post(args)
1184 fn print_expr_method_call(&mut self,
1185 name: Spanned<ast::Name>,
1189 let base_args = &args[1..];
1190 self.print_expr(&args[0])?;
1191 word(&mut self.s, ".")?;
1192 self.print_name(name.node)?;
1193 if !tys.is_empty() {
1194 word(&mut self.s, "::<")?;
1195 self.commasep(Inconsistent, tys, |s, ty| s.print_type(&ty))?;
1196 word(&mut self.s, ">")?;
1198 self.print_call_post(base_args)
1201 fn print_expr_binary(&mut self,
1206 self.print_expr(lhs)?;
1207 space(&mut self.s)?;
1208 self.word_space(op.node.as_str())?;
1209 self.print_expr(rhs)
1212 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1213 word(&mut self.s, op.as_str())?;
1214 self.print_expr_maybe_paren(expr)
1217 fn print_expr_addr_of(&mut self,
1218 mutability: hir::Mutability,
1221 word(&mut self.s, "&")?;
1222 self.print_mutability(mutability)?;
1223 self.print_expr_maybe_paren(expr)
1226 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1227 self.maybe_print_comment(expr.span.lo)?;
1228 self.print_outer_attributes(&expr.attrs)?;
1229 self.ibox(indent_unit)?;
1230 self.ann.pre(self, NodeExpr(expr))?;
1232 hir::ExprBox(ref expr) => {
1233 self.word_space("box")?;
1234 self.print_expr(expr)?;
1236 hir::ExprArray(ref exprs) => {
1237 self.print_expr_vec(exprs)?;
1239 hir::ExprRepeat(ref element, count) => {
1240 self.print_expr_repeat(&element, count)?;
1242 hir::ExprStruct(ref qpath, ref fields, ref wth) => {
1243 self.print_expr_struct(qpath, &fields[..], wth)?;
1245 hir::ExprTup(ref exprs) => {
1246 self.print_expr_tup(exprs)?;
1248 hir::ExprCall(ref func, ref args) => {
1249 self.print_expr_call(&func, args)?;
1251 hir::ExprMethodCall(name, ref tys, ref args) => {
1252 self.print_expr_method_call(name, &tys[..], args)?;
1254 hir::ExprBinary(op, ref lhs, ref rhs) => {
1255 self.print_expr_binary(op, &lhs, &rhs)?;
1257 hir::ExprUnary(op, ref expr) => {
1258 self.print_expr_unary(op, &expr)?;
1260 hir::ExprAddrOf(m, ref expr) => {
1261 self.print_expr_addr_of(m, &expr)?;
1263 hir::ExprLit(ref lit) => {
1264 self.print_literal(&lit)?;
1266 hir::ExprCast(ref expr, ref ty) => {
1267 self.print_expr(&expr)?;
1268 space(&mut self.s)?;
1269 self.word_space("as")?;
1270 self.print_type(&ty)?;
1272 hir::ExprType(ref expr, ref ty) => {
1273 self.print_expr(&expr)?;
1274 self.word_space(":")?;
1275 self.print_type(&ty)?;
1277 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1278 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1280 hir::ExprWhile(ref test, ref blk, opt_sp_name) => {
1281 if let Some(sp_name) = opt_sp_name {
1282 self.print_name(sp_name.node)?;
1283 self.word_space(":")?;
1285 self.head("while")?;
1286 self.print_expr(&test)?;
1287 space(&mut self.s)?;
1288 self.print_block(&blk)?;
1290 hir::ExprLoop(ref blk, opt_sp_name, _) => {
1291 if let Some(sp_name) = opt_sp_name {
1292 self.print_name(sp_name.node)?;
1293 self.word_space(":")?;
1296 space(&mut self.s)?;
1297 self.print_block(&blk)?;
1299 hir::ExprMatch(ref expr, ref arms, _) => {
1300 self.cbox(indent_unit)?;
1302 self.word_nbsp("match")?;
1303 self.print_expr(&expr)?;
1304 space(&mut self.s)?;
1307 self.print_arm(arm)?;
1309 self.bclose_(expr.span, indent_unit)?;
1311 hir::ExprClosure(capture_clause, ref decl, body, _fn_decl_span) => {
1312 self.print_capture_clause(capture_clause)?;
1314 self.print_closure_args(&decl, body)?;
1315 space(&mut self.s)?;
1317 // this is a bare expression
1318 self.ann.nested(self, Nested::Body(body))?;
1319 self.end()?; // need to close a box
1321 // a box will be closed by print_expr, but we didn't want an overall
1322 // wrapper so we closed the corresponding opening. so create an
1323 // empty box to satisfy the close.
1326 hir::ExprBlock(ref blk) => {
1327 // containing cbox, will be closed by print-block at }
1328 self.cbox(indent_unit)?;
1329 // head-box, will be closed by print-block after {
1331 self.print_block(&blk)?;
1333 hir::ExprAssign(ref lhs, ref rhs) => {
1334 self.print_expr(&lhs)?;
1335 space(&mut self.s)?;
1336 self.word_space("=")?;
1337 self.print_expr(&rhs)?;
1339 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1340 self.print_expr(&lhs)?;
1341 space(&mut self.s)?;
1342 word(&mut self.s, op.node.as_str())?;
1343 self.word_space("=")?;
1344 self.print_expr(&rhs)?;
1346 hir::ExprField(ref expr, name) => {
1347 self.print_expr(&expr)?;
1348 word(&mut self.s, ".")?;
1349 self.print_name(name.node)?;
1351 hir::ExprTupField(ref expr, id) => {
1352 self.print_expr(&expr)?;
1353 word(&mut self.s, ".")?;
1354 self.print_usize(id.node)?;
1356 hir::ExprIndex(ref expr, ref index) => {
1357 self.print_expr(&expr)?;
1358 word(&mut self.s, "[")?;
1359 self.print_expr(&index)?;
1360 word(&mut self.s, "]")?;
1362 hir::ExprPath(ref qpath) => {
1363 self.print_qpath(qpath, true)?
1365 hir::ExprBreak(label, ref opt_expr) => {
1366 word(&mut self.s, "break")?;
1367 space(&mut self.s)?;
1368 if let Some(label_ident) = label.ident {
1369 self.print_name(label_ident.node.name)?;
1370 space(&mut self.s)?;
1372 if let Some(ref expr) = *opt_expr {
1373 self.print_expr(expr)?;
1374 space(&mut self.s)?;
1377 hir::ExprAgain(label) => {
1378 word(&mut self.s, "continue")?;
1379 space(&mut self.s)?;
1380 if let Some(label_ident) = label.ident {
1381 self.print_name(label_ident.node.name)?;
1385 hir::ExprRet(ref result) => {
1386 word(&mut self.s, "return")?;
1389 word(&mut self.s, " ")?;
1390 self.print_expr(&expr)?;
1395 hir::ExprInlineAsm(ref a, ref outputs, ref inputs) => {
1396 word(&mut self.s, "asm!")?;
1398 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
1399 self.word_space(":")?;
1401 let mut out_idx = 0;
1402 self.commasep(Inconsistent, &a.outputs, |s, out| {
1403 let constraint = out.constraint.as_str();
1404 let mut ch = constraint.chars();
1406 Some('=') if out.is_rw => {
1407 s.print_string(&format!("+{}", ch.as_str()),
1408 ast::StrStyle::Cooked)?
1410 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
1413 s.print_expr(&outputs[out_idx])?;
1418 space(&mut self.s)?;
1419 self.word_space(":")?;
1422 self.commasep(Inconsistent, &a.inputs, |s, co| {
1423 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1425 s.print_expr(&inputs[in_idx])?;
1430 space(&mut self.s)?;
1431 self.word_space(":")?;
1433 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1434 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1438 let mut options = vec![];
1440 options.push("volatile");
1443 options.push("alignstack");
1445 if a.dialect == ast::AsmDialect::Intel {
1446 options.push("intel");
1449 if !options.is_empty() {
1450 space(&mut self.s)?;
1451 self.word_space(":")?;
1452 self.commasep(Inconsistent, &options, |s, &co| {
1453 s.print_string(co, ast::StrStyle::Cooked)?;
1461 self.ann.post(self, NodeExpr(expr))?;
1465 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1466 self.print_pat(&loc.pat)?;
1467 if let Some(ref ty) = loc.ty {
1468 self.word_space(":")?;
1469 self.print_type(&ty)?;
1474 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1475 self.maybe_print_comment(decl.span.lo)?;
1477 hir::DeclLocal(ref loc) => {
1478 self.space_if_not_bol()?;
1479 self.ibox(indent_unit)?;
1480 self.word_nbsp("let")?;
1482 self.ibox(indent_unit)?;
1483 self.print_local_decl(&loc)?;
1485 if let Some(ref init) = loc.init {
1487 self.word_space("=")?;
1488 self.print_expr(&init)?;
1492 hir::DeclItem(item) => {
1493 self.ann.nested(self, Nested::Item(item))
1498 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1499 word(&mut self.s, &i.to_string())
1502 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1503 word(&mut self.s, &name.as_str())?;
1504 self.ann.post(self, NodeName(&name))
1507 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1508 self.print_local_decl(loc)?;
1509 space(&mut self.s)?;
1510 self.word_space("in")?;
1511 self.print_expr(coll)
1514 pub fn print_path(&mut self,
1516 colons_before_params: bool)
1518 self.maybe_print_comment(path.span.lo)?;
1520 for (i, segment) in path.segments.iter().enumerate() {
1522 word(&mut self.s, "::")?
1524 if segment.name != keywords::CrateRoot.name() && segment.name != "$crate" {
1525 self.print_name(segment.name)?;
1526 self.print_path_parameters(&segment.parameters, colons_before_params)?;
1533 pub fn print_qpath(&mut self,
1535 colons_before_params: bool)
1538 hir::QPath::Resolved(None, ref path) => {
1539 self.print_path(path, colons_before_params)
1541 hir::QPath::Resolved(Some(ref qself), ref path) => {
1542 word(&mut self.s, "<")?;
1543 self.print_type(qself)?;
1544 space(&mut self.s)?;
1545 self.word_space("as")?;
1547 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1549 word(&mut self.s, "::")?
1551 if segment.name != keywords::CrateRoot.name() && segment.name != "$crate" {
1552 self.print_name(segment.name)?;
1553 self.print_path_parameters(&segment.parameters, colons_before_params)?;
1557 word(&mut self.s, ">")?;
1558 word(&mut self.s, "::")?;
1559 let item_segment = path.segments.last().unwrap();
1560 self.print_name(item_segment.name)?;
1561 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1563 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1564 word(&mut self.s, "<")?;
1565 self.print_type(qself)?;
1566 word(&mut self.s, ">")?;
1567 word(&mut self.s, "::")?;
1568 self.print_name(item_segment.name)?;
1569 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1574 fn print_path_parameters(&mut self,
1575 parameters: &hir::PathParameters,
1576 colons_before_params: bool)
1579 hir::AngleBracketedParameters(ref data) => {
1580 let start = if colons_before_params { "::<" } else { "<" };
1581 let empty = Cell::new(true);
1582 let start_or_comma = |this: &mut Self| {
1585 word(&mut this.s, start)
1587 this.word_space(",")
1591 if !data.lifetimes.iter().all(|lt| lt.is_elided()) {
1592 for lifetime in &data.lifetimes {
1593 start_or_comma(self)?;
1594 self.print_lifetime(lifetime)?;
1598 if !data.types.is_empty() {
1599 start_or_comma(self)?;
1600 self.commasep(Inconsistent, &data.types, |s, ty| s.print_type(&ty))?;
1603 // FIXME(eddyb) This would leak into error messages, e.g.:
1604 // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1605 if data.infer_types && false {
1606 start_or_comma(self)?;
1607 word(&mut self.s, "..")?;
1610 for binding in data.bindings.iter() {
1611 start_or_comma(self)?;
1612 self.print_name(binding.name)?;
1613 space(&mut self.s)?;
1614 self.word_space("=")?;
1615 self.print_type(&binding.ty)?;
1619 word(&mut self.s, ">")?
1623 hir::ParenthesizedParameters(ref data) => {
1624 word(&mut self.s, "(")?;
1625 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(&ty))?;
1626 word(&mut self.s, ")")?;
1628 if let Some(ref ty) = data.output {
1629 self.space_if_not_bol()?;
1630 self.word_space("->")?;
1631 self.print_type(&ty)?;
1639 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1640 self.maybe_print_comment(pat.span.lo)?;
1641 self.ann.pre(self, NodePat(pat))?;
1642 // Pat isn't normalized, but the beauty of it
1643 // is that it doesn't matter
1645 PatKind::Wild => word(&mut self.s, "_")?,
1646 PatKind::Binding(binding_mode, _, ref path1, ref sub) => {
1647 match binding_mode {
1648 hir::BindByRef(mutbl) => {
1649 self.word_nbsp("ref")?;
1650 self.print_mutability(mutbl)?;
1652 hir::BindByValue(hir::MutImmutable) => {}
1653 hir::BindByValue(hir::MutMutable) => {
1654 self.word_nbsp("mut")?;
1657 self.print_name(path1.node)?;
1658 if let Some(ref p) = *sub {
1659 word(&mut self.s, "@")?;
1660 self.print_pat(&p)?;
1663 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1664 self.print_qpath(qpath, true)?;
1666 if let Some(ddpos) = ddpos {
1667 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1669 self.word_space(",")?;
1671 word(&mut self.s, "..")?;
1672 if ddpos != elts.len() {
1673 word(&mut self.s, ",")?;
1674 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1677 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1681 PatKind::Path(ref qpath) => {
1682 self.print_qpath(qpath, true)?;
1684 PatKind::Struct(ref qpath, ref fields, etc) => {
1685 self.print_qpath(qpath, true)?;
1687 self.word_space("{")?;
1688 self.commasep_cmnt(Consistent,
1691 s.cbox(indent_unit)?;
1692 if !f.node.is_shorthand {
1693 s.print_name(f.node.name)?;
1696 s.print_pat(&f.node.pat)?;
1699 |f| f.node.pat.span)?;
1701 if !fields.is_empty() {
1702 self.word_space(",")?;
1704 word(&mut self.s, "..")?;
1706 space(&mut self.s)?;
1707 word(&mut self.s, "}")?;
1709 PatKind::Tuple(ref elts, ddpos) => {
1711 if let Some(ddpos) = ddpos {
1712 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1714 self.word_space(",")?;
1716 word(&mut self.s, "..")?;
1717 if ddpos != elts.len() {
1718 word(&mut self.s, ",")?;
1719 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1722 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1723 if elts.len() == 1 {
1724 word(&mut self.s, ",")?;
1729 PatKind::Box(ref inner) => {
1730 word(&mut self.s, "box ")?;
1731 self.print_pat(&inner)?;
1733 PatKind::Ref(ref inner, mutbl) => {
1734 word(&mut self.s, "&")?;
1735 if mutbl == hir::MutMutable {
1736 word(&mut self.s, "mut ")?;
1738 self.print_pat(&inner)?;
1740 PatKind::Lit(ref e) => self.print_expr(&e)?,
1741 PatKind::Range(ref begin, ref end, ref end_kind) => {
1742 self.print_expr(&begin)?;
1743 space(&mut self.s)?;
1745 RangeEnd::Included => word(&mut self.s, "...")?,
1746 RangeEnd::Excluded => word(&mut self.s, "..")?,
1748 self.print_expr(&end)?;
1750 PatKind::Slice(ref before, ref slice, ref after) => {
1751 word(&mut self.s, "[")?;
1752 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1753 if let Some(ref p) = *slice {
1754 if !before.is_empty() {
1755 self.word_space(",")?;
1757 if p.node != PatKind::Wild {
1758 self.print_pat(&p)?;
1760 word(&mut self.s, "..")?;
1761 if !after.is_empty() {
1762 self.word_space(",")?;
1765 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1766 word(&mut self.s, "]")?;
1769 self.ann.post(self, NodePat(pat))
1772 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1773 // I have no idea why this check is necessary, but here it
1775 if arm.attrs.is_empty() {
1776 space(&mut self.s)?;
1778 self.cbox(indent_unit)?;
1780 self.print_outer_attributes(&arm.attrs)?;
1781 let mut first = true;
1782 for p in &arm.pats {
1786 space(&mut self.s)?;
1787 self.word_space("|")?;
1789 self.print_pat(&p)?;
1791 space(&mut self.s)?;
1792 if let Some(ref e) = arm.guard {
1793 self.word_space("if")?;
1794 self.print_expr(&e)?;
1795 space(&mut self.s)?;
1797 self.word_space("=>")?;
1799 match arm.body.node {
1800 hir::ExprBlock(ref blk) => {
1801 // the block will close the pattern's ibox
1802 self.print_block_unclosed_indent(&blk, indent_unit)?;
1804 // If it is a user-provided unsafe block, print a comma after it
1805 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1806 word(&mut self.s, ",")?;
1810 self.end()?; // close the ibox for the pattern
1811 self.print_expr(&arm.body)?;
1812 word(&mut self.s, ",")?;
1815 self.end() // close enclosing cbox
1818 pub fn print_fn(&mut self,
1820 unsafety: hir::Unsafety,
1821 constness: hir::Constness,
1823 name: Option<ast::Name>,
1824 generics: &hir::Generics,
1825 vis: &hir::Visibility,
1826 arg_names: &[Spanned<ast::Name>],
1827 body_id: Option<hir::BodyId>)
1829 self.print_fn_header_info(unsafety, constness, abi, vis)?;
1831 if let Some(name) = name {
1833 self.print_name(name)?;
1835 self.print_generics(generics)?;
1839 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1840 assert!(arg_names.is_empty() || body_id.is_none());
1841 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1842 s.ibox(indent_unit)?;
1843 if let Some(name) = arg_names.get(i) {
1844 word(&mut s.s, &name.node.as_str())?;
1845 word(&mut s.s, ":")?;
1847 } else if let Some(body_id) = body_id {
1848 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
1849 word(&mut s.s, ":")?;
1857 word(&mut self.s, ", ...")?;
1861 self.print_fn_output(decl)?;
1862 self.print_where_clause(&generics.where_clause)
1865 fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
1866 word(&mut self.s, "|")?;
1868 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1869 s.ibox(indent_unit)?;
1871 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
1874 if ty.node != hir::TyInfer {
1875 word(&mut s.s, ":")?;
1881 word(&mut self.s, "|")?;
1883 if let hir::DefaultReturn(..) = decl.output {
1887 self.space_if_not_bol()?;
1888 self.word_space("->")?;
1890 hir::Return(ref ty) => {
1891 self.print_type(&ty)?;
1892 self.maybe_print_comment(ty.span.lo)
1894 hir::DefaultReturn(..) => unreachable!(),
1898 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
1899 match capture_clause {
1900 hir::CaptureByValue => self.word_space("move"),
1901 hir::CaptureByRef => Ok(()),
1905 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
1906 if !bounds.is_empty() {
1907 word(&mut self.s, prefix)?;
1908 let mut first = true;
1909 for bound in bounds {
1914 self.word_space("+")?;
1918 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
1919 self.print_poly_trait_ref(tref)
1921 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
1922 word(&mut self.s, "?")?;
1923 self.print_poly_trait_ref(tref)
1925 RegionTyParamBound(ref lt) => {
1926 self.print_lifetime(lt)
1936 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
1937 self.print_name(lifetime.name)
1940 pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
1941 self.print_lifetime(&lifetime.lifetime)?;
1943 for v in &lifetime.bounds {
1944 word(&mut self.s, sep)?;
1945 self.print_lifetime(v)?;
1951 pub fn print_generics(&mut self, generics: &hir::Generics) -> io::Result<()> {
1952 let total = generics.lifetimes.len() + generics.ty_params.len();
1957 word(&mut self.s, "<")?;
1959 let mut ints = Vec::new();
1964 self.commasep(Inconsistent, &ints[..], |s, &idx| {
1965 if idx < generics.lifetimes.len() {
1966 let lifetime = &generics.lifetimes[idx];
1967 s.print_lifetime_def(lifetime)
1969 let idx = idx - generics.lifetimes.len();
1970 let param = &generics.ty_params[idx];
1971 s.print_ty_param(param)
1975 word(&mut self.s, ">")?;
1979 pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
1980 self.print_name(param.name)?;
1981 self.print_bounds(":", ¶m.bounds)?;
1982 match param.default {
1983 Some(ref default) => {
1984 space(&mut self.s)?;
1985 self.word_space("=")?;
1986 self.print_type(&default)
1992 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
1993 if where_clause.predicates.is_empty() {
1997 space(&mut self.s)?;
1998 self.word_space("where")?;
2000 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2002 self.word_space(",")?;
2006 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2010 self.print_formal_lifetime_list(bound_lifetimes)?;
2011 self.print_type(&bounded_ty)?;
2012 self.print_bounds(":", bounds)?;
2014 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2017 self.print_lifetime(lifetime)?;
2018 word(&mut self.s, ":")?;
2020 for (i, bound) in bounds.iter().enumerate() {
2021 self.print_lifetime(bound)?;
2024 word(&mut self.s, ":")?;
2028 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
2031 self.print_type(lhs_ty)?;
2032 space(&mut self.s)?;
2033 self.word_space("=")?;
2034 self.print_type(rhs_ty)?;
2042 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2044 hir::MutMutable => self.word_nbsp("mut"),
2045 hir::MutImmutable => Ok(()),
2049 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2050 self.print_mutability(mt.mutbl)?;
2051 self.print_type(&mt.ty)
2054 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2055 if let hir::DefaultReturn(..) = decl.output {
2059 self.space_if_not_bol()?;
2060 self.ibox(indent_unit)?;
2061 self.word_space("->")?;
2063 hir::DefaultReturn(..) => unreachable!(),
2064 hir::Return(ref ty) => self.print_type(&ty)?,
2069 hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
2074 pub fn print_ty_fn(&mut self,
2076 unsafety: hir::Unsafety,
2078 name: Option<ast::Name>,
2079 generics: &hir::Generics)
2081 self.ibox(indent_unit)?;
2082 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2083 word(&mut self.s, "for")?;
2084 self.print_generics(generics)?;
2086 let generics = hir::Generics {
2087 lifetimes: hir::HirVec::new(),
2088 ty_params: hir::HirVec::new(),
2089 where_clause: hir::WhereClause {
2090 id: ast::DUMMY_NODE_ID,
2091 predicates: hir::HirVec::new(),
2093 span: syntax_pos::DUMMY_SP,
2097 hir::Constness::NotConst,
2107 pub fn maybe_print_trailing_comment(&mut self,
2108 span: syntax_pos::Span,
2109 next_pos: Option<BytePos>)
2111 let cm = match self.cm {
2115 if let Some(ref cmnt) = self.next_comment() {
2116 if (*cmnt).style != comments::Trailing {
2119 let span_line = cm.lookup_char_pos(span.hi);
2120 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2121 let mut next = (*cmnt).pos + BytePos(1);
2122 if let Some(p) = next_pos {
2125 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2126 span_line.line == comment_line.line {
2127 self.print_comment(cmnt)?;
2128 self.cur_cmnt_and_lit.cur_cmnt += 1;
2134 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2135 // If there aren't any remaining comments, then we need to manually
2136 // make sure there is a line break at the end.
2137 if self.next_comment().is_none() {
2138 hardbreak(&mut self.s)?;
2141 match self.next_comment() {
2143 self.print_comment(cmnt)?;
2144 self.cur_cmnt_and_lit.cur_cmnt += 1;
2152 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2153 opt_abi: Option<Abi>)
2156 Some(Abi::Rust) => Ok(()),
2158 self.word_nbsp("extern")?;
2159 self.word_nbsp(&abi.to_string())
2165 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2168 self.word_nbsp("extern")?;
2169 self.word_nbsp(&abi.to_string())
2175 pub fn print_fn_header_info(&mut self,
2176 unsafety: hir::Unsafety,
2177 constness: hir::Constness,
2179 vis: &hir::Visibility)
2181 word(&mut self.s, &visibility_qualified(vis, ""))?;
2182 self.print_unsafety(unsafety)?;
2185 hir::Constness::NotConst => {}
2186 hir::Constness::Const => self.word_nbsp("const")?,
2189 if abi != Abi::Rust {
2190 self.word_nbsp("extern")?;
2191 self.word_nbsp(&abi.to_string())?;
2194 word(&mut self.s, "fn")
2197 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2199 hir::Unsafety::Normal => Ok(()),
2200 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2205 // Dup'ed from parse::classify, but adapted for the HIR.
2206 /// Does this expression require a semicolon to be treated
2207 /// as a statement? The negation of this: 'can this expression
2208 /// be used as a statement without a semicolon' -- is used
2209 /// as an early-bail-out in the parser so that, for instance,
2210 /// if true {...} else {...}
2212 /// isn't parsed as (if true {...} else {...} | x) | 5
2213 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2216 hir::ExprMatch(..) |
2218 hir::ExprWhile(..) |
2219 hir::ExprLoop(..) => false,
2224 /// this statement requires a semicolon after it.
2225 /// note that in one case (stmt_semi), we've already
2226 /// seen the semicolon, and thus don't need another.
2227 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2229 hir::StmtDecl(ref d, _) => {
2231 hir::DeclLocal(_) => true,
2232 hir::DeclItem(_) => false,
2235 hir::StmtExpr(ref e, _) => {
2236 expr_requires_semi_to_be_stmt(&e)
2238 hir::StmtSemi(..) => {