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::TyImplTraitExistential(hir_id, _def_id, ref _lifetimes) => {
424 match self.ann.try_fetch_item(hir_id.id).map(|it| &it.node) {
425 None => self.word_space("impl {{Trait}}")?,
426 Some(&hir::ItemExistential(ref exist_ty)) => {
427 self.print_bounds("impl", &exist_ty.bounds)?;
429 other => bug!("impl Trait pointed to {:#?}", other),
432 hir::TyArray(ref ty, ref length) => {
434 self.print_type(&ty)?;
436 self.print_anon_const(length)?;
439 hir::TyTypeof(ref e) => {
440 self.s.word("typeof(")?;
441 self.print_anon_const(e)?;
454 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
455 self.hardbreak_if_not_bol()?;
456 self.maybe_print_comment(item.span.lo())?;
457 self.print_outer_attributes(&item.attrs)?;
459 hir::ForeignItemFn(ref decl, ref arg_names, ref generics) => {
463 unsafety: hir::Unsafety::Normal,
464 constness: hir::Constness::NotConst,
466 asyncness: hir::IsAsync::NotAsync,
473 self.end()?; // end head-ibox
475 self.end() // end the outer fn box
477 hir::ForeignItemStatic(ref t, m) => {
478 self.head(&visibility_qualified(&item.vis, "static"))?;
480 self.word_space("mut")?;
482 self.print_name(item.name)?;
483 self.word_space(":")?;
484 self.print_type(&t)?;
486 self.end()?; // end the head-ibox
487 self.end() // end the outer cbox
489 hir::ForeignItemType => {
490 self.head(&visibility_qualified(&item.vis, "type"))?;
491 self.print_name(item.name)?;
493 self.end()?; // end the head-ibox
494 self.end() // end the outer cbox
499 fn print_associated_const(&mut self,
502 default: Option<hir::BodyId>,
503 vis: &hir::Visibility)
505 self.s.word(&visibility_qualified(vis, ""))?;
506 self.word_space("const")?;
507 self.print_ident(ident)?;
508 self.word_space(":")?;
509 self.print_type(ty)?;
510 if let Some(expr) = default {
512 self.word_space("=")?;
513 self.ann.nested(self, Nested::Body(expr))?;
518 fn print_associated_type(&mut self,
520 bounds: Option<&hir::GenericBounds>,
521 ty: Option<&hir::Ty>)
523 self.word_space("type")?;
524 self.print_ident(ident)?;
525 if let Some(bounds) = bounds {
526 self.print_bounds(":", bounds)?;
528 if let Some(ty) = ty {
530 self.word_space("=")?;
531 self.print_type(ty)?;
536 /// Pretty-print an item
537 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
538 self.hardbreak_if_not_bol()?;
539 self.maybe_print_comment(item.span.lo())?;
540 self.print_outer_attributes(&item.attrs)?;
541 self.ann.pre(self, NodeItem(item))?;
543 hir::ItemExternCrate(orig_name) => {
544 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
545 if let Some(orig_name) = orig_name {
546 self.print_name(orig_name)?;
551 self.print_name(item.name)?;
553 self.end()?; // end inner head-block
554 self.end()?; // end outer head-block
556 hir::ItemUse(ref path, kind) => {
557 self.head(&visibility_qualified(&item.vis, "use"))?;
558 self.print_path(path, false)?;
561 hir::UseKind::Single => {
562 if path.segments.last().unwrap().ident.name != item.name {
564 self.word_space("as")?;
565 self.print_name(item.name)?;
569 hir::UseKind::Glob => self.s.word("::*;")?,
570 hir::UseKind::ListStem => self.s.word("::{};")?
572 self.end()?; // end inner head-block
573 self.end()?; // end outer head-block
575 hir::ItemStatic(ref ty, m, expr) => {
576 self.head(&visibility_qualified(&item.vis, "static"))?;
577 if m == hir::MutMutable {
578 self.word_space("mut")?;
580 self.print_name(item.name)?;
581 self.word_space(":")?;
582 self.print_type(&ty)?;
584 self.end()?; // end the head-ibox
586 self.word_space("=")?;
587 self.ann.nested(self, Nested::Body(expr))?;
589 self.end()?; // end the outer cbox
591 hir::ItemConst(ref ty, expr) => {
592 self.head(&visibility_qualified(&item.vis, "const"))?;
593 self.print_name(item.name)?;
594 self.word_space(":")?;
595 self.print_type(&ty)?;
597 self.end()?; // end the head-ibox
599 self.word_space("=")?;
600 self.ann.nested(self, Nested::Body(expr))?;
602 self.end()?; // end the outer cbox
604 hir::ItemFn(ref decl, header, ref typarams, body) => {
614 self.end()?; // need to close a box
615 self.end()?; // need to close a box
616 self.ann.nested(self, Nested::Body(body))?;
618 hir::ItemMod(ref _mod) => {
619 self.head(&visibility_qualified(&item.vis, "mod"))?;
620 self.print_name(item.name)?;
623 self.print_mod(_mod, &item.attrs)?;
624 self.bclose(item.span)?;
626 hir::ItemForeignMod(ref nmod) => {
627 self.head("extern")?;
628 self.word_nbsp(&nmod.abi.to_string())?;
630 self.print_foreign_mod(nmod, &item.attrs)?;
631 self.bclose(item.span)?;
633 hir::ItemGlobalAsm(ref ga) => {
634 self.head(&visibility_qualified(&item.vis, "global asm"))?;
635 self.s.word(&ga.asm.as_str())?;
638 hir::ItemTy(ref ty, ref generics) => {
639 self.ibox(indent_unit)?;
641 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
642 self.print_name(item.name)?;
643 self.print_generic_params(&generics.params)?;
644 self.end()?; // end the inner ibox
646 self.print_where_clause(&generics.where_clause)?;
648 self.word_space("=")?;
649 self.print_type(&ty)?;
651 self.end()?; // end the outer ibox
653 hir::ItemExistential(ref exist) => {
654 self.ibox(indent_unit)?;
656 self.word_nbsp(&visibility_qualified(&item.vis, "existential type"))?;
657 self.print_name(item.name)?;
658 self.print_generic_params(&exist.generics.params)?;
659 self.end()?; // end the inner ibox
661 self.print_where_clause(&exist.generics.where_clause)?;
663 self.word_space(":")?;
664 let mut real_bounds = Vec::with_capacity(exist.bounds.len());
665 for b in exist.bounds.iter() {
666 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
668 self.word_space("for ?")?;
669 self.print_trait_ref(&ptr.trait_ref)?;
671 real_bounds.push(b.clone());
674 self.print_bounds(":", &real_bounds[..])?;
676 self.end()?; // end the outer ibox
678 hir::ItemEnum(ref enum_definition, ref params) => {
679 self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
681 hir::ItemStruct(ref struct_def, ref generics) => {
682 self.head(&visibility_qualified(&item.vis, "struct"))?;
683 self.print_struct(struct_def, generics, item.name, item.span, true)?;
685 hir::ItemUnion(ref struct_def, ref generics) => {
686 self.head(&visibility_qualified(&item.vis, "union"))?;
687 self.print_struct(struct_def, generics, item.name, item.span, true)?;
689 hir::ItemImpl(unsafety,
697 self.print_visibility(&item.vis)?;
698 self.print_defaultness(defaultness)?;
699 self.print_unsafety(unsafety)?;
700 self.word_nbsp("impl")?;
702 if !generics.params.is_empty() {
703 self.print_generic_params(&generics.params)?;
708 hir::ImplPolarity::Negative => {
716 self.print_trait_ref(t)?;
718 self.word_space("for")?;
723 self.print_type(&ty)?;
724 self.print_where_clause(&generics.where_clause)?;
728 self.print_inner_attributes(&item.attrs)?;
729 for impl_item in impl_items {
730 self.ann.nested(self, Nested::ImplItem(impl_item.id))?;
732 self.bclose(item.span)?;
734 hir::ItemTrait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
736 self.print_visibility(&item.vis)?;
737 self.print_is_auto(is_auto)?;
738 self.print_unsafety(unsafety)?;
739 self.word_nbsp("trait")?;
740 self.print_name(item.name)?;
741 self.print_generic_params(&generics.params)?;
742 let mut real_bounds = Vec::with_capacity(bounds.len());
743 for b in bounds.iter() {
744 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
746 self.word_space("for ?")?;
747 self.print_trait_ref(&ptr.trait_ref)?;
749 real_bounds.push(b.clone());
752 self.print_bounds(":", &real_bounds[..])?;
753 self.print_where_clause(&generics.where_clause)?;
756 for trait_item in trait_items {
757 self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
759 self.bclose(item.span)?;
761 hir::ItemTraitAlias(ref generics, ref bounds) => {
763 self.print_visibility(&item.vis)?;
764 self.word_nbsp("trait")?;
765 self.print_name(item.name)?;
766 self.print_generic_params(&generics.params)?;
767 let mut real_bounds = Vec::with_capacity(bounds.len());
768 // FIXME(durka) this seems to be some quite outdated syntax
769 for b in bounds.iter() {
770 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
772 self.word_space("for ?")?;
773 self.print_trait_ref(&ptr.trait_ref)?;
775 real_bounds.push(b.clone());
779 self.print_bounds("=", &real_bounds[..])?;
780 self.print_where_clause(&generics.where_clause)?;
784 self.ann.post(self, NodeItem(item))
787 pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
788 self.print_path(&t.path, false)
791 fn print_formal_generic_params(
793 generic_params: &[hir::GenericParam]
794 ) -> io::Result<()> {
795 if !generic_params.is_empty() {
797 self.print_generic_params(generic_params)?;
803 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
804 self.print_formal_generic_params(&t.bound_generic_params)?;
805 self.print_trait_ref(&t.trait_ref)
808 pub fn print_enum_def(&mut self,
809 enum_definition: &hir::EnumDef,
810 generics: &hir::Generics,
812 span: syntax_pos::Span,
813 visibility: &hir::Visibility)
815 self.head(&visibility_qualified(visibility, "enum"))?;
816 self.print_name(name)?;
817 self.print_generic_params(&generics.params)?;
818 self.print_where_clause(&generics.where_clause)?;
820 self.print_variants(&enum_definition.variants, span)
823 pub fn print_variants(&mut self,
824 variants: &[hir::Variant],
825 span: syntax_pos::Span)
829 self.space_if_not_bol()?;
830 self.maybe_print_comment(v.span.lo())?;
831 self.print_outer_attributes(&v.node.attrs)?;
832 self.ibox(indent_unit)?;
833 self.print_variant(v)?;
836 self.maybe_print_trailing_comment(v.span, None)?;
841 pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
843 hir::VisibilityKind::Public => self.word_nbsp("pub")?,
844 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate")?,
845 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)")?,
846 hir::VisibilityKind::Restricted { ref path, .. } => {
847 self.s.word("pub(")?;
848 if path.segments.len() == 1 &&
849 path.segments[0].ident.name == keywords::Super.name() {
850 // Special case: `super` can print like `pub(super)`.
851 self.s.word("super")?;
853 // Everything else requires `in` at present.
854 self.word_nbsp("in")?;
855 self.print_path(path, false)?;
857 self.word_nbsp(")")?;
859 hir::VisibilityKind::Inherited => ()
865 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) -> io::Result<()> {
867 hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
868 hir::Defaultness::Final => (),
873 pub fn print_struct(&mut self,
874 struct_def: &hir::VariantData,
875 generics: &hir::Generics,
877 span: syntax_pos::Span,
878 print_finalizer: bool)
880 self.print_name(name)?;
881 self.print_generic_params(&generics.params)?;
882 if !struct_def.is_struct() {
883 if struct_def.is_tuple() {
885 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
886 s.maybe_print_comment(field.span.lo())?;
887 s.print_outer_attributes(&field.attrs)?;
888 s.print_visibility(&field.vis)?;
889 s.print_type(&field.ty)
893 self.print_where_clause(&generics.where_clause)?;
898 self.end() // close the outer-box
900 self.print_where_clause(&generics.where_clause)?;
903 self.hardbreak_if_not_bol()?;
905 for field in struct_def.fields() {
906 self.hardbreak_if_not_bol()?;
907 self.maybe_print_comment(field.span.lo())?;
908 self.print_outer_attributes(&field.attrs)?;
909 self.print_visibility(&field.vis)?;
910 self.print_ident(field.ident)?;
911 self.word_nbsp(":")?;
912 self.print_type(&field.ty)?;
920 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
922 let generics = hir::Generics::empty();
923 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
924 if let Some(ref d) = v.node.disr_expr {
926 self.word_space("=")?;
927 self.print_anon_const(d)?;
931 pub fn print_method_sig(&mut self,
934 generics: &hir::Generics,
935 vis: &hir::Visibility,
936 arg_names: &[ast::Ident],
937 body_id: Option<hir::BodyId>)
939 self.print_fn(&m.decl,
948 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
949 self.ann.pre(self, NodeSubItem(ti.id))?;
950 self.hardbreak_if_not_bol()?;
951 self.maybe_print_comment(ti.span.lo())?;
952 self.print_outer_attributes(&ti.attrs)?;
954 hir::TraitItemKind::Const(ref ty, default) => {
955 let vis = Spanned { span: syntax_pos::DUMMY_SP,
956 node: hir::VisibilityKind::Inherited };
957 self.print_associated_const(ti.ident, &ty, default, &vis)?;
959 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
960 let vis = Spanned { span: syntax_pos::DUMMY_SP,
961 node: hir::VisibilityKind::Inherited };
962 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None)?;
965 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
966 let vis = Spanned { span: syntax_pos::DUMMY_SP,
967 node: hir::VisibilityKind::Inherited };
969 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body))?;
971 self.end()?; // need to close a box
972 self.end()?; // need to close a box
973 self.ann.nested(self, Nested::Body(body))?;
975 hir::TraitItemKind::Type(ref bounds, ref default) => {
976 self.print_associated_type(ti.ident,
978 default.as_ref().map(|ty| &**ty))?;
981 self.ann.post(self, NodeSubItem(ti.id))
984 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
985 self.ann.pre(self, NodeSubItem(ii.id))?;
986 self.hardbreak_if_not_bol()?;
987 self.maybe_print_comment(ii.span.lo())?;
988 self.print_outer_attributes(&ii.attrs)?;
989 self.print_defaultness(ii.defaultness)?;
992 hir::ImplItemKind::Const(ref ty, expr) => {
993 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis)?;
995 hir::ImplItemKind::Method(ref sig, body) => {
997 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body))?;
999 self.end()?; // need to close a box
1000 self.end()?; // need to close a box
1001 self.ann.nested(self, Nested::Body(body))?;
1003 hir::ImplItemKind::Type(ref ty) => {
1004 self.print_associated_type(ii.ident, None, Some(ty))?;
1007 self.ann.post(self, NodeSubItem(ii.id))
1010 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1011 self.maybe_print_comment(st.span.lo())?;
1013 hir::StmtDecl(ref decl, _) => {
1014 self.print_decl(&decl)?;
1016 hir::StmtExpr(ref expr, _) => {
1017 self.space_if_not_bol()?;
1018 self.print_expr(&expr)?;
1020 hir::StmtSemi(ref expr, _) => {
1021 self.space_if_not_bol()?;
1022 self.print_expr(&expr)?;
1026 if stmt_ends_with_semi(&st.node) {
1029 self.maybe_print_trailing_comment(st.span, None)
1032 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1033 self.print_block_with_attrs(blk, &[])
1036 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1037 self.print_block_unclosed_indent(blk, indent_unit)
1040 pub fn print_block_unclosed_indent(&mut self,
1044 self.print_block_maybe_unclosed(blk, indented, &[], false)
1047 pub fn print_block_with_attrs(&mut self,
1049 attrs: &[ast::Attribute])
1051 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1054 pub fn print_block_maybe_unclosed(&mut self,
1057 attrs: &[ast::Attribute],
1061 hir::UnsafeBlock(..) => self.word_space("unsafe")?,
1062 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
1063 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
1064 hir::DefaultBlock => (),
1066 self.maybe_print_comment(blk.span.lo())?;
1067 self.ann.pre(self, NodeBlock(blk))?;
1070 self.print_inner_attributes(attrs)?;
1072 for st in &blk.stmts {
1073 self.print_stmt(st)?;
1077 self.space_if_not_bol()?;
1078 self.print_expr(&expr)?;
1079 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1083 self.bclose_maybe_open(blk.span, indented, close_box)?;
1084 self.ann.post(self, NodeBlock(blk))
1087 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1091 // "another else-if"
1092 hir::ExprIf(ref i, ref then, ref e) => {
1093 self.cbox(indent_unit - 1)?;
1095 self.s.word(" else if ")?;
1096 self.print_expr_as_cond(&i)?;
1098 self.print_expr(&then)?;
1099 self.print_else(e.as_ref().map(|e| &**e))
1102 hir::ExprBlock(ref b, _) => {
1103 self.cbox(indent_unit - 1)?;
1105 self.s.word(" else ")?;
1106 self.print_block(&b)
1108 // BLEAH, constraints would be great here
1110 panic!("print_if saw if with weird alternative");
1118 pub fn print_if(&mut self,
1121 elseopt: Option<&hir::Expr>)
1124 self.print_expr_as_cond(test)?;
1126 self.print_expr(blk)?;
1127 self.print_else(elseopt)
1130 pub fn print_if_let(&mut self,
1134 elseopt: Option<&hir::Expr>)
1136 self.head("if let")?;
1137 self.print_pat(pat)?;
1139 self.word_space("=")?;
1140 self.print_expr_as_cond(expr)?;
1142 self.print_block(blk)?;
1143 self.print_else(elseopt)
1146 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) -> io::Result<()> {
1147 self.ann.nested(self, Nested::Body(constant.body))
1150 fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
1152 self.commasep_exprs(Inconsistent, args)?;
1156 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr, prec: i8) -> io::Result<()> {
1157 let needs_par = expr.precedence().order() < prec;
1161 self.print_expr(expr)?;
1168 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1169 /// `if cond { ... }`.
1170 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr) -> io::Result<()> {
1171 let needs_par = match expr.node {
1172 // These cases need parens due to the parse error observed in #26461: `if return {}`
1173 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1174 hir::ExprClosure(..) |
1176 hir::ExprBreak(..) => true,
1178 _ => contains_exterior_struct_lit(expr),
1184 self.print_expr(expr)?;
1191 fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1192 self.ibox(indent_unit)?;
1194 self.commasep_exprs(Inconsistent, exprs)?;
1199 fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::AnonConst) -> io::Result<()> {
1200 self.ibox(indent_unit)?;
1202 self.print_expr(element)?;
1203 self.word_space(";")?;
1204 self.print_anon_const(count)?;
1209 fn print_expr_struct(&mut self,
1211 fields: &[hir::Field],
1212 wth: &Option<P<hir::Expr>>)
1214 self.print_qpath(qpath, true)?;
1216 self.commasep_cmnt(Consistent,
1219 s.ibox(indent_unit)?;
1220 if !field.is_shorthand {
1221 s.print_ident(field.ident)?;
1224 s.print_expr(&field.expr)?;
1230 self.ibox(indent_unit)?;
1231 if !fields.is_empty() {
1236 self.print_expr(&expr)?;
1239 _ => if !fields.is_empty() {
1247 fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1249 self.commasep_exprs(Inconsistent, exprs)?;
1250 if exprs.len() == 1 {
1256 fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1259 hir::ExprField(..) => parser::PREC_FORCE_PAREN,
1260 _ => parser::PREC_POSTFIX,
1263 self.print_expr_maybe_paren(func, prec)?;
1264 self.print_call_post(args)
1267 fn print_expr_method_call(&mut self,
1268 segment: &hir::PathSegment,
1271 let base_args = &args[1..];
1272 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
1274 self.print_ident(segment.ident)?;
1276 segment.with_generic_args(|generic_args| {
1277 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1278 return self.print_generic_args(&generic_args, segment.infer_types, true);
1282 self.print_call_post(base_args)
1285 fn print_expr_binary(&mut self,
1290 let assoc_op = bin_op_to_assoc_op(op.node);
1291 let prec = assoc_op.precedence() as i8;
1292 let fixity = assoc_op.fixity();
1294 let (left_prec, right_prec) = match fixity {
1295 Fixity::Left => (prec, prec + 1),
1296 Fixity::Right => (prec + 1, prec),
1297 Fixity::None => (prec + 1, prec + 1),
1300 let left_prec = match (&lhs.node, op.node) {
1301 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1302 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1303 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1304 (&hir::ExprCast { .. }, hir::BinOp_::BiLt) |
1305 (&hir::ExprCast { .. }, hir::BinOp_::BiShl) => parser::PREC_FORCE_PAREN,
1309 self.print_expr_maybe_paren(lhs, left_prec)?;
1311 self.word_space(op.node.as_str())?;
1312 self.print_expr_maybe_paren(rhs, right_prec)
1315 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1316 self.s.word(op.as_str())?;
1317 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1320 fn print_expr_addr_of(&mut self,
1321 mutability: hir::Mutability,
1325 self.print_mutability(mutability)?;
1326 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1329 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1330 self.maybe_print_comment(expr.span.lo())?;
1331 self.print_outer_attributes(&expr.attrs)?;
1332 self.ibox(indent_unit)?;
1333 self.ann.pre(self, NodeExpr(expr))?;
1335 hir::ExprBox(ref expr) => {
1336 self.word_space("box")?;
1337 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
1339 hir::ExprArray(ref exprs) => {
1340 self.print_expr_vec(exprs)?;
1342 hir::ExprRepeat(ref element, ref count) => {
1343 self.print_expr_repeat(&element, count)?;
1345 hir::ExprStruct(ref qpath, ref fields, ref wth) => {
1346 self.print_expr_struct(qpath, &fields[..], wth)?;
1348 hir::ExprTup(ref exprs) => {
1349 self.print_expr_tup(exprs)?;
1351 hir::ExprCall(ref func, ref args) => {
1352 self.print_expr_call(&func, args)?;
1354 hir::ExprMethodCall(ref segment, _, ref args) => {
1355 self.print_expr_method_call(segment, args)?;
1357 hir::ExprBinary(op, ref lhs, ref rhs) => {
1358 self.print_expr_binary(op, &lhs, &rhs)?;
1360 hir::ExprUnary(op, ref expr) => {
1361 self.print_expr_unary(op, &expr)?;
1363 hir::ExprAddrOf(m, ref expr) => {
1364 self.print_expr_addr_of(m, &expr)?;
1366 hir::ExprLit(ref lit) => {
1367 self.print_literal(&lit)?;
1369 hir::ExprCast(ref expr, ref ty) => {
1370 let prec = AssocOp::As.precedence() as i8;
1371 self.print_expr_maybe_paren(&expr, prec)?;
1373 self.word_space("as")?;
1374 self.print_type(&ty)?;
1376 hir::ExprType(ref expr, ref ty) => {
1377 let prec = AssocOp::Colon.precedence() as i8;
1378 self.print_expr_maybe_paren(&expr, prec)?;
1379 self.word_space(":")?;
1380 self.print_type(&ty)?;
1382 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1383 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1385 hir::ExprWhile(ref test, ref blk, opt_label) => {
1386 if let Some(label) = opt_label {
1387 self.print_ident(label.ident)?;
1388 self.word_space(":")?;
1390 self.head("while")?;
1391 self.print_expr_as_cond(&test)?;
1393 self.print_block(&blk)?;
1395 hir::ExprLoop(ref blk, opt_label, _) => {
1396 if let Some(label) = opt_label {
1397 self.print_ident(label.ident)?;
1398 self.word_space(":")?;
1402 self.print_block(&blk)?;
1404 hir::ExprMatch(ref expr, ref arms, _) => {
1405 self.cbox(indent_unit)?;
1407 self.word_nbsp("match")?;
1408 self.print_expr_as_cond(&expr)?;
1412 self.print_arm(arm)?;
1414 self.bclose_(expr.span, indent_unit)?;
1416 hir::ExprClosure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1417 self.print_capture_clause(capture_clause)?;
1419 self.print_closure_args(&decl, body)?;
1422 // this is a bare expression
1423 self.ann.nested(self, Nested::Body(body))?;
1424 self.end()?; // need to close a box
1426 // a box will be closed by print_expr, but we didn't want an overall
1427 // wrapper so we closed the corresponding opening. so create an
1428 // empty box to satisfy the close.
1431 hir::ExprBlock(ref blk, opt_label) => {
1432 if let Some(label) = opt_label {
1433 self.print_ident(label.ident)?;
1434 self.word_space(":")?;
1436 // containing cbox, will be closed by print-block at }
1437 self.cbox(indent_unit)?;
1438 // head-box, will be closed by print-block after {
1440 self.print_block(&blk)?;
1442 hir::ExprAssign(ref lhs, ref rhs) => {
1443 let prec = AssocOp::Assign.precedence() as i8;
1444 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1446 self.word_space("=")?;
1447 self.print_expr_maybe_paren(&rhs, prec)?;
1449 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1450 let prec = AssocOp::Assign.precedence() as i8;
1451 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1453 self.s.word(op.node.as_str())?;
1454 self.word_space("=")?;
1455 self.print_expr_maybe_paren(&rhs, prec)?;
1457 hir::ExprField(ref expr, ident) => {
1458 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
1460 self.print_ident(ident)?;
1462 hir::ExprIndex(ref expr, ref index) => {
1463 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1465 self.print_expr(&index)?;
1468 hir::ExprPath(ref qpath) => {
1469 self.print_qpath(qpath, true)?
1471 hir::ExprBreak(destination, ref opt_expr) => {
1472 self.s.word("break")?;
1474 if let Some(label) = destination.label {
1475 self.print_ident(label.ident)?;
1478 if let Some(ref expr) = *opt_expr {
1479 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
1483 hir::ExprContinue(destination) => {
1484 self.s.word("continue")?;
1486 if let Some(label) = destination.label {
1487 self.print_ident(label.ident)?;
1491 hir::ExprRet(ref result) => {
1492 self.s.word("return")?;
1496 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1501 hir::ExprInlineAsm(ref a, ref outputs, ref inputs) => {
1502 self.s.word("asm!")?;
1504 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
1505 self.word_space(":")?;
1507 let mut out_idx = 0;
1508 self.commasep(Inconsistent, &a.outputs, |s, out| {
1509 let constraint = out.constraint.as_str();
1510 let mut ch = constraint.chars();
1512 Some('=') if out.is_rw => {
1513 s.print_string(&format!("+{}", ch.as_str()),
1514 ast::StrStyle::Cooked)?
1516 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
1519 s.print_expr(&outputs[out_idx])?;
1525 self.word_space(":")?;
1528 self.commasep(Inconsistent, &a.inputs, |s, co| {
1529 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1531 s.print_expr(&inputs[in_idx])?;
1537 self.word_space(":")?;
1539 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1540 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1544 let mut options = vec![];
1546 options.push("volatile");
1549 options.push("alignstack");
1551 if a.dialect == ast::AsmDialect::Intel {
1552 options.push("intel");
1555 if !options.is_empty() {
1557 self.word_space(":")?;
1558 self.commasep(Inconsistent, &options, |s, &co| {
1559 s.print_string(co, ast::StrStyle::Cooked)?;
1566 hir::ExprYield(ref expr) => {
1567 self.word_space("yield")?;
1568 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1571 self.ann.post(self, NodeExpr(expr))?;
1575 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1576 self.print_pat(&loc.pat)?;
1577 if let Some(ref ty) = loc.ty {
1578 self.word_space(":")?;
1579 self.print_type(&ty)?;
1584 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1585 self.maybe_print_comment(decl.span.lo())?;
1587 hir::DeclLocal(ref loc) => {
1588 self.space_if_not_bol()?;
1589 self.ibox(indent_unit)?;
1590 self.word_nbsp("let")?;
1592 self.ibox(indent_unit)?;
1593 self.print_local_decl(&loc)?;
1595 if let Some(ref init) = loc.init {
1597 self.word_space("=")?;
1598 self.print_expr(&init)?;
1602 hir::DeclItem(item) => {
1603 self.ann.nested(self, Nested::Item(item))
1608 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1609 self.s.word(&i.to_string())
1612 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
1613 if ident.is_raw_guess() {
1614 self.s.word(&format!("r#{}", ident.name))?;
1616 self.s.word(&ident.as_str())?;
1618 self.ann.post(self, NodeName(&ident.name))
1621 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1622 self.print_ident(ast::Ident::with_empty_ctxt(name))
1625 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1626 self.print_local_decl(loc)?;
1628 self.word_space("in")?;
1629 self.print_expr(coll)
1632 pub fn print_path(&mut self,
1634 colons_before_params: bool)
1636 self.maybe_print_comment(path.span.lo())?;
1638 for (i, segment) in path.segments.iter().enumerate() {
1642 if segment.ident.name != keywords::CrateRoot.name() &&
1643 segment.ident.name != keywords::DollarCrate.name() {
1644 self.print_ident(segment.ident)?;
1645 segment.with_generic_args(|generic_args| {
1646 self.print_generic_args(generic_args, segment.infer_types,
1647 colons_before_params)
1655 pub fn print_qpath(&mut self,
1657 colons_before_params: bool)
1660 hir::QPath::Resolved(None, ref path) => {
1661 self.print_path(path, colons_before_params)
1663 hir::QPath::Resolved(Some(ref qself), ref path) => {
1665 self.print_type(qself)?;
1667 self.word_space("as")?;
1669 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1673 if segment.ident.name != keywords::CrateRoot.name() &&
1674 segment.ident.name != keywords::DollarCrate.name() {
1675 self.print_ident(segment.ident)?;
1676 segment.with_generic_args(|generic_args| {
1677 self.print_generic_args(generic_args,
1678 segment.infer_types,
1679 colons_before_params)
1686 let item_segment = path.segments.last().unwrap();
1687 self.print_ident(item_segment.ident)?;
1688 item_segment.with_generic_args(|generic_args| {
1689 self.print_generic_args(generic_args,
1690 item_segment.infer_types,
1691 colons_before_params)
1694 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1696 self.print_type(qself)?;
1699 self.print_ident(item_segment.ident)?;
1700 item_segment.with_generic_args(|generic_args| {
1701 self.print_generic_args(generic_args,
1702 item_segment.infer_types,
1703 colons_before_params)
1709 fn print_generic_args(&mut self,
1710 generic_args: &hir::GenericArgs,
1712 colons_before_params: bool)
1714 if generic_args.parenthesized {
1716 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty))?;
1719 self.space_if_not_bol()?;
1720 self.word_space("->")?;
1721 self.print_type(&generic_args.bindings[0].ty)?;
1723 let start = if colons_before_params { "::<" } else { "<" };
1724 let empty = Cell::new(true);
1725 let start_or_comma = |this: &mut Self| {
1730 this.word_space(",")
1734 let mut types = vec![];
1735 let mut elide_lifetimes = true;
1736 for arg in &generic_args.args {
1738 GenericArg::Lifetime(lt) => {
1739 if !lt.is_elided() {
1740 elide_lifetimes = false;
1743 GenericArg::Type(ty) => {
1748 if !elide_lifetimes {
1749 start_or_comma(self)?;
1750 self.commasep(Inconsistent, &generic_args.args, |s, generic_arg| {
1752 GenericArg::Lifetime(lt) => s.print_lifetime(lt),
1753 GenericArg::Type(ty) => s.print_type(ty),
1756 } else if !types.is_empty() {
1757 start_or_comma(self)?;
1758 self.commasep(Inconsistent, &types, |s, ty| s.print_type(&ty))?;
1761 // FIXME(eddyb) This would leak into error messages, e.g.:
1762 // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1763 if infer_types && false {
1764 start_or_comma(self)?;
1768 for binding in generic_args.bindings.iter() {
1769 start_or_comma(self)?;
1770 self.print_ident(binding.ident)?;
1772 self.word_space("=")?;
1773 self.print_type(&binding.ty)?;
1784 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1785 self.maybe_print_comment(pat.span.lo())?;
1786 self.ann.pre(self, NodePat(pat))?;
1787 // Pat isn't normalized, but the beauty of it
1788 // is that it doesn't matter
1790 PatKind::Wild => self.s.word("_")?,
1791 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1792 match binding_mode {
1793 hir::BindingAnnotation::Ref => {
1794 self.word_nbsp("ref")?;
1795 self.print_mutability(hir::MutImmutable)?;
1797 hir::BindingAnnotation::RefMut => {
1798 self.word_nbsp("ref")?;
1799 self.print_mutability(hir::MutMutable)?;
1801 hir::BindingAnnotation::Unannotated => {}
1802 hir::BindingAnnotation::Mutable => {
1803 self.word_nbsp("mut")?;
1806 self.print_ident(ident)?;
1807 if let Some(ref p) = *sub {
1809 self.print_pat(&p)?;
1812 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1813 self.print_qpath(qpath, true)?;
1815 if let Some(ddpos) = ddpos {
1816 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1818 self.word_space(",")?;
1821 if ddpos != elts.len() {
1823 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1826 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1830 PatKind::Path(ref qpath) => {
1831 self.print_qpath(qpath, true)?;
1833 PatKind::Struct(ref qpath, ref fields, etc) => {
1834 self.print_qpath(qpath, true)?;
1836 self.word_space("{")?;
1837 self.commasep_cmnt(Consistent,
1840 s.cbox(indent_unit)?;
1841 if !f.node.is_shorthand {
1842 s.print_ident(f.node.ident)?;
1845 s.print_pat(&f.node.pat)?;
1848 |f| f.node.pat.span)?;
1850 if !fields.is_empty() {
1851 self.word_space(",")?;
1858 PatKind::Tuple(ref elts, ddpos) => {
1860 if let Some(ddpos) = ddpos {
1861 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1863 self.word_space(",")?;
1866 if ddpos != elts.len() {
1868 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1871 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1872 if elts.len() == 1 {
1878 PatKind::Box(ref inner) => {
1879 let is_range_inner = match inner.node {
1880 PatKind::Range(..) => true,
1883 self.s.word("box ")?;
1887 self.print_pat(&inner)?;
1892 PatKind::Ref(ref inner, mutbl) => {
1893 let is_range_inner = match inner.node {
1894 PatKind::Range(..) => true,
1898 if mutbl == hir::MutMutable {
1899 self.s.word("mut ")?;
1904 self.print_pat(&inner)?;
1909 PatKind::Lit(ref e) => self.print_expr(&e)?,
1910 PatKind::Range(ref begin, ref end, ref end_kind) => {
1911 self.print_expr(&begin)?;
1914 RangeEnd::Included => self.s.word("...")?,
1915 RangeEnd::Excluded => self.s.word("..")?,
1917 self.print_expr(&end)?;
1919 PatKind::Slice(ref before, ref slice, ref after) => {
1921 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1922 if let Some(ref p) = *slice {
1923 if !before.is_empty() {
1924 self.word_space(",")?;
1926 if p.node != PatKind::Wild {
1927 self.print_pat(&p)?;
1930 if !after.is_empty() {
1931 self.word_space(",")?;
1934 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1938 self.ann.post(self, NodePat(pat))
1941 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1942 // I have no idea why this check is necessary, but here it
1944 if arm.attrs.is_empty() {
1947 self.cbox(indent_unit)?;
1949 self.print_outer_attributes(&arm.attrs)?;
1950 let mut first = true;
1951 for p in &arm.pats {
1956 self.word_space("|")?;
1958 self.print_pat(&p)?;
1961 if let Some(ref e) = arm.guard {
1962 self.word_space("if")?;
1963 self.print_expr(&e)?;
1966 self.word_space("=>")?;
1968 match arm.body.node {
1969 hir::ExprBlock(ref blk, opt_label) => {
1970 if let Some(label) = opt_label {
1971 self.print_ident(label.ident)?;
1972 self.word_space(":")?;
1974 // the block will close the pattern's ibox
1975 self.print_block_unclosed_indent(&blk, indent_unit)?;
1977 // If it is a user-provided unsafe block, print a comma after it
1978 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1983 self.end()?; // close the ibox for the pattern
1984 self.print_expr(&arm.body)?;
1988 self.end() // close enclosing cbox
1991 pub fn print_fn(&mut self,
1993 header: hir::FnHeader,
1994 name: Option<ast::Name>,
1995 generics: &hir::Generics,
1996 vis: &hir::Visibility,
1997 arg_names: &[ast::Ident],
1998 body_id: Option<hir::BodyId>)
2000 self.print_fn_header_info(header, vis)?;
2002 if let Some(name) = name {
2004 self.print_name(name)?;
2006 self.print_generic_params(&generics.params)?;
2010 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2011 assert!(arg_names.is_empty() || body_id.is_none());
2012 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2013 s.ibox(indent_unit)?;
2014 if let Some(arg_name) = arg_names.get(i) {
2015 s.s.word(&arg_name.as_str())?;
2018 } else if let Some(body_id) = body_id {
2019 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2028 self.s.word(", ...")?;
2032 self.print_fn_output(decl)?;
2033 self.print_where_clause(&generics.where_clause)
2036 fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
2039 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2040 s.ibox(indent_unit)?;
2042 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2045 if ty.node != hir::TyInfer {
2054 if let hir::DefaultReturn(..) = decl.output {
2058 self.space_if_not_bol()?;
2059 self.word_space("->")?;
2061 hir::Return(ref ty) => {
2062 self.print_type(&ty)?;
2063 self.maybe_print_comment(ty.span.lo())
2065 hir::DefaultReturn(..) => unreachable!(),
2069 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
2070 match capture_clause {
2071 hir::CaptureByValue => self.word_space("move"),
2072 hir::CaptureByRef => Ok(()),
2076 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::GenericBound]) -> io::Result<()> {
2077 if !bounds.is_empty() {
2078 self.s.word(prefix)?;
2079 let mut first = true;
2080 for bound in bounds {
2081 if !(first && prefix.is_empty()) {
2087 self.word_space("+")?;
2091 GenericBound::Trait(tref, modifier) => {
2092 if modifier == &TraitBoundModifier::Maybe {
2095 self.print_poly_trait_ref(tref)?;
2097 GenericBound::Outlives(lt) => {
2098 self.print_lifetime(lt)?;
2106 pub fn print_generic_params(&mut self, generic_params: &[GenericParam]) -> io::Result<()> {
2107 if !generic_params.is_empty() {
2110 self.commasep(Inconsistent, generic_params, |s, param| {
2111 s.print_generic_param(param)
2119 pub fn print_generic_param(&mut self, param: &GenericParam) -> io::Result<()> {
2120 self.print_ident(param.name.ident())?;
2122 GenericParamKind::Lifetime { .. } => {
2124 for bound in ¶m.bounds {
2126 GenericBound::Outlives(lt) => {
2128 self.print_lifetime(lt)?;
2136 GenericParamKind::Type { ref default, .. } => {
2137 self.print_bounds(":", ¶m.bounds)?;
2141 self.word_space("=")?;
2142 self.print_type(&default)
2150 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2151 self.print_ident(lifetime.name.ident())
2154 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2155 if where_clause.predicates.is_empty() {
2160 self.word_space("where")?;
2162 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2164 self.word_space(",")?;
2168 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2169 ref bound_generic_params,
2174 self.print_formal_generic_params(bound_generic_params)?;
2175 self.print_type(&bounded_ty)?;
2176 self.print_bounds(":", bounds)?;
2178 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2181 self.print_lifetime(lifetime)?;
2184 for (i, bound) in bounds.iter().enumerate() {
2186 GenericBound::Outlives(lt) => {
2187 self.print_lifetime(lt)?;
2197 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
2200 self.print_type(lhs_ty)?;
2202 self.word_space("=")?;
2203 self.print_type(rhs_ty)?;
2211 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2213 hir::MutMutable => self.word_nbsp("mut"),
2214 hir::MutImmutable => Ok(()),
2218 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2219 self.print_mutability(mt.mutbl)?;
2220 self.print_type(&mt.ty)
2223 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2224 if let hir::DefaultReturn(..) = decl.output {
2228 self.space_if_not_bol()?;
2229 self.ibox(indent_unit)?;
2230 self.word_space("->")?;
2232 hir::DefaultReturn(..) => unreachable!(),
2233 hir::Return(ref ty) => self.print_type(&ty)?,
2238 hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2243 pub fn print_ty_fn(&mut self,
2245 unsafety: hir::Unsafety,
2247 name: Option<ast::Name>,
2248 generic_params: &[hir::GenericParam],
2249 arg_names: &[ast::Ident])
2251 self.ibox(indent_unit)?;
2252 if !generic_params.is_empty() {
2253 self.s.word("for")?;
2254 self.print_generic_params(generic_params)?;
2256 let generics = hir::Generics {
2257 params: hir::HirVec::new(),
2258 where_clause: hir::WhereClause {
2259 id: ast::DUMMY_NODE_ID,
2260 predicates: hir::HirVec::new(),
2262 span: syntax_pos::DUMMY_SP,
2268 constness: hir::Constness::NotConst,
2269 asyncness: hir::IsAsync::NotAsync,
2273 &Spanned { span: syntax_pos::DUMMY_SP,
2274 node: hir::VisibilityKind::Inherited },
2280 pub fn maybe_print_trailing_comment(&mut self,
2281 span: syntax_pos::Span,
2282 next_pos: Option<BytePos>)
2284 let cm = match self.cm {
2288 if let Some(ref cmnt) = self.next_comment() {
2289 if (*cmnt).style != comments::Trailing {
2292 let span_line = cm.lookup_char_pos(span.hi());
2293 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2294 let mut next = (*cmnt).pos + BytePos(1);
2295 if let Some(p) = next_pos {
2298 if span.hi() < (*cmnt).pos && (*cmnt).pos < next &&
2299 span_line.line == comment_line.line {
2300 self.print_comment(cmnt)?;
2306 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2307 // If there aren't any remaining comments, then we need to manually
2308 // make sure there is a line break at the end.
2309 if self.next_comment().is_none() {
2310 self.s.hardbreak()?;
2312 while let Some(ref cmnt) = self.next_comment() {
2313 self.print_comment(cmnt)?
2318 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2319 opt_abi: Option<Abi>)
2322 Some(Abi::Rust) => Ok(()),
2324 self.word_nbsp("extern")?;
2325 self.word_nbsp(&abi.to_string())
2331 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2334 self.word_nbsp("extern")?;
2335 self.word_nbsp(&abi.to_string())
2341 pub fn print_fn_header_info(&mut self,
2342 header: hir::FnHeader,
2343 vis: &hir::Visibility)
2345 self.s.word(&visibility_qualified(vis, ""))?;
2347 match header.constness {
2348 hir::Constness::NotConst => {}
2349 hir::Constness::Const => self.word_nbsp("const")?,
2352 match header.asyncness {
2353 hir::IsAsync::NotAsync => {}
2354 hir::IsAsync::Async => self.word_nbsp("async")?,
2357 self.print_unsafety(header.unsafety)?;
2359 if header.abi != Abi::Rust {
2360 self.word_nbsp("extern")?;
2361 self.word_nbsp(&header.abi.to_string())?;
2367 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2369 hir::Unsafety::Normal => Ok(()),
2370 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2374 pub fn print_is_auto(&mut self, s: hir::IsAuto) -> io::Result<()> {
2376 hir::IsAuto::Yes => self.word_nbsp("auto"),
2377 hir::IsAuto::No => Ok(()),
2382 // Dup'ed from parse::classify, but adapted for the HIR.
2383 /// Does this expression require a semicolon to be treated
2384 /// as a statement? The negation of this: 'can this expression
2385 /// be used as a statement without a semicolon' -- is used
2386 /// as an early-bail-out in the parser so that, for instance,
2387 /// if true {...} else {...}
2389 /// isn't parsed as (if true {...} else {...} | x) | 5
2390 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2393 hir::ExprMatch(..) |
2394 hir::ExprBlock(..) |
2395 hir::ExprWhile(..) |
2396 hir::ExprLoop(..) => false,
2401 /// this statement requires a semicolon after it.
2402 /// note that in one case (stmt_semi), we've already
2403 /// seen the semicolon, and thus don't need another.
2404 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2406 hir::StmtDecl(ref d, _) => {
2408 hir::DeclLocal(_) => true,
2409 hir::DeclItem(_) => false,
2412 hir::StmtExpr(ref e, _) => {
2413 expr_requires_semi_to_be_stmt(&e)
2415 hir::StmtSemi(..) => {
2421 fn bin_op_to_assoc_op(op: hir::BinOp_) -> AssocOp {
2424 BiAdd => AssocOp::Add,
2425 BiSub => AssocOp::Subtract,
2426 BiMul => AssocOp::Multiply,
2427 BiDiv => AssocOp::Divide,
2428 BiRem => AssocOp::Modulus,
2430 BiAnd => AssocOp::LAnd,
2431 BiOr => AssocOp::LOr,
2433 BiBitXor => AssocOp::BitXor,
2434 BiBitAnd => AssocOp::BitAnd,
2435 BiBitOr => AssocOp::BitOr,
2436 BiShl => AssocOp::ShiftLeft,
2437 BiShr => AssocOp::ShiftRight,
2439 BiEq => AssocOp::Equal,
2440 BiLt => AssocOp::Less,
2441 BiLe => AssocOp::LessEqual,
2442 BiNe => AssocOp::NotEqual,
2443 BiGe => AssocOp::GreaterEqual,
2444 BiGt => AssocOp::Greater,
2448 /// Expressions that syntactically contain an "exterior" struct literal i.e. not surrounded by any
2449 /// parens or other delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2450 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2451 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
2453 hir::ExprStruct(..) => true,
2455 hir::ExprAssign(ref lhs, ref rhs) |
2456 hir::ExprAssignOp(_, ref lhs, ref rhs) |
2457 hir::ExprBinary(_, ref lhs, ref rhs) => {
2458 // X { y: 1 } + X { y: 2 }
2459 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2461 hir::ExprUnary(_, ref x) |
2462 hir::ExprCast(ref x, _) |
2463 hir::ExprType(ref x, _) |
2464 hir::ExprField(ref x, _) |
2465 hir::ExprIndex(ref x, _) => {
2466 // &X { y: 1 }, X { y: 1 }.y
2467 contains_exterior_struct_lit(&x)
2470 hir::ExprMethodCall(.., ref exprs) => {
2471 // X { y: 1 }.bar(...)
2472 contains_exterior_struct_lit(&exprs[0])