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, Breaks};
19 use syntax::print::pp::Breaks::{Consistent, Inconsistent};
20 use syntax::print::pprust::PrintState;
22 use syntax::symbol::keywords;
23 use syntax::util::parser::{self, AssocOp, Fixity};
24 use syntax_pos::{self, BytePos};
27 use hir::{PatKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier, RangeEnd};
30 use std::io::{self, Write, Read};
31 use std::iter::Peekable;
34 pub enum AnnNode<'a> {
35 NodeName(&'a ast::Name),
36 NodeBlock(&'a hir::Block),
37 NodeItem(&'a hir::Item),
38 NodeSubItem(ast::NodeId),
39 NodeExpr(&'a hir::Expr),
40 NodePat(&'a hir::Pat),
45 TraitItem(hir::TraitItemId),
46 ImplItem(hir::ImplItemId),
48 BodyArgPat(hir::BodyId, usize)
52 fn nested(&self, _state: &mut State, _nested: Nested) -> io::Result<()> {
55 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
58 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
64 impl PpAnn for NoAnn {}
65 pub const NO_ANN: &'static PpAnn = &NoAnn;
67 impl PpAnn for hir::Crate {
68 fn nested(&self, state: &mut State, nested: Nested) -> io::Result<()> {
70 Nested::Item(id) => state.print_item(self.item(id.id)),
71 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
72 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
73 Nested::Body(id) => state.print_expr(&self.body(id).value),
74 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
79 pub struct State<'a> {
80 pub s: pp::Printer<'a>,
81 cm: Option<&'a CodeMap>,
82 comments: Option<Vec<comments::Comment>>,
83 literals: Peekable<vec::IntoIter<comments::Literal>>,
85 boxes: Vec<pp::Breaks>,
86 ann: &'a (PpAnn + 'a),
89 impl<'a> PrintState<'a> for State<'a> {
90 fn writer(&mut self) -> &mut pp::Printer<'a> {
94 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
98 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
102 fn cur_cmnt(&mut self) -> &mut usize {
106 fn cur_lit(&mut self) -> Option<&comments::Literal> {
110 fn bump_lit(&mut self) -> Option<comments::Literal> {
115 #[allow(non_upper_case_globals)]
116 pub const indent_unit: usize = 4;
118 #[allow(non_upper_case_globals)]
119 pub const default_columns: usize = 78;
122 /// Requires you to pass an input filename and reader so that
123 /// it can scan the input text for comments and literals to
125 pub fn print_crate<'a>(cm: &'a CodeMap,
130 out: Box<Write + 'a>,
134 let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
136 // When printing the AST, we sometimes need to inject `#[no_std]` here.
137 // Since you can't compile the HIR, it's not necessary.
139 s.print_mod(&krate.module, &krate.attrs)?;
140 s.print_remaining_comments()?;
145 pub fn new_from_input(cm: &'a CodeMap,
149 out: Box<Write + 'a>,
153 let (cmnts, lits) = comments::gather_comments_and_literals(sess, filename, input);
159 // If the code is post expansion, don't use the table of
160 // literals, since it doesn't correspond with the literals
161 // in the AST anymore.
169 pub fn new(cm: &'a CodeMap,
170 out: Box<Write + 'a>,
172 comments: Option<Vec<comments::Comment>>,
173 literals: Option<Vec<comments::Literal>>)
176 s: pp::mk_printer(out, default_columns),
178 comments: comments.clone(),
179 literals: literals.unwrap_or_default().into_iter().peekable(),
187 pub fn to_string<F>(ann: &PpAnn, f: F) -> String
188 where F: FnOnce(&mut State) -> io::Result<()>
190 let mut wr = Vec::new();
192 let mut printer = State {
193 s: pp::mk_printer(Box::new(&mut wr), default_columns),
196 literals: vec![].into_iter().peekable(),
201 f(&mut printer).unwrap();
202 printer.s.eof().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)?;
215 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
216 self.boxes.push(pp::Breaks::Consistent);
220 pub fn nbsp(&mut self) -> io::Result<()> {
224 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
229 pub fn head(&mut self, w: &str) -> io::Result<()> {
230 // outer-box is consistent
231 self.cbox(indent_unit)?;
232 // head-box is inconsistent
233 self.ibox(w.len() + 1)?;
234 // keyword that starts the head
241 pub fn bopen(&mut self) -> io::Result<()> {
243 self.end() // close the head-box
246 pub fn bclose_(&mut self, span: syntax_pos::Span, indented: usize) -> io::Result<()> {
247 self.bclose_maybe_open(span, indented, true)
249 pub fn bclose_maybe_open(&mut self,
250 span: syntax_pos::Span,
254 self.maybe_print_comment(span.hi())?;
255 self.break_offset_if_not_bol(1, -(indented as isize))?;
258 self.end()?; // close the outer-box
262 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
263 self.bclose_(span, indent_unit)
266 pub fn in_cbox(&self) -> bool {
267 match self.boxes.last() {
268 Some(&last_box) => last_box == pp::Breaks::Consistent,
272 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
278 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
280 self.s.break_offset(n, off)
282 if off != 0 && self.s.last_token().is_hardbreak_tok() {
283 // We do something pretty sketchy here: tuck the nonzero
284 // offset-adjustment we were going to deposit along with the
285 // break into the previous hardbreak.
286 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
292 // Synthesizes a comment that was not textually present in the original source
294 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
297 self.s.word(&text[..])?;
303 pub fn commasep_cmnt<T, F, G>(&mut self,
309 where F: FnMut(&mut State, &T) -> io::Result<()>,
310 G: FnMut(&T) -> syntax_pos::Span
313 let len = elts.len();
316 self.maybe_print_comment(get_span(elt).hi())?;
321 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()))?;
322 self.space_if_not_bol()?;
328 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr]) -> io::Result<()> {
329 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
332 pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
333 self.print_inner_attributes(attrs)?;
334 for &item_id in &_mod.item_ids {
335 self.ann.nested(self, Nested::Item(item_id))?;
340 pub fn print_foreign_mod(&mut self,
341 nmod: &hir::ForeignMod,
342 attrs: &[ast::Attribute])
344 self.print_inner_attributes(attrs)?;
345 for item in &nmod.items {
346 self.print_foreign_item(item)?;
351 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
352 if !lifetime.is_elided() {
353 self.print_lifetime(lifetime)?;
359 pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
360 self.maybe_print_comment(ty.span.lo())?;
363 hir::TySlice(ref ty) => {
365 self.print_type(&ty)?;
368 hir::TyPtr(ref mt) => {
371 hir::MutMutable => self.word_nbsp("mut")?,
372 hir::MutImmutable => self.word_nbsp("const")?,
374 self.print_type(&mt.ty)?;
376 hir::TyRptr(ref lifetime, ref mt) => {
378 self.print_opt_lifetime(lifetime)?;
384 hir::TyTup(ref elts) => {
386 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty))?;
392 hir::TyBareFn(ref f) => {
393 let generics = hir::Generics {
394 lifetimes: f.lifetimes.clone(),
395 ty_params: hir::HirVec::new(),
396 where_clause: hir::WhereClause {
397 id: ast::DUMMY_NODE_ID,
398 predicates: hir::HirVec::new(),
400 span: syntax_pos::DUMMY_SP,
402 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &generics,
405 hir::TyPath(ref qpath) => {
406 self.print_qpath(qpath, false)?
408 hir::TyTraitObject(ref bounds, ref lifetime) => {
409 let mut first = true;
410 for bound in bounds {
415 self.word_space("+")?;
417 self.print_poly_trait_ref(bound)?;
419 if !lifetime.is_elided() {
420 self.word_space("+")?;
421 self.print_lifetime(lifetime)?;
424 hir::TyImplTrait(ref bounds) => {
425 self.print_bounds("impl ", &bounds[..])?;
427 hir::TyArray(ref ty, v) => {
429 self.print_type(&ty)?;
431 self.ann.nested(self, Nested::Body(v))?;
434 hir::TyTypeof(e) => {
435 self.s.word("typeof(")?;
436 self.ann.nested(self, Nested::Body(e))?;
449 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
450 self.hardbreak_if_not_bol()?;
451 self.maybe_print_comment(item.span.lo())?;
452 self.print_outer_attributes(&item.attrs)?;
454 hir::ForeignItemFn(ref decl, ref arg_names, ref generics) => {
457 hir::Unsafety::Normal,
458 hir::Constness::NotConst,
465 self.end()?; // end head-ibox
467 self.end() // end the outer fn box
469 hir::ForeignItemStatic(ref t, m) => {
470 self.head(&visibility_qualified(&item.vis, "static"))?;
472 self.word_space("mut")?;
474 self.print_name(item.name)?;
475 self.word_space(":")?;
476 self.print_type(&t)?;
478 self.end()?; // end the head-ibox
479 self.end() // end the outer cbox
481 hir::ForeignItemType => {
482 self.head(&visibility_qualified(&item.vis, "type"))?;
483 self.print_name(item.name)?;
485 self.end()?; // end the head-ibox
486 self.end() // end the outer cbox
491 fn print_associated_const(&mut self,
494 default: Option<hir::BodyId>,
495 vis: &hir::Visibility)
497 self.s.word(&visibility_qualified(vis, ""))?;
498 self.word_space("const")?;
499 self.print_name(name)?;
500 self.word_space(":")?;
501 self.print_type(ty)?;
502 if let Some(expr) = default {
504 self.word_space("=")?;
505 self.ann.nested(self, Nested::Body(expr))?;
510 fn print_associated_type(&mut self,
512 bounds: Option<&hir::TyParamBounds>,
513 ty: Option<&hir::Ty>)
515 self.word_space("type")?;
516 self.print_name(name)?;
517 if let Some(bounds) = bounds {
518 self.print_bounds(":", bounds)?;
520 if let Some(ty) = ty {
522 self.word_space("=")?;
523 self.print_type(ty)?;
528 /// Pretty-print an item
529 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
530 self.hardbreak_if_not_bol()?;
531 self.maybe_print_comment(item.span.lo())?;
532 self.print_outer_attributes(&item.attrs)?;
533 self.ann.pre(self, NodeItem(item))?;
535 hir::ItemExternCrate(ref optional_path) => {
536 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
537 if let Some(p) = *optional_path {
538 let val = p.as_str();
539 if val.contains("-") {
540 self.print_string(&val, ast::StrStyle::Cooked)?;
548 self.print_name(item.name)?;
550 self.end()?; // end inner head-block
551 self.end()?; // end outer head-block
553 hir::ItemUse(ref path, kind) => {
554 self.head(&visibility_qualified(&item.vis, "use"))?;
555 self.print_path(path, false)?;
558 hir::UseKind::Single => {
559 if path.segments.last().unwrap().name != item.name {
561 self.word_space("as")?;
562 self.print_name(item.name)?;
566 hir::UseKind::Glob => self.s.word("::*;")?,
567 hir::UseKind::ListStem => self.s.word("::{};")?
569 self.end()?; // end inner head-block
570 self.end()?; // end outer head-block
572 hir::ItemStatic(ref ty, m, expr) => {
573 self.head(&visibility_qualified(&item.vis, "static"))?;
574 if m == hir::MutMutable {
575 self.word_space("mut")?;
577 self.print_name(item.name)?;
578 self.word_space(":")?;
579 self.print_type(&ty)?;
581 self.end()?; // end the head-ibox
583 self.word_space("=")?;
584 self.ann.nested(self, Nested::Body(expr))?;
586 self.end()?; // end the outer cbox
588 hir::ItemConst(ref ty, expr) => {
589 self.head(&visibility_qualified(&item.vis, "const"))?;
590 self.print_name(item.name)?;
591 self.word_space(":")?;
592 self.print_type(&ty)?;
594 self.end()?; // end the head-ibox
596 self.word_space("=")?;
597 self.ann.nested(self, Nested::Body(expr))?;
599 self.end()?; // end the outer cbox
601 hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, body) => {
613 self.end()?; // need to close a box
614 self.end()?; // need to close a box
615 self.ann.nested(self, Nested::Body(body))?;
617 hir::ItemMod(ref _mod) => {
618 self.head(&visibility_qualified(&item.vis, "mod"))?;
619 self.print_name(item.name)?;
622 self.print_mod(_mod, &item.attrs)?;
623 self.bclose(item.span)?;
625 hir::ItemForeignMod(ref nmod) => {
626 self.head("extern")?;
627 self.word_nbsp(&nmod.abi.to_string())?;
629 self.print_foreign_mod(nmod, &item.attrs)?;
630 self.bclose(item.span)?;
632 hir::ItemGlobalAsm(ref ga) => {
633 self.head(&visibility_qualified(&item.vis, "global asm"))?;
634 self.s.word(&ga.asm.as_str())?;
637 hir::ItemTy(ref ty, ref params) => {
638 self.ibox(indent_unit)?;
640 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
641 self.print_name(item.name)?;
642 self.print_generics(params)?;
643 self.end()?; // end the inner ibox
645 self.print_where_clause(¶ms.where_clause)?;
647 self.word_space("=")?;
648 self.print_type(&ty)?;
650 self.end()?; // end the outer ibox
652 hir::ItemEnum(ref enum_definition, ref params) => {
653 self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
655 hir::ItemStruct(ref struct_def, ref generics) => {
656 self.head(&visibility_qualified(&item.vis, "struct"))?;
657 self.print_struct(struct_def, generics, item.name, item.span, true)?;
659 hir::ItemUnion(ref struct_def, ref generics) => {
660 self.head(&visibility_qualified(&item.vis, "union"))?;
661 self.print_struct(struct_def, generics, item.name, item.span, true)?;
663 hir::ItemAutoImpl(unsafety, ref trait_ref) => {
665 self.print_visibility(&item.vis)?;
666 self.print_unsafety(unsafety)?;
667 self.word_nbsp("impl")?;
668 self.print_trait_ref(trait_ref)?;
670 self.word_space("for")?;
671 self.word_space("..")?;
673 self.bclose(item.span)?;
675 hir::ItemImpl(unsafety,
683 self.print_visibility(&item.vis)?;
684 self.print_defaultness(defaultness)?;
685 self.print_unsafety(unsafety)?;
686 self.word_nbsp("impl")?;
688 if generics.is_parameterized() {
689 self.print_generics(generics)?;
694 hir::ImplPolarity::Negative => {
702 self.print_trait_ref(t)?;
704 self.word_space("for")?;
709 self.print_type(&ty)?;
710 self.print_where_clause(&generics.where_clause)?;
714 self.print_inner_attributes(&item.attrs)?;
715 for impl_item in impl_items {
716 self.ann.nested(self, Nested::ImplItem(impl_item.id))?;
718 self.bclose(item.span)?;
720 hir::ItemTrait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
722 self.print_visibility(&item.vis)?;
723 self.print_is_auto(is_auto)?;
724 self.print_unsafety(unsafety)?;
725 self.word_nbsp("trait")?;
726 self.print_name(item.name)?;
727 self.print_generics(generics)?;
728 let mut real_bounds = Vec::with_capacity(bounds.len());
729 for b in bounds.iter() {
730 if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
732 self.word_space("for ?")?;
733 self.print_trait_ref(&ptr.trait_ref)?;
735 real_bounds.push(b.clone());
738 self.print_bounds(":", &real_bounds[..])?;
739 self.print_where_clause(&generics.where_clause)?;
742 for trait_item in trait_items {
743 self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
745 self.bclose(item.span)?;
748 self.ann.post(self, NodeItem(item))
751 pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
752 self.print_path(&t.path, false)
755 fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
756 if !lifetimes.is_empty() {
757 self.s.word("for<")?;
758 let mut comma = false;
759 for lifetime_def in lifetimes {
761 self.word_space(",")?
763 self.print_lifetime_def(lifetime_def)?;
771 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
772 self.print_formal_lifetime_list(&t.bound_lifetimes)?;
773 self.print_trait_ref(&t.trait_ref)
776 pub fn print_enum_def(&mut self,
777 enum_definition: &hir::EnumDef,
778 generics: &hir::Generics,
780 span: syntax_pos::Span,
781 visibility: &hir::Visibility)
783 self.head(&visibility_qualified(visibility, "enum"))?;
784 self.print_name(name)?;
785 self.print_generics(generics)?;
786 self.print_where_clause(&generics.where_clause)?;
788 self.print_variants(&enum_definition.variants, span)
791 pub fn print_variants(&mut self,
792 variants: &[hir::Variant],
793 span: syntax_pos::Span)
797 self.space_if_not_bol()?;
798 self.maybe_print_comment(v.span.lo())?;
799 self.print_outer_attributes(&v.node.attrs)?;
800 self.ibox(indent_unit)?;
801 self.print_variant(v)?;
804 self.maybe_print_trailing_comment(v.span, None)?;
809 pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
811 hir::Public => self.word_nbsp("pub"),
812 hir::Visibility::Crate => self.word_nbsp("pub(crate)"),
813 hir::Visibility::Restricted { ref path, .. } => {
814 self.s.word("pub(")?;
815 self.print_path(path, false)?;
818 hir::Inherited => Ok(()),
822 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) -> io::Result<()> {
824 hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
825 hir::Defaultness::Final => (),
830 pub fn print_struct(&mut self,
831 struct_def: &hir::VariantData,
832 generics: &hir::Generics,
834 span: syntax_pos::Span,
835 print_finalizer: bool)
837 self.print_name(name)?;
838 self.print_generics(generics)?;
839 if !struct_def.is_struct() {
840 if struct_def.is_tuple() {
842 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
843 s.maybe_print_comment(field.span.lo())?;
844 s.print_outer_attributes(&field.attrs)?;
845 s.print_visibility(&field.vis)?;
846 s.print_type(&field.ty)
850 self.print_where_clause(&generics.where_clause)?;
855 self.end() // close the outer-box
857 self.print_where_clause(&generics.where_clause)?;
860 self.hardbreak_if_not_bol()?;
862 for field in struct_def.fields() {
863 self.hardbreak_if_not_bol()?;
864 self.maybe_print_comment(field.span.lo())?;
865 self.print_outer_attributes(&field.attrs)?;
866 self.print_visibility(&field.vis)?;
867 self.print_name(field.name)?;
868 self.word_nbsp(":")?;
869 self.print_type(&field.ty)?;
877 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
879 let generics = hir::Generics::empty();
880 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
881 if let Some(d) = v.node.disr_expr {
883 self.word_space("=")?;
884 self.ann.nested(self, Nested::Body(d))?;
888 pub fn print_method_sig(&mut self,
891 generics: &hir::Generics,
892 vis: &hir::Visibility,
893 arg_names: &[Spanned<ast::Name>],
894 body_id: Option<hir::BodyId>)
896 self.print_fn(&m.decl,
907 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
908 self.ann.pre(self, NodeSubItem(ti.id))?;
909 self.hardbreak_if_not_bol()?;
910 self.maybe_print_comment(ti.span.lo())?;
911 self.print_outer_attributes(&ti.attrs)?;
913 hir::TraitItemKind::Const(ref ty, default) => {
914 self.print_associated_const(ti.name, &ty, default, &hir::Inherited)?;
916 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
917 self.print_method_sig(ti.name, sig, &ti.generics, &hir::Inherited, arg_names,
921 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
923 self.print_method_sig(ti.name, sig, &ti.generics, &hir::Inherited, &[],
926 self.end()?; // need to close a box
927 self.end()?; // need to close a box
928 self.ann.nested(self, Nested::Body(body))?;
930 hir::TraitItemKind::Type(ref bounds, ref default) => {
931 self.print_associated_type(ti.name,
933 default.as_ref().map(|ty| &**ty))?;
936 self.ann.post(self, NodeSubItem(ti.id))
939 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
940 self.ann.pre(self, NodeSubItem(ii.id))?;
941 self.hardbreak_if_not_bol()?;
942 self.maybe_print_comment(ii.span.lo())?;
943 self.print_outer_attributes(&ii.attrs)?;
944 self.print_defaultness(ii.defaultness)?;
947 hir::ImplItemKind::Const(ref ty, expr) => {
948 self.print_associated_const(ii.name, &ty, Some(expr), &ii.vis)?;
950 hir::ImplItemKind::Method(ref sig, body) => {
952 self.print_method_sig(ii.name, sig, &ii.generics, &ii.vis, &[], Some(body))?;
954 self.end()?; // need to close a box
955 self.end()?; // need to close a box
956 self.ann.nested(self, Nested::Body(body))?;
958 hir::ImplItemKind::Type(ref ty) => {
959 self.print_associated_type(ii.name, None, Some(ty))?;
962 self.ann.post(self, NodeSubItem(ii.id))
965 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
966 self.maybe_print_comment(st.span.lo())?;
968 hir::StmtDecl(ref decl, _) => {
969 self.print_decl(&decl)?;
971 hir::StmtExpr(ref expr, _) => {
972 self.space_if_not_bol()?;
973 self.print_expr(&expr)?;
975 hir::StmtSemi(ref expr, _) => {
976 self.space_if_not_bol()?;
977 self.print_expr(&expr)?;
981 if stmt_ends_with_semi(&st.node) {
984 self.maybe_print_trailing_comment(st.span, None)
987 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
988 self.print_block_with_attrs(blk, &[])
991 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
992 self.print_block_unclosed_indent(blk, indent_unit)
995 pub fn print_block_unclosed_indent(&mut self,
999 self.print_block_maybe_unclosed(blk, indented, &[], false)
1002 pub fn print_block_with_attrs(&mut self,
1004 attrs: &[ast::Attribute])
1006 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1009 pub fn print_block_maybe_unclosed(&mut self,
1012 attrs: &[ast::Attribute],
1016 hir::UnsafeBlock(..) => self.word_space("unsafe")?,
1017 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
1018 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
1019 hir::DefaultBlock => (),
1021 self.maybe_print_comment(blk.span.lo())?;
1022 self.ann.pre(self, NodeBlock(blk))?;
1025 self.print_inner_attributes(attrs)?;
1027 for st in &blk.stmts {
1028 self.print_stmt(st)?;
1032 self.space_if_not_bol()?;
1033 self.print_expr(&expr)?;
1034 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1038 self.bclose_maybe_open(blk.span, indented, close_box)?;
1039 self.ann.post(self, NodeBlock(blk))
1042 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1046 // "another else-if"
1047 hir::ExprIf(ref i, ref then, ref e) => {
1048 self.cbox(indent_unit - 1)?;
1050 self.s.word(" else if ")?;
1051 self.print_expr_as_cond(&i)?;
1053 self.print_expr(&then)?;
1054 self.print_else(e.as_ref().map(|e| &**e))
1057 hir::ExprBlock(ref b) => {
1058 self.cbox(indent_unit - 1)?;
1060 self.s.word(" else ")?;
1061 self.print_block(&b)
1063 // BLEAH, constraints would be great here
1065 panic!("print_if saw if with weird alternative");
1073 pub fn print_if(&mut self,
1076 elseopt: Option<&hir::Expr>)
1079 self.print_expr_as_cond(test)?;
1081 self.print_expr(blk)?;
1082 self.print_else(elseopt)
1085 pub fn print_if_let(&mut self,
1089 elseopt: Option<&hir::Expr>)
1091 self.head("if let")?;
1092 self.print_pat(pat)?;
1094 self.word_space("=")?;
1095 self.print_expr_as_cond(expr)?;
1097 self.print_block(blk)?;
1098 self.print_else(elseopt)
1102 fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
1104 self.commasep_exprs(Inconsistent, args)?;
1108 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr, prec: i8) -> io::Result<()> {
1109 let needs_par = expr_precedence(expr) < prec;
1113 self.print_expr(expr)?;
1120 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1121 /// `if cond { ... }`.
1122 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr) -> io::Result<()> {
1123 let needs_par = match expr.node {
1124 // These cases need parens due to the parse error observed in #26461: `if return {}`
1125 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1126 hir::ExprClosure(..) |
1128 hir::ExprBreak(..) => true,
1130 _ => contains_exterior_struct_lit(expr),
1136 self.print_expr(expr)?;
1143 fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1144 self.ibox(indent_unit)?;
1146 self.commasep_exprs(Inconsistent, exprs)?;
1151 fn print_expr_repeat(&mut self, element: &hir::Expr, count: hir::BodyId) -> io::Result<()> {
1152 self.ibox(indent_unit)?;
1154 self.print_expr(element)?;
1155 self.word_space(";")?;
1156 self.ann.nested(self, Nested::Body(count))?;
1161 fn print_expr_struct(&mut self,
1163 fields: &[hir::Field],
1164 wth: &Option<P<hir::Expr>>)
1166 self.print_qpath(qpath, true)?;
1168 self.commasep_cmnt(Consistent,
1171 s.ibox(indent_unit)?;
1172 if !field.is_shorthand {
1173 s.print_name(field.name.node)?;
1176 s.print_expr(&field.expr)?;
1182 self.ibox(indent_unit)?;
1183 if !fields.is_empty() {
1188 self.print_expr(&expr)?;
1191 _ => if !fields.is_empty() {
1199 fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1201 self.commasep_exprs(Inconsistent, exprs)?;
1202 if exprs.len() == 1 {
1208 fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1211 hir::ExprField(..) |
1212 hir::ExprTupField(..) => parser::PREC_FORCE_PAREN,
1213 _ => parser::PREC_POSTFIX,
1216 self.print_expr_maybe_paren(func, prec)?;
1217 self.print_call_post(args)
1220 fn print_expr_method_call(&mut self,
1221 segment: &hir::PathSegment,
1224 let base_args = &args[1..];
1225 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
1227 self.print_name(segment.name)?;
1229 segment.with_parameters(|parameters| {
1230 if !parameters.lifetimes.is_empty() ||
1231 !parameters.types.is_empty() ||
1232 !parameters.bindings.is_empty()
1234 self.print_path_parameters(¶meters, segment.infer_types, true)
1239 self.print_call_post(base_args)
1242 fn print_expr_binary(&mut self,
1247 let assoc_op = bin_op_to_assoc_op(op.node);
1248 let prec = assoc_op.precedence() as i8;
1249 let fixity = assoc_op.fixity();
1251 let (left_prec, right_prec) = match fixity {
1252 Fixity::Left => (prec, prec + 1),
1253 Fixity::Right => (prec + 1, prec),
1254 Fixity::None => (prec + 1, prec + 1),
1257 let left_prec = match (&lhs.node, op.node) {
1258 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1259 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1260 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1261 (&hir::ExprCast { .. }, hir::BinOp_::BiLt) |
1262 (&hir::ExprCast { .. }, hir::BinOp_::BiShl) => parser::PREC_FORCE_PAREN,
1266 self.print_expr_maybe_paren(lhs, left_prec)?;
1268 self.word_space(op.node.as_str())?;
1269 self.print_expr_maybe_paren(rhs, right_prec)
1272 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1273 self.s.word(op.as_str())?;
1274 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1277 fn print_expr_addr_of(&mut self,
1278 mutability: hir::Mutability,
1282 self.print_mutability(mutability)?;
1283 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1286 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1287 self.maybe_print_comment(expr.span.lo())?;
1288 self.print_outer_attributes(&expr.attrs)?;
1289 self.ibox(indent_unit)?;
1290 self.ann.pre(self, NodeExpr(expr))?;
1292 hir::ExprBox(ref expr) => {
1293 self.word_space("box")?;
1294 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
1296 hir::ExprArray(ref exprs) => {
1297 self.print_expr_vec(exprs)?;
1299 hir::ExprRepeat(ref element, count) => {
1300 self.print_expr_repeat(&element, count)?;
1302 hir::ExprStruct(ref qpath, ref fields, ref wth) => {
1303 self.print_expr_struct(qpath, &fields[..], wth)?;
1305 hir::ExprTup(ref exprs) => {
1306 self.print_expr_tup(exprs)?;
1308 hir::ExprCall(ref func, ref args) => {
1309 self.print_expr_call(&func, args)?;
1311 hir::ExprMethodCall(ref segment, _, ref args) => {
1312 self.print_expr_method_call(segment, args)?;
1314 hir::ExprBinary(op, ref lhs, ref rhs) => {
1315 self.print_expr_binary(op, &lhs, &rhs)?;
1317 hir::ExprUnary(op, ref expr) => {
1318 self.print_expr_unary(op, &expr)?;
1320 hir::ExprAddrOf(m, ref expr) => {
1321 self.print_expr_addr_of(m, &expr)?;
1323 hir::ExprLit(ref lit) => {
1324 self.print_literal(&lit)?;
1326 hir::ExprCast(ref expr, ref ty) => {
1327 let prec = AssocOp::As.precedence() as i8;
1328 self.print_expr_maybe_paren(&expr, prec)?;
1330 self.word_space("as")?;
1331 self.print_type(&ty)?;
1333 hir::ExprType(ref expr, ref ty) => {
1334 let prec = AssocOp::Colon.precedence() as i8;
1335 self.print_expr_maybe_paren(&expr, prec)?;
1336 self.word_space(":")?;
1337 self.print_type(&ty)?;
1339 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1340 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1342 hir::ExprWhile(ref test, ref blk, opt_sp_name) => {
1343 if let Some(sp_name) = opt_sp_name {
1344 self.print_name(sp_name.node)?;
1345 self.word_space(":")?;
1347 self.head("while")?;
1348 self.print_expr_as_cond(&test)?;
1350 self.print_block(&blk)?;
1352 hir::ExprLoop(ref blk, opt_sp_name, _) => {
1353 if let Some(sp_name) = opt_sp_name {
1354 self.print_name(sp_name.node)?;
1355 self.word_space(":")?;
1359 self.print_block(&blk)?;
1361 hir::ExprMatch(ref expr, ref arms, _) => {
1362 self.cbox(indent_unit)?;
1364 self.word_nbsp("match")?;
1365 self.print_expr_as_cond(&expr)?;
1369 self.print_arm(arm)?;
1371 self.bclose_(expr.span, indent_unit)?;
1373 hir::ExprClosure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1374 self.print_capture_clause(capture_clause)?;
1376 self.print_closure_args(&decl, body)?;
1379 // this is a bare expression
1380 self.ann.nested(self, Nested::Body(body))?;
1381 self.end()?; // need to close a box
1383 // a box will be closed by print_expr, but we didn't want an overall
1384 // wrapper so we closed the corresponding opening. so create an
1385 // empty box to satisfy the close.
1388 hir::ExprBlock(ref blk) => {
1389 // containing cbox, will be closed by print-block at }
1390 self.cbox(indent_unit)?;
1391 // head-box, will be closed by print-block after {
1393 self.print_block(&blk)?;
1395 hir::ExprAssign(ref lhs, ref rhs) => {
1396 let prec = AssocOp::Assign.precedence() as i8;
1397 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1399 self.word_space("=")?;
1400 self.print_expr_maybe_paren(&rhs, prec)?;
1402 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1403 let prec = AssocOp::Assign.precedence() as i8;
1404 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1406 self.s.word(op.node.as_str())?;
1407 self.word_space("=")?;
1408 self.print_expr_maybe_paren(&rhs, prec)?;
1410 hir::ExprField(ref expr, name) => {
1411 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
1413 self.print_name(name.node)?;
1415 hir::ExprTupField(ref expr, id) => {
1416 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1418 self.print_usize(id.node)?;
1420 hir::ExprIndex(ref expr, ref index) => {
1421 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1423 self.print_expr(&index)?;
1426 hir::ExprPath(ref qpath) => {
1427 self.print_qpath(qpath, true)?
1429 hir::ExprBreak(label, ref opt_expr) => {
1430 self.s.word("break")?;
1432 if let Some(label_ident) = label.ident {
1433 self.print_name(label_ident.node.name)?;
1436 if let Some(ref expr) = *opt_expr {
1437 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
1441 hir::ExprAgain(label) => {
1442 self.s.word("continue")?;
1444 if let Some(label_ident) = label.ident {
1445 self.print_name(label_ident.node.name)?;
1449 hir::ExprRet(ref result) => {
1450 self.s.word("return")?;
1454 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1459 hir::ExprInlineAsm(ref a, ref outputs, ref inputs) => {
1460 self.s.word("asm!")?;
1462 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
1463 self.word_space(":")?;
1465 let mut out_idx = 0;
1466 self.commasep(Inconsistent, &a.outputs, |s, out| {
1467 let constraint = out.constraint.as_str();
1468 let mut ch = constraint.chars();
1470 Some('=') if out.is_rw => {
1471 s.print_string(&format!("+{}", ch.as_str()),
1472 ast::StrStyle::Cooked)?
1474 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
1477 s.print_expr(&outputs[out_idx])?;
1483 self.word_space(":")?;
1486 self.commasep(Inconsistent, &a.inputs, |s, co| {
1487 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1489 s.print_expr(&inputs[in_idx])?;
1495 self.word_space(":")?;
1497 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1498 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1502 let mut options = vec![];
1504 options.push("volatile");
1507 options.push("alignstack");
1509 if a.dialect == ast::AsmDialect::Intel {
1510 options.push("intel");
1513 if !options.is_empty() {
1515 self.word_space(":")?;
1516 self.commasep(Inconsistent, &options, |s, &co| {
1517 s.print_string(co, ast::StrStyle::Cooked)?;
1524 hir::ExprYield(ref expr) => {
1525 self.word_space("yield")?;
1526 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1529 self.ann.post(self, NodeExpr(expr))?;
1533 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1534 self.print_pat(&loc.pat)?;
1535 if let Some(ref ty) = loc.ty {
1536 self.word_space(":")?;
1537 self.print_type(&ty)?;
1542 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1543 self.maybe_print_comment(decl.span.lo())?;
1545 hir::DeclLocal(ref loc) => {
1546 self.space_if_not_bol()?;
1547 self.ibox(indent_unit)?;
1548 self.word_nbsp("let")?;
1550 self.ibox(indent_unit)?;
1551 self.print_local_decl(&loc)?;
1553 if let Some(ref init) = loc.init {
1555 self.word_space("=")?;
1556 self.print_expr(&init)?;
1560 hir::DeclItem(item) => {
1561 self.ann.nested(self, Nested::Item(item))
1566 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1567 self.s.word(&i.to_string())
1570 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1571 self.s.word(&name.as_str())?;
1572 self.ann.post(self, NodeName(&name))
1575 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1576 self.print_local_decl(loc)?;
1578 self.word_space("in")?;
1579 self.print_expr(coll)
1582 pub fn print_path(&mut self,
1584 colons_before_params: bool)
1586 self.maybe_print_comment(path.span.lo())?;
1588 for (i, segment) in path.segments.iter().enumerate() {
1592 if segment.name != keywords::CrateRoot.name() &&
1593 segment.name != keywords::DollarCrate.name() {
1594 self.print_name(segment.name)?;
1595 segment.with_parameters(|parameters| {
1596 self.print_path_parameters(parameters,
1597 segment.infer_types,
1598 colons_before_params)
1606 pub fn print_qpath(&mut self,
1608 colons_before_params: bool)
1611 hir::QPath::Resolved(None, ref path) => {
1612 self.print_path(path, colons_before_params)
1614 hir::QPath::Resolved(Some(ref qself), ref path) => {
1616 self.print_type(qself)?;
1618 self.word_space("as")?;
1620 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1624 if segment.name != keywords::CrateRoot.name() &&
1625 segment.name != keywords::DollarCrate.name() {
1626 self.print_name(segment.name)?;
1627 segment.with_parameters(|parameters| {
1628 self.print_path_parameters(parameters,
1629 segment.infer_types,
1630 colons_before_params)
1637 let item_segment = path.segments.last().unwrap();
1638 self.print_name(item_segment.name)?;
1639 item_segment.with_parameters(|parameters| {
1640 self.print_path_parameters(parameters,
1641 item_segment.infer_types,
1642 colons_before_params)
1645 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1647 self.print_type(qself)?;
1650 self.print_name(item_segment.name)?;
1651 item_segment.with_parameters(|parameters| {
1652 self.print_path_parameters(parameters,
1653 item_segment.infer_types,
1654 colons_before_params)
1660 fn print_path_parameters(&mut self,
1661 parameters: &hir::PathParameters,
1663 colons_before_params: bool)
1665 if parameters.parenthesized {
1667 self.commasep(Inconsistent, parameters.inputs(), |s, ty| s.print_type(&ty))?;
1670 self.space_if_not_bol()?;
1671 self.word_space("->")?;
1672 self.print_type(¶meters.bindings[0].ty)?;
1674 let start = if colons_before_params { "::<" } else { "<" };
1675 let empty = Cell::new(true);
1676 let start_or_comma = |this: &mut Self| {
1681 this.word_space(",")
1685 if !parameters.lifetimes.iter().all(|lt| lt.is_elided()) {
1686 for lifetime in ¶meters.lifetimes {
1687 start_or_comma(self)?;
1688 self.print_lifetime(lifetime)?;
1692 if !parameters.types.is_empty() {
1693 start_or_comma(self)?;
1694 self.commasep(Inconsistent, ¶meters.types, |s, ty| s.print_type(&ty))?;
1697 // FIXME(eddyb) This would leak into error messages, e.g.:
1698 // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1699 if infer_types && false {
1700 start_or_comma(self)?;
1704 for binding in parameters.bindings.iter() {
1705 start_or_comma(self)?;
1706 self.print_name(binding.name)?;
1708 self.word_space("=")?;
1709 self.print_type(&binding.ty)?;
1720 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1721 self.maybe_print_comment(pat.span.lo())?;
1722 self.ann.pre(self, NodePat(pat))?;
1723 // Pat isn't normalized, but the beauty of it
1724 // is that it doesn't matter
1726 PatKind::Wild => self.s.word("_")?,
1727 PatKind::Binding(binding_mode, _, ref path1, ref sub) => {
1728 match binding_mode {
1729 hir::BindingAnnotation::Ref => {
1730 self.word_nbsp("ref")?;
1731 self.print_mutability(hir::MutImmutable)?;
1733 hir::BindingAnnotation::RefMut => {
1734 self.word_nbsp("ref")?;
1735 self.print_mutability(hir::MutMutable)?;
1737 hir::BindingAnnotation::Unannotated => {}
1738 hir::BindingAnnotation::Mutable => {
1739 self.word_nbsp("mut")?;
1742 self.print_name(path1.node)?;
1743 if let Some(ref p) = *sub {
1745 self.print_pat(&p)?;
1748 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1749 self.print_qpath(qpath, true)?;
1751 if let Some(ddpos) = ddpos {
1752 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1754 self.word_space(",")?;
1757 if ddpos != elts.len() {
1759 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1762 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1766 PatKind::Path(ref qpath) => {
1767 self.print_qpath(qpath, true)?;
1769 PatKind::Struct(ref qpath, ref fields, etc) => {
1770 self.print_qpath(qpath, true)?;
1772 self.word_space("{")?;
1773 self.commasep_cmnt(Consistent,
1776 s.cbox(indent_unit)?;
1777 if !f.node.is_shorthand {
1778 s.print_name(f.node.name)?;
1781 s.print_pat(&f.node.pat)?;
1784 |f| f.node.pat.span)?;
1786 if !fields.is_empty() {
1787 self.word_space(",")?;
1794 PatKind::Tuple(ref elts, ddpos) => {
1796 if let Some(ddpos) = ddpos {
1797 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1799 self.word_space(",")?;
1802 if ddpos != elts.len() {
1804 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1807 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1808 if elts.len() == 1 {
1814 PatKind::Box(ref inner) => {
1815 self.s.word("box ")?;
1816 self.print_pat(&inner)?;
1818 PatKind::Ref(ref inner, mutbl) => {
1820 if mutbl == hir::MutMutable {
1821 self.s.word("mut ")?;
1823 self.print_pat(&inner)?;
1825 PatKind::Lit(ref e) => self.print_expr(&e)?,
1826 PatKind::Range(ref begin, ref end, ref end_kind) => {
1827 self.print_expr(&begin)?;
1830 RangeEnd::Included => self.s.word("...")?,
1831 RangeEnd::Excluded => self.s.word("..")?,
1833 self.print_expr(&end)?;
1835 PatKind::Slice(ref before, ref slice, ref after) => {
1837 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1838 if let Some(ref p) = *slice {
1839 if !before.is_empty() {
1840 self.word_space(",")?;
1842 if p.node != PatKind::Wild {
1843 self.print_pat(&p)?;
1846 if !after.is_empty() {
1847 self.word_space(",")?;
1850 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1854 self.ann.post(self, NodePat(pat))
1857 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1858 // I have no idea why this check is necessary, but here it
1860 if arm.attrs.is_empty() {
1863 self.cbox(indent_unit)?;
1865 self.print_outer_attributes(&arm.attrs)?;
1866 let mut first = true;
1867 for p in &arm.pats {
1872 self.word_space("|")?;
1874 self.print_pat(&p)?;
1877 if let Some(ref e) = arm.guard {
1878 self.word_space("if")?;
1879 self.print_expr(&e)?;
1882 self.word_space("=>")?;
1884 match arm.body.node {
1885 hir::ExprBlock(ref blk) => {
1886 // the block will close the pattern's ibox
1887 self.print_block_unclosed_indent(&blk, indent_unit)?;
1889 // If it is a user-provided unsafe block, print a comma after it
1890 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1895 self.end()?; // close the ibox for the pattern
1896 self.print_expr(&arm.body)?;
1900 self.end() // close enclosing cbox
1903 pub fn print_fn(&mut self,
1905 unsafety: hir::Unsafety,
1906 constness: hir::Constness,
1908 name: Option<ast::Name>,
1909 generics: &hir::Generics,
1910 vis: &hir::Visibility,
1911 arg_names: &[Spanned<ast::Name>],
1912 body_id: Option<hir::BodyId>)
1914 self.print_fn_header_info(unsafety, constness, abi, vis)?;
1916 if let Some(name) = name {
1918 self.print_name(name)?;
1920 self.print_generics(generics)?;
1924 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1925 assert!(arg_names.is_empty() || body_id.is_none());
1926 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1927 s.ibox(indent_unit)?;
1928 if let Some(name) = arg_names.get(i) {
1929 s.s.word(&name.node.as_str())?;
1932 } else if let Some(body_id) = body_id {
1933 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
1942 self.s.word(", ...")?;
1946 self.print_fn_output(decl)?;
1947 self.print_where_clause(&generics.where_clause)
1950 fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
1953 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1954 s.ibox(indent_unit)?;
1956 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
1959 if ty.node != hir::TyInfer {
1968 if let hir::DefaultReturn(..) = decl.output {
1972 self.space_if_not_bol()?;
1973 self.word_space("->")?;
1975 hir::Return(ref ty) => {
1976 self.print_type(&ty)?;
1977 self.maybe_print_comment(ty.span.lo())
1979 hir::DefaultReturn(..) => unreachable!(),
1983 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
1984 match capture_clause {
1985 hir::CaptureByValue => self.word_space("move"),
1986 hir::CaptureByRef => Ok(()),
1990 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
1991 if !bounds.is_empty() {
1992 self.s.word(prefix)?;
1993 let mut first = true;
1994 for bound in bounds {
1999 self.word_space("+")?;
2003 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2004 self.print_poly_trait_ref(tref)
2006 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2008 self.print_poly_trait_ref(tref)
2010 RegionTyParamBound(ref lt) => {
2011 self.print_lifetime(lt)
2021 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2022 self.print_name(lifetime.name.name())
2025 pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
2026 self.print_lifetime(&lifetime.lifetime)?;
2028 for v in &lifetime.bounds {
2030 self.print_lifetime(v)?;
2036 pub fn print_generics(&mut self, generics: &hir::Generics) -> io::Result<()> {
2037 let total = generics.lifetimes.len() + generics.ty_params.len();
2044 let mut ints = Vec::new();
2049 self.commasep(Inconsistent, &ints[..], |s, &idx| {
2050 if idx < generics.lifetimes.len() {
2051 let lifetime = &generics.lifetimes[idx];
2052 s.print_lifetime_def(lifetime)
2054 let idx = idx - generics.lifetimes.len();
2055 let param = &generics.ty_params[idx];
2056 s.print_ty_param(param)
2064 pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
2065 self.print_name(param.name)?;
2066 self.print_bounds(":", ¶m.bounds)?;
2067 match param.default {
2068 Some(ref default) => {
2070 self.word_space("=")?;
2071 self.print_type(&default)
2077 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2078 if where_clause.predicates.is_empty() {
2083 self.word_space("where")?;
2085 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2087 self.word_space(",")?;
2091 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2095 self.print_formal_lifetime_list(bound_lifetimes)?;
2096 self.print_type(&bounded_ty)?;
2097 self.print_bounds(":", bounds)?;
2099 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2102 self.print_lifetime(lifetime)?;
2105 for (i, bound) in bounds.iter().enumerate() {
2106 self.print_lifetime(bound)?;
2113 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
2116 self.print_type(lhs_ty)?;
2118 self.word_space("=")?;
2119 self.print_type(rhs_ty)?;
2127 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2129 hir::MutMutable => self.word_nbsp("mut"),
2130 hir::MutImmutable => Ok(()),
2134 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2135 self.print_mutability(mt.mutbl)?;
2136 self.print_type(&mt.ty)
2139 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2140 if let hir::DefaultReturn(..) = decl.output {
2144 self.space_if_not_bol()?;
2145 self.ibox(indent_unit)?;
2146 self.word_space("->")?;
2148 hir::DefaultReturn(..) => unreachable!(),
2149 hir::Return(ref ty) => self.print_type(&ty)?,
2154 hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2159 pub fn print_ty_fn(&mut self,
2161 unsafety: hir::Unsafety,
2163 name: Option<ast::Name>,
2164 generics: &hir::Generics,
2165 arg_names: &[Spanned<ast::Name>])
2167 self.ibox(indent_unit)?;
2168 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2169 self.s.word("for")?;
2170 self.print_generics(generics)?;
2172 let generics = hir::Generics {
2173 lifetimes: hir::HirVec::new(),
2174 ty_params: hir::HirVec::new(),
2175 where_clause: hir::WhereClause {
2176 id: ast::DUMMY_NODE_ID,
2177 predicates: hir::HirVec::new(),
2179 span: syntax_pos::DUMMY_SP,
2183 hir::Constness::NotConst,
2193 pub fn maybe_print_trailing_comment(&mut self,
2194 span: syntax_pos::Span,
2195 next_pos: Option<BytePos>)
2197 let cm = match self.cm {
2201 if let Some(ref cmnt) = self.next_comment() {
2202 if (*cmnt).style != comments::Trailing {
2205 let span_line = cm.lookup_char_pos(span.hi());
2206 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2207 let mut next = (*cmnt).pos + BytePos(1);
2208 if let Some(p) = next_pos {
2211 if span.hi() < (*cmnt).pos && (*cmnt).pos < next &&
2212 span_line.line == comment_line.line {
2213 self.print_comment(cmnt)?;
2219 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2220 // If there aren't any remaining comments, then we need to manually
2221 // make sure there is a line break at the end.
2222 if self.next_comment().is_none() {
2223 self.s.hardbreak()?;
2226 match self.next_comment() {
2228 self.print_comment(cmnt)?;
2236 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2237 opt_abi: Option<Abi>)
2240 Some(Abi::Rust) => Ok(()),
2242 self.word_nbsp("extern")?;
2243 self.word_nbsp(&abi.to_string())
2249 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2252 self.word_nbsp("extern")?;
2253 self.word_nbsp(&abi.to_string())
2259 pub fn print_fn_header_info(&mut self,
2260 unsafety: hir::Unsafety,
2261 constness: hir::Constness,
2263 vis: &hir::Visibility)
2265 self.s.word(&visibility_qualified(vis, ""))?;
2266 self.print_unsafety(unsafety)?;
2269 hir::Constness::NotConst => {}
2270 hir::Constness::Const => self.word_nbsp("const")?,
2273 if abi != Abi::Rust {
2274 self.word_nbsp("extern")?;
2275 self.word_nbsp(&abi.to_string())?;
2281 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2283 hir::Unsafety::Normal => Ok(()),
2284 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2288 pub fn print_is_auto(&mut self, s: hir::IsAuto) -> io::Result<()> {
2290 hir::IsAuto::Yes => self.word_nbsp("auto"),
2291 hir::IsAuto::No => Ok(()),
2296 // Dup'ed from parse::classify, but adapted for the HIR.
2297 /// Does this expression require a semicolon to be treated
2298 /// as a statement? The negation of this: 'can this expression
2299 /// be used as a statement without a semicolon' -- is used
2300 /// as an early-bail-out in the parser so that, for instance,
2301 /// if true {...} else {...}
2303 /// isn't parsed as (if true {...} else {...} | x) | 5
2304 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2307 hir::ExprMatch(..) |
2309 hir::ExprWhile(..) |
2310 hir::ExprLoop(..) => false,
2315 /// this statement requires a semicolon after it.
2316 /// note that in one case (stmt_semi), we've already
2317 /// seen the semicolon, and thus don't need another.
2318 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2320 hir::StmtDecl(ref d, _) => {
2322 hir::DeclLocal(_) => true,
2323 hir::DeclItem(_) => false,
2326 hir::StmtExpr(ref e, _) => {
2327 expr_requires_semi_to_be_stmt(&e)
2329 hir::StmtSemi(..) => {
2336 fn expr_precedence(expr: &hir::Expr) -> i8 {
2337 use syntax::util::parser::*;
2340 hir::ExprClosure(..) => PREC_CLOSURE,
2342 hir::ExprBreak(..) |
2343 hir::ExprAgain(..) |
2345 hir::ExprYield(..) => PREC_JUMP,
2347 // Binop-like expr kinds, handled by `AssocOp`.
2348 hir::ExprBinary(op, _, _) => bin_op_to_assoc_op(op.node).precedence() as i8,
2350 hir::ExprCast(..) => AssocOp::As.precedence() as i8,
2351 hir::ExprType(..) => AssocOp::Colon.precedence() as i8,
2353 hir::ExprAssign(..) |
2354 hir::ExprAssignOp(..) => AssocOp::Assign.precedence() as i8,
2358 hir::ExprAddrOf(..) |
2359 hir::ExprUnary(..) => PREC_PREFIX,
2363 hir::ExprMethodCall(..) |
2364 hir::ExprField(..) |
2365 hir::ExprTupField(..) |
2366 hir::ExprIndex(..) |
2367 hir::ExprInlineAsm(..) => PREC_POSTFIX,
2369 // Never need parens
2370 hir::ExprArray(..) |
2371 hir::ExprRepeat(..) |
2376 hir::ExprWhile(..) |
2378 hir::ExprMatch(..) |
2379 hir::ExprBlock(..) |
2380 hir::ExprStruct(..) => PREC_PAREN,
2384 fn bin_op_to_assoc_op(op: hir::BinOp_) -> AssocOp {
2387 BiAdd => AssocOp::Add,
2388 BiSub => AssocOp::Subtract,
2389 BiMul => AssocOp::Multiply,
2390 BiDiv => AssocOp::Divide,
2391 BiRem => AssocOp::Modulus,
2393 BiAnd => AssocOp::LAnd,
2394 BiOr => AssocOp::LOr,
2396 BiBitXor => AssocOp::BitXor,
2397 BiBitAnd => AssocOp::BitAnd,
2398 BiBitOr => AssocOp::BitOr,
2399 BiShl => AssocOp::ShiftLeft,
2400 BiShr => AssocOp::ShiftRight,
2402 BiEq => AssocOp::Equal,
2403 BiLt => AssocOp::Less,
2404 BiLe => AssocOp::LessEqual,
2405 BiNe => AssocOp::NotEqual,
2406 BiGe => AssocOp::GreaterEqual,
2407 BiGt => AssocOp::Greater,
2411 /// Expressions that syntactically contain an "exterior" struct literal i.e. not surrounded by any
2412 /// parens or other delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2413 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2414 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
2416 hir::ExprStruct(..) => true,
2418 hir::ExprAssign(ref lhs, ref rhs) |
2419 hir::ExprAssignOp(_, ref lhs, ref rhs) |
2420 hir::ExprBinary(_, ref lhs, ref rhs) => {
2421 // X { y: 1 } + X { y: 2 }
2422 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2424 hir::ExprUnary(_, ref x) |
2425 hir::ExprCast(ref x, _) |
2426 hir::ExprType(ref x, _) |
2427 hir::ExprField(ref x, _) |
2428 hir::ExprTupField(ref x, _) |
2429 hir::ExprIndex(ref x, _) => {
2430 // &X { y: 1 }, X { y: 1 }.y
2431 contains_exterior_struct_lit(&x)
2434 hir::ExprMethodCall(.., ref exprs) => {
2435 // X { y: 1 }.bar(...)
2436 contains_exterior_struct_lit(&exprs[0])