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 use rustc_target::spec::abi::Abi;
13 use syntax::source_map::{SourceMap, Spanned};
14 use syntax::parse::ParseSess;
15 use syntax::parse::lexer::comments;
16 use syntax::print::pp::{self, Breaks};
17 use syntax::print::pp::Breaks::{Consistent, Inconsistent};
18 use syntax::print::pprust::PrintState;
20 use syntax::symbol::keywords;
21 use syntax::util::parser::{self, AssocOp, Fixity};
22 use syntax_pos::{self, BytePos, FileName};
25 use hir::{PatKind, GenericBound, TraitBoundModifier, RangeEnd};
26 use hir::{GenericParam, GenericParamKind, GenericArg};
29 use std::io::{self, Write, Read};
30 use std::iter::Peekable;
33 pub enum AnnNode<'a> {
35 Block(&'a hir::Block),
44 TraitItem(hir::TraitItemId),
45 ImplItem(hir::ImplItemId),
47 BodyArgPat(hir::BodyId, usize)
51 fn nested(&self, _state: &mut State<'_>, _nested: Nested) -> io::Result<()> {
54 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) -> io::Result<()> {
57 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) -> io::Result<()> {
60 fn try_fetch_item(&self, _: ast::NodeId) -> Option<&hir::Item> {
66 impl PpAnn for NoAnn {}
67 pub const NO_ANN: &'static dyn PpAnn = &NoAnn;
69 impl PpAnn for hir::Crate {
70 fn try_fetch_item(&self, item: ast::NodeId) -> Option<&hir::Item> {
73 fn nested(&self, state: &mut State<'_>, nested: Nested) -> io::Result<()> {
75 Nested::Item(id) => state.print_item(self.item(id.id)),
76 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
77 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
78 Nested::Body(id) => state.print_expr(&self.body(id).value),
79 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
84 pub struct State<'a> {
85 pub s: pp::Printer<'a>,
86 cm: Option<&'a SourceMap>,
87 comments: Option<Vec<comments::Comment>>,
88 literals: Peekable<vec::IntoIter<comments::Literal>>,
90 boxes: Vec<pp::Breaks>,
91 ann: &'a (dyn PpAnn + 'a),
94 impl<'a> PrintState<'a> for State<'a> {
95 fn writer(&mut self) -> &mut pp::Printer<'a> {
99 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
103 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
107 fn cur_cmnt(&mut self) -> &mut usize {
111 fn cur_lit(&mut self) -> Option<&comments::Literal> {
115 fn bump_lit(&mut self) -> Option<comments::Literal> {
120 #[allow(non_upper_case_globals)]
121 pub const indent_unit: usize = 4;
123 #[allow(non_upper_case_globals)]
124 pub const default_columns: usize = 78;
127 /// Requires you to pass an input filename and reader so that
128 /// it can scan the input text for comments and literals to
130 pub fn print_crate<'a>(cm: &'a SourceMap,
134 input: &mut dyn Read,
135 out: Box<dyn Write + 'a>,
139 let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
141 // When printing the AST, we sometimes need to inject `#[no_std]` here.
142 // Since you can't compile the HIR, it's not necessary.
144 s.print_mod(&krate.module, &krate.attrs)?;
145 s.print_remaining_comments()?;
150 pub fn new_from_input(cm: &'a SourceMap,
153 input: &mut dyn Read,
154 out: Box<dyn Write + 'a>,
158 let (cmnts, lits) = comments::gather_comments_and_literals(sess, filename, input);
164 // If the code is post expansion, don't use the table of
165 // literals, since it doesn't correspond with the literals
166 // in the AST anymore.
174 pub fn new(cm: &'a SourceMap,
175 out: Box<dyn Write + 'a>,
177 comments: Option<Vec<comments::Comment>>,
178 literals: Option<Vec<comments::Literal>>)
181 s: pp::mk_printer(out, default_columns),
183 comments: comments.clone(),
184 literals: literals.unwrap_or_default().into_iter().peekable(),
192 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
193 where F: FnOnce(&mut State<'_>) -> io::Result<()>
195 let mut wr = Vec::new();
197 let mut printer = State {
198 s: pp::mk_printer(Box::new(&mut wr), default_columns),
201 literals: vec![].into_iter().peekable(),
206 f(&mut printer).unwrap();
207 printer.s.eof().unwrap();
209 String::from_utf8(wr).unwrap()
212 pub fn visibility_qualified(vis: &hir::Visibility, w: &str) -> String {
213 to_string(NO_ANN, |s| {
214 s.print_visibility(vis)?;
220 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
221 self.boxes.push(pp::Breaks::Consistent);
225 pub fn nbsp(&mut self) -> io::Result<()> {
229 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
234 pub fn head(&mut self, w: &str) -> io::Result<()> {
235 // outer-box is consistent
236 self.cbox(indent_unit)?;
237 // head-box is inconsistent
238 self.ibox(w.len() + 1)?;
239 // keyword that starts the head
246 pub fn bopen(&mut self) -> io::Result<()> {
248 self.end() // close the head-box
251 pub fn bclose_(&mut self, span: syntax_pos::Span, indented: usize) -> io::Result<()> {
252 self.bclose_maybe_open(span, indented, true)
255 pub fn bclose_maybe_open(&mut self,
256 span: syntax_pos::Span,
260 self.maybe_print_comment(span.hi())?;
261 self.break_offset_if_not_bol(1, -(indented as isize))?;
264 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,
280 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
287 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
289 self.s.break_offset(n, off)
291 if off != 0 && self.s.last_token().is_hardbreak_tok() {
292 // We do something pretty sketchy here: tuck the nonzero
293 // offset-adjustment we were going to deposit along with the
294 // break into the previous hardbreak.
295 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
301 // Synthesizes a comment that was not textually present in the original source
303 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
306 self.s.word(&text[..])?;
311 pub fn commasep_cmnt<T, F, G>(&mut self,
317 where F: FnMut(&mut State<'_>, &T) -> io::Result<()>,
318 G: FnMut(&T) -> syntax_pos::Span
321 let len = elts.len();
324 self.maybe_print_comment(get_span(elt).hi())?;
329 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()))?;
330 self.space_if_not_bol()?;
336 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr]) -> io::Result<()> {
337 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
340 pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
341 self.print_inner_attributes(attrs)?;
342 for &item_id in &_mod.item_ids {
343 self.ann.nested(self, Nested::Item(item_id))?;
348 pub fn print_foreign_mod(&mut self,
349 nmod: &hir::ForeignMod,
350 attrs: &[ast::Attribute])
352 self.print_inner_attributes(attrs)?;
353 for item in &nmod.items {
354 self.print_foreign_item(item)?;
359 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
360 if !lifetime.is_elided() {
361 self.print_lifetime(lifetime)?;
367 pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
368 self.maybe_print_comment(ty.span.lo())?;
371 hir::TyKind::Slice(ref ty) => {
373 self.print_type(&ty)?;
376 hir::TyKind::Ptr(ref mt) => {
379 hir::MutMutable => self.word_nbsp("mut")?,
380 hir::MutImmutable => self.word_nbsp("const")?,
382 self.print_type(&mt.ty)?;
384 hir::TyKind::Rptr(ref lifetime, ref mt) => {
386 self.print_opt_lifetime(lifetime)?;
389 hir::TyKind::Never => {
392 hir::TyKind::Tup(ref elts) => {
394 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty))?;
400 hir::TyKind::BareFn(ref f) => {
401 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &f.generic_params,
404 hir::TyKind::Path(ref qpath) => {
405 self.print_qpath(qpath, false)?
407 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
408 let mut first = true;
409 for bound in bounds {
414 self.word_space("+")?;
416 self.print_poly_trait_ref(bound)?;
418 if !lifetime.is_elided() {
420 self.word_space("+")?;
421 self.print_lifetime(lifetime)?;
424 hir::TyKind::Array(ref ty, ref length) => {
426 self.print_type(&ty)?;
428 self.print_anon_const(length)?;
431 hir::TyKind::Typeof(ref e) => {
432 self.s.word("typeof(")?;
433 self.print_anon_const(e)?;
436 hir::TyKind::Infer => {
439 hir::TyKind::Err => {
446 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
447 self.hardbreak_if_not_bol()?;
448 self.maybe_print_comment(item.span.lo())?;
449 self.print_outer_attributes(&item.attrs)?;
451 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
455 unsafety: hir::Unsafety::Normal,
456 constness: hir::Constness::NotConst,
458 asyncness: hir::IsAsync::NotAsync,
465 self.end()?; // end head-ibox
467 self.end() // end the outer fn box
469 hir::ForeignItemKind::Static(ref t, m) => {
470 self.head(&visibility_qualified(&item.vis, "static"))?;
472 self.word_space("mut")?;
474 self.print_name(item.name)?;
475 self.word_space(":")?;
476 self.print_type(&t)?;
478 self.end()?; // end the head-ibox
479 self.end() // end the outer cbox
481 hir::ForeignItemKind::Type => {
482 self.head(&visibility_qualified(&item.vis, "type"))?;
483 self.print_name(item.name)?;
485 self.end()?; // end the head-ibox
486 self.end() // end the outer cbox
491 fn print_associated_const(&mut self,
494 default: Option<hir::BodyId>,
495 vis: &hir::Visibility)
497 self.s.word(&visibility_qualified(vis, ""))?;
498 self.word_space("const")?;
499 self.print_ident(ident)?;
500 self.word_space(":")?;
501 self.print_type(ty)?;
502 if let Some(expr) = default {
504 self.word_space("=")?;
505 self.ann.nested(self, Nested::Body(expr))?;
510 fn print_associated_type(&mut self,
512 bounds: Option<&hir::GenericBounds>,
513 ty: Option<&hir::Ty>)
515 self.word_space("type")?;
516 self.print_ident(ident)?;
517 if let Some(bounds) = bounds {
518 self.print_bounds(":", bounds)?;
520 if let Some(ty) = ty {
522 self.word_space("=")?;
523 self.print_type(ty)?;
528 /// Pretty-print an item
529 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
530 self.hardbreak_if_not_bol()?;
531 self.maybe_print_comment(item.span.lo())?;
532 self.print_outer_attributes(&item.attrs)?;
533 self.ann.pre(self, AnnNode::Item(item))?;
535 hir::ItemKind::ExternCrate(orig_name) => {
536 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
537 if let Some(orig_name) = orig_name {
538 self.print_name(orig_name)?;
543 self.print_name(item.name)?;
545 self.end()?; // end inner head-block
546 self.end()?; // end outer head-block
548 hir::ItemKind::Use(ref path, kind) => {
549 self.head(&visibility_qualified(&item.vis, "use"))?;
550 self.print_path(path, false)?;
553 hir::UseKind::Single => {
554 if path.segments.last().unwrap().ident.name != item.name {
556 self.word_space("as")?;
557 self.print_name(item.name)?;
561 hir::UseKind::Glob => self.s.word("::*;")?,
562 hir::UseKind::ListStem => self.s.word("::{};")?
564 self.end()?; // end inner head-block
565 self.end()?; // end outer head-block
567 hir::ItemKind::Static(ref ty, m, expr) => {
568 self.head(&visibility_qualified(&item.vis, "static"))?;
569 if m == hir::MutMutable {
570 self.word_space("mut")?;
572 self.print_name(item.name)?;
573 self.word_space(":")?;
574 self.print_type(&ty)?;
576 self.end()?; // end the head-ibox
578 self.word_space("=")?;
579 self.ann.nested(self, Nested::Body(expr))?;
581 self.end()?; // end the outer cbox
583 hir::ItemKind::Const(ref ty, expr) => {
584 self.head(&visibility_qualified(&item.vis, "const"))?;
585 self.print_name(item.name)?;
586 self.word_space(":")?;
587 self.print_type(&ty)?;
589 self.end()?; // end the head-ibox
591 self.word_space("=")?;
592 self.ann.nested(self, Nested::Body(expr))?;
594 self.end()?; // end the outer cbox
596 hir::ItemKind::Fn(ref decl, header, ref typarams, body) => {
606 self.end()?; // need to close a box
607 self.end()?; // need to close a box
608 self.ann.nested(self, Nested::Body(body))?;
610 hir::ItemKind::Mod(ref _mod) => {
611 self.head(&visibility_qualified(&item.vis, "mod"))?;
612 self.print_name(item.name)?;
615 self.print_mod(_mod, &item.attrs)?;
616 self.bclose(item.span)?;
618 hir::ItemKind::ForeignMod(ref nmod) => {
619 self.head("extern")?;
620 self.word_nbsp(&nmod.abi.to_string())?;
622 self.print_foreign_mod(nmod, &item.attrs)?;
623 self.bclose(item.span)?;
625 hir::ItemKind::GlobalAsm(ref ga) => {
626 self.head(&visibility_qualified(&item.vis, "global asm"))?;
627 self.s.word(&ga.asm.as_str())?;
630 hir::ItemKind::Ty(ref ty, ref generics) => {
631 self.head(&visibility_qualified(&item.vis, "type"))?;
632 self.print_name(item.name)?;
633 self.print_generic_params(&generics.params)?;
634 self.end()?; // end the inner ibox
636 self.print_where_clause(&generics.where_clause)?;
638 self.word_space("=")?;
639 self.print_type(&ty)?;
641 self.end()?; // end the outer ibox
643 hir::ItemKind::Existential(ref exist) => {
644 self.head(&visibility_qualified(&item.vis, "existential type"))?;
645 self.print_name(item.name)?;
646 self.print_generic_params(&exist.generics.params)?;
647 self.end()?; // end the inner ibox
649 self.print_where_clause(&exist.generics.where_clause)?;
651 self.word_space(":")?;
652 let mut real_bounds = Vec::with_capacity(exist.bounds.len());
653 for b in exist.bounds.iter() {
654 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
656 self.word_space("for ?")?;
657 self.print_trait_ref(&ptr.trait_ref)?;
659 real_bounds.push(b.clone());
662 self.print_bounds(":", &real_bounds[..])?;
664 self.end()?; // end the outer ibox
666 hir::ItemKind::Enum(ref enum_definition, ref params) => {
667 self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
669 hir::ItemKind::Struct(ref struct_def, ref generics) => {
670 self.head(&visibility_qualified(&item.vis, "struct"))?;
671 self.print_struct(struct_def, generics, item.name, item.span, true)?;
673 hir::ItemKind::Union(ref struct_def, ref generics) => {
674 self.head(&visibility_qualified(&item.vis, "union"))?;
675 self.print_struct(struct_def, generics, item.name, item.span, true)?;
677 hir::ItemKind::Impl(unsafety,
685 self.print_visibility(&item.vis)?;
686 self.print_defaultness(defaultness)?;
687 self.print_unsafety(unsafety)?;
688 self.word_nbsp("impl")?;
690 if !generics.params.is_empty() {
691 self.print_generic_params(&generics.params)?;
695 if let hir::ImplPolarity::Negative = polarity {
699 if let Some(ref t) = opt_trait {
700 self.print_trait_ref(t)?;
702 self.word_space("for")?;
705 self.print_type(&ty)?;
706 self.print_where_clause(&generics.where_clause)?;
710 self.print_inner_attributes(&item.attrs)?;
711 for impl_item in impl_items {
712 self.ann.nested(self, Nested::ImplItem(impl_item.id))?;
714 self.bclose(item.span)?;
716 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
718 self.print_visibility(&item.vis)?;
719 self.print_is_auto(is_auto)?;
720 self.print_unsafety(unsafety)?;
721 self.word_nbsp("trait")?;
722 self.print_name(item.name)?;
723 self.print_generic_params(&generics.params)?;
724 let mut real_bounds = Vec::with_capacity(bounds.len());
725 for b in bounds.iter() {
726 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
728 self.word_space("for ?")?;
729 self.print_trait_ref(&ptr.trait_ref)?;
731 real_bounds.push(b.clone());
734 self.print_bounds(":", &real_bounds[..])?;
735 self.print_where_clause(&generics.where_clause)?;
738 for trait_item in trait_items {
739 self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
741 self.bclose(item.span)?;
743 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
745 self.print_visibility(&item.vis)?;
746 self.word_nbsp("trait")?;
747 self.print_name(item.name)?;
748 self.print_generic_params(&generics.params)?;
749 let mut real_bounds = Vec::with_capacity(bounds.len());
750 // FIXME(durka) this seems to be some quite outdated syntax
751 for b in bounds.iter() {
752 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
754 self.word_space("for ?")?;
755 self.print_trait_ref(&ptr.trait_ref)?;
757 real_bounds.push(b.clone());
761 self.print_bounds("=", &real_bounds[..])?;
762 self.print_where_clause(&generics.where_clause)?;
766 self.ann.post(self, AnnNode::Item(item))
769 pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
770 self.print_path(&t.path, false)
773 fn print_formal_generic_params(
775 generic_params: &[hir::GenericParam]
776 ) -> io::Result<()> {
777 if !generic_params.is_empty() {
779 self.print_generic_params(generic_params)?;
785 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
786 self.print_formal_generic_params(&t.bound_generic_params)?;
787 self.print_trait_ref(&t.trait_ref)
790 pub fn print_enum_def(&mut self,
791 enum_definition: &hir::EnumDef,
792 generics: &hir::Generics,
794 span: syntax_pos::Span,
795 visibility: &hir::Visibility)
797 self.head(&visibility_qualified(visibility, "enum"))?;
798 self.print_name(name)?;
799 self.print_generic_params(&generics.params)?;
800 self.print_where_clause(&generics.where_clause)?;
802 self.print_variants(&enum_definition.variants, span)
805 pub fn print_variants(&mut self,
806 variants: &[hir::Variant],
807 span: syntax_pos::Span)
811 self.space_if_not_bol()?;
812 self.maybe_print_comment(v.span.lo())?;
813 self.print_outer_attributes(&v.node.attrs)?;
814 self.ibox(indent_unit)?;
815 self.print_variant(v)?;
818 self.maybe_print_trailing_comment(v.span, None)?;
823 pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
825 hir::VisibilityKind::Public => self.word_nbsp("pub")?,
826 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate")?,
827 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)")?,
828 hir::VisibilityKind::Restricted { ref path, .. } => {
829 self.s.word("pub(")?;
830 if path.segments.len() == 1 &&
831 path.segments[0].ident.name == keywords::Super.name() {
832 // Special case: `super` can print like `pub(super)`.
833 self.s.word("super")?;
835 // Everything else requires `in` at present.
836 self.word_nbsp("in")?;
837 self.print_path(path, false)?;
839 self.word_nbsp(")")?;
841 hir::VisibilityKind::Inherited => ()
847 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) -> io::Result<()> {
849 hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
850 hir::Defaultness::Final => (),
855 pub fn print_struct(&mut self,
856 struct_def: &hir::VariantData,
857 generics: &hir::Generics,
859 span: syntax_pos::Span,
860 print_finalizer: bool)
862 self.print_name(name)?;
863 self.print_generic_params(&generics.params)?;
864 if !struct_def.is_struct() {
865 if struct_def.is_tuple() {
867 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
868 s.maybe_print_comment(field.span.lo())?;
869 s.print_outer_attributes(&field.attrs)?;
870 s.print_visibility(&field.vis)?;
871 s.print_type(&field.ty)
875 self.print_where_clause(&generics.where_clause)?;
880 self.end() // close the outer-box
882 self.print_where_clause(&generics.where_clause)?;
885 self.hardbreak_if_not_bol()?;
887 for field in struct_def.fields() {
888 self.hardbreak_if_not_bol()?;
889 self.maybe_print_comment(field.span.lo())?;
890 self.print_outer_attributes(&field.attrs)?;
891 self.print_visibility(&field.vis)?;
892 self.print_ident(field.ident)?;
893 self.word_nbsp(":")?;
894 self.print_type(&field.ty)?;
902 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
904 let generics = hir::Generics::empty();
905 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
906 if let Some(ref d) = v.node.disr_expr {
908 self.word_space("=")?;
909 self.print_anon_const(d)?;
913 pub fn print_method_sig(&mut self,
916 generics: &hir::Generics,
917 vis: &hir::Visibility,
918 arg_names: &[ast::Ident],
919 body_id: Option<hir::BodyId>)
921 self.print_fn(&m.decl,
930 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
931 self.ann.pre(self, AnnNode::SubItem(ti.id))?;
932 self.hardbreak_if_not_bol()?;
933 self.maybe_print_comment(ti.span.lo())?;
934 self.print_outer_attributes(&ti.attrs)?;
936 hir::TraitItemKind::Const(ref ty, default) => {
937 let vis = Spanned { span: syntax_pos::DUMMY_SP,
938 node: hir::VisibilityKind::Inherited };
939 self.print_associated_const(ti.ident, &ty, default, &vis)?;
941 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
942 let vis = Spanned { span: syntax_pos::DUMMY_SP,
943 node: hir::VisibilityKind::Inherited };
944 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None)?;
947 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
948 let vis = Spanned { span: syntax_pos::DUMMY_SP,
949 node: hir::VisibilityKind::Inherited };
951 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body))?;
953 self.end()?; // need to close a box
954 self.end()?; // need to close a box
955 self.ann.nested(self, Nested::Body(body))?;
957 hir::TraitItemKind::Type(ref bounds, ref default) => {
958 self.print_associated_type(ti.ident,
960 default.as_ref().map(|ty| &**ty))?;
963 self.ann.post(self, AnnNode::SubItem(ti.id))
966 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
967 self.ann.pre(self, AnnNode::SubItem(ii.id))?;
968 self.hardbreak_if_not_bol()?;
969 self.maybe_print_comment(ii.span.lo())?;
970 self.print_outer_attributes(&ii.attrs)?;
971 self.print_defaultness(ii.defaultness)?;
974 hir::ImplItemKind::Const(ref ty, expr) => {
975 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis)?;
977 hir::ImplItemKind::Method(ref sig, body) => {
979 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body))?;
981 self.end()?; // need to close a box
982 self.end()?; // need to close a box
983 self.ann.nested(self, Nested::Body(body))?;
985 hir::ImplItemKind::Type(ref ty) => {
986 self.print_associated_type(ii.ident, None, Some(ty))?;
988 hir::ImplItemKind::Existential(ref bounds) => {
989 self.word_space("existential")?;
990 self.print_associated_type(ii.ident, Some(bounds), None)?;
993 self.ann.post(self, AnnNode::SubItem(ii.id))
996 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
997 self.maybe_print_comment(st.span.lo())?;
999 hir::StmtKind::Decl(ref decl, _) => {
1000 self.print_decl(&decl)?;
1002 hir::StmtKind::Expr(ref expr, _) => {
1003 self.space_if_not_bol()?;
1004 self.print_expr(&expr)?;
1006 hir::StmtKind::Semi(ref expr, _) => {
1007 self.space_if_not_bol()?;
1008 self.print_expr(&expr)?;
1012 if stmt_ends_with_semi(&st.node) {
1015 self.maybe_print_trailing_comment(st.span, None)
1018 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1019 self.print_block_with_attrs(blk, &[])
1022 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1023 self.print_block_unclosed_indent(blk, indent_unit)
1026 pub fn print_block_unclosed_indent(&mut self,
1030 self.print_block_maybe_unclosed(blk, indented, &[], false)
1033 pub fn print_block_with_attrs(&mut self,
1035 attrs: &[ast::Attribute])
1037 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1040 pub fn print_block_maybe_unclosed(&mut self,
1043 attrs: &[ast::Attribute],
1047 hir::UnsafeBlock(..) => self.word_space("unsafe")?,
1048 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
1049 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
1050 hir::DefaultBlock => (),
1052 self.maybe_print_comment(blk.span.lo())?;
1053 self.ann.pre(self, AnnNode::Block(blk))?;
1056 self.print_inner_attributes(attrs)?;
1058 for st in &blk.stmts {
1059 self.print_stmt(st)?;
1061 if let Some(ref expr) = blk.expr {
1062 self.space_if_not_bol()?;
1063 self.print_expr(&expr)?;
1064 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1066 self.bclose_maybe_open(blk.span, indented, close_box)?;
1067 self.ann.post(self, AnnNode::Block(blk))
1070 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1074 // "another else-if"
1075 hir::ExprKind::If(ref i, ref then, ref e) => {
1076 self.cbox(indent_unit - 1)?;
1078 self.s.word(" else if ")?;
1079 self.print_expr_as_cond(&i)?;
1081 self.print_expr(&then)?;
1082 self.print_else(e.as_ref().map(|e| &**e))
1085 hir::ExprKind::Block(ref b, _) => {
1086 self.cbox(indent_unit - 1)?;
1088 self.s.word(" else ")?;
1089 self.print_block(&b)
1091 // BLEAH, constraints would be great here
1093 panic!("print_if saw if with weird alternative");
1101 pub fn print_if(&mut self,
1104 elseopt: Option<&hir::Expr>)
1107 self.print_expr_as_cond(test)?;
1109 self.print_expr(blk)?;
1110 self.print_else(elseopt)
1113 pub fn print_if_let(&mut self,
1117 elseopt: Option<&hir::Expr>)
1119 self.head("if let")?;
1120 self.print_pat(pat)?;
1122 self.word_space("=")?;
1123 self.print_expr_as_cond(expr)?;
1125 self.print_block(blk)?;
1126 self.print_else(elseopt)
1129 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) -> io::Result<()> {
1130 self.ann.nested(self, Nested::Body(constant.body))
1133 fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
1135 self.commasep_exprs(Inconsistent, args)?;
1139 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr, prec: i8) -> io::Result<()> {
1140 let needs_par = expr.precedence().order() < prec;
1144 self.print_expr(expr)?;
1151 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1152 /// `if cond { ... }`.
1153 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr) -> io::Result<()> {
1154 let needs_par = match expr.node {
1155 // These cases need parens due to the parse error observed in #26461: `if return {}`
1156 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1157 hir::ExprKind::Closure(..) |
1158 hir::ExprKind::Ret(..) |
1159 hir::ExprKind::Break(..) => true,
1161 _ => contains_exterior_struct_lit(expr),
1167 self.print_expr(expr)?;
1174 fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1175 self.ibox(indent_unit)?;
1177 self.commasep_exprs(Inconsistent, exprs)?;
1182 fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::AnonConst) -> io::Result<()> {
1183 self.ibox(indent_unit)?;
1185 self.print_expr(element)?;
1186 self.word_space(";")?;
1187 self.print_anon_const(count)?;
1192 fn print_expr_struct(&mut self,
1194 fields: &[hir::Field],
1195 wth: &Option<P<hir::Expr>>)
1197 self.print_qpath(qpath, true)?;
1199 self.commasep_cmnt(Consistent,
1202 s.ibox(indent_unit)?;
1203 if !field.is_shorthand {
1204 s.print_ident(field.ident)?;
1207 s.print_expr(&field.expr)?;
1213 self.ibox(indent_unit)?;
1214 if !fields.is_empty() {
1219 self.print_expr(&expr)?;
1222 _ => if !fields.is_empty() {
1230 fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1232 self.commasep_exprs(Inconsistent, exprs)?;
1233 if exprs.len() == 1 {
1239 fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1242 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1243 _ => parser::PREC_POSTFIX,
1246 self.print_expr_maybe_paren(func, prec)?;
1247 self.print_call_post(args)
1250 fn print_expr_method_call(&mut self,
1251 segment: &hir::PathSegment,
1254 let base_args = &args[1..];
1255 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
1257 self.print_ident(segment.ident)?;
1259 segment.with_generic_args(|generic_args| {
1260 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1261 return self.print_generic_args(&generic_args, segment.infer_types, true);
1265 self.print_call_post(base_args)
1268 fn print_expr_binary(&mut self,
1273 let assoc_op = bin_op_to_assoc_op(op.node);
1274 let prec = assoc_op.precedence() as i8;
1275 let fixity = assoc_op.fixity();
1277 let (left_prec, right_prec) = match fixity {
1278 Fixity::Left => (prec, prec + 1),
1279 Fixity::Right => (prec + 1, prec),
1280 Fixity::None => (prec + 1, prec + 1),
1283 let left_prec = match (&lhs.node, op.node) {
1284 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1285 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1286 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1287 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt) |
1288 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1292 self.print_expr_maybe_paren(lhs, left_prec)?;
1294 self.word_space(op.node.as_str())?;
1295 self.print_expr_maybe_paren(rhs, right_prec)
1298 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1299 self.s.word(op.as_str())?;
1300 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1303 fn print_expr_addr_of(&mut self,
1304 mutability: hir::Mutability,
1308 self.print_mutability(mutability)?;
1309 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1312 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1313 self.maybe_print_comment(expr.span.lo())?;
1314 self.print_outer_attributes(&expr.attrs)?;
1315 self.ibox(indent_unit)?;
1316 self.ann.pre(self, AnnNode::Expr(expr))?;
1318 hir::ExprKind::Box(ref expr) => {
1319 self.word_space("box")?;
1320 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
1322 hir::ExprKind::Array(ref exprs) => {
1323 self.print_expr_vec(exprs)?;
1325 hir::ExprKind::Repeat(ref element, ref count) => {
1326 self.print_expr_repeat(&element, count)?;
1328 hir::ExprKind::Struct(ref qpath, ref fields, ref wth) => {
1329 self.print_expr_struct(qpath, &fields[..], wth)?;
1331 hir::ExprKind::Tup(ref exprs) => {
1332 self.print_expr_tup(exprs)?;
1334 hir::ExprKind::Call(ref func, ref args) => {
1335 self.print_expr_call(&func, args)?;
1337 hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1338 self.print_expr_method_call(segment, args)?;
1340 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1341 self.print_expr_binary(op, &lhs, &rhs)?;
1343 hir::ExprKind::Unary(op, ref expr) => {
1344 self.print_expr_unary(op, &expr)?;
1346 hir::ExprKind::AddrOf(m, ref expr) => {
1347 self.print_expr_addr_of(m, &expr)?;
1349 hir::ExprKind::Lit(ref lit) => {
1350 self.print_literal(&lit)?;
1352 hir::ExprKind::Cast(ref expr, ref ty) => {
1353 let prec = AssocOp::As.precedence() as i8;
1354 self.print_expr_maybe_paren(&expr, prec)?;
1356 self.word_space("as")?;
1357 self.print_type(&ty)?;
1359 hir::ExprKind::Type(ref expr, ref ty) => {
1360 let prec = AssocOp::Colon.precedence() as i8;
1361 self.print_expr_maybe_paren(&expr, prec)?;
1362 self.word_space(":")?;
1363 self.print_type(&ty)?;
1365 hir::ExprKind::If(ref test, ref blk, ref elseopt) => {
1366 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1368 hir::ExprKind::While(ref test, ref blk, opt_label) => {
1369 if let Some(label) = opt_label {
1370 self.print_ident(label.ident)?;
1371 self.word_space(":")?;
1373 self.head("while")?;
1374 self.print_expr_as_cond(&test)?;
1376 self.print_block(&blk)?;
1378 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1379 if let Some(label) = opt_label {
1380 self.print_ident(label.ident)?;
1381 self.word_space(":")?;
1385 self.print_block(&blk)?;
1387 hir::ExprKind::Match(ref expr, ref arms, _) => {
1388 self.cbox(indent_unit)?;
1390 self.word_nbsp("match")?;
1391 self.print_expr_as_cond(&expr)?;
1395 self.print_arm(arm)?;
1397 self.bclose_(expr.span, indent_unit)?;
1399 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1400 self.print_capture_clause(capture_clause)?;
1402 self.print_closure_args(&decl, body)?;
1405 // this is a bare expression
1406 self.ann.nested(self, Nested::Body(body))?;
1407 self.end()?; // need to close a box
1409 // a box will be closed by print_expr, but we didn't want an overall
1410 // wrapper so we closed the corresponding opening. so create an
1411 // empty box to satisfy the close.
1414 hir::ExprKind::Block(ref blk, opt_label) => {
1415 if let Some(label) = opt_label {
1416 self.print_ident(label.ident)?;
1417 self.word_space(":")?;
1419 // containing cbox, will be closed by print-block at }
1420 self.cbox(indent_unit)?;
1421 // head-box, will be closed by print-block after {
1423 self.print_block(&blk)?;
1425 hir::ExprKind::Assign(ref lhs, ref rhs) => {
1426 let prec = AssocOp::Assign.precedence() as i8;
1427 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1429 self.word_space("=")?;
1430 self.print_expr_maybe_paren(&rhs, prec)?;
1432 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1433 let prec = AssocOp::Assign.precedence() as i8;
1434 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1436 self.s.word(op.node.as_str())?;
1437 self.word_space("=")?;
1438 self.print_expr_maybe_paren(&rhs, prec)?;
1440 hir::ExprKind::Field(ref expr, ident) => {
1441 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
1443 self.print_ident(ident)?;
1445 hir::ExprKind::Index(ref expr, ref index) => {
1446 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1448 self.print_expr(&index)?;
1451 hir::ExprKind::Path(ref qpath) => {
1452 self.print_qpath(qpath, true)?
1454 hir::ExprKind::Break(destination, ref opt_expr) => {
1455 self.s.word("break")?;
1457 if let Some(label) = destination.label {
1458 self.print_ident(label.ident)?;
1461 if let Some(ref expr) = *opt_expr {
1462 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
1466 hir::ExprKind::Continue(destination) => {
1467 self.s.word("continue")?;
1469 if let Some(label) = destination.label {
1470 self.print_ident(label.ident)?;
1474 hir::ExprKind::Ret(ref result) => {
1475 self.s.word("return")?;
1476 if let Some(ref expr) = *result {
1478 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1481 hir::ExprKind::InlineAsm(ref a, ref outputs, ref inputs) => {
1482 self.s.word("asm!")?;
1484 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
1485 self.word_space(":")?;
1487 let mut out_idx = 0;
1488 self.commasep(Inconsistent, &a.outputs, |s, out| {
1489 let constraint = out.constraint.as_str();
1490 let mut ch = constraint.chars();
1492 Some('=') if out.is_rw => {
1493 s.print_string(&format!("+{}", ch.as_str()),
1494 ast::StrStyle::Cooked)?
1496 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
1499 s.print_expr(&outputs[out_idx])?;
1505 self.word_space(":")?;
1508 self.commasep(Inconsistent, &a.inputs, |s, co| {
1509 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1511 s.print_expr(&inputs[in_idx])?;
1517 self.word_space(":")?;
1519 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1520 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1524 let mut options = vec![];
1526 options.push("volatile");
1529 options.push("alignstack");
1531 if a.dialect == ast::AsmDialect::Intel {
1532 options.push("intel");
1535 if !options.is_empty() {
1537 self.word_space(":")?;
1538 self.commasep(Inconsistent, &options, |s, &co| {
1539 s.print_string(co, ast::StrStyle::Cooked)?;
1546 hir::ExprKind::Yield(ref expr) => {
1547 self.word_space("yield")?;
1548 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1551 self.ann.post(self, AnnNode::Expr(expr))?;
1555 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1556 self.print_pat(&loc.pat)?;
1557 if let Some(ref ty) = loc.ty {
1558 self.word_space(":")?;
1559 self.print_type(&ty)?;
1564 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1565 self.maybe_print_comment(decl.span.lo())?;
1567 hir::DeclKind::Local(ref loc) => {
1568 self.space_if_not_bol()?;
1569 self.ibox(indent_unit)?;
1570 self.word_nbsp("let")?;
1572 self.ibox(indent_unit)?;
1573 self.print_local_decl(&loc)?;
1575 if let Some(ref init) = loc.init {
1577 self.word_space("=")?;
1578 self.print_expr(&init)?;
1582 hir::DeclKind::Item(item) => {
1583 self.ann.nested(self, Nested::Item(item))
1588 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1589 self.s.word(&i.to_string())
1592 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
1593 if ident.is_raw_guess() {
1594 self.s.word(&format!("r#{}", ident.name))?;
1596 self.s.word(&ident.as_str())?;
1598 self.ann.post(self, AnnNode::Name(&ident.name))
1601 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1602 self.print_ident(ast::Ident::with_empty_ctxt(name))
1605 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1606 self.print_local_decl(loc)?;
1608 self.word_space("in")?;
1609 self.print_expr(coll)
1612 pub fn print_path(&mut self,
1614 colons_before_params: bool)
1616 self.maybe_print_comment(path.span.lo())?;
1618 for (i, segment) in path.segments.iter().enumerate() {
1622 if segment.ident.name != keywords::CrateRoot.name() &&
1623 segment.ident.name != keywords::DollarCrate.name() {
1624 self.print_ident(segment.ident)?;
1625 segment.with_generic_args(|generic_args| {
1626 self.print_generic_args(generic_args, segment.infer_types,
1627 colons_before_params)
1635 pub fn print_qpath(&mut self,
1637 colons_before_params: bool)
1640 hir::QPath::Resolved(None, ref path) => {
1641 self.print_path(path, colons_before_params)
1643 hir::QPath::Resolved(Some(ref qself), ref path) => {
1645 self.print_type(qself)?;
1647 self.word_space("as")?;
1649 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1653 if segment.ident.name != keywords::CrateRoot.name() &&
1654 segment.ident.name != keywords::DollarCrate.name() {
1655 self.print_ident(segment.ident)?;
1656 segment.with_generic_args(|generic_args| {
1657 self.print_generic_args(generic_args,
1658 segment.infer_types,
1659 colons_before_params)
1666 let item_segment = path.segments.last().unwrap();
1667 self.print_ident(item_segment.ident)?;
1668 item_segment.with_generic_args(|generic_args| {
1669 self.print_generic_args(generic_args,
1670 item_segment.infer_types,
1671 colons_before_params)
1674 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1676 self.print_type(qself)?;
1679 self.print_ident(item_segment.ident)?;
1680 item_segment.with_generic_args(|generic_args| {
1681 self.print_generic_args(generic_args,
1682 item_segment.infer_types,
1683 colons_before_params)
1689 fn print_generic_args(&mut self,
1690 generic_args: &hir::GenericArgs,
1692 colons_before_params: bool)
1694 if generic_args.parenthesized {
1696 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty))?;
1699 self.space_if_not_bol()?;
1700 self.word_space("->")?;
1701 self.print_type(&generic_args.bindings[0].ty)?;
1703 let start = if colons_before_params { "::<" } else { "<" };
1704 let empty = Cell::new(true);
1705 let start_or_comma = |this: &mut Self| {
1710 this.word_space(",")
1714 let mut types = vec![];
1715 let mut elide_lifetimes = true;
1716 for arg in &generic_args.args {
1718 GenericArg::Lifetime(lt) => {
1719 if !lt.is_elided() {
1720 elide_lifetimes = false;
1723 GenericArg::Type(ty) => {
1728 if !elide_lifetimes {
1729 start_or_comma(self)?;
1730 self.commasep(Inconsistent, &generic_args.args, |s, generic_arg| {
1732 GenericArg::Lifetime(lt) => s.print_lifetime(lt),
1733 GenericArg::Type(ty) => s.print_type(ty),
1736 } else if !types.is_empty() {
1737 start_or_comma(self)?;
1738 self.commasep(Inconsistent, &types, |s, ty| s.print_type(&ty))?;
1741 // FIXME(eddyb) This would leak into error messages, e.g.:
1742 // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1743 if infer_types && false {
1744 start_or_comma(self)?;
1748 for binding in generic_args.bindings.iter() {
1749 start_or_comma(self)?;
1750 self.print_ident(binding.ident)?;
1752 self.word_space("=")?;
1753 self.print_type(&binding.ty)?;
1764 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1765 self.maybe_print_comment(pat.span.lo())?;
1766 self.ann.pre(self, AnnNode::Pat(pat))?;
1767 // Pat isn't normalized, but the beauty of it
1768 // is that it doesn't matter
1770 PatKind::Wild => self.s.word("_")?,
1771 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1772 match binding_mode {
1773 hir::BindingAnnotation::Ref => {
1774 self.word_nbsp("ref")?;
1775 self.print_mutability(hir::MutImmutable)?;
1777 hir::BindingAnnotation::RefMut => {
1778 self.word_nbsp("ref")?;
1779 self.print_mutability(hir::MutMutable)?;
1781 hir::BindingAnnotation::Unannotated => {}
1782 hir::BindingAnnotation::Mutable => {
1783 self.word_nbsp("mut")?;
1786 self.print_ident(ident)?;
1787 if let Some(ref p) = *sub {
1789 self.print_pat(&p)?;
1792 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1793 self.print_qpath(qpath, true)?;
1795 if let Some(ddpos) = ddpos {
1796 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1798 self.word_space(",")?;
1801 if ddpos != elts.len() {
1803 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1806 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1810 PatKind::Path(ref qpath) => {
1811 self.print_qpath(qpath, true)?;
1813 PatKind::Struct(ref qpath, ref fields, etc) => {
1814 self.print_qpath(qpath, true)?;
1816 self.word_space("{")?;
1817 self.commasep_cmnt(Consistent,
1820 s.cbox(indent_unit)?;
1821 if !f.node.is_shorthand {
1822 s.print_ident(f.node.ident)?;
1825 s.print_pat(&f.node.pat)?;
1828 |f| f.node.pat.span)?;
1830 if !fields.is_empty() {
1831 self.word_space(",")?;
1838 PatKind::Tuple(ref elts, ddpos) => {
1840 if let Some(ddpos) = ddpos {
1841 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1843 self.word_space(",")?;
1846 if ddpos != elts.len() {
1848 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1851 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1852 if elts.len() == 1 {
1858 PatKind::Box(ref inner) => {
1859 let is_range_inner = match inner.node {
1860 PatKind::Range(..) => true,
1863 self.s.word("box ")?;
1867 self.print_pat(&inner)?;
1872 PatKind::Ref(ref inner, mutbl) => {
1873 let is_range_inner = match inner.node {
1874 PatKind::Range(..) => true,
1878 if mutbl == hir::MutMutable {
1879 self.s.word("mut ")?;
1884 self.print_pat(&inner)?;
1889 PatKind::Lit(ref e) => self.print_expr(&e)?,
1890 PatKind::Range(ref begin, ref end, ref end_kind) => {
1891 self.print_expr(&begin)?;
1894 RangeEnd::Included => self.s.word("...")?,
1895 RangeEnd::Excluded => self.s.word("..")?,
1897 self.print_expr(&end)?;
1899 PatKind::Slice(ref before, ref slice, ref after) => {
1901 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1902 if let Some(ref p) = *slice {
1903 if !before.is_empty() {
1904 self.word_space(",")?;
1906 if let PatKind::Wild = p.node {
1909 self.print_pat(&p)?;
1912 if !after.is_empty() {
1913 self.word_space(",")?;
1916 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1920 self.ann.post(self, AnnNode::Pat(pat))
1923 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1924 // I have no idea why this check is necessary, but here it
1926 if arm.attrs.is_empty() {
1929 self.cbox(indent_unit)?;
1931 self.print_outer_attributes(&arm.attrs)?;
1932 let mut first = true;
1933 for p in &arm.pats {
1938 self.word_space("|")?;
1940 self.print_pat(&p)?;
1943 if let Some(ref g) = arm.guard {
1945 hir::Guard::If(e) => {
1946 self.word_space("if")?;
1947 self.print_expr(&e)?;
1952 self.word_space("=>")?;
1954 match arm.body.node {
1955 hir::ExprKind::Block(ref blk, opt_label) => {
1956 if let Some(label) = opt_label {
1957 self.print_ident(label.ident)?;
1958 self.word_space(":")?;
1960 // the block will close the pattern's ibox
1961 self.print_block_unclosed_indent(&blk, indent_unit)?;
1963 // If it is a user-provided unsafe block, print a comma after it
1964 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1969 self.end()?; // close the ibox for the pattern
1970 self.print_expr(&arm.body)?;
1974 self.end() // close enclosing cbox
1977 pub fn print_fn(&mut self,
1979 header: hir::FnHeader,
1980 name: Option<ast::Name>,
1981 generics: &hir::Generics,
1982 vis: &hir::Visibility,
1983 arg_names: &[ast::Ident],
1984 body_id: Option<hir::BodyId>)
1986 self.print_fn_header_info(header, vis)?;
1988 if let Some(name) = name {
1990 self.print_name(name)?;
1992 self.print_generic_params(&generics.params)?;
1996 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1997 assert!(arg_names.is_empty() || body_id.is_none());
1998 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1999 s.ibox(indent_unit)?;
2000 if let Some(arg_name) = arg_names.get(i) {
2001 s.s.word(&arg_name.as_str())?;
2004 } else if let Some(body_id) = body_id {
2005 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2014 self.s.word(", ...")?;
2018 self.print_fn_output(decl)?;
2019 self.print_where_clause(&generics.where_clause)
2022 fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
2025 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2026 s.ibox(indent_unit)?;
2028 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2031 if let hir::TyKind::Infer = ty.node {
2042 if let hir::DefaultReturn(..) = decl.output {
2046 self.space_if_not_bol()?;
2047 self.word_space("->")?;
2049 hir::Return(ref ty) => {
2050 self.print_type(&ty)?;
2051 self.maybe_print_comment(ty.span.lo())
2053 hir::DefaultReturn(..) => unreachable!(),
2057 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
2058 match capture_clause {
2059 hir::CaptureByValue => self.word_space("move"),
2060 hir::CaptureByRef => Ok(()),
2064 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::GenericBound]) -> io::Result<()> {
2065 if !bounds.is_empty() {
2066 self.s.word(prefix)?;
2067 let mut first = true;
2068 for bound in bounds {
2069 if !(first && prefix.is_empty()) {
2075 self.word_space("+")?;
2079 GenericBound::Trait(tref, modifier) => {
2080 if modifier == &TraitBoundModifier::Maybe {
2083 self.print_poly_trait_ref(tref)?;
2085 GenericBound::Outlives(lt) => {
2086 self.print_lifetime(lt)?;
2094 pub fn print_generic_params(&mut self, generic_params: &[GenericParam]) -> io::Result<()> {
2095 if !generic_params.is_empty() {
2098 self.commasep(Inconsistent, generic_params, |s, param| {
2099 s.print_generic_param(param)
2107 pub fn print_generic_param(&mut self, param: &GenericParam) -> io::Result<()> {
2108 self.print_ident(param.name.ident())?;
2110 GenericParamKind::Lifetime { .. } => {
2112 for bound in ¶m.bounds {
2114 GenericBound::Outlives(lt) => {
2116 self.print_lifetime(lt)?;
2124 GenericParamKind::Type { ref default, .. } => {
2125 self.print_bounds(":", ¶m.bounds)?;
2129 self.word_space("=")?;
2130 self.print_type(&default)
2138 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2139 self.print_ident(lifetime.name.ident())
2142 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2143 if where_clause.predicates.is_empty() {
2148 self.word_space("where")?;
2150 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2152 self.word_space(",")?;
2156 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2157 ref bound_generic_params,
2162 self.print_formal_generic_params(bound_generic_params)?;
2163 self.print_type(&bounded_ty)?;
2164 self.print_bounds(":", bounds)?;
2166 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2169 self.print_lifetime(lifetime)?;
2172 for (i, bound) in bounds.iter().enumerate() {
2174 GenericBound::Outlives(lt) => {
2175 self.print_lifetime(lt)?;
2185 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
2188 self.print_type(lhs_ty)?;
2190 self.word_space("=")?;
2191 self.print_type(rhs_ty)?;
2199 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2201 hir::MutMutable => self.word_nbsp("mut"),
2202 hir::MutImmutable => Ok(()),
2206 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2207 self.print_mutability(mt.mutbl)?;
2208 self.print_type(&mt.ty)
2211 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2212 if let hir::DefaultReturn(..) = decl.output {
2216 self.space_if_not_bol()?;
2217 self.ibox(indent_unit)?;
2218 self.word_space("->")?;
2220 hir::DefaultReturn(..) => unreachable!(),
2221 hir::Return(ref ty) => self.print_type(&ty)?,
2226 hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2231 pub fn print_ty_fn(&mut self,
2233 unsafety: hir::Unsafety,
2235 name: Option<ast::Name>,
2236 generic_params: &[hir::GenericParam],
2237 arg_names: &[ast::Ident])
2239 self.ibox(indent_unit)?;
2240 if !generic_params.is_empty() {
2241 self.s.word("for")?;
2242 self.print_generic_params(generic_params)?;
2244 let generics = hir::Generics {
2245 params: hir::HirVec::new(),
2246 where_clause: hir::WhereClause {
2247 id: ast::DUMMY_NODE_ID,
2248 predicates: hir::HirVec::new(),
2250 span: syntax_pos::DUMMY_SP,
2256 constness: hir::Constness::NotConst,
2257 asyncness: hir::IsAsync::NotAsync,
2261 &Spanned { span: syntax_pos::DUMMY_SP,
2262 node: hir::VisibilityKind::Inherited },
2268 pub fn maybe_print_trailing_comment(&mut self,
2269 span: syntax_pos::Span,
2270 next_pos: Option<BytePos>)
2272 let cm = match self.cm {
2276 if let Some(ref cmnt) = self.next_comment() {
2277 if (*cmnt).style != comments::Trailing {
2280 let span_line = cm.lookup_char_pos(span.hi());
2281 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2282 let mut next = (*cmnt).pos + BytePos(1);
2283 if let Some(p) = next_pos {
2286 if span.hi() < (*cmnt).pos && (*cmnt).pos < next &&
2287 span_line.line == comment_line.line {
2288 self.print_comment(cmnt)?;
2294 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2295 // If there aren't any remaining comments, then we need to manually
2296 // make sure there is a line break at the end.
2297 if self.next_comment().is_none() {
2298 self.s.hardbreak()?;
2300 while let Some(ref cmnt) = self.next_comment() {
2301 self.print_comment(cmnt)?
2306 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2307 opt_abi: Option<Abi>)
2310 Some(Abi::Rust) => Ok(()),
2312 self.word_nbsp("extern")?;
2313 self.word_nbsp(&abi.to_string())
2319 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2322 self.word_nbsp("extern")?;
2323 self.word_nbsp(&abi.to_string())
2329 pub fn print_fn_header_info(&mut self,
2330 header: hir::FnHeader,
2331 vis: &hir::Visibility)
2333 self.s.word(&visibility_qualified(vis, ""))?;
2335 match header.constness {
2336 hir::Constness::NotConst => {}
2337 hir::Constness::Const => self.word_nbsp("const")?,
2340 match header.asyncness {
2341 hir::IsAsync::NotAsync => {}
2342 hir::IsAsync::Async => self.word_nbsp("async")?,
2345 self.print_unsafety(header.unsafety)?;
2347 if header.abi != Abi::Rust {
2348 self.word_nbsp("extern")?;
2349 self.word_nbsp(&header.abi.to_string())?;
2355 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2357 hir::Unsafety::Normal => Ok(()),
2358 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2362 pub fn print_is_auto(&mut self, s: hir::IsAuto) -> io::Result<()> {
2364 hir::IsAuto::Yes => self.word_nbsp("auto"),
2365 hir::IsAuto::No => Ok(()),
2370 // Dup'ed from parse::classify, but adapted for the HIR.
2371 /// Does this expression require a semicolon to be treated
2372 /// as a statement? The negation of this: 'can this expression
2373 /// be used as a statement without a semicolon' -- is used
2374 /// as an early-bail-out in the parser so that, for instance,
2375 /// if true {...} else {...}
2377 /// isn't parsed as (if true {...} else {...} | x) | 5
2378 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2380 hir::ExprKind::If(..) |
2381 hir::ExprKind::Match(..) |
2382 hir::ExprKind::Block(..) |
2383 hir::ExprKind::While(..) |
2384 hir::ExprKind::Loop(..) => false,
2389 /// this statement requires a semicolon after it.
2390 /// note that in one case (stmt_semi), we've already
2391 /// seen the semicolon, and thus don't need another.
2392 fn stmt_ends_with_semi(stmt: &hir::StmtKind) -> bool {
2394 hir::StmtKind::Decl(ref d, _) => {
2396 hir::DeclKind::Local(_) => true,
2397 hir::DeclKind::Item(_) => false,
2400 hir::StmtKind::Expr(ref e, _) => {
2401 expr_requires_semi_to_be_stmt(&e)
2403 hir::StmtKind::Semi(..) => {
2409 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2410 use hir::BinOpKind::*;
2412 Add => AssocOp::Add,
2413 Sub => AssocOp::Subtract,
2414 Mul => AssocOp::Multiply,
2415 Div => AssocOp::Divide,
2416 Rem => AssocOp::Modulus,
2418 And => AssocOp::LAnd,
2421 BitXor => AssocOp::BitXor,
2422 BitAnd => AssocOp::BitAnd,
2423 BitOr => AssocOp::BitOr,
2424 Shl => AssocOp::ShiftLeft,
2425 Shr => AssocOp::ShiftRight,
2427 Eq => AssocOp::Equal,
2428 Lt => AssocOp::Less,
2429 Le => AssocOp::LessEqual,
2430 Ne => AssocOp::NotEqual,
2431 Ge => AssocOp::GreaterEqual,
2432 Gt => AssocOp::Greater,
2436 /// Expressions that syntactically contain an "exterior" struct literal i.e. not surrounded by any
2437 /// parens or other delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2438 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2439 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
2441 hir::ExprKind::Struct(..) => true,
2443 hir::ExprKind::Assign(ref lhs, ref rhs) |
2444 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) |
2445 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2446 // X { y: 1 } + X { y: 2 }
2447 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2449 hir::ExprKind::Unary(_, ref x) |
2450 hir::ExprKind::Cast(ref x, _) |
2451 hir::ExprKind::Type(ref x, _) |
2452 hir::ExprKind::Field(ref x, _) |
2453 hir::ExprKind::Index(ref x, _) => {
2454 // &X { y: 1 }, X { y: 1 }.y
2455 contains_exterior_struct_lit(&x)
2458 hir::ExprKind::MethodCall(.., ref exprs) => {
2459 // X { y: 1 }.bar(...)
2460 contains_exterior_struct_lit(&exprs[0])