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::VisibilityPublic => self.word_nbsp("pub")?,
844 hir::VisibilityCrate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate")?,
845 hir::VisibilityCrate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)")?,
846 hir::VisibilityRestricted { 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::VisibilityInherited => ()
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, node: hir::VisibilityInherited };
956 self.print_associated_const(ti.ident, &ty, default, &vis)?;
958 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
959 let vis = Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityInherited };
960 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None)?;
963 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
964 let vis = Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityInherited };
966 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body))?;
968 self.end()?; // need to close a box
969 self.end()?; // need to close a box
970 self.ann.nested(self, Nested::Body(body))?;
972 hir::TraitItemKind::Type(ref bounds, ref default) => {
973 self.print_associated_type(ti.ident,
975 default.as_ref().map(|ty| &**ty))?;
978 self.ann.post(self, NodeSubItem(ti.id))
981 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
982 self.ann.pre(self, NodeSubItem(ii.id))?;
983 self.hardbreak_if_not_bol()?;
984 self.maybe_print_comment(ii.span.lo())?;
985 self.print_outer_attributes(&ii.attrs)?;
986 self.print_defaultness(ii.defaultness)?;
989 hir::ImplItemKind::Const(ref ty, expr) => {
990 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis)?;
992 hir::ImplItemKind::Method(ref sig, body) => {
994 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body))?;
996 self.end()?; // need to close a box
997 self.end()?; // need to close a box
998 self.ann.nested(self, Nested::Body(body))?;
1000 hir::ImplItemKind::Type(ref ty) => {
1001 self.print_associated_type(ii.ident, None, Some(ty))?;
1004 self.ann.post(self, NodeSubItem(ii.id))
1007 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1008 self.maybe_print_comment(st.span.lo())?;
1010 hir::StmtDecl(ref decl, _) => {
1011 self.print_decl(&decl)?;
1013 hir::StmtExpr(ref expr, _) => {
1014 self.space_if_not_bol()?;
1015 self.print_expr(&expr)?;
1017 hir::StmtSemi(ref expr, _) => {
1018 self.space_if_not_bol()?;
1019 self.print_expr(&expr)?;
1023 if stmt_ends_with_semi(&st.node) {
1026 self.maybe_print_trailing_comment(st.span, None)
1029 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1030 self.print_block_with_attrs(blk, &[])
1033 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1034 self.print_block_unclosed_indent(blk, indent_unit)
1037 pub fn print_block_unclosed_indent(&mut self,
1041 self.print_block_maybe_unclosed(blk, indented, &[], false)
1044 pub fn print_block_with_attrs(&mut self,
1046 attrs: &[ast::Attribute])
1048 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1051 pub fn print_block_maybe_unclosed(&mut self,
1054 attrs: &[ast::Attribute],
1058 hir::UnsafeBlock(..) => self.word_space("unsafe")?,
1059 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
1060 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
1061 hir::DefaultBlock => (),
1063 self.maybe_print_comment(blk.span.lo())?;
1064 self.ann.pre(self, NodeBlock(blk))?;
1067 self.print_inner_attributes(attrs)?;
1069 for st in &blk.stmts {
1070 self.print_stmt(st)?;
1074 self.space_if_not_bol()?;
1075 self.print_expr(&expr)?;
1076 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1080 self.bclose_maybe_open(blk.span, indented, close_box)?;
1081 self.ann.post(self, NodeBlock(blk))
1084 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1088 // "another else-if"
1089 hir::ExprIf(ref i, ref then, ref e) => {
1090 self.cbox(indent_unit - 1)?;
1092 self.s.word(" else if ")?;
1093 self.print_expr_as_cond(&i)?;
1095 self.print_expr(&then)?;
1096 self.print_else(e.as_ref().map(|e| &**e))
1099 hir::ExprBlock(ref b, _) => {
1100 self.cbox(indent_unit - 1)?;
1102 self.s.word(" else ")?;
1103 self.print_block(&b)
1105 // BLEAH, constraints would be great here
1107 panic!("print_if saw if with weird alternative");
1115 pub fn print_if(&mut self,
1118 elseopt: Option<&hir::Expr>)
1121 self.print_expr_as_cond(test)?;
1123 self.print_expr(blk)?;
1124 self.print_else(elseopt)
1127 pub fn print_if_let(&mut self,
1131 elseopt: Option<&hir::Expr>)
1133 self.head("if let")?;
1134 self.print_pat(pat)?;
1136 self.word_space("=")?;
1137 self.print_expr_as_cond(expr)?;
1139 self.print_block(blk)?;
1140 self.print_else(elseopt)
1143 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) -> io::Result<()> {
1144 self.ann.nested(self, Nested::Body(constant.body))
1147 fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
1149 self.commasep_exprs(Inconsistent, args)?;
1153 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr, prec: i8) -> io::Result<()> {
1154 let needs_par = expr.precedence().order() < prec;
1158 self.print_expr(expr)?;
1165 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1166 /// `if cond { ... }`.
1167 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr) -> io::Result<()> {
1168 let needs_par = match expr.node {
1169 // These cases need parens due to the parse error observed in #26461: `if return {}`
1170 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1171 hir::ExprClosure(..) |
1173 hir::ExprBreak(..) => true,
1175 _ => contains_exterior_struct_lit(expr),
1181 self.print_expr(expr)?;
1188 fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1189 self.ibox(indent_unit)?;
1191 self.commasep_exprs(Inconsistent, exprs)?;
1196 fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::AnonConst) -> io::Result<()> {
1197 self.ibox(indent_unit)?;
1199 self.print_expr(element)?;
1200 self.word_space(";")?;
1201 self.print_anon_const(count)?;
1206 fn print_expr_struct(&mut self,
1208 fields: &[hir::Field],
1209 wth: &Option<P<hir::Expr>>)
1211 self.print_qpath(qpath, true)?;
1213 self.commasep_cmnt(Consistent,
1216 s.ibox(indent_unit)?;
1217 if !field.is_shorthand {
1218 s.print_ident(field.ident)?;
1221 s.print_expr(&field.expr)?;
1227 self.ibox(indent_unit)?;
1228 if !fields.is_empty() {
1233 self.print_expr(&expr)?;
1236 _ => if !fields.is_empty() {
1244 fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1246 self.commasep_exprs(Inconsistent, exprs)?;
1247 if exprs.len() == 1 {
1253 fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1256 hir::ExprField(..) => parser::PREC_FORCE_PAREN,
1257 _ => parser::PREC_POSTFIX,
1260 self.print_expr_maybe_paren(func, prec)?;
1261 self.print_call_post(args)
1264 fn print_expr_method_call(&mut self,
1265 segment: &hir::PathSegment,
1268 let base_args = &args[1..];
1269 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
1271 self.print_ident(segment.ident)?;
1273 segment.with_generic_args(|generic_args| {
1274 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1275 return self.print_generic_args(&generic_args, segment.infer_types, true);
1279 self.print_call_post(base_args)
1282 fn print_expr_binary(&mut self,
1287 let assoc_op = bin_op_to_assoc_op(op.node);
1288 let prec = assoc_op.precedence() as i8;
1289 let fixity = assoc_op.fixity();
1291 let (left_prec, right_prec) = match fixity {
1292 Fixity::Left => (prec, prec + 1),
1293 Fixity::Right => (prec + 1, prec),
1294 Fixity::None => (prec + 1, prec + 1),
1297 let left_prec = match (&lhs.node, op.node) {
1298 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1299 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1300 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1301 (&hir::ExprCast { .. }, hir::BinOp_::BiLt) |
1302 (&hir::ExprCast { .. }, hir::BinOp_::BiShl) => parser::PREC_FORCE_PAREN,
1306 self.print_expr_maybe_paren(lhs, left_prec)?;
1308 self.word_space(op.node.as_str())?;
1309 self.print_expr_maybe_paren(rhs, right_prec)
1312 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1313 self.s.word(op.as_str())?;
1314 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1317 fn print_expr_addr_of(&mut self,
1318 mutability: hir::Mutability,
1322 self.print_mutability(mutability)?;
1323 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1326 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1327 self.maybe_print_comment(expr.span.lo())?;
1328 self.print_outer_attributes(&expr.attrs)?;
1329 self.ibox(indent_unit)?;
1330 self.ann.pre(self, NodeExpr(expr))?;
1332 hir::ExprBox(ref expr) => {
1333 self.word_space("box")?;
1334 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
1336 hir::ExprArray(ref exprs) => {
1337 self.print_expr_vec(exprs)?;
1339 hir::ExprRepeat(ref element, ref count) => {
1340 self.print_expr_repeat(&element, count)?;
1342 hir::ExprStruct(ref qpath, ref fields, ref wth) => {
1343 self.print_expr_struct(qpath, &fields[..], wth)?;
1345 hir::ExprTup(ref exprs) => {
1346 self.print_expr_tup(exprs)?;
1348 hir::ExprCall(ref func, ref args) => {
1349 self.print_expr_call(&func, args)?;
1351 hir::ExprMethodCall(ref segment, _, ref args) => {
1352 self.print_expr_method_call(segment, args)?;
1354 hir::ExprBinary(op, ref lhs, ref rhs) => {
1355 self.print_expr_binary(op, &lhs, &rhs)?;
1357 hir::ExprUnary(op, ref expr) => {
1358 self.print_expr_unary(op, &expr)?;
1360 hir::ExprAddrOf(m, ref expr) => {
1361 self.print_expr_addr_of(m, &expr)?;
1363 hir::ExprLit(ref lit) => {
1364 self.print_literal(&lit)?;
1366 hir::ExprCast(ref expr, ref ty) => {
1367 let prec = AssocOp::As.precedence() as i8;
1368 self.print_expr_maybe_paren(&expr, prec)?;
1370 self.word_space("as")?;
1371 self.print_type(&ty)?;
1373 hir::ExprType(ref expr, ref ty) => {
1374 let prec = AssocOp::Colon.precedence() as i8;
1375 self.print_expr_maybe_paren(&expr, prec)?;
1376 self.word_space(":")?;
1377 self.print_type(&ty)?;
1379 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1380 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1382 hir::ExprWhile(ref test, ref blk, opt_label) => {
1383 if let Some(label) = opt_label {
1384 self.print_ident(label.ident)?;
1385 self.word_space(":")?;
1387 self.head("while")?;
1388 self.print_expr_as_cond(&test)?;
1390 self.print_block(&blk)?;
1392 hir::ExprLoop(ref blk, opt_label, _) => {
1393 if let Some(label) = opt_label {
1394 self.print_ident(label.ident)?;
1395 self.word_space(":")?;
1399 self.print_block(&blk)?;
1401 hir::ExprMatch(ref expr, ref arms, _) => {
1402 self.cbox(indent_unit)?;
1404 self.word_nbsp("match")?;
1405 self.print_expr_as_cond(&expr)?;
1409 self.print_arm(arm)?;
1411 self.bclose_(expr.span, indent_unit)?;
1413 hir::ExprClosure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1414 self.print_capture_clause(capture_clause)?;
1416 self.print_closure_args(&decl, body)?;
1419 // this is a bare expression
1420 self.ann.nested(self, Nested::Body(body))?;
1421 self.end()?; // need to close a box
1423 // a box will be closed by print_expr, but we didn't want an overall
1424 // wrapper so we closed the corresponding opening. so create an
1425 // empty box to satisfy the close.
1428 hir::ExprBlock(ref blk, opt_label) => {
1429 if let Some(label) = opt_label {
1430 self.print_ident(label.ident)?;
1431 self.word_space(":")?;
1433 // containing cbox, will be closed by print-block at }
1434 self.cbox(indent_unit)?;
1435 // head-box, will be closed by print-block after {
1437 self.print_block(&blk)?;
1439 hir::ExprAssign(ref lhs, ref rhs) => {
1440 let prec = AssocOp::Assign.precedence() as i8;
1441 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1443 self.word_space("=")?;
1444 self.print_expr_maybe_paren(&rhs, prec)?;
1446 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1447 let prec = AssocOp::Assign.precedence() as i8;
1448 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1450 self.s.word(op.node.as_str())?;
1451 self.word_space("=")?;
1452 self.print_expr_maybe_paren(&rhs, prec)?;
1454 hir::ExprField(ref expr, ident) => {
1455 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
1457 self.print_ident(ident)?;
1459 hir::ExprIndex(ref expr, ref index) => {
1460 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1462 self.print_expr(&index)?;
1465 hir::ExprPath(ref qpath) => {
1466 self.print_qpath(qpath, true)?
1468 hir::ExprBreak(destination, ref opt_expr) => {
1469 self.s.word("break")?;
1471 if let Some(label) = destination.label {
1472 self.print_ident(label.ident)?;
1475 if let Some(ref expr) = *opt_expr {
1476 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
1480 hir::ExprContinue(destination) => {
1481 self.s.word("continue")?;
1483 if let Some(label) = destination.label {
1484 self.print_ident(label.ident)?;
1488 hir::ExprRet(ref result) => {
1489 self.s.word("return")?;
1493 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1498 hir::ExprInlineAsm(ref a, ref outputs, ref inputs) => {
1499 self.s.word("asm!")?;
1501 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
1502 self.word_space(":")?;
1504 let mut out_idx = 0;
1505 self.commasep(Inconsistent, &a.outputs, |s, out| {
1506 let constraint = out.constraint.as_str();
1507 let mut ch = constraint.chars();
1509 Some('=') if out.is_rw => {
1510 s.print_string(&format!("+{}", ch.as_str()),
1511 ast::StrStyle::Cooked)?
1513 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
1516 s.print_expr(&outputs[out_idx])?;
1522 self.word_space(":")?;
1525 self.commasep(Inconsistent, &a.inputs, |s, co| {
1526 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1528 s.print_expr(&inputs[in_idx])?;
1534 self.word_space(":")?;
1536 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1537 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1541 let mut options = vec![];
1543 options.push("volatile");
1546 options.push("alignstack");
1548 if a.dialect == ast::AsmDialect::Intel {
1549 options.push("intel");
1552 if !options.is_empty() {
1554 self.word_space(":")?;
1555 self.commasep(Inconsistent, &options, |s, &co| {
1556 s.print_string(co, ast::StrStyle::Cooked)?;
1563 hir::ExprYield(ref expr) => {
1564 self.word_space("yield")?;
1565 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1568 self.ann.post(self, NodeExpr(expr))?;
1572 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1573 self.print_pat(&loc.pat)?;
1574 if let Some(ref ty) = loc.ty {
1575 self.word_space(":")?;
1576 self.print_type(&ty)?;
1581 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1582 self.maybe_print_comment(decl.span.lo())?;
1584 hir::DeclLocal(ref loc) => {
1585 self.space_if_not_bol()?;
1586 self.ibox(indent_unit)?;
1587 self.word_nbsp("let")?;
1589 self.ibox(indent_unit)?;
1590 self.print_local_decl(&loc)?;
1592 if let Some(ref init) = loc.init {
1594 self.word_space("=")?;
1595 self.print_expr(&init)?;
1599 hir::DeclItem(item) => {
1600 self.ann.nested(self, Nested::Item(item))
1605 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1606 self.s.word(&i.to_string())
1609 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
1610 if ident.is_raw_guess() {
1611 self.s.word(&format!("r#{}", ident.name))?;
1613 self.s.word(&ident.as_str())?;
1615 self.ann.post(self, NodeName(&ident.name))
1618 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1619 self.print_ident(ast::Ident::with_empty_ctxt(name))
1622 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1623 self.print_local_decl(loc)?;
1625 self.word_space("in")?;
1626 self.print_expr(coll)
1629 pub fn print_path(&mut self,
1631 colons_before_params: bool)
1633 self.maybe_print_comment(path.span.lo())?;
1635 for (i, segment) in path.segments.iter().enumerate() {
1639 if segment.ident.name != keywords::CrateRoot.name() &&
1640 segment.ident.name != keywords::DollarCrate.name() {
1641 self.print_ident(segment.ident)?;
1642 segment.with_generic_args(|generic_args| {
1643 self.print_generic_args(generic_args, segment.infer_types,
1644 colons_before_params)
1652 pub fn print_qpath(&mut self,
1654 colons_before_params: bool)
1657 hir::QPath::Resolved(None, ref path) => {
1658 self.print_path(path, colons_before_params)
1660 hir::QPath::Resolved(Some(ref qself), ref path) => {
1662 self.print_type(qself)?;
1664 self.word_space("as")?;
1666 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1670 if segment.ident.name != keywords::CrateRoot.name() &&
1671 segment.ident.name != keywords::DollarCrate.name() {
1672 self.print_ident(segment.ident)?;
1673 segment.with_generic_args(|generic_args| {
1674 self.print_generic_args(generic_args,
1675 segment.infer_types,
1676 colons_before_params)
1683 let item_segment = path.segments.last().unwrap();
1684 self.print_ident(item_segment.ident)?;
1685 item_segment.with_generic_args(|generic_args| {
1686 self.print_generic_args(generic_args,
1687 item_segment.infer_types,
1688 colons_before_params)
1691 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1693 self.print_type(qself)?;
1696 self.print_ident(item_segment.ident)?;
1697 item_segment.with_generic_args(|generic_args| {
1698 self.print_generic_args(generic_args,
1699 item_segment.infer_types,
1700 colons_before_params)
1706 fn print_generic_args(&mut self,
1707 generic_args: &hir::GenericArgs,
1709 colons_before_params: bool)
1711 if generic_args.parenthesized {
1713 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty))?;
1716 self.space_if_not_bol()?;
1717 self.word_space("->")?;
1718 self.print_type(&generic_args.bindings[0].ty)?;
1720 let start = if colons_before_params { "::<" } else { "<" };
1721 let empty = Cell::new(true);
1722 let start_or_comma = |this: &mut Self| {
1727 this.word_space(",")
1731 let mut types = vec![];
1732 let mut elide_lifetimes = true;
1733 for arg in &generic_args.args {
1735 GenericArg::Lifetime(lt) => {
1736 if !lt.is_elided() {
1737 elide_lifetimes = false;
1740 GenericArg::Type(ty) => {
1745 if !elide_lifetimes {
1746 start_or_comma(self)?;
1747 self.commasep(Inconsistent, &generic_args.args, |s, generic_arg| {
1749 GenericArg::Lifetime(lt) => s.print_lifetime(lt),
1750 GenericArg::Type(ty) => s.print_type(ty),
1753 } else if !types.is_empty() {
1754 start_or_comma(self)?;
1755 self.commasep(Inconsistent, &types, |s, ty| s.print_type(&ty))?;
1758 // FIXME(eddyb) This would leak into error messages, e.g.:
1759 // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1760 if infer_types && false {
1761 start_or_comma(self)?;
1765 for binding in generic_args.bindings.iter() {
1766 start_or_comma(self)?;
1767 self.print_ident(binding.ident)?;
1769 self.word_space("=")?;
1770 self.print_type(&binding.ty)?;
1781 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1782 self.maybe_print_comment(pat.span.lo())?;
1783 self.ann.pre(self, NodePat(pat))?;
1784 // Pat isn't normalized, but the beauty of it
1785 // is that it doesn't matter
1787 PatKind::Wild => self.s.word("_")?,
1788 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1789 match binding_mode {
1790 hir::BindingAnnotation::Ref => {
1791 self.word_nbsp("ref")?;
1792 self.print_mutability(hir::MutImmutable)?;
1794 hir::BindingAnnotation::RefMut => {
1795 self.word_nbsp("ref")?;
1796 self.print_mutability(hir::MutMutable)?;
1798 hir::BindingAnnotation::Unannotated => {}
1799 hir::BindingAnnotation::Mutable => {
1800 self.word_nbsp("mut")?;
1803 self.print_ident(ident)?;
1804 if let Some(ref p) = *sub {
1806 self.print_pat(&p)?;
1809 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1810 self.print_qpath(qpath, true)?;
1812 if let Some(ddpos) = ddpos {
1813 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1815 self.word_space(",")?;
1818 if ddpos != elts.len() {
1820 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1823 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1827 PatKind::Path(ref qpath) => {
1828 self.print_qpath(qpath, true)?;
1830 PatKind::Struct(ref qpath, ref fields, etc) => {
1831 self.print_qpath(qpath, true)?;
1833 self.word_space("{")?;
1834 self.commasep_cmnt(Consistent,
1837 s.cbox(indent_unit)?;
1838 if !f.node.is_shorthand {
1839 s.print_ident(f.node.ident)?;
1842 s.print_pat(&f.node.pat)?;
1845 |f| f.node.pat.span)?;
1847 if !fields.is_empty() {
1848 self.word_space(",")?;
1855 PatKind::Tuple(ref elts, ddpos) => {
1857 if let Some(ddpos) = ddpos {
1858 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1860 self.word_space(",")?;
1863 if ddpos != elts.len() {
1865 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1868 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1869 if elts.len() == 1 {
1875 PatKind::Box(ref inner) => {
1876 let is_range_inner = match inner.node {
1877 PatKind::Range(..) => true,
1880 self.s.word("box ")?;
1884 self.print_pat(&inner)?;
1889 PatKind::Ref(ref inner, mutbl) => {
1890 let is_range_inner = match inner.node {
1891 PatKind::Range(..) => true,
1895 if mutbl == hir::MutMutable {
1896 self.s.word("mut ")?;
1901 self.print_pat(&inner)?;
1906 PatKind::Lit(ref e) => self.print_expr(&e)?,
1907 PatKind::Range(ref begin, ref end, ref end_kind) => {
1908 self.print_expr(&begin)?;
1911 RangeEnd::Included => self.s.word("...")?,
1912 RangeEnd::Excluded => self.s.word("..")?,
1914 self.print_expr(&end)?;
1916 PatKind::Slice(ref before, ref slice, ref after) => {
1918 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1919 if let Some(ref p) = *slice {
1920 if !before.is_empty() {
1921 self.word_space(",")?;
1923 if p.node != PatKind::Wild {
1924 self.print_pat(&p)?;
1927 if !after.is_empty() {
1928 self.word_space(",")?;
1931 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1935 self.ann.post(self, NodePat(pat))
1938 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1939 // I have no idea why this check is necessary, but here it
1941 if arm.attrs.is_empty() {
1944 self.cbox(indent_unit)?;
1946 self.print_outer_attributes(&arm.attrs)?;
1947 let mut first = true;
1948 for p in &arm.pats {
1953 self.word_space("|")?;
1955 self.print_pat(&p)?;
1958 if let Some(ref e) = arm.guard {
1959 self.word_space("if")?;
1960 self.print_expr(&e)?;
1963 self.word_space("=>")?;
1965 match arm.body.node {
1966 hir::ExprBlock(ref blk, opt_label) => {
1967 if let Some(label) = opt_label {
1968 self.print_ident(label.ident)?;
1969 self.word_space(":")?;
1971 // the block will close the pattern's ibox
1972 self.print_block_unclosed_indent(&blk, indent_unit)?;
1974 // If it is a user-provided unsafe block, print a comma after it
1975 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1980 self.end()?; // close the ibox for the pattern
1981 self.print_expr(&arm.body)?;
1985 self.end() // close enclosing cbox
1988 pub fn print_fn(&mut self,
1990 header: hir::FnHeader,
1991 name: Option<ast::Name>,
1992 generics: &hir::Generics,
1993 vis: &hir::Visibility,
1994 arg_names: &[ast::Ident],
1995 body_id: Option<hir::BodyId>)
1997 self.print_fn_header_info(header, vis)?;
1999 if let Some(name) = name {
2001 self.print_name(name)?;
2003 self.print_generic_params(&generics.params)?;
2007 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2008 assert!(arg_names.is_empty() || body_id.is_none());
2009 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2010 s.ibox(indent_unit)?;
2011 if let Some(arg_name) = arg_names.get(i) {
2012 s.s.word(&arg_name.as_str())?;
2015 } else if let Some(body_id) = body_id {
2016 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2025 self.s.word(", ...")?;
2029 self.print_fn_output(decl)?;
2030 self.print_where_clause(&generics.where_clause)
2033 fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
2036 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2037 s.ibox(indent_unit)?;
2039 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2042 if ty.node != hir::TyInfer {
2051 if let hir::DefaultReturn(..) = decl.output {
2055 self.space_if_not_bol()?;
2056 self.word_space("->")?;
2058 hir::Return(ref ty) => {
2059 self.print_type(&ty)?;
2060 self.maybe_print_comment(ty.span.lo())
2062 hir::DefaultReturn(..) => unreachable!(),
2066 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
2067 match capture_clause {
2068 hir::CaptureByValue => self.word_space("move"),
2069 hir::CaptureByRef => Ok(()),
2073 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::GenericBound]) -> io::Result<()> {
2074 if !bounds.is_empty() {
2075 self.s.word(prefix)?;
2076 let mut first = true;
2077 for bound in bounds {
2078 if !(first && prefix.is_empty()) {
2084 self.word_space("+")?;
2088 GenericBound::Trait(tref, modifier) => {
2089 if modifier == &TraitBoundModifier::Maybe {
2092 self.print_poly_trait_ref(tref)?;
2094 GenericBound::Outlives(lt) => {
2095 self.print_lifetime(lt)?;
2103 pub fn print_generic_params(&mut self, generic_params: &[GenericParam]) -> io::Result<()> {
2104 if !generic_params.is_empty() {
2107 self.commasep(Inconsistent, generic_params, |s, param| {
2108 s.print_generic_param(param)
2116 pub fn print_generic_param(&mut self, param: &GenericParam) -> io::Result<()> {
2117 self.print_ident(param.name.ident())?;
2119 GenericParamKind::Lifetime { .. } => {
2121 for bound in ¶m.bounds {
2123 GenericBound::Outlives(lt) => {
2125 self.print_lifetime(lt)?;
2133 GenericParamKind::Type { ref default, .. } => {
2134 self.print_bounds(":", ¶m.bounds)?;
2138 self.word_space("=")?;
2139 self.print_type(&default)
2147 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2148 self.print_ident(lifetime.name.ident())
2151 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2152 if where_clause.predicates.is_empty() {
2157 self.word_space("where")?;
2159 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2161 self.word_space(",")?;
2165 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2166 ref bound_generic_params,
2171 self.print_formal_generic_params(bound_generic_params)?;
2172 self.print_type(&bounded_ty)?;
2173 self.print_bounds(":", bounds)?;
2175 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2178 self.print_lifetime(lifetime)?;
2181 for (i, bound) in bounds.iter().enumerate() {
2183 GenericBound::Outlives(lt) => {
2184 self.print_lifetime(lt)?;
2194 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
2197 self.print_type(lhs_ty)?;
2199 self.word_space("=")?;
2200 self.print_type(rhs_ty)?;
2208 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2210 hir::MutMutable => self.word_nbsp("mut"),
2211 hir::MutImmutable => Ok(()),
2215 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2216 self.print_mutability(mt.mutbl)?;
2217 self.print_type(&mt.ty)
2220 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2221 if let hir::DefaultReturn(..) = decl.output {
2225 self.space_if_not_bol()?;
2226 self.ibox(indent_unit)?;
2227 self.word_space("->")?;
2229 hir::DefaultReturn(..) => unreachable!(),
2230 hir::Return(ref ty) => self.print_type(&ty)?,
2235 hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2240 pub fn print_ty_fn(&mut self,
2242 unsafety: hir::Unsafety,
2244 name: Option<ast::Name>,
2245 generic_params: &[hir::GenericParam],
2246 arg_names: &[ast::Ident])
2248 self.ibox(indent_unit)?;
2249 if !generic_params.is_empty() {
2250 self.s.word("for")?;
2251 self.print_generic_params(generic_params)?;
2253 let generics = hir::Generics {
2254 params: hir::HirVec::new(),
2255 where_clause: hir::WhereClause {
2256 id: ast::DUMMY_NODE_ID,
2257 predicates: hir::HirVec::new(),
2259 span: syntax_pos::DUMMY_SP,
2265 constness: hir::Constness::NotConst,
2266 asyncness: hir::IsAsync::NotAsync,
2270 &Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityInherited },
2276 pub fn maybe_print_trailing_comment(&mut self,
2277 span: syntax_pos::Span,
2278 next_pos: Option<BytePos>)
2280 let cm = match self.cm {
2284 if let Some(ref cmnt) = self.next_comment() {
2285 if (*cmnt).style != comments::Trailing {
2288 let span_line = cm.lookup_char_pos(span.hi());
2289 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2290 let mut next = (*cmnt).pos + BytePos(1);
2291 if let Some(p) = next_pos {
2294 if span.hi() < (*cmnt).pos && (*cmnt).pos < next &&
2295 span_line.line == comment_line.line {
2296 self.print_comment(cmnt)?;
2302 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2303 // If there aren't any remaining comments, then we need to manually
2304 // make sure there is a line break at the end.
2305 if self.next_comment().is_none() {
2306 self.s.hardbreak()?;
2308 while let Some(ref cmnt) = self.next_comment() {
2309 self.print_comment(cmnt)?
2314 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2315 opt_abi: Option<Abi>)
2318 Some(Abi::Rust) => Ok(()),
2320 self.word_nbsp("extern")?;
2321 self.word_nbsp(&abi.to_string())
2327 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2330 self.word_nbsp("extern")?;
2331 self.word_nbsp(&abi.to_string())
2337 pub fn print_fn_header_info(&mut self,
2338 header: hir::FnHeader,
2339 vis: &hir::Visibility)
2341 self.s.word(&visibility_qualified(vis, ""))?;
2343 match header.constness {
2344 hir::Constness::NotConst => {}
2345 hir::Constness::Const => self.word_nbsp("const")?,
2348 match header.asyncness {
2349 hir::IsAsync::NotAsync => {}
2350 hir::IsAsync::Async => self.word_nbsp("async")?,
2353 self.print_unsafety(header.unsafety)?;
2355 if header.abi != Abi::Rust {
2356 self.word_nbsp("extern")?;
2357 self.word_nbsp(&header.abi.to_string())?;
2363 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2365 hir::Unsafety::Normal => Ok(()),
2366 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2370 pub fn print_is_auto(&mut self, s: hir::IsAuto) -> io::Result<()> {
2372 hir::IsAuto::Yes => self.word_nbsp("auto"),
2373 hir::IsAuto::No => Ok(()),
2378 // Dup'ed from parse::classify, but adapted for the HIR.
2379 /// Does this expression require a semicolon to be treated
2380 /// as a statement? The negation of this: 'can this expression
2381 /// be used as a statement without a semicolon' -- is used
2382 /// as an early-bail-out in the parser so that, for instance,
2383 /// if true {...} else {...}
2385 /// isn't parsed as (if true {...} else {...} | x) | 5
2386 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2389 hir::ExprMatch(..) |
2390 hir::ExprBlock(..) |
2391 hir::ExprWhile(..) |
2392 hir::ExprLoop(..) => false,
2397 /// this statement requires a semicolon after it.
2398 /// note that in one case (stmt_semi), we've already
2399 /// seen the semicolon, and thus don't need another.
2400 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2402 hir::StmtDecl(ref d, _) => {
2404 hir::DeclLocal(_) => true,
2405 hir::DeclItem(_) => false,
2408 hir::StmtExpr(ref e, _) => {
2409 expr_requires_semi_to_be_stmt(&e)
2411 hir::StmtSemi(..) => {
2417 fn bin_op_to_assoc_op(op: hir::BinOp_) -> AssocOp {
2420 BiAdd => AssocOp::Add,
2421 BiSub => AssocOp::Subtract,
2422 BiMul => AssocOp::Multiply,
2423 BiDiv => AssocOp::Divide,
2424 BiRem => AssocOp::Modulus,
2426 BiAnd => AssocOp::LAnd,
2427 BiOr => AssocOp::LOr,
2429 BiBitXor => AssocOp::BitXor,
2430 BiBitAnd => AssocOp::BitAnd,
2431 BiBitOr => AssocOp::BitOr,
2432 BiShl => AssocOp::ShiftLeft,
2433 BiShr => AssocOp::ShiftRight,
2435 BiEq => AssocOp::Equal,
2436 BiLt => AssocOp::Less,
2437 BiLe => AssocOp::LessEqual,
2438 BiNe => AssocOp::NotEqual,
2439 BiGe => AssocOp::GreaterEqual,
2440 BiGt => AssocOp::Greater,
2444 /// Expressions that syntactically contain an "exterior" struct literal i.e. not surrounded by any
2445 /// parens or other delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2446 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2447 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
2449 hir::ExprStruct(..) => true,
2451 hir::ExprAssign(ref lhs, ref rhs) |
2452 hir::ExprAssignOp(_, ref lhs, ref rhs) |
2453 hir::ExprBinary(_, ref lhs, ref rhs) => {
2454 // X { y: 1 } + X { y: 2 }
2455 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2457 hir::ExprUnary(_, ref x) |
2458 hir::ExprCast(ref x, _) |
2459 hir::ExprType(ref x, _) |
2460 hir::ExprField(ref x, _) |
2461 hir::ExprIndex(ref x, _) => {
2462 // &X { y: 1 }, X { y: 1 }.y
2463 contains_exterior_struct_lit(&x)
2466 hir::ExprMethodCall(.., ref exprs) => {
2467 // X { y: 1 }.bar(...)
2468 contains_exterior_struct_lit(&exprs[0])