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::TySlice(ref ty) => {
372 self.print_type(&ty)?;
375 hir::TyPtr(ref mt) => {
378 hir::MutMutable => self.word_nbsp("mut")?,
379 hir::MutImmutable => self.word_nbsp("const")?,
381 self.print_type(&mt.ty)?;
383 hir::TyRptr(ref lifetime, ref mt) => {
385 self.print_opt_lifetime(lifetime)?;
391 hir::TyTup(ref elts) => {
393 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty))?;
399 hir::TyBareFn(ref f) => {
400 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &f.generic_params,
403 hir::TyPath(ref qpath) => {
404 self.print_qpath(qpath, false)?
406 hir::TyTraitObject(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::TyArray(ref ty, ref length) => {
425 self.print_type(&ty)?;
427 self.print_anon_const(length)?;
430 hir::TyTypeof(ref e) => {
431 self.s.word("typeof(")?;
432 self.print_anon_const(e)?;
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::ForeignItemFn(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::ForeignItemStatic(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::ForeignItemType => {
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::ItemExternCrate(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::ItemUse(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::ItemStatic(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::ItemConst(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::ItemFn(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::ItemMod(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::ItemForeignMod(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::ItemGlobalAsm(ref ga) => {
625 self.head(&visibility_qualified(&item.vis, "global asm"))?;
626 self.s.word(&ga.asm.as_str())?;
629 hir::ItemTy(ref ty, ref generics) => {
630 self.ibox(indent_unit)?;
632 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
633 self.print_name(item.name)?;
634 self.print_generic_params(&generics.params)?;
635 self.end()?; // end the inner ibox
637 self.print_where_clause(&generics.where_clause)?;
639 self.word_space("=")?;
640 self.print_type(&ty)?;
642 self.end()?; // end the outer ibox
644 hir::ItemExistential(ref exist) => {
645 self.ibox(indent_unit)?;
647 self.word_nbsp(&visibility_qualified(&item.vis, "existential type"))?;
648 self.print_name(item.name)?;
649 self.print_generic_params(&exist.generics.params)?;
650 self.end()?; // end the inner ibox
652 self.print_where_clause(&exist.generics.where_clause)?;
654 self.word_space(":")?;
655 let mut real_bounds = Vec::with_capacity(exist.bounds.len());
656 for b in exist.bounds.iter() {
657 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
659 self.word_space("for ?")?;
660 self.print_trait_ref(&ptr.trait_ref)?;
662 real_bounds.push(b.clone());
665 self.print_bounds(":", &real_bounds[..])?;
667 self.end()?; // end the outer ibox
669 hir::ItemEnum(ref enum_definition, ref params) => {
670 self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
672 hir::ItemStruct(ref struct_def, ref generics) => {
673 self.head(&visibility_qualified(&item.vis, "struct"))?;
674 self.print_struct(struct_def, generics, item.name, item.span, true)?;
676 hir::ItemUnion(ref struct_def, ref generics) => {
677 self.head(&visibility_qualified(&item.vis, "union"))?;
678 self.print_struct(struct_def, generics, item.name, item.span, true)?;
680 hir::ItemImpl(unsafety,
688 self.print_visibility(&item.vis)?;
689 self.print_defaultness(defaultness)?;
690 self.print_unsafety(unsafety)?;
691 self.word_nbsp("impl")?;
693 if !generics.params.is_empty() {
694 self.print_generic_params(&generics.params)?;
699 hir::ImplPolarity::Negative => {
707 self.print_trait_ref(t)?;
709 self.word_space("for")?;
714 self.print_type(&ty)?;
715 self.print_where_clause(&generics.where_clause)?;
719 self.print_inner_attributes(&item.attrs)?;
720 for impl_item in impl_items {
721 self.ann.nested(self, Nested::ImplItem(impl_item.id))?;
723 self.bclose(item.span)?;
725 hir::ItemTrait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
727 self.print_visibility(&item.vis)?;
728 self.print_is_auto(is_auto)?;
729 self.print_unsafety(unsafety)?;
730 self.word_nbsp("trait")?;
731 self.print_name(item.name)?;
732 self.print_generic_params(&generics.params)?;
733 let mut real_bounds = Vec::with_capacity(bounds.len());
734 for b in bounds.iter() {
735 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
737 self.word_space("for ?")?;
738 self.print_trait_ref(&ptr.trait_ref)?;
740 real_bounds.push(b.clone());
743 self.print_bounds(":", &real_bounds[..])?;
744 self.print_where_clause(&generics.where_clause)?;
747 for trait_item in trait_items {
748 self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
750 self.bclose(item.span)?;
752 hir::ItemTraitAlias(ref generics, ref bounds) => {
754 self.print_visibility(&item.vis)?;
755 self.word_nbsp("trait")?;
756 self.print_name(item.name)?;
757 self.print_generic_params(&generics.params)?;
758 let mut real_bounds = Vec::with_capacity(bounds.len());
759 // FIXME(durka) this seems to be some quite outdated syntax
760 for b in bounds.iter() {
761 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
763 self.word_space("for ?")?;
764 self.print_trait_ref(&ptr.trait_ref)?;
766 real_bounds.push(b.clone());
770 self.print_bounds("=", &real_bounds[..])?;
771 self.print_where_clause(&generics.where_clause)?;
775 self.ann.post(self, NodeItem(item))
778 pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
779 self.print_path(&t.path, false)
782 fn print_formal_generic_params(
784 generic_params: &[hir::GenericParam]
785 ) -> io::Result<()> {
786 if !generic_params.is_empty() {
788 self.print_generic_params(generic_params)?;
794 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
795 self.print_formal_generic_params(&t.bound_generic_params)?;
796 self.print_trait_ref(&t.trait_ref)
799 pub fn print_enum_def(&mut self,
800 enum_definition: &hir::EnumDef,
801 generics: &hir::Generics,
803 span: syntax_pos::Span,
804 visibility: &hir::Visibility)
806 self.head(&visibility_qualified(visibility, "enum"))?;
807 self.print_name(name)?;
808 self.print_generic_params(&generics.params)?;
809 self.print_where_clause(&generics.where_clause)?;
811 self.print_variants(&enum_definition.variants, span)
814 pub fn print_variants(&mut self,
815 variants: &[hir::Variant],
816 span: syntax_pos::Span)
820 self.space_if_not_bol()?;
821 self.maybe_print_comment(v.span.lo())?;
822 self.print_outer_attributes(&v.node.attrs)?;
823 self.ibox(indent_unit)?;
824 self.print_variant(v)?;
827 self.maybe_print_trailing_comment(v.span, None)?;
832 pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
834 hir::VisibilityKind::Public => self.word_nbsp("pub")?,
835 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate")?,
836 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)")?,
837 hir::VisibilityKind::Restricted { ref path, .. } => {
838 self.s.word("pub(")?;
839 if path.segments.len() == 1 &&
840 path.segments[0].ident.name == keywords::Super.name() {
841 // Special case: `super` can print like `pub(super)`.
842 self.s.word("super")?;
844 // Everything else requires `in` at present.
845 self.word_nbsp("in")?;
846 self.print_path(path, false)?;
848 self.word_nbsp(")")?;
850 hir::VisibilityKind::Inherited => ()
856 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) -> io::Result<()> {
858 hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
859 hir::Defaultness::Final => (),
864 pub fn print_struct(&mut self,
865 struct_def: &hir::VariantData,
866 generics: &hir::Generics,
868 span: syntax_pos::Span,
869 print_finalizer: bool)
871 self.print_name(name)?;
872 self.print_generic_params(&generics.params)?;
873 if !struct_def.is_struct() {
874 if struct_def.is_tuple() {
876 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
877 s.maybe_print_comment(field.span.lo())?;
878 s.print_outer_attributes(&field.attrs)?;
879 s.print_visibility(&field.vis)?;
880 s.print_type(&field.ty)
884 self.print_where_clause(&generics.where_clause)?;
889 self.end() // close the outer-box
891 self.print_where_clause(&generics.where_clause)?;
894 self.hardbreak_if_not_bol()?;
896 for field in struct_def.fields() {
897 self.hardbreak_if_not_bol()?;
898 self.maybe_print_comment(field.span.lo())?;
899 self.print_outer_attributes(&field.attrs)?;
900 self.print_visibility(&field.vis)?;
901 self.print_ident(field.ident)?;
902 self.word_nbsp(":")?;
903 self.print_type(&field.ty)?;
911 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
913 let generics = hir::Generics::empty();
914 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
915 if let Some(ref d) = v.node.disr_expr {
917 self.word_space("=")?;
918 self.print_anon_const(d)?;
922 pub fn print_method_sig(&mut self,
925 generics: &hir::Generics,
926 vis: &hir::Visibility,
927 arg_names: &[ast::Ident],
928 body_id: Option<hir::BodyId>)
930 self.print_fn(&m.decl,
939 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
940 self.ann.pre(self, NodeSubItem(ti.id))?;
941 self.hardbreak_if_not_bol()?;
942 self.maybe_print_comment(ti.span.lo())?;
943 self.print_outer_attributes(&ti.attrs)?;
945 hir::TraitItemKind::Const(ref ty, default) => {
946 let vis = Spanned { span: syntax_pos::DUMMY_SP,
947 node: hir::VisibilityKind::Inherited };
948 self.print_associated_const(ti.ident, &ty, default, &vis)?;
950 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
951 let vis = Spanned { span: syntax_pos::DUMMY_SP,
952 node: hir::VisibilityKind::Inherited };
953 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None)?;
956 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
957 let vis = Spanned { span: syntax_pos::DUMMY_SP,
958 node: hir::VisibilityKind::Inherited };
960 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body))?;
962 self.end()?; // need to close a box
963 self.end()?; // need to close a box
964 self.ann.nested(self, Nested::Body(body))?;
966 hir::TraitItemKind::Type(ref bounds, ref default) => {
967 self.print_associated_type(ti.ident,
969 default.as_ref().map(|ty| &**ty))?;
972 self.ann.post(self, NodeSubItem(ti.id))
975 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
976 self.ann.pre(self, NodeSubItem(ii.id))?;
977 self.hardbreak_if_not_bol()?;
978 self.maybe_print_comment(ii.span.lo())?;
979 self.print_outer_attributes(&ii.attrs)?;
980 self.print_defaultness(ii.defaultness)?;
983 hir::ImplItemKind::Const(ref ty, expr) => {
984 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis)?;
986 hir::ImplItemKind::Method(ref sig, body) => {
988 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body))?;
990 self.end()?; // need to close a box
991 self.end()?; // need to close a box
992 self.ann.nested(self, Nested::Body(body))?;
994 hir::ImplItemKind::Type(ref ty) => {
995 self.print_associated_type(ii.ident, None, Some(ty))?;
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::StmtDecl(ref decl, _) => {
1005 self.print_decl(&decl)?;
1007 hir::StmtExpr(ref expr, _) => {
1008 self.space_if_not_bol()?;
1009 self.print_expr(&expr)?;
1011 hir::StmtSemi(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::ExprIf(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::ExprBlock(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::ExprClosure(..) |
1167 hir::ExprBreak(..) => 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::ExprField(..) => 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::ExprCast { .. }, hir::BinOp_::BiLt) |
1296 (&hir::ExprCast { .. }, hir::BinOp_::BiShl) => 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::ExprBox(ref expr) => {
1327 self.word_space("box")?;
1328 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
1330 hir::ExprArray(ref exprs) => {
1331 self.print_expr_vec(exprs)?;
1333 hir::ExprRepeat(ref element, ref count) => {
1334 self.print_expr_repeat(&element, count)?;
1336 hir::ExprStruct(ref qpath, ref fields, ref wth) => {
1337 self.print_expr_struct(qpath, &fields[..], wth)?;
1339 hir::ExprTup(ref exprs) => {
1340 self.print_expr_tup(exprs)?;
1342 hir::ExprCall(ref func, ref args) => {
1343 self.print_expr_call(&func, args)?;
1345 hir::ExprMethodCall(ref segment, _, ref args) => {
1346 self.print_expr_method_call(segment, args)?;
1348 hir::ExprBinary(op, ref lhs, ref rhs) => {
1349 self.print_expr_binary(op, &lhs, &rhs)?;
1351 hir::ExprUnary(op, ref expr) => {
1352 self.print_expr_unary(op, &expr)?;
1354 hir::ExprAddrOf(m, ref expr) => {
1355 self.print_expr_addr_of(m, &expr)?;
1357 hir::ExprLit(ref lit) => {
1358 self.print_literal(&lit)?;
1360 hir::ExprCast(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::ExprType(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::ExprIf(ref test, ref blk, ref elseopt) => {
1374 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1376 hir::ExprWhile(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::ExprLoop(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::ExprMatch(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::ExprClosure(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::ExprBlock(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::ExprAssign(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::ExprAssignOp(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::ExprField(ref expr, ident) => {
1449 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
1451 self.print_ident(ident)?;
1453 hir::ExprIndex(ref expr, ref index) => {
1454 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1456 self.print_expr(&index)?;
1459 hir::ExprPath(ref qpath) => {
1460 self.print_qpath(qpath, true)?
1462 hir::ExprBreak(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::ExprContinue(destination) => {
1475 self.s.word("continue")?;
1477 if let Some(label) = destination.label {
1478 self.print_ident(label.ident)?;
1482 hir::ExprRet(ref result) => {
1483 self.s.word("return")?;
1487 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1492 hir::ExprInlineAsm(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::ExprYield(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::DeclLocal(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::DeclItem(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 p.node != PatKind::Wild {
1918 self.print_pat(&p)?;
1921 if !after.is_empty() {
1922 self.word_space(",")?;
1925 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1929 self.ann.post(self, NodePat(pat))
1932 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1933 // I have no idea why this check is necessary, but here it
1935 if arm.attrs.is_empty() {
1938 self.cbox(indent_unit)?;
1940 self.print_outer_attributes(&arm.attrs)?;
1941 let mut first = true;
1942 for p in &arm.pats {
1947 self.word_space("|")?;
1949 self.print_pat(&p)?;
1952 if let Some(ref e) = arm.guard {
1953 self.word_space("if")?;
1954 self.print_expr(&e)?;
1957 self.word_space("=>")?;
1959 match arm.body.node {
1960 hir::ExprBlock(ref blk, opt_label) => {
1961 if let Some(label) = opt_label {
1962 self.print_ident(label.ident)?;
1963 self.word_space(":")?;
1965 // the block will close the pattern's ibox
1966 self.print_block_unclosed_indent(&blk, indent_unit)?;
1968 // If it is a user-provided unsafe block, print a comma after it
1969 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1974 self.end()?; // close the ibox for the pattern
1975 self.print_expr(&arm.body)?;
1979 self.end() // close enclosing cbox
1982 pub fn print_fn(&mut self,
1984 header: hir::FnHeader,
1985 name: Option<ast::Name>,
1986 generics: &hir::Generics,
1987 vis: &hir::Visibility,
1988 arg_names: &[ast::Ident],
1989 body_id: Option<hir::BodyId>)
1991 self.print_fn_header_info(header, vis)?;
1993 if let Some(name) = name {
1995 self.print_name(name)?;
1997 self.print_generic_params(&generics.params)?;
2001 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2002 assert!(arg_names.is_empty() || body_id.is_none());
2003 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2004 s.ibox(indent_unit)?;
2005 if let Some(arg_name) = arg_names.get(i) {
2006 s.s.word(&arg_name.as_str())?;
2009 } else if let Some(body_id) = body_id {
2010 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2019 self.s.word(", ...")?;
2023 self.print_fn_output(decl)?;
2024 self.print_where_clause(&generics.where_clause)
2027 fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
2030 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2031 s.ibox(indent_unit)?;
2033 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2036 if ty.node != hir::TyInfer {
2045 if let hir::DefaultReturn(..) = decl.output {
2049 self.space_if_not_bol()?;
2050 self.word_space("->")?;
2052 hir::Return(ref ty) => {
2053 self.print_type(&ty)?;
2054 self.maybe_print_comment(ty.span.lo())
2056 hir::DefaultReturn(..) => unreachable!(),
2060 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
2061 match capture_clause {
2062 hir::CaptureByValue => self.word_space("move"),
2063 hir::CaptureByRef => Ok(()),
2067 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::GenericBound]) -> io::Result<()> {
2068 if !bounds.is_empty() {
2069 self.s.word(prefix)?;
2070 let mut first = true;
2071 for bound in bounds {
2072 if !(first && prefix.is_empty()) {
2078 self.word_space("+")?;
2082 GenericBound::Trait(tref, modifier) => {
2083 if modifier == &TraitBoundModifier::Maybe {
2086 self.print_poly_trait_ref(tref)?;
2088 GenericBound::Outlives(lt) => {
2089 self.print_lifetime(lt)?;
2097 pub fn print_generic_params(&mut self, generic_params: &[GenericParam]) -> io::Result<()> {
2098 if !generic_params.is_empty() {
2101 self.commasep(Inconsistent, generic_params, |s, param| {
2102 s.print_generic_param(param)
2110 pub fn print_generic_param(&mut self, param: &GenericParam) -> io::Result<()> {
2111 self.print_ident(param.name.ident())?;
2113 GenericParamKind::Lifetime { .. } => {
2115 for bound in ¶m.bounds {
2117 GenericBound::Outlives(lt) => {
2119 self.print_lifetime(lt)?;
2127 GenericParamKind::Type { ref default, .. } => {
2128 self.print_bounds(":", ¶m.bounds)?;
2132 self.word_space("=")?;
2133 self.print_type(&default)
2141 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2142 self.print_ident(lifetime.name.ident())
2145 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2146 if where_clause.predicates.is_empty() {
2151 self.word_space("where")?;
2153 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2155 self.word_space(",")?;
2159 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2160 ref bound_generic_params,
2165 self.print_formal_generic_params(bound_generic_params)?;
2166 self.print_type(&bounded_ty)?;
2167 self.print_bounds(":", bounds)?;
2169 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2172 self.print_lifetime(lifetime)?;
2175 for (i, bound) in bounds.iter().enumerate() {
2177 GenericBound::Outlives(lt) => {
2178 self.print_lifetime(lt)?;
2188 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
2191 self.print_type(lhs_ty)?;
2193 self.word_space("=")?;
2194 self.print_type(rhs_ty)?;
2202 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2204 hir::MutMutable => self.word_nbsp("mut"),
2205 hir::MutImmutable => Ok(()),
2209 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2210 self.print_mutability(mt.mutbl)?;
2211 self.print_type(&mt.ty)
2214 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2215 if let hir::DefaultReturn(..) = decl.output {
2219 self.space_if_not_bol()?;
2220 self.ibox(indent_unit)?;
2221 self.word_space("->")?;
2223 hir::DefaultReturn(..) => unreachable!(),
2224 hir::Return(ref ty) => self.print_type(&ty)?,
2229 hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2234 pub fn print_ty_fn(&mut self,
2236 unsafety: hir::Unsafety,
2238 name: Option<ast::Name>,
2239 generic_params: &[hir::GenericParam],
2240 arg_names: &[ast::Ident])
2242 self.ibox(indent_unit)?;
2243 if !generic_params.is_empty() {
2244 self.s.word("for")?;
2245 self.print_generic_params(generic_params)?;
2247 let generics = hir::Generics {
2248 params: hir::HirVec::new(),
2249 where_clause: hir::WhereClause {
2250 id: ast::DUMMY_NODE_ID,
2251 predicates: hir::HirVec::new(),
2253 span: syntax_pos::DUMMY_SP,
2259 constness: hir::Constness::NotConst,
2260 asyncness: hir::IsAsync::NotAsync,
2264 &Spanned { span: syntax_pos::DUMMY_SP,
2265 node: hir::VisibilityKind::Inherited },
2271 pub fn maybe_print_trailing_comment(&mut self,
2272 span: syntax_pos::Span,
2273 next_pos: Option<BytePos>)
2275 let cm = match self.cm {
2279 if let Some(ref cmnt) = self.next_comment() {
2280 if (*cmnt).style != comments::Trailing {
2283 let span_line = cm.lookup_char_pos(span.hi());
2284 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2285 let mut next = (*cmnt).pos + BytePos(1);
2286 if let Some(p) = next_pos {
2289 if span.hi() < (*cmnt).pos && (*cmnt).pos < next &&
2290 span_line.line == comment_line.line {
2291 self.print_comment(cmnt)?;
2297 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2298 // If there aren't any remaining comments, then we need to manually
2299 // make sure there is a line break at the end.
2300 if self.next_comment().is_none() {
2301 self.s.hardbreak()?;
2303 while let Some(ref cmnt) = self.next_comment() {
2304 self.print_comment(cmnt)?
2309 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2310 opt_abi: Option<Abi>)
2313 Some(Abi::Rust) => Ok(()),
2315 self.word_nbsp("extern")?;
2316 self.word_nbsp(&abi.to_string())
2322 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2325 self.word_nbsp("extern")?;
2326 self.word_nbsp(&abi.to_string())
2332 pub fn print_fn_header_info(&mut self,
2333 header: hir::FnHeader,
2334 vis: &hir::Visibility)
2336 self.s.word(&visibility_qualified(vis, ""))?;
2338 match header.constness {
2339 hir::Constness::NotConst => {}
2340 hir::Constness::Const => self.word_nbsp("const")?,
2343 match header.asyncness {
2344 hir::IsAsync::NotAsync => {}
2345 hir::IsAsync::Async => self.word_nbsp("async")?,
2348 self.print_unsafety(header.unsafety)?;
2350 if header.abi != Abi::Rust {
2351 self.word_nbsp("extern")?;
2352 self.word_nbsp(&header.abi.to_string())?;
2358 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2360 hir::Unsafety::Normal => Ok(()),
2361 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2365 pub fn print_is_auto(&mut self, s: hir::IsAuto) -> io::Result<()> {
2367 hir::IsAuto::Yes => self.word_nbsp("auto"),
2368 hir::IsAuto::No => Ok(()),
2373 // Dup'ed from parse::classify, but adapted for the HIR.
2374 /// Does this expression require a semicolon to be treated
2375 /// as a statement? The negation of this: 'can this expression
2376 /// be used as a statement without a semicolon' -- is used
2377 /// as an early-bail-out in the parser so that, for instance,
2378 /// if true {...} else {...}
2380 /// isn't parsed as (if true {...} else {...} | x) | 5
2381 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2384 hir::ExprMatch(..) |
2385 hir::ExprBlock(..) |
2386 hir::ExprWhile(..) |
2387 hir::ExprLoop(..) => false,
2392 /// this statement requires a semicolon after it.
2393 /// note that in one case (stmt_semi), we've already
2394 /// seen the semicolon, and thus don't need another.
2395 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2397 hir::StmtDecl(ref d, _) => {
2399 hir::DeclLocal(_) => true,
2400 hir::DeclItem(_) => false,
2403 hir::StmtExpr(ref e, _) => {
2404 expr_requires_semi_to_be_stmt(&e)
2406 hir::StmtSemi(..) => {
2412 fn bin_op_to_assoc_op(op: hir::BinOp_) -> AssocOp {
2415 BiAdd => AssocOp::Add,
2416 BiSub => AssocOp::Subtract,
2417 BiMul => AssocOp::Multiply,
2418 BiDiv => AssocOp::Divide,
2419 BiRem => AssocOp::Modulus,
2421 BiAnd => AssocOp::LAnd,
2422 BiOr => AssocOp::LOr,
2424 BiBitXor => AssocOp::BitXor,
2425 BiBitAnd => AssocOp::BitAnd,
2426 BiBitOr => AssocOp::BitOr,
2427 BiShl => AssocOp::ShiftLeft,
2428 BiShr => AssocOp::ShiftRight,
2430 BiEq => AssocOp::Equal,
2431 BiLt => AssocOp::Less,
2432 BiLe => AssocOp::LessEqual,
2433 BiNe => AssocOp::NotEqual,
2434 BiGe => AssocOp::GreaterEqual,
2435 BiGt => AssocOp::Greater,
2439 /// Expressions that syntactically contain an "exterior" struct literal i.e. not surrounded by any
2440 /// parens or other delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2441 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2442 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
2444 hir::ExprStruct(..) => true,
2446 hir::ExprAssign(ref lhs, ref rhs) |
2447 hir::ExprAssignOp(_, ref lhs, ref rhs) |
2448 hir::ExprBinary(_, ref lhs, ref rhs) => {
2449 // X { y: 1 } + X { y: 2 }
2450 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2452 hir::ExprUnary(_, ref x) |
2453 hir::ExprCast(ref x, _) |
2454 hir::ExprType(ref x, _) |
2455 hir::ExprField(ref x, _) |
2456 hir::ExprIndex(ref x, _) => {
2457 // &X { y: 1 }, X { y: 1 }.y
2458 contains_exterior_struct_lit(&x)
2461 hir::ExprMethodCall(.., ref exprs) => {
2462 // X { y: 1 }.bar(...)
2463 contains_exterior_struct_lit(&exprs[0])