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::*;
13 use rustc_target::spec::abi::Abi;
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, FileName};
27 use hir::{PatKind, GenericBound, TraitBoundModifier, RangeEnd};
28 use hir::{GenericParam, GenericParamKind, GenericArg};
31 use std::io::{self, Write, Read};
32 use std::iter::Peekable;
35 pub enum AnnNode<'a> {
36 NodeName(&'a ast::Name),
37 NodeBlock(&'a hir::Block),
38 NodeItem(&'a hir::Item),
39 NodeSubItem(ast::NodeId),
40 NodeExpr(&'a hir::Expr),
41 NodePat(&'a hir::Pat),
46 TraitItem(hir::TraitItemId),
47 ImplItem(hir::ImplItemId),
49 BodyArgPat(hir::BodyId, usize)
53 fn nested(&self, _state: &mut State, _nested: Nested) -> io::Result<()> {
56 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
59 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
62 fn try_fetch_item(&self, _: ast::NodeId) -> Option<&hir::Item> {
68 impl PpAnn for NoAnn {}
69 pub const NO_ANN: &'static dyn PpAnn = &NoAnn;
71 impl PpAnn for hir::Crate {
72 fn try_fetch_item(&self, item: ast::NodeId) -> Option<&hir::Item> {
75 fn nested(&self, state: &mut State, nested: Nested) -> io::Result<()> {
77 Nested::Item(id) => state.print_item(self.item(id.id)),
78 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
79 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
80 Nested::Body(id) => state.print_expr(&self.body(id).value),
81 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
86 pub struct State<'a> {
87 pub s: pp::Printer<'a>,
88 cm: Option<&'a CodeMap>,
89 comments: Option<Vec<comments::Comment>>,
90 literals: Peekable<vec::IntoIter<comments::Literal>>,
92 boxes: Vec<pp::Breaks>,
93 ann: &'a (dyn PpAnn + 'a),
96 impl<'a> PrintState<'a> for State<'a> {
97 fn writer(&mut self) -> &mut pp::Printer<'a> {
101 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
105 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
109 fn cur_cmnt(&mut self) -> &mut usize {
113 fn cur_lit(&mut self) -> Option<&comments::Literal> {
117 fn bump_lit(&mut self) -> Option<comments::Literal> {
122 #[allow(non_upper_case_globals)]
123 pub const indent_unit: usize = 4;
125 #[allow(non_upper_case_globals)]
126 pub const default_columns: usize = 78;
129 /// Requires you to pass an input filename and reader so that
130 /// it can scan the input text for comments and literals to
132 pub fn print_crate<'a>(cm: &'a CodeMap,
136 input: &mut dyn Read,
137 out: Box<dyn Write + 'a>,
141 let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
143 // When printing the AST, we sometimes need to inject `#[no_std]` here.
144 // Since you can't compile the HIR, it's not necessary.
146 s.print_mod(&krate.module, &krate.attrs)?;
147 s.print_remaining_comments()?;
152 pub fn new_from_input(cm: &'a CodeMap,
155 input: &mut dyn Read,
156 out: Box<dyn Write + 'a>,
160 let (cmnts, lits) = comments::gather_comments_and_literals(sess, filename, input);
166 // If the code is post expansion, don't use the table of
167 // literals, since it doesn't correspond with the literals
168 // in the AST anymore.
176 pub fn new(cm: &'a CodeMap,
177 out: Box<dyn Write + 'a>,
179 comments: Option<Vec<comments::Comment>>,
180 literals: Option<Vec<comments::Literal>>)
183 s: pp::mk_printer(out, default_columns),
185 comments: comments.clone(),
186 literals: literals.unwrap_or_default().into_iter().peekable(),
194 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
195 where F: FnOnce(&mut State) -> io::Result<()>
197 let mut wr = Vec::new();
199 let mut printer = State {
200 s: pp::mk_printer(Box::new(&mut wr), default_columns),
203 literals: vec![].into_iter().peekable(),
208 f(&mut printer).unwrap();
209 printer.s.eof().unwrap();
211 String::from_utf8(wr).unwrap()
214 pub fn visibility_qualified(vis: &hir::Visibility, w: &str) -> String {
215 to_string(NO_ANN, |s| {
216 s.print_visibility(vis)?;
222 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
223 self.boxes.push(pp::Breaks::Consistent);
227 pub fn nbsp(&mut self) -> io::Result<()> {
231 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
236 pub fn head(&mut self, w: &str) -> io::Result<()> {
237 // outer-box is consistent
238 self.cbox(indent_unit)?;
239 // head-box is inconsistent
240 self.ibox(w.len() + 1)?;
241 // keyword that starts the head
248 pub fn bopen(&mut self) -> io::Result<()> {
250 self.end() // close the head-box
253 pub fn bclose_(&mut self, span: syntax_pos::Span, indented: usize) -> io::Result<()> {
254 self.bclose_maybe_open(span, indented, true)
256 pub fn bclose_maybe_open(&mut self,
257 span: syntax_pos::Span,
261 self.maybe_print_comment(span.hi())?;
262 self.break_offset_if_not_bol(1, -(indented as isize))?;
265 self.end()?; // close the outer-box
269 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
270 self.bclose_(span, indent_unit)
273 pub fn in_cbox(&self) -> bool {
274 match self.boxes.last() {
275 Some(&last_box) => last_box == pp::Breaks::Consistent,
279 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
285 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
287 self.s.break_offset(n, off)
289 if off != 0 && self.s.last_token().is_hardbreak_tok() {
290 // We do something pretty sketchy here: tuck the nonzero
291 // offset-adjustment we were going to deposit along with the
292 // break into the previous hardbreak.
293 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
299 // Synthesizes a comment that was not textually present in the original source
301 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
304 self.s.word(&text[..])?;
310 pub fn commasep_cmnt<T, F, G>(&mut self,
316 where F: FnMut(&mut State, &T) -> io::Result<()>,
317 G: FnMut(&T) -> syntax_pos::Span
320 let len = elts.len();
323 self.maybe_print_comment(get_span(elt).hi())?;
328 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()))?;
329 self.space_if_not_bol()?;
335 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr]) -> io::Result<()> {
336 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
339 pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
340 self.print_inner_attributes(attrs)?;
341 for &item_id in &_mod.item_ids {
342 self.ann.nested(self, Nested::Item(item_id))?;
347 pub fn print_foreign_mod(&mut self,
348 nmod: &hir::ForeignMod,
349 attrs: &[ast::Attribute])
351 self.print_inner_attributes(attrs)?;
352 for item in &nmod.items {
353 self.print_foreign_item(item)?;
358 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
359 if !lifetime.is_elided() {
360 self.print_lifetime(lifetime)?;
366 pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
367 self.maybe_print_comment(ty.span.lo())?;
370 hir::TyKind::Slice(ref ty) => {
372 self.print_type(&ty)?;
375 hir::TyKind::Ptr(ref mt) => {
378 hir::MutMutable => self.word_nbsp("mut")?,
379 hir::MutImmutable => self.word_nbsp("const")?,
381 self.print_type(&mt.ty)?;
383 hir::TyKind::Rptr(ref lifetime, ref mt) => {
385 self.print_opt_lifetime(lifetime)?;
388 hir::TyKind::Never => {
391 hir::TyKind::Tup(ref elts) => {
393 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty))?;
399 hir::TyKind::BareFn(ref f) => {
400 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &f.generic_params,
403 hir::TyKind::Path(ref qpath) => {
404 self.print_qpath(qpath, false)?
406 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
407 let mut first = true;
408 for bound in bounds {
413 self.word_space("+")?;
415 self.print_poly_trait_ref(bound)?;
417 if !lifetime.is_elided() {
419 self.word_space("+")?;
420 self.print_lifetime(lifetime)?;
423 hir::TyKind::Array(ref ty, ref length) => {
425 self.print_type(&ty)?;
427 self.print_anon_const(length)?;
430 hir::TyKind::Typeof(ref e) => {
431 self.s.word("typeof(")?;
432 self.print_anon_const(e)?;
435 hir::TyKind::Infer => {
438 hir::TyKind::Err => {
445 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
446 self.hardbreak_if_not_bol()?;
447 self.maybe_print_comment(item.span.lo())?;
448 self.print_outer_attributes(&item.attrs)?;
450 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
454 unsafety: hir::Unsafety::Normal,
455 constness: hir::Constness::NotConst,
457 asyncness: hir::IsAsync::NotAsync,
464 self.end()?; // end head-ibox
466 self.end() // end the outer fn box
468 hir::ForeignItemKind::Static(ref t, m) => {
469 self.head(&visibility_qualified(&item.vis, "static"))?;
471 self.word_space("mut")?;
473 self.print_name(item.name)?;
474 self.word_space(":")?;
475 self.print_type(&t)?;
477 self.end()?; // end the head-ibox
478 self.end() // end the outer cbox
480 hir::ForeignItemKind::Type => {
481 self.head(&visibility_qualified(&item.vis, "type"))?;
482 self.print_name(item.name)?;
484 self.end()?; // end the head-ibox
485 self.end() // end the outer cbox
490 fn print_associated_const(&mut self,
493 default: Option<hir::BodyId>,
494 vis: &hir::Visibility)
496 self.s.word(&visibility_qualified(vis, ""))?;
497 self.word_space("const")?;
498 self.print_ident(ident)?;
499 self.word_space(":")?;
500 self.print_type(ty)?;
501 if let Some(expr) = default {
503 self.word_space("=")?;
504 self.ann.nested(self, Nested::Body(expr))?;
509 fn print_associated_type(&mut self,
511 bounds: Option<&hir::GenericBounds>,
512 ty: Option<&hir::Ty>)
514 self.word_space("type")?;
515 self.print_ident(ident)?;
516 if let Some(bounds) = bounds {
517 self.print_bounds(":", bounds)?;
519 if let Some(ty) = ty {
521 self.word_space("=")?;
522 self.print_type(ty)?;
527 /// Pretty-print an item
528 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
529 self.hardbreak_if_not_bol()?;
530 self.maybe_print_comment(item.span.lo())?;
531 self.print_outer_attributes(&item.attrs)?;
532 self.ann.pre(self, NodeItem(item))?;
534 hir::ItemKind::ExternCrate(orig_name) => {
535 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
536 if let Some(orig_name) = orig_name {
537 self.print_name(orig_name)?;
542 self.print_name(item.name)?;
544 self.end()?; // end inner head-block
545 self.end()?; // end outer head-block
547 hir::ItemKind::Use(ref path, kind) => {
548 self.head(&visibility_qualified(&item.vis, "use"))?;
549 self.print_path(path, false)?;
552 hir::UseKind::Single => {
553 if path.segments.last().unwrap().ident.name != item.name {
555 self.word_space("as")?;
556 self.print_name(item.name)?;
560 hir::UseKind::Glob => self.s.word("::*;")?,
561 hir::UseKind::ListStem => self.s.word("::{};")?
563 self.end()?; // end inner head-block
564 self.end()?; // end outer head-block
566 hir::ItemKind::Static(ref ty, m, expr) => {
567 self.head(&visibility_qualified(&item.vis, "static"))?;
568 if m == hir::MutMutable {
569 self.word_space("mut")?;
571 self.print_name(item.name)?;
572 self.word_space(":")?;
573 self.print_type(&ty)?;
575 self.end()?; // end the head-ibox
577 self.word_space("=")?;
578 self.ann.nested(self, Nested::Body(expr))?;
580 self.end()?; // end the outer cbox
582 hir::ItemKind::Const(ref ty, expr) => {
583 self.head(&visibility_qualified(&item.vis, "const"))?;
584 self.print_name(item.name)?;
585 self.word_space(":")?;
586 self.print_type(&ty)?;
588 self.end()?; // end the head-ibox
590 self.word_space("=")?;
591 self.ann.nested(self, Nested::Body(expr))?;
593 self.end()?; // end the outer cbox
595 hir::ItemKind::Fn(ref decl, header, ref typarams, body) => {
605 self.end()?; // need to close a box
606 self.end()?; // need to close a box
607 self.ann.nested(self, Nested::Body(body))?;
609 hir::ItemKind::Mod(ref _mod) => {
610 self.head(&visibility_qualified(&item.vis, "mod"))?;
611 self.print_name(item.name)?;
614 self.print_mod(_mod, &item.attrs)?;
615 self.bclose(item.span)?;
617 hir::ItemKind::ForeignMod(ref nmod) => {
618 self.head("extern")?;
619 self.word_nbsp(&nmod.abi.to_string())?;
621 self.print_foreign_mod(nmod, &item.attrs)?;
622 self.bclose(item.span)?;
624 hir::ItemKind::GlobalAsm(ref ga) => {
625 self.head(&visibility_qualified(&item.vis, "global asm"))?;
626 self.s.word(&ga.asm.as_str())?;
629 hir::ItemKind::Ty(ref ty, ref generics) => {
630 self.head(&visibility_qualified(&item.vis, "type"))?;
631 self.print_name(item.name)?;
632 self.print_generic_params(&generics.params)?;
633 self.end()?; // end the inner ibox
635 self.print_where_clause(&generics.where_clause)?;
637 self.word_space("=")?;
638 self.print_type(&ty)?;
640 self.end()?; // end the outer ibox
642 hir::ItemKind::Existential(ref exist) => {
643 self.head(&visibility_qualified(&item.vis, "existential type"))?;
644 self.print_name(item.name)?;
645 self.print_generic_params(&exist.generics.params)?;
646 self.end()?; // end the inner ibox
648 self.print_where_clause(&exist.generics.where_clause)?;
650 self.word_space(":")?;
651 let mut real_bounds = Vec::with_capacity(exist.bounds.len());
652 for b in exist.bounds.iter() {
653 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
655 self.word_space("for ?")?;
656 self.print_trait_ref(&ptr.trait_ref)?;
658 real_bounds.push(b.clone());
661 self.print_bounds(":", &real_bounds[..])?;
663 self.end()?; // end the outer ibox
665 hir::ItemKind::Enum(ref enum_definition, ref params) => {
666 self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
668 hir::ItemKind::Struct(ref struct_def, ref generics) => {
669 self.head(&visibility_qualified(&item.vis, "struct"))?;
670 self.print_struct(struct_def, generics, item.name, item.span, true)?;
672 hir::ItemKind::Union(ref struct_def, ref generics) => {
673 self.head(&visibility_qualified(&item.vis, "union"))?;
674 self.print_struct(struct_def, generics, item.name, item.span, true)?;
676 hir::ItemKind::Impl(unsafety,
684 self.print_visibility(&item.vis)?;
685 self.print_defaultness(defaultness)?;
686 self.print_unsafety(unsafety)?;
687 self.word_nbsp("impl")?;
689 if !generics.params.is_empty() {
690 self.print_generic_params(&generics.params)?;
695 hir::ImplPolarity::Negative => {
703 self.print_trait_ref(t)?;
705 self.word_space("for")?;
710 self.print_type(&ty)?;
711 self.print_where_clause(&generics.where_clause)?;
715 self.print_inner_attributes(&item.attrs)?;
716 for impl_item in impl_items {
717 self.ann.nested(self, Nested::ImplItem(impl_item.id))?;
719 self.bclose(item.span)?;
721 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
723 self.print_visibility(&item.vis)?;
724 self.print_is_auto(is_auto)?;
725 self.print_unsafety(unsafety)?;
726 self.word_nbsp("trait")?;
727 self.print_name(item.name)?;
728 self.print_generic_params(&generics.params)?;
729 let mut real_bounds = Vec::with_capacity(bounds.len());
730 for b in bounds.iter() {
731 if let GenericBound::Trait(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)?;
743 for trait_item in trait_items {
744 self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
746 self.bclose(item.span)?;
748 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
750 self.print_visibility(&item.vis)?;
751 self.word_nbsp("trait")?;
752 self.print_name(item.name)?;
753 self.print_generic_params(&generics.params)?;
754 let mut real_bounds = Vec::with_capacity(bounds.len());
755 // FIXME(durka) this seems to be some quite outdated syntax
756 for b in bounds.iter() {
757 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
759 self.word_space("for ?")?;
760 self.print_trait_ref(&ptr.trait_ref)?;
762 real_bounds.push(b.clone());
766 self.print_bounds("=", &real_bounds[..])?;
767 self.print_where_clause(&generics.where_clause)?;
771 self.ann.post(self, NodeItem(item))
774 pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
775 self.print_path(&t.path, false)
778 fn print_formal_generic_params(
780 generic_params: &[hir::GenericParam]
781 ) -> io::Result<()> {
782 if !generic_params.is_empty() {
784 self.print_generic_params(generic_params)?;
790 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
791 self.print_formal_generic_params(&t.bound_generic_params)?;
792 self.print_trait_ref(&t.trait_ref)
795 pub fn print_enum_def(&mut self,
796 enum_definition: &hir::EnumDef,
797 generics: &hir::Generics,
799 span: syntax_pos::Span,
800 visibility: &hir::Visibility)
802 self.head(&visibility_qualified(visibility, "enum"))?;
803 self.print_name(name)?;
804 self.print_generic_params(&generics.params)?;
805 self.print_where_clause(&generics.where_clause)?;
807 self.print_variants(&enum_definition.variants, span)
810 pub fn print_variants(&mut self,
811 variants: &[hir::Variant],
812 span: syntax_pos::Span)
816 self.space_if_not_bol()?;
817 self.maybe_print_comment(v.span.lo())?;
818 self.print_outer_attributes(&v.node.attrs)?;
819 self.ibox(indent_unit)?;
820 self.print_variant(v)?;
823 self.maybe_print_trailing_comment(v.span, None)?;
828 pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
830 hir::VisibilityKind::Public => self.word_nbsp("pub")?,
831 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate")?,
832 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)")?,
833 hir::VisibilityKind::Restricted { ref path, .. } => {
834 self.s.word("pub(")?;
835 if path.segments.len() == 1 &&
836 path.segments[0].ident.name == keywords::Super.name() {
837 // Special case: `super` can print like `pub(super)`.
838 self.s.word("super")?;
840 // Everything else requires `in` at present.
841 self.word_nbsp("in")?;
842 self.print_path(path, false)?;
844 self.word_nbsp(")")?;
846 hir::VisibilityKind::Inherited => ()
852 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) -> io::Result<()> {
854 hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
855 hir::Defaultness::Final => (),
860 pub fn print_struct(&mut self,
861 struct_def: &hir::VariantData,
862 generics: &hir::Generics,
864 span: syntax_pos::Span,
865 print_finalizer: bool)
867 self.print_name(name)?;
868 self.print_generic_params(&generics.params)?;
869 if !struct_def.is_struct() {
870 if struct_def.is_tuple() {
872 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
873 s.maybe_print_comment(field.span.lo())?;
874 s.print_outer_attributes(&field.attrs)?;
875 s.print_visibility(&field.vis)?;
876 s.print_type(&field.ty)
880 self.print_where_clause(&generics.where_clause)?;
885 self.end() // close the outer-box
887 self.print_where_clause(&generics.where_clause)?;
890 self.hardbreak_if_not_bol()?;
892 for field in struct_def.fields() {
893 self.hardbreak_if_not_bol()?;
894 self.maybe_print_comment(field.span.lo())?;
895 self.print_outer_attributes(&field.attrs)?;
896 self.print_visibility(&field.vis)?;
897 self.print_ident(field.ident)?;
898 self.word_nbsp(":")?;
899 self.print_type(&field.ty)?;
907 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
909 let generics = hir::Generics::empty();
910 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
911 if let Some(ref d) = v.node.disr_expr {
913 self.word_space("=")?;
914 self.print_anon_const(d)?;
918 pub fn print_method_sig(&mut self,
921 generics: &hir::Generics,
922 vis: &hir::Visibility,
923 arg_names: &[ast::Ident],
924 body_id: Option<hir::BodyId>)
926 self.print_fn(&m.decl,
935 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
936 self.ann.pre(self, NodeSubItem(ti.id))?;
937 self.hardbreak_if_not_bol()?;
938 self.maybe_print_comment(ti.span.lo())?;
939 self.print_outer_attributes(&ti.attrs)?;
941 hir::TraitItemKind::Const(ref ty, default) => {
942 let vis = Spanned { span: syntax_pos::DUMMY_SP,
943 node: hir::VisibilityKind::Inherited };
944 self.print_associated_const(ti.ident, &ty, default, &vis)?;
946 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
947 let vis = Spanned { span: syntax_pos::DUMMY_SP,
948 node: hir::VisibilityKind::Inherited };
949 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None)?;
952 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
953 let vis = Spanned { span: syntax_pos::DUMMY_SP,
954 node: hir::VisibilityKind::Inherited };
956 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body))?;
958 self.end()?; // need to close a box
959 self.end()?; // need to close a box
960 self.ann.nested(self, Nested::Body(body))?;
962 hir::TraitItemKind::Type(ref bounds, ref default) => {
963 self.print_associated_type(ti.ident,
965 default.as_ref().map(|ty| &**ty))?;
968 self.ann.post(self, NodeSubItem(ti.id))
971 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
972 self.ann.pre(self, NodeSubItem(ii.id))?;
973 self.hardbreak_if_not_bol()?;
974 self.maybe_print_comment(ii.span.lo())?;
975 self.print_outer_attributes(&ii.attrs)?;
976 self.print_defaultness(ii.defaultness)?;
979 hir::ImplItemKind::Const(ref ty, expr) => {
980 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis)?;
982 hir::ImplItemKind::Method(ref sig, body) => {
984 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body))?;
986 self.end()?; // need to close a box
987 self.end()?; // need to close a box
988 self.ann.nested(self, Nested::Body(body))?;
990 hir::ImplItemKind::Type(ref ty) => {
991 self.print_associated_type(ii.ident, None, Some(ty))?;
993 hir::ImplItemKind::Existential(ref bounds) => {
994 self.word_space("existential")?;
995 self.print_associated_type(ii.ident, Some(bounds), None)?;
998 self.ann.post(self, NodeSubItem(ii.id))
1001 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1002 self.maybe_print_comment(st.span.lo())?;
1004 hir::StmtKind::Decl(ref decl, _) => {
1005 self.print_decl(&decl)?;
1007 hir::StmtKind::Expr(ref expr, _) => {
1008 self.space_if_not_bol()?;
1009 self.print_expr(&expr)?;
1011 hir::StmtKind::Semi(ref expr, _) => {
1012 self.space_if_not_bol()?;
1013 self.print_expr(&expr)?;
1017 if stmt_ends_with_semi(&st.node) {
1020 self.maybe_print_trailing_comment(st.span, None)
1023 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1024 self.print_block_with_attrs(blk, &[])
1027 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1028 self.print_block_unclosed_indent(blk, indent_unit)
1031 pub fn print_block_unclosed_indent(&mut self,
1035 self.print_block_maybe_unclosed(blk, indented, &[], false)
1038 pub fn print_block_with_attrs(&mut self,
1040 attrs: &[ast::Attribute])
1042 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1045 pub fn print_block_maybe_unclosed(&mut self,
1048 attrs: &[ast::Attribute],
1052 hir::UnsafeBlock(..) => self.word_space("unsafe")?,
1053 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
1054 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
1055 hir::DefaultBlock => (),
1057 self.maybe_print_comment(blk.span.lo())?;
1058 self.ann.pre(self, NodeBlock(blk))?;
1061 self.print_inner_attributes(attrs)?;
1063 for st in &blk.stmts {
1064 self.print_stmt(st)?;
1068 self.space_if_not_bol()?;
1069 self.print_expr(&expr)?;
1070 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1074 self.bclose_maybe_open(blk.span, indented, close_box)?;
1075 self.ann.post(self, NodeBlock(blk))
1078 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1082 // "another else-if"
1083 hir::ExprKind::If(ref i, ref then, ref e) => {
1084 self.cbox(indent_unit - 1)?;
1086 self.s.word(" else if ")?;
1087 self.print_expr_as_cond(&i)?;
1089 self.print_expr(&then)?;
1090 self.print_else(e.as_ref().map(|e| &**e))
1093 hir::ExprKind::Block(ref b, _) => {
1094 self.cbox(indent_unit - 1)?;
1096 self.s.word(" else ")?;
1097 self.print_block(&b)
1099 // BLEAH, constraints would be great here
1101 panic!("print_if saw if with weird alternative");
1109 pub fn print_if(&mut self,
1112 elseopt: Option<&hir::Expr>)
1115 self.print_expr_as_cond(test)?;
1117 self.print_expr(blk)?;
1118 self.print_else(elseopt)
1121 pub fn print_if_let(&mut self,
1125 elseopt: Option<&hir::Expr>)
1127 self.head("if let")?;
1128 self.print_pat(pat)?;
1130 self.word_space("=")?;
1131 self.print_expr_as_cond(expr)?;
1133 self.print_block(blk)?;
1134 self.print_else(elseopt)
1137 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) -> io::Result<()> {
1138 self.ann.nested(self, Nested::Body(constant.body))
1141 fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
1143 self.commasep_exprs(Inconsistent, args)?;
1147 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr, prec: i8) -> io::Result<()> {
1148 let needs_par = expr.precedence().order() < prec;
1152 self.print_expr(expr)?;
1159 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1160 /// `if cond { ... }`.
1161 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr) -> io::Result<()> {
1162 let needs_par = match expr.node {
1163 // These cases need parens due to the parse error observed in #26461: `if return {}`
1164 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1165 hir::ExprKind::Closure(..) |
1166 hir::ExprKind::Ret(..) |
1167 hir::ExprKind::Break(..) => true,
1169 _ => contains_exterior_struct_lit(expr),
1175 self.print_expr(expr)?;
1182 fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1183 self.ibox(indent_unit)?;
1185 self.commasep_exprs(Inconsistent, exprs)?;
1190 fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::AnonConst) -> io::Result<()> {
1191 self.ibox(indent_unit)?;
1193 self.print_expr(element)?;
1194 self.word_space(";")?;
1195 self.print_anon_const(count)?;
1200 fn print_expr_struct(&mut self,
1202 fields: &[hir::Field],
1203 wth: &Option<P<hir::Expr>>)
1205 self.print_qpath(qpath, true)?;
1207 self.commasep_cmnt(Consistent,
1210 s.ibox(indent_unit)?;
1211 if !field.is_shorthand {
1212 s.print_ident(field.ident)?;
1215 s.print_expr(&field.expr)?;
1221 self.ibox(indent_unit)?;
1222 if !fields.is_empty() {
1227 self.print_expr(&expr)?;
1230 _ => if !fields.is_empty() {
1238 fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1240 self.commasep_exprs(Inconsistent, exprs)?;
1241 if exprs.len() == 1 {
1247 fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1250 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1251 _ => parser::PREC_POSTFIX,
1254 self.print_expr_maybe_paren(func, prec)?;
1255 self.print_call_post(args)
1258 fn print_expr_method_call(&mut self,
1259 segment: &hir::PathSegment,
1262 let base_args = &args[1..];
1263 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
1265 self.print_ident(segment.ident)?;
1267 segment.with_generic_args(|generic_args| {
1268 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1269 return self.print_generic_args(&generic_args, segment.infer_types, true);
1273 self.print_call_post(base_args)
1276 fn print_expr_binary(&mut self,
1281 let assoc_op = bin_op_to_assoc_op(op.node);
1282 let prec = assoc_op.precedence() as i8;
1283 let fixity = assoc_op.fixity();
1285 let (left_prec, right_prec) = match fixity {
1286 Fixity::Left => (prec, prec + 1),
1287 Fixity::Right => (prec + 1, prec),
1288 Fixity::None => (prec + 1, prec + 1),
1291 let left_prec = match (&lhs.node, op.node) {
1292 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1293 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1294 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1295 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt) |
1296 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1300 self.print_expr_maybe_paren(lhs, left_prec)?;
1302 self.word_space(op.node.as_str())?;
1303 self.print_expr_maybe_paren(rhs, right_prec)
1306 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1307 self.s.word(op.as_str())?;
1308 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1311 fn print_expr_addr_of(&mut self,
1312 mutability: hir::Mutability,
1316 self.print_mutability(mutability)?;
1317 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1320 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1321 self.maybe_print_comment(expr.span.lo())?;
1322 self.print_outer_attributes(&expr.attrs)?;
1323 self.ibox(indent_unit)?;
1324 self.ann.pre(self, NodeExpr(expr))?;
1326 hir::ExprKind::Box(ref expr) => {
1327 self.word_space("box")?;
1328 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
1330 hir::ExprKind::Array(ref exprs) => {
1331 self.print_expr_vec(exprs)?;
1333 hir::ExprKind::Repeat(ref element, ref count) => {
1334 self.print_expr_repeat(&element, count)?;
1336 hir::ExprKind::Struct(ref qpath, ref fields, ref wth) => {
1337 self.print_expr_struct(qpath, &fields[..], wth)?;
1339 hir::ExprKind::Tup(ref exprs) => {
1340 self.print_expr_tup(exprs)?;
1342 hir::ExprKind::Call(ref func, ref args) => {
1343 self.print_expr_call(&func, args)?;
1345 hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1346 self.print_expr_method_call(segment, args)?;
1348 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1349 self.print_expr_binary(op, &lhs, &rhs)?;
1351 hir::ExprKind::Unary(op, ref expr) => {
1352 self.print_expr_unary(op, &expr)?;
1354 hir::ExprKind::AddrOf(m, ref expr) => {
1355 self.print_expr_addr_of(m, &expr)?;
1357 hir::ExprKind::Lit(ref lit) => {
1358 self.print_literal(&lit)?;
1360 hir::ExprKind::Cast(ref expr, ref ty) => {
1361 let prec = AssocOp::As.precedence() as i8;
1362 self.print_expr_maybe_paren(&expr, prec)?;
1364 self.word_space("as")?;
1365 self.print_type(&ty)?;
1367 hir::ExprKind::Type(ref expr, ref ty) => {
1368 let prec = AssocOp::Colon.precedence() as i8;
1369 self.print_expr_maybe_paren(&expr, prec)?;
1370 self.word_space(":")?;
1371 self.print_type(&ty)?;
1373 hir::ExprKind::If(ref test, ref blk, ref elseopt) => {
1374 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1376 hir::ExprKind::While(ref test, ref blk, opt_label) => {
1377 if let Some(label) = opt_label {
1378 self.print_ident(label.ident)?;
1379 self.word_space(":")?;
1381 self.head("while")?;
1382 self.print_expr_as_cond(&test)?;
1384 self.print_block(&blk)?;
1386 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1387 if let Some(label) = opt_label {
1388 self.print_ident(label.ident)?;
1389 self.word_space(":")?;
1393 self.print_block(&blk)?;
1395 hir::ExprKind::Match(ref expr, ref arms, _) => {
1396 self.cbox(indent_unit)?;
1398 self.word_nbsp("match")?;
1399 self.print_expr_as_cond(&expr)?;
1403 self.print_arm(arm)?;
1405 self.bclose_(expr.span, indent_unit)?;
1407 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1408 self.print_capture_clause(capture_clause)?;
1410 self.print_closure_args(&decl, body)?;
1413 // this is a bare expression
1414 self.ann.nested(self, Nested::Body(body))?;
1415 self.end()?; // need to close a box
1417 // a box will be closed by print_expr, but we didn't want an overall
1418 // wrapper so we closed the corresponding opening. so create an
1419 // empty box to satisfy the close.
1422 hir::ExprKind::Block(ref blk, opt_label) => {
1423 if let Some(label) = opt_label {
1424 self.print_ident(label.ident)?;
1425 self.word_space(":")?;
1427 // containing cbox, will be closed by print-block at }
1428 self.cbox(indent_unit)?;
1429 // head-box, will be closed by print-block after {
1431 self.print_block(&blk)?;
1433 hir::ExprKind::Assign(ref lhs, ref rhs) => {
1434 let prec = AssocOp::Assign.precedence() as i8;
1435 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1437 self.word_space("=")?;
1438 self.print_expr_maybe_paren(&rhs, prec)?;
1440 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1441 let prec = AssocOp::Assign.precedence() as i8;
1442 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1444 self.s.word(op.node.as_str())?;
1445 self.word_space("=")?;
1446 self.print_expr_maybe_paren(&rhs, prec)?;
1448 hir::ExprKind::Field(ref expr, ident) => {
1449 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
1451 self.print_ident(ident)?;
1453 hir::ExprKind::Index(ref expr, ref index) => {
1454 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1456 self.print_expr(&index)?;
1459 hir::ExprKind::Path(ref qpath) => {
1460 self.print_qpath(qpath, true)?
1462 hir::ExprKind::Break(destination, ref opt_expr) => {
1463 self.s.word("break")?;
1465 if let Some(label) = destination.label {
1466 self.print_ident(label.ident)?;
1469 if let Some(ref expr) = *opt_expr {
1470 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
1474 hir::ExprKind::Continue(destination) => {
1475 self.s.word("continue")?;
1477 if let Some(label) = destination.label {
1478 self.print_ident(label.ident)?;
1482 hir::ExprKind::Ret(ref result) => {
1483 self.s.word("return")?;
1487 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1492 hir::ExprKind::InlineAsm(ref a, ref outputs, ref inputs) => {
1493 self.s.word("asm!")?;
1495 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
1496 self.word_space(":")?;
1498 let mut out_idx = 0;
1499 self.commasep(Inconsistent, &a.outputs, |s, out| {
1500 let constraint = out.constraint.as_str();
1501 let mut ch = constraint.chars();
1503 Some('=') if out.is_rw => {
1504 s.print_string(&format!("+{}", ch.as_str()),
1505 ast::StrStyle::Cooked)?
1507 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
1510 s.print_expr(&outputs[out_idx])?;
1516 self.word_space(":")?;
1519 self.commasep(Inconsistent, &a.inputs, |s, co| {
1520 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1522 s.print_expr(&inputs[in_idx])?;
1528 self.word_space(":")?;
1530 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1531 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1535 let mut options = vec![];
1537 options.push("volatile");
1540 options.push("alignstack");
1542 if a.dialect == ast::AsmDialect::Intel {
1543 options.push("intel");
1546 if !options.is_empty() {
1548 self.word_space(":")?;
1549 self.commasep(Inconsistent, &options, |s, &co| {
1550 s.print_string(co, ast::StrStyle::Cooked)?;
1557 hir::ExprKind::Yield(ref expr) => {
1558 self.word_space("yield")?;
1559 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1562 self.ann.post(self, NodeExpr(expr))?;
1566 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1567 self.print_pat(&loc.pat)?;
1568 if let Some(ref ty) = loc.ty {
1569 self.word_space(":")?;
1570 self.print_type(&ty)?;
1575 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1576 self.maybe_print_comment(decl.span.lo())?;
1578 hir::DeclKind::Local(ref loc) => {
1579 self.space_if_not_bol()?;
1580 self.ibox(indent_unit)?;
1581 self.word_nbsp("let")?;
1583 self.ibox(indent_unit)?;
1584 self.print_local_decl(&loc)?;
1586 if let Some(ref init) = loc.init {
1588 self.word_space("=")?;
1589 self.print_expr(&init)?;
1593 hir::DeclKind::Item(item) => {
1594 self.ann.nested(self, Nested::Item(item))
1599 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1600 self.s.word(&i.to_string())
1603 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
1604 if ident.is_raw_guess() {
1605 self.s.word(&format!("r#{}", ident.name))?;
1607 self.s.word(&ident.as_str())?;
1609 self.ann.post(self, NodeName(&ident.name))
1612 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1613 self.print_ident(ast::Ident::with_empty_ctxt(name))
1616 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1617 self.print_local_decl(loc)?;
1619 self.word_space("in")?;
1620 self.print_expr(coll)
1623 pub fn print_path(&mut self,
1625 colons_before_params: bool)
1627 self.maybe_print_comment(path.span.lo())?;
1629 for (i, segment) in path.segments.iter().enumerate() {
1633 if segment.ident.name != keywords::CrateRoot.name() &&
1634 segment.ident.name != keywords::DollarCrate.name() {
1635 self.print_ident(segment.ident)?;
1636 segment.with_generic_args(|generic_args| {
1637 self.print_generic_args(generic_args, segment.infer_types,
1638 colons_before_params)
1646 pub fn print_qpath(&mut self,
1648 colons_before_params: bool)
1651 hir::QPath::Resolved(None, ref path) => {
1652 self.print_path(path, colons_before_params)
1654 hir::QPath::Resolved(Some(ref qself), ref path) => {
1656 self.print_type(qself)?;
1658 self.word_space("as")?;
1660 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1664 if segment.ident.name != keywords::CrateRoot.name() &&
1665 segment.ident.name != keywords::DollarCrate.name() {
1666 self.print_ident(segment.ident)?;
1667 segment.with_generic_args(|generic_args| {
1668 self.print_generic_args(generic_args,
1669 segment.infer_types,
1670 colons_before_params)
1677 let item_segment = path.segments.last().unwrap();
1678 self.print_ident(item_segment.ident)?;
1679 item_segment.with_generic_args(|generic_args| {
1680 self.print_generic_args(generic_args,
1681 item_segment.infer_types,
1682 colons_before_params)
1685 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1687 self.print_type(qself)?;
1690 self.print_ident(item_segment.ident)?;
1691 item_segment.with_generic_args(|generic_args| {
1692 self.print_generic_args(generic_args,
1693 item_segment.infer_types,
1694 colons_before_params)
1700 fn print_generic_args(&mut self,
1701 generic_args: &hir::GenericArgs,
1703 colons_before_params: bool)
1705 if generic_args.parenthesized {
1707 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty))?;
1710 self.space_if_not_bol()?;
1711 self.word_space("->")?;
1712 self.print_type(&generic_args.bindings[0].ty)?;
1714 let start = if colons_before_params { "::<" } else { "<" };
1715 let empty = Cell::new(true);
1716 let start_or_comma = |this: &mut Self| {
1721 this.word_space(",")
1725 let mut types = vec![];
1726 let mut elide_lifetimes = true;
1727 for arg in &generic_args.args {
1729 GenericArg::Lifetime(lt) => {
1730 if !lt.is_elided() {
1731 elide_lifetimes = false;
1734 GenericArg::Type(ty) => {
1739 if !elide_lifetimes {
1740 start_or_comma(self)?;
1741 self.commasep(Inconsistent, &generic_args.args, |s, generic_arg| {
1743 GenericArg::Lifetime(lt) => s.print_lifetime(lt),
1744 GenericArg::Type(ty) => s.print_type(ty),
1747 } else if !types.is_empty() {
1748 start_or_comma(self)?;
1749 self.commasep(Inconsistent, &types, |s, ty| s.print_type(&ty))?;
1752 // FIXME(eddyb) This would leak into error messages, e.g.:
1753 // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1754 if infer_types && false {
1755 start_or_comma(self)?;
1759 for binding in generic_args.bindings.iter() {
1760 start_or_comma(self)?;
1761 self.print_ident(binding.ident)?;
1763 self.word_space("=")?;
1764 self.print_type(&binding.ty)?;
1775 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1776 self.maybe_print_comment(pat.span.lo())?;
1777 self.ann.pre(self, NodePat(pat))?;
1778 // Pat isn't normalized, but the beauty of it
1779 // is that it doesn't matter
1781 PatKind::Wild => self.s.word("_")?,
1782 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1783 match binding_mode {
1784 hir::BindingAnnotation::Ref => {
1785 self.word_nbsp("ref")?;
1786 self.print_mutability(hir::MutImmutable)?;
1788 hir::BindingAnnotation::RefMut => {
1789 self.word_nbsp("ref")?;
1790 self.print_mutability(hir::MutMutable)?;
1792 hir::BindingAnnotation::Unannotated => {}
1793 hir::BindingAnnotation::Mutable => {
1794 self.word_nbsp("mut")?;
1797 self.print_ident(ident)?;
1798 if let Some(ref p) = *sub {
1800 self.print_pat(&p)?;
1803 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1804 self.print_qpath(qpath, true)?;
1806 if let Some(ddpos) = ddpos {
1807 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1809 self.word_space(",")?;
1812 if ddpos != elts.len() {
1814 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1817 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1821 PatKind::Path(ref qpath) => {
1822 self.print_qpath(qpath, true)?;
1824 PatKind::Struct(ref qpath, ref fields, etc) => {
1825 self.print_qpath(qpath, true)?;
1827 self.word_space("{")?;
1828 self.commasep_cmnt(Consistent,
1831 s.cbox(indent_unit)?;
1832 if !f.node.is_shorthand {
1833 s.print_ident(f.node.ident)?;
1836 s.print_pat(&f.node.pat)?;
1839 |f| f.node.pat.span)?;
1841 if !fields.is_empty() {
1842 self.word_space(",")?;
1849 PatKind::Tuple(ref elts, ddpos) => {
1851 if let Some(ddpos) = ddpos {
1852 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1854 self.word_space(",")?;
1857 if ddpos != elts.len() {
1859 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1862 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1863 if elts.len() == 1 {
1869 PatKind::Box(ref inner) => {
1870 let is_range_inner = match inner.node {
1871 PatKind::Range(..) => true,
1874 self.s.word("box ")?;
1878 self.print_pat(&inner)?;
1883 PatKind::Ref(ref inner, mutbl) => {
1884 let is_range_inner = match inner.node {
1885 PatKind::Range(..) => true,
1889 if mutbl == hir::MutMutable {
1890 self.s.word("mut ")?;
1895 self.print_pat(&inner)?;
1900 PatKind::Lit(ref e) => self.print_expr(&e)?,
1901 PatKind::Range(ref begin, ref end, ref end_kind) => {
1902 self.print_expr(&begin)?;
1905 RangeEnd::Included => self.s.word("...")?,
1906 RangeEnd::Excluded => self.s.word("..")?,
1908 self.print_expr(&end)?;
1910 PatKind::Slice(ref before, ref slice, ref after) => {
1912 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1913 if let Some(ref p) = *slice {
1914 if !before.is_empty() {
1915 self.word_space(",")?;
1917 if let PatKind::Wild = p.node {
1920 self.print_pat(&p)?;
1923 if !after.is_empty() {
1924 self.word_space(",")?;
1927 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1931 self.ann.post(self, NodePat(pat))
1934 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1935 // I have no idea why this check is necessary, but here it
1937 if arm.attrs.is_empty() {
1940 self.cbox(indent_unit)?;
1942 self.print_outer_attributes(&arm.attrs)?;
1943 let mut first = true;
1944 for p in &arm.pats {
1949 self.word_space("|")?;
1951 self.print_pat(&p)?;
1954 if let Some(ref e) = arm.guard {
1955 self.word_space("if")?;
1956 self.print_expr(&e)?;
1959 self.word_space("=>")?;
1961 match arm.body.node {
1962 hir::ExprKind::Block(ref blk, opt_label) => {
1963 if let Some(label) = opt_label {
1964 self.print_ident(label.ident)?;
1965 self.word_space(":")?;
1967 // the block will close the pattern's ibox
1968 self.print_block_unclosed_indent(&blk, indent_unit)?;
1970 // If it is a user-provided unsafe block, print a comma after it
1971 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1976 self.end()?; // close the ibox for the pattern
1977 self.print_expr(&arm.body)?;
1981 self.end() // close enclosing cbox
1984 pub fn print_fn(&mut self,
1986 header: hir::FnHeader,
1987 name: Option<ast::Name>,
1988 generics: &hir::Generics,
1989 vis: &hir::Visibility,
1990 arg_names: &[ast::Ident],
1991 body_id: Option<hir::BodyId>)
1993 self.print_fn_header_info(header, vis)?;
1995 if let Some(name) = name {
1997 self.print_name(name)?;
1999 self.print_generic_params(&generics.params)?;
2003 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2004 assert!(arg_names.is_empty() || body_id.is_none());
2005 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2006 s.ibox(indent_unit)?;
2007 if let Some(arg_name) = arg_names.get(i) {
2008 s.s.word(&arg_name.as_str())?;
2011 } else if let Some(body_id) = body_id {
2012 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2021 self.s.word(", ...")?;
2025 self.print_fn_output(decl)?;
2026 self.print_where_clause(&generics.where_clause)
2029 fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
2032 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2033 s.ibox(indent_unit)?;
2035 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2038 if let hir::TyKind::Infer = ty.node {
2049 if let hir::DefaultReturn(..) = decl.output {
2053 self.space_if_not_bol()?;
2054 self.word_space("->")?;
2056 hir::Return(ref ty) => {
2057 self.print_type(&ty)?;
2058 self.maybe_print_comment(ty.span.lo())
2060 hir::DefaultReturn(..) => unreachable!(),
2064 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
2065 match capture_clause {
2066 hir::CaptureByValue => self.word_space("move"),
2067 hir::CaptureByRef => Ok(()),
2071 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::GenericBound]) -> io::Result<()> {
2072 if !bounds.is_empty() {
2073 self.s.word(prefix)?;
2074 let mut first = true;
2075 for bound in bounds {
2076 if !(first && prefix.is_empty()) {
2082 self.word_space("+")?;
2086 GenericBound::Trait(tref, modifier) => {
2087 if modifier == &TraitBoundModifier::Maybe {
2090 self.print_poly_trait_ref(tref)?;
2092 GenericBound::Outlives(lt) => {
2093 self.print_lifetime(lt)?;
2101 pub fn print_generic_params(&mut self, generic_params: &[GenericParam]) -> io::Result<()> {
2102 if !generic_params.is_empty() {
2105 self.commasep(Inconsistent, generic_params, |s, param| {
2106 s.print_generic_param(param)
2114 pub fn print_generic_param(&mut self, param: &GenericParam) -> io::Result<()> {
2115 self.print_ident(param.name.ident())?;
2117 GenericParamKind::Lifetime { .. } => {
2119 for bound in ¶m.bounds {
2121 GenericBound::Outlives(lt) => {
2123 self.print_lifetime(lt)?;
2131 GenericParamKind::Type { ref default, .. } => {
2132 self.print_bounds(":", ¶m.bounds)?;
2136 self.word_space("=")?;
2137 self.print_type(&default)
2145 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2146 self.print_ident(lifetime.name.ident())
2149 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2150 if where_clause.predicates.is_empty() {
2155 self.word_space("where")?;
2157 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2159 self.word_space(",")?;
2163 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2164 ref bound_generic_params,
2169 self.print_formal_generic_params(bound_generic_params)?;
2170 self.print_type(&bounded_ty)?;
2171 self.print_bounds(":", bounds)?;
2173 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2176 self.print_lifetime(lifetime)?;
2179 for (i, bound) in bounds.iter().enumerate() {
2181 GenericBound::Outlives(lt) => {
2182 self.print_lifetime(lt)?;
2192 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
2195 self.print_type(lhs_ty)?;
2197 self.word_space("=")?;
2198 self.print_type(rhs_ty)?;
2206 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2208 hir::MutMutable => self.word_nbsp("mut"),
2209 hir::MutImmutable => Ok(()),
2213 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2214 self.print_mutability(mt.mutbl)?;
2215 self.print_type(&mt.ty)
2218 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2219 if let hir::DefaultReturn(..) = decl.output {
2223 self.space_if_not_bol()?;
2224 self.ibox(indent_unit)?;
2225 self.word_space("->")?;
2227 hir::DefaultReturn(..) => unreachable!(),
2228 hir::Return(ref ty) => self.print_type(&ty)?,
2233 hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2238 pub fn print_ty_fn(&mut self,
2240 unsafety: hir::Unsafety,
2242 name: Option<ast::Name>,
2243 generic_params: &[hir::GenericParam],
2244 arg_names: &[ast::Ident])
2246 self.ibox(indent_unit)?;
2247 if !generic_params.is_empty() {
2248 self.s.word("for")?;
2249 self.print_generic_params(generic_params)?;
2251 let generics = hir::Generics {
2252 params: hir::HirVec::new(),
2253 where_clause: hir::WhereClause {
2254 id: ast::DUMMY_NODE_ID,
2255 predicates: hir::HirVec::new(),
2257 span: syntax_pos::DUMMY_SP,
2263 constness: hir::Constness::NotConst,
2264 asyncness: hir::IsAsync::NotAsync,
2268 &Spanned { span: syntax_pos::DUMMY_SP,
2269 node: hir::VisibilityKind::Inherited },
2275 pub fn maybe_print_trailing_comment(&mut self,
2276 span: syntax_pos::Span,
2277 next_pos: Option<BytePos>)
2279 let cm = match self.cm {
2283 if let Some(ref cmnt) = self.next_comment() {
2284 if (*cmnt).style != comments::Trailing {
2287 let span_line = cm.lookup_char_pos(span.hi());
2288 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2289 let mut next = (*cmnt).pos + BytePos(1);
2290 if let Some(p) = next_pos {
2293 if span.hi() < (*cmnt).pos && (*cmnt).pos < next &&
2294 span_line.line == comment_line.line {
2295 self.print_comment(cmnt)?;
2301 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2302 // If there aren't any remaining comments, then we need to manually
2303 // make sure there is a line break at the end.
2304 if self.next_comment().is_none() {
2305 self.s.hardbreak()?;
2307 while let Some(ref cmnt) = self.next_comment() {
2308 self.print_comment(cmnt)?
2313 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2314 opt_abi: Option<Abi>)
2317 Some(Abi::Rust) => Ok(()),
2319 self.word_nbsp("extern")?;
2320 self.word_nbsp(&abi.to_string())
2326 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2329 self.word_nbsp("extern")?;
2330 self.word_nbsp(&abi.to_string())
2336 pub fn print_fn_header_info(&mut self,
2337 header: hir::FnHeader,
2338 vis: &hir::Visibility)
2340 self.s.word(&visibility_qualified(vis, ""))?;
2342 match header.constness {
2343 hir::Constness::NotConst => {}
2344 hir::Constness::Const => self.word_nbsp("const")?,
2347 match header.asyncness {
2348 hir::IsAsync::NotAsync => {}
2349 hir::IsAsync::Async => self.word_nbsp("async")?,
2352 self.print_unsafety(header.unsafety)?;
2354 if header.abi != Abi::Rust {
2355 self.word_nbsp("extern")?;
2356 self.word_nbsp(&header.abi.to_string())?;
2362 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2364 hir::Unsafety::Normal => Ok(()),
2365 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2369 pub fn print_is_auto(&mut self, s: hir::IsAuto) -> io::Result<()> {
2371 hir::IsAuto::Yes => self.word_nbsp("auto"),
2372 hir::IsAuto::No => Ok(()),
2377 // Dup'ed from parse::classify, but adapted for the HIR.
2378 /// Does this expression require a semicolon to be treated
2379 /// as a statement? The negation of this: 'can this expression
2380 /// be used as a statement without a semicolon' -- is used
2381 /// as an early-bail-out in the parser so that, for instance,
2382 /// if true {...} else {...}
2384 /// isn't parsed as (if true {...} else {...} | x) | 5
2385 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2387 hir::ExprKind::If(..) |
2388 hir::ExprKind::Match(..) |
2389 hir::ExprKind::Block(..) |
2390 hir::ExprKind::While(..) |
2391 hir::ExprKind::Loop(..) => false,
2396 /// this statement requires a semicolon after it.
2397 /// note that in one case (stmt_semi), we've already
2398 /// seen the semicolon, and thus don't need another.
2399 fn stmt_ends_with_semi(stmt: &hir::StmtKind) -> bool {
2401 hir::StmtKind::Decl(ref d, _) => {
2403 hir::DeclKind::Local(_) => true,
2404 hir::DeclKind::Item(_) => false,
2407 hir::StmtKind::Expr(ref e, _) => {
2408 expr_requires_semi_to_be_stmt(&e)
2410 hir::StmtKind::Semi(..) => {
2416 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2417 use hir::BinOpKind::*;
2419 Add => AssocOp::Add,
2420 Sub => AssocOp::Subtract,
2421 Mul => AssocOp::Multiply,
2422 Div => AssocOp::Divide,
2423 Rem => AssocOp::Modulus,
2425 And => AssocOp::LAnd,
2428 BitXor => AssocOp::BitXor,
2429 BitAnd => AssocOp::BitAnd,
2430 BitOr => AssocOp::BitOr,
2431 Shl => AssocOp::ShiftLeft,
2432 Shr => AssocOp::ShiftRight,
2434 Eq => AssocOp::Equal,
2435 Lt => AssocOp::Less,
2436 Le => AssocOp::LessEqual,
2437 Ne => AssocOp::NotEqual,
2438 Ge => AssocOp::GreaterEqual,
2439 Gt => AssocOp::Greater,
2443 /// Expressions that syntactically contain an "exterior" struct literal i.e. not surrounded by any
2444 /// parens or other delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2445 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2446 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
2448 hir::ExprKind::Struct(..) => true,
2450 hir::ExprKind::Assign(ref lhs, ref rhs) |
2451 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) |
2452 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2453 // X { y: 1 } + X { y: 2 }
2454 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2456 hir::ExprKind::Unary(_, ref x) |
2457 hir::ExprKind::Cast(ref x, _) |
2458 hir::ExprKind::Type(ref x, _) |
2459 hir::ExprKind::Field(ref x, _) |
2460 hir::ExprKind::Index(ref x, _) => {
2461 // &X { y: 1 }, X { y: 1 }.y
2462 contains_exterior_struct_lit(&x)
2465 hir::ExprKind::MethodCall(.., ref exprs) => {
2466 // X { y: 1 }.bar(...)
2467 contains_exterior_struct_lit(&exprs[0])