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)
254 pub fn bclose_maybe_open(&mut self,
255 span: syntax_pos::Span,
259 self.maybe_print_comment(span.hi())?;
260 self.break_offset_if_not_bol(1, -(indented as isize))?;
263 self.end()?; // close the outer-box
267 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
268 self.bclose_(span, indent_unit)
271 pub fn in_cbox(&self) -> bool {
272 match self.boxes.last() {
273 Some(&last_box) => last_box == pp::Breaks::Consistent,
277 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
283 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
285 self.s.break_offset(n, off)
287 if off != 0 && self.s.last_token().is_hardbreak_tok() {
288 // We do something pretty sketchy here: tuck the nonzero
289 // offset-adjustment we were going to deposit along with the
290 // break into the previous hardbreak.
291 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
297 // Synthesizes a comment that was not textually present in the original source
299 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
302 self.s.word(&text[..])?;
308 pub fn commasep_cmnt<T, F, G>(&mut self,
314 where F: FnMut(&mut State, &T) -> io::Result<()>,
315 G: FnMut(&T) -> syntax_pos::Span
318 let len = elts.len();
321 self.maybe_print_comment(get_span(elt).hi())?;
326 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()))?;
327 self.space_if_not_bol()?;
333 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr]) -> io::Result<()> {
334 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
337 pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
338 self.print_inner_attributes(attrs)?;
339 for &item_id in &_mod.item_ids {
340 self.ann.nested(self, Nested::Item(item_id))?;
345 pub fn print_foreign_mod(&mut self,
346 nmod: &hir::ForeignMod,
347 attrs: &[ast::Attribute])
349 self.print_inner_attributes(attrs)?;
350 for item in &nmod.items {
351 self.print_foreign_item(item)?;
356 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
357 if !lifetime.is_elided() {
358 self.print_lifetime(lifetime)?;
364 pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
365 self.maybe_print_comment(ty.span.lo())?;
368 hir::TyKind::Slice(ref ty) => {
370 self.print_type(&ty)?;
373 hir::TyKind::Ptr(ref mt) => {
376 hir::MutMutable => self.word_nbsp("mut")?,
377 hir::MutImmutable => self.word_nbsp("const")?,
379 self.print_type(&mt.ty)?;
381 hir::TyKind::Rptr(ref lifetime, ref mt) => {
383 self.print_opt_lifetime(lifetime)?;
386 hir::TyKind::Never => {
389 hir::TyKind::Tup(ref elts) => {
391 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty))?;
397 hir::TyKind::BareFn(ref f) => {
398 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &f.generic_params,
401 hir::TyKind::Path(ref qpath) => {
402 self.print_qpath(qpath, false)?
404 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
405 let mut first = true;
406 for bound in bounds {
411 self.word_space("+")?;
413 self.print_poly_trait_ref(bound)?;
415 if !lifetime.is_elided() {
417 self.word_space("+")?;
418 self.print_lifetime(lifetime)?;
421 hir::TyKind::Array(ref ty, ref length) => {
423 self.print_type(&ty)?;
425 self.print_anon_const(length)?;
428 hir::TyKind::Typeof(ref e) => {
429 self.s.word("typeof(")?;
430 self.print_anon_const(e)?;
433 hir::TyKind::Infer => {
436 hir::TyKind::Err => {
443 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
444 self.hardbreak_if_not_bol()?;
445 self.maybe_print_comment(item.span.lo())?;
446 self.print_outer_attributes(&item.attrs)?;
448 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
452 unsafety: hir::Unsafety::Normal,
453 constness: hir::Constness::NotConst,
455 asyncness: hir::IsAsync::NotAsync,
462 self.end()?; // end head-ibox
464 self.end() // end the outer fn box
466 hir::ForeignItemKind::Static(ref t, m) => {
467 self.head(&visibility_qualified(&item.vis, "static"))?;
469 self.word_space("mut")?;
471 self.print_name(item.name)?;
472 self.word_space(":")?;
473 self.print_type(&t)?;
475 self.end()?; // end the head-ibox
476 self.end() // end the outer cbox
478 hir::ForeignItemKind::Type => {
479 self.head(&visibility_qualified(&item.vis, "type"))?;
480 self.print_name(item.name)?;
482 self.end()?; // end the head-ibox
483 self.end() // end the outer cbox
488 fn print_associated_const(&mut self,
491 default: Option<hir::BodyId>,
492 vis: &hir::Visibility)
494 self.s.word(&visibility_qualified(vis, ""))?;
495 self.word_space("const")?;
496 self.print_ident(ident)?;
497 self.word_space(":")?;
498 self.print_type(ty)?;
499 if let Some(expr) = default {
501 self.word_space("=")?;
502 self.ann.nested(self, Nested::Body(expr))?;
507 fn print_associated_type(&mut self,
509 bounds: Option<&hir::GenericBounds>,
510 ty: Option<&hir::Ty>)
512 self.word_space("type")?;
513 self.print_ident(ident)?;
514 if let Some(bounds) = bounds {
515 self.print_bounds(":", bounds)?;
517 if let Some(ty) = ty {
519 self.word_space("=")?;
520 self.print_type(ty)?;
525 /// Pretty-print an item
526 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
527 self.hardbreak_if_not_bol()?;
528 self.maybe_print_comment(item.span.lo())?;
529 self.print_outer_attributes(&item.attrs)?;
530 self.ann.pre(self, AnnNode::Item(item))?;
532 hir::ItemKind::ExternCrate(orig_name) => {
533 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
534 if let Some(orig_name) = orig_name {
535 self.print_name(orig_name)?;
540 self.print_name(item.name)?;
542 self.end()?; // end inner head-block
543 self.end()?; // end outer head-block
545 hir::ItemKind::Use(ref path, kind) => {
546 self.head(&visibility_qualified(&item.vis, "use"))?;
547 self.print_path(path, false)?;
550 hir::UseKind::Single => {
551 if path.segments.last().unwrap().ident.name != item.name {
553 self.word_space("as")?;
554 self.print_name(item.name)?;
558 hir::UseKind::Glob => self.s.word("::*;")?,
559 hir::UseKind::ListStem => self.s.word("::{};")?
561 self.end()?; // end inner head-block
562 self.end()?; // end outer head-block
564 hir::ItemKind::Static(ref ty, m, expr) => {
565 self.head(&visibility_qualified(&item.vis, "static"))?;
566 if m == hir::MutMutable {
567 self.word_space("mut")?;
569 self.print_name(item.name)?;
570 self.word_space(":")?;
571 self.print_type(&ty)?;
573 self.end()?; // end the head-ibox
575 self.word_space("=")?;
576 self.ann.nested(self, Nested::Body(expr))?;
578 self.end()?; // end the outer cbox
580 hir::ItemKind::Const(ref ty, expr) => {
581 self.head(&visibility_qualified(&item.vis, "const"))?;
582 self.print_name(item.name)?;
583 self.word_space(":")?;
584 self.print_type(&ty)?;
586 self.end()?; // end the head-ibox
588 self.word_space("=")?;
589 self.ann.nested(self, Nested::Body(expr))?;
591 self.end()?; // end the outer cbox
593 hir::ItemKind::Fn(ref decl, header, ref typarams, body) => {
603 self.end()?; // need to close a box
604 self.end()?; // need to close a box
605 self.ann.nested(self, Nested::Body(body))?;
607 hir::ItemKind::Mod(ref _mod) => {
608 self.head(&visibility_qualified(&item.vis, "mod"))?;
609 self.print_name(item.name)?;
612 self.print_mod(_mod, &item.attrs)?;
613 self.bclose(item.span)?;
615 hir::ItemKind::ForeignMod(ref nmod) => {
616 self.head("extern")?;
617 self.word_nbsp(&nmod.abi.to_string())?;
619 self.print_foreign_mod(nmod, &item.attrs)?;
620 self.bclose(item.span)?;
622 hir::ItemKind::GlobalAsm(ref ga) => {
623 self.head(&visibility_qualified(&item.vis, "global asm"))?;
624 self.s.word(&ga.asm.as_str())?;
627 hir::ItemKind::Ty(ref ty, ref generics) => {
628 self.head(&visibility_qualified(&item.vis, "type"))?;
629 self.print_name(item.name)?;
630 self.print_generic_params(&generics.params)?;
631 self.end()?; // end the inner ibox
633 self.print_where_clause(&generics.where_clause)?;
635 self.word_space("=")?;
636 self.print_type(&ty)?;
638 self.end()?; // end the outer ibox
640 hir::ItemKind::Existential(ref exist) => {
641 self.head(&visibility_qualified(&item.vis, "existential type"))?;
642 self.print_name(item.name)?;
643 self.print_generic_params(&exist.generics.params)?;
644 self.end()?; // end the inner ibox
646 self.print_where_clause(&exist.generics.where_clause)?;
648 self.word_space(":")?;
649 let mut real_bounds = Vec::with_capacity(exist.bounds.len());
650 for b in exist.bounds.iter() {
651 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
653 self.word_space("for ?")?;
654 self.print_trait_ref(&ptr.trait_ref)?;
656 real_bounds.push(b.clone());
659 self.print_bounds(":", &real_bounds[..])?;
661 self.end()?; // end the outer ibox
663 hir::ItemKind::Enum(ref enum_definition, ref params) => {
664 self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
666 hir::ItemKind::Struct(ref struct_def, ref generics) => {
667 self.head(&visibility_qualified(&item.vis, "struct"))?;
668 self.print_struct(struct_def, generics, item.name, item.span, true)?;
670 hir::ItemKind::Union(ref struct_def, ref generics) => {
671 self.head(&visibility_qualified(&item.vis, "union"))?;
672 self.print_struct(struct_def, generics, item.name, item.span, true)?;
674 hir::ItemKind::Impl(unsafety,
682 self.print_visibility(&item.vis)?;
683 self.print_defaultness(defaultness)?;
684 self.print_unsafety(unsafety)?;
685 self.word_nbsp("impl")?;
687 if !generics.params.is_empty() {
688 self.print_generic_params(&generics.params)?;
693 hir::ImplPolarity::Negative => {
701 self.print_trait_ref(t)?;
703 self.word_space("for")?;
708 self.print_type(&ty)?;
709 self.print_where_clause(&generics.where_clause)?;
713 self.print_inner_attributes(&item.attrs)?;
714 for impl_item in impl_items {
715 self.ann.nested(self, Nested::ImplItem(impl_item.id))?;
717 self.bclose(item.span)?;
719 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
721 self.print_visibility(&item.vis)?;
722 self.print_is_auto(is_auto)?;
723 self.print_unsafety(unsafety)?;
724 self.word_nbsp("trait")?;
725 self.print_name(item.name)?;
726 self.print_generic_params(&generics.params)?;
727 let mut real_bounds = Vec::with_capacity(bounds.len());
728 for b in bounds.iter() {
729 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
731 self.word_space("for ?")?;
732 self.print_trait_ref(&ptr.trait_ref)?;
734 real_bounds.push(b.clone());
737 self.print_bounds(":", &real_bounds[..])?;
738 self.print_where_clause(&generics.where_clause)?;
741 for trait_item in trait_items {
742 self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
744 self.bclose(item.span)?;
746 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
748 self.print_visibility(&item.vis)?;
749 self.word_nbsp("trait")?;
750 self.print_name(item.name)?;
751 self.print_generic_params(&generics.params)?;
752 let mut real_bounds = Vec::with_capacity(bounds.len());
753 // FIXME(durka) this seems to be some quite outdated syntax
754 for b in bounds.iter() {
755 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
757 self.word_space("for ?")?;
758 self.print_trait_ref(&ptr.trait_ref)?;
760 real_bounds.push(b.clone());
764 self.print_bounds("=", &real_bounds[..])?;
765 self.print_where_clause(&generics.where_clause)?;
769 self.ann.post(self, AnnNode::Item(item))
772 pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
773 self.print_path(&t.path, false)
776 fn print_formal_generic_params(
778 generic_params: &[hir::GenericParam]
779 ) -> io::Result<()> {
780 if !generic_params.is_empty() {
782 self.print_generic_params(generic_params)?;
788 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
789 self.print_formal_generic_params(&t.bound_generic_params)?;
790 self.print_trait_ref(&t.trait_ref)
793 pub fn print_enum_def(&mut self,
794 enum_definition: &hir::EnumDef,
795 generics: &hir::Generics,
797 span: syntax_pos::Span,
798 visibility: &hir::Visibility)
800 self.head(&visibility_qualified(visibility, "enum"))?;
801 self.print_name(name)?;
802 self.print_generic_params(&generics.params)?;
803 self.print_where_clause(&generics.where_clause)?;
805 self.print_variants(&enum_definition.variants, span)
808 pub fn print_variants(&mut self,
809 variants: &[hir::Variant],
810 span: syntax_pos::Span)
814 self.space_if_not_bol()?;
815 self.maybe_print_comment(v.span.lo())?;
816 self.print_outer_attributes(&v.node.attrs)?;
817 self.ibox(indent_unit)?;
818 self.print_variant(v)?;
821 self.maybe_print_trailing_comment(v.span, None)?;
826 pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
828 hir::VisibilityKind::Public => self.word_nbsp("pub")?,
829 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate")?,
830 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)")?,
831 hir::VisibilityKind::Restricted { ref path, .. } => {
832 self.s.word("pub(")?;
833 if path.segments.len() == 1 &&
834 path.segments[0].ident.name == keywords::Super.name() {
835 // Special case: `super` can print like `pub(super)`.
836 self.s.word("super")?;
838 // Everything else requires `in` at present.
839 self.word_nbsp("in")?;
840 self.print_path(path, false)?;
842 self.word_nbsp(")")?;
844 hir::VisibilityKind::Inherited => ()
850 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) -> io::Result<()> {
852 hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
853 hir::Defaultness::Final => (),
858 pub fn print_struct(&mut self,
859 struct_def: &hir::VariantData,
860 generics: &hir::Generics,
862 span: syntax_pos::Span,
863 print_finalizer: bool)
865 self.print_name(name)?;
866 self.print_generic_params(&generics.params)?;
867 if !struct_def.is_struct() {
868 if struct_def.is_tuple() {
870 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
871 s.maybe_print_comment(field.span.lo())?;
872 s.print_outer_attributes(&field.attrs)?;
873 s.print_visibility(&field.vis)?;
874 s.print_type(&field.ty)
878 self.print_where_clause(&generics.where_clause)?;
883 self.end() // close the outer-box
885 self.print_where_clause(&generics.where_clause)?;
888 self.hardbreak_if_not_bol()?;
890 for field in struct_def.fields() {
891 self.hardbreak_if_not_bol()?;
892 self.maybe_print_comment(field.span.lo())?;
893 self.print_outer_attributes(&field.attrs)?;
894 self.print_visibility(&field.vis)?;
895 self.print_ident(field.ident)?;
896 self.word_nbsp(":")?;
897 self.print_type(&field.ty)?;
905 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
907 let generics = hir::Generics::empty();
908 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
909 if let Some(ref d) = v.node.disr_expr {
911 self.word_space("=")?;
912 self.print_anon_const(d)?;
916 pub fn print_method_sig(&mut self,
919 generics: &hir::Generics,
920 vis: &hir::Visibility,
921 arg_names: &[ast::Ident],
922 body_id: Option<hir::BodyId>)
924 self.print_fn(&m.decl,
933 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
934 self.ann.pre(self, AnnNode::SubItem(ti.id))?;
935 self.hardbreak_if_not_bol()?;
936 self.maybe_print_comment(ti.span.lo())?;
937 self.print_outer_attributes(&ti.attrs)?;
939 hir::TraitItemKind::Const(ref ty, default) => {
940 let vis = Spanned { span: syntax_pos::DUMMY_SP,
941 node: hir::VisibilityKind::Inherited };
942 self.print_associated_const(ti.ident, &ty, default, &vis)?;
944 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
945 let vis = Spanned { span: syntax_pos::DUMMY_SP,
946 node: hir::VisibilityKind::Inherited };
947 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None)?;
950 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
951 let vis = Spanned { span: syntax_pos::DUMMY_SP,
952 node: hir::VisibilityKind::Inherited };
954 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body))?;
956 self.end()?; // need to close a box
957 self.end()?; // need to close a box
958 self.ann.nested(self, Nested::Body(body))?;
960 hir::TraitItemKind::Type(ref bounds, ref default) => {
961 self.print_associated_type(ti.ident,
963 default.as_ref().map(|ty| &**ty))?;
966 self.ann.post(self, AnnNode::SubItem(ti.id))
969 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
970 self.ann.pre(self, AnnNode::SubItem(ii.id))?;
971 self.hardbreak_if_not_bol()?;
972 self.maybe_print_comment(ii.span.lo())?;
973 self.print_outer_attributes(&ii.attrs)?;
974 self.print_defaultness(ii.defaultness)?;
977 hir::ImplItemKind::Const(ref ty, expr) => {
978 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis)?;
980 hir::ImplItemKind::Method(ref sig, body) => {
982 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body))?;
984 self.end()?; // need to close a box
985 self.end()?; // need to close a box
986 self.ann.nested(self, Nested::Body(body))?;
988 hir::ImplItemKind::Type(ref ty) => {
989 self.print_associated_type(ii.ident, None, Some(ty))?;
991 hir::ImplItemKind::Existential(ref bounds) => {
992 self.word_space("existential")?;
993 self.print_associated_type(ii.ident, Some(bounds), None)?;
996 self.ann.post(self, AnnNode::SubItem(ii.id))
999 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1000 self.maybe_print_comment(st.span.lo())?;
1002 hir::StmtKind::Decl(ref decl, _) => {
1003 self.print_decl(&decl)?;
1005 hir::StmtKind::Expr(ref expr, _) => {
1006 self.space_if_not_bol()?;
1007 self.print_expr(&expr)?;
1009 hir::StmtKind::Semi(ref expr, _) => {
1010 self.space_if_not_bol()?;
1011 self.print_expr(&expr)?;
1015 if stmt_ends_with_semi(&st.node) {
1018 self.maybe_print_trailing_comment(st.span, None)
1021 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1022 self.print_block_with_attrs(blk, &[])
1025 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1026 self.print_block_unclosed_indent(blk, indent_unit)
1029 pub fn print_block_unclosed_indent(&mut self,
1033 self.print_block_maybe_unclosed(blk, indented, &[], false)
1036 pub fn print_block_with_attrs(&mut self,
1038 attrs: &[ast::Attribute])
1040 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1043 pub fn print_block_maybe_unclosed(&mut self,
1046 attrs: &[ast::Attribute],
1050 hir::UnsafeBlock(..) => self.word_space("unsafe")?,
1051 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
1052 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
1053 hir::DefaultBlock => (),
1055 self.maybe_print_comment(blk.span.lo())?;
1056 self.ann.pre(self, AnnNode::Block(blk))?;
1059 self.print_inner_attributes(attrs)?;
1061 for st in &blk.stmts {
1062 self.print_stmt(st)?;
1066 self.space_if_not_bol()?;
1067 self.print_expr(&expr)?;
1068 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1072 self.bclose_maybe_open(blk.span, indented, close_box)?;
1073 self.ann.post(self, AnnNode::Block(blk))
1076 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1080 // "another else-if"
1081 hir::ExprKind::If(ref i, ref then, ref e) => {
1082 self.cbox(indent_unit - 1)?;
1084 self.s.word(" else if ")?;
1085 self.print_expr_as_cond(&i)?;
1087 self.print_expr(&then)?;
1088 self.print_else(e.as_ref().map(|e| &**e))
1091 hir::ExprKind::Block(ref b, _) => {
1092 self.cbox(indent_unit - 1)?;
1094 self.s.word(" else ")?;
1095 self.print_block(&b)
1097 // BLEAH, constraints would be great here
1099 panic!("print_if saw if with weird alternative");
1107 pub fn print_if(&mut self,
1110 elseopt: Option<&hir::Expr>)
1113 self.print_expr_as_cond(test)?;
1115 self.print_expr(blk)?;
1116 self.print_else(elseopt)
1119 pub fn print_if_let(&mut self,
1123 elseopt: Option<&hir::Expr>)
1125 self.head("if let")?;
1126 self.print_pat(pat)?;
1128 self.word_space("=")?;
1129 self.print_expr_as_cond(expr)?;
1131 self.print_block(blk)?;
1132 self.print_else(elseopt)
1135 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) -> io::Result<()> {
1136 self.ann.nested(self, Nested::Body(constant.body))
1139 fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
1141 self.commasep_exprs(Inconsistent, args)?;
1145 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr, prec: i8) -> io::Result<()> {
1146 let needs_par = expr.precedence().order() < prec;
1150 self.print_expr(expr)?;
1157 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1158 /// `if cond { ... }`.
1159 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr) -> io::Result<()> {
1160 let needs_par = match expr.node {
1161 // These cases need parens due to the parse error observed in #26461: `if return {}`
1162 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1163 hir::ExprKind::Closure(..) |
1164 hir::ExprKind::Ret(..) |
1165 hir::ExprKind::Break(..) => true,
1167 _ => contains_exterior_struct_lit(expr),
1173 self.print_expr(expr)?;
1180 fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1181 self.ibox(indent_unit)?;
1183 self.commasep_exprs(Inconsistent, exprs)?;
1188 fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::AnonConst) -> io::Result<()> {
1189 self.ibox(indent_unit)?;
1191 self.print_expr(element)?;
1192 self.word_space(";")?;
1193 self.print_anon_const(count)?;
1198 fn print_expr_struct(&mut self,
1200 fields: &[hir::Field],
1201 wth: &Option<P<hir::Expr>>)
1203 self.print_qpath(qpath, true)?;
1205 self.commasep_cmnt(Consistent,
1208 s.ibox(indent_unit)?;
1209 if !field.is_shorthand {
1210 s.print_ident(field.ident)?;
1213 s.print_expr(&field.expr)?;
1219 self.ibox(indent_unit)?;
1220 if !fields.is_empty() {
1225 self.print_expr(&expr)?;
1228 _ => if !fields.is_empty() {
1236 fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1238 self.commasep_exprs(Inconsistent, exprs)?;
1239 if exprs.len() == 1 {
1245 fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1248 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1249 _ => parser::PREC_POSTFIX,
1252 self.print_expr_maybe_paren(func, prec)?;
1253 self.print_call_post(args)
1256 fn print_expr_method_call(&mut self,
1257 segment: &hir::PathSegment,
1260 let base_args = &args[1..];
1261 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
1263 self.print_ident(segment.ident)?;
1265 segment.with_generic_args(|generic_args| {
1266 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1267 return self.print_generic_args(&generic_args, segment.infer_types, true);
1271 self.print_call_post(base_args)
1274 fn print_expr_binary(&mut self,
1279 let assoc_op = bin_op_to_assoc_op(op.node);
1280 let prec = assoc_op.precedence() as i8;
1281 let fixity = assoc_op.fixity();
1283 let (left_prec, right_prec) = match fixity {
1284 Fixity::Left => (prec, prec + 1),
1285 Fixity::Right => (prec + 1, prec),
1286 Fixity::None => (prec + 1, prec + 1),
1289 let left_prec = match (&lhs.node, op.node) {
1290 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1291 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1292 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1293 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt) |
1294 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1298 self.print_expr_maybe_paren(lhs, left_prec)?;
1300 self.word_space(op.node.as_str())?;
1301 self.print_expr_maybe_paren(rhs, right_prec)
1304 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1305 self.s.word(op.as_str())?;
1306 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1309 fn print_expr_addr_of(&mut self,
1310 mutability: hir::Mutability,
1314 self.print_mutability(mutability)?;
1315 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1318 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1319 self.maybe_print_comment(expr.span.lo())?;
1320 self.print_outer_attributes(&expr.attrs)?;
1321 self.ibox(indent_unit)?;
1322 self.ann.pre(self, AnnNode::Expr(expr))?;
1324 hir::ExprKind::Box(ref expr) => {
1325 self.word_space("box")?;
1326 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
1328 hir::ExprKind::Array(ref exprs) => {
1329 self.print_expr_vec(exprs)?;
1331 hir::ExprKind::Repeat(ref element, ref count) => {
1332 self.print_expr_repeat(&element, count)?;
1334 hir::ExprKind::Struct(ref qpath, ref fields, ref wth) => {
1335 self.print_expr_struct(qpath, &fields[..], wth)?;
1337 hir::ExprKind::Tup(ref exprs) => {
1338 self.print_expr_tup(exprs)?;
1340 hir::ExprKind::Call(ref func, ref args) => {
1341 self.print_expr_call(&func, args)?;
1343 hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1344 self.print_expr_method_call(segment, args)?;
1346 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1347 self.print_expr_binary(op, &lhs, &rhs)?;
1349 hir::ExprKind::Unary(op, ref expr) => {
1350 self.print_expr_unary(op, &expr)?;
1352 hir::ExprKind::AddrOf(m, ref expr) => {
1353 self.print_expr_addr_of(m, &expr)?;
1355 hir::ExprKind::Lit(ref lit) => {
1356 self.print_literal(&lit)?;
1358 hir::ExprKind::Cast(ref expr, ref ty) => {
1359 let prec = AssocOp::As.precedence() as i8;
1360 self.print_expr_maybe_paren(&expr, prec)?;
1362 self.word_space("as")?;
1363 self.print_type(&ty)?;
1365 hir::ExprKind::Type(ref expr, ref ty) => {
1366 let prec = AssocOp::Colon.precedence() as i8;
1367 self.print_expr_maybe_paren(&expr, prec)?;
1368 self.word_space(":")?;
1369 self.print_type(&ty)?;
1371 hir::ExprKind::If(ref test, ref blk, ref elseopt) => {
1372 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1374 hir::ExprKind::While(ref test, ref blk, opt_label) => {
1375 if let Some(label) = opt_label {
1376 self.print_ident(label.ident)?;
1377 self.word_space(":")?;
1379 self.head("while")?;
1380 self.print_expr_as_cond(&test)?;
1382 self.print_block(&blk)?;
1384 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1385 if let Some(label) = opt_label {
1386 self.print_ident(label.ident)?;
1387 self.word_space(":")?;
1391 self.print_block(&blk)?;
1393 hir::ExprKind::Match(ref expr, ref arms, _) => {
1394 self.cbox(indent_unit)?;
1396 self.word_nbsp("match")?;
1397 self.print_expr_as_cond(&expr)?;
1401 self.print_arm(arm)?;
1403 self.bclose_(expr.span, indent_unit)?;
1405 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1406 self.print_capture_clause(capture_clause)?;
1408 self.print_closure_args(&decl, body)?;
1411 // this is a bare expression
1412 self.ann.nested(self, Nested::Body(body))?;
1413 self.end()?; // need to close a box
1415 // a box will be closed by print_expr, but we didn't want an overall
1416 // wrapper so we closed the corresponding opening. so create an
1417 // empty box to satisfy the close.
1420 hir::ExprKind::Block(ref blk, opt_label) => {
1421 if let Some(label) = opt_label {
1422 self.print_ident(label.ident)?;
1423 self.word_space(":")?;
1425 // containing cbox, will be closed by print-block at }
1426 self.cbox(indent_unit)?;
1427 // head-box, will be closed by print-block after {
1429 self.print_block(&blk)?;
1431 hir::ExprKind::Assign(ref lhs, ref rhs) => {
1432 let prec = AssocOp::Assign.precedence() as i8;
1433 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1435 self.word_space("=")?;
1436 self.print_expr_maybe_paren(&rhs, prec)?;
1438 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1439 let prec = AssocOp::Assign.precedence() as i8;
1440 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1442 self.s.word(op.node.as_str())?;
1443 self.word_space("=")?;
1444 self.print_expr_maybe_paren(&rhs, prec)?;
1446 hir::ExprKind::Field(ref expr, ident) => {
1447 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
1449 self.print_ident(ident)?;
1451 hir::ExprKind::Index(ref expr, ref index) => {
1452 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1454 self.print_expr(&index)?;
1457 hir::ExprKind::Path(ref qpath) => {
1458 self.print_qpath(qpath, true)?
1460 hir::ExprKind::Break(destination, ref opt_expr) => {
1461 self.s.word("break")?;
1463 if let Some(label) = destination.label {
1464 self.print_ident(label.ident)?;
1467 if let Some(ref expr) = *opt_expr {
1468 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
1472 hir::ExprKind::Continue(destination) => {
1473 self.s.word("continue")?;
1475 if let Some(label) = destination.label {
1476 self.print_ident(label.ident)?;
1480 hir::ExprKind::Ret(ref result) => {
1481 self.s.word("return")?;
1485 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1490 hir::ExprKind::InlineAsm(ref a, ref outputs, ref inputs) => {
1491 self.s.word("asm!")?;
1493 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
1494 self.word_space(":")?;
1496 let mut out_idx = 0;
1497 self.commasep(Inconsistent, &a.outputs, |s, out| {
1498 let constraint = out.constraint.as_str();
1499 let mut ch = constraint.chars();
1501 Some('=') if out.is_rw => {
1502 s.print_string(&format!("+{}", ch.as_str()),
1503 ast::StrStyle::Cooked)?
1505 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
1508 s.print_expr(&outputs[out_idx])?;
1514 self.word_space(":")?;
1517 self.commasep(Inconsistent, &a.inputs, |s, co| {
1518 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1520 s.print_expr(&inputs[in_idx])?;
1526 self.word_space(":")?;
1528 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1529 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1533 let mut options = vec![];
1535 options.push("volatile");
1538 options.push("alignstack");
1540 if a.dialect == ast::AsmDialect::Intel {
1541 options.push("intel");
1544 if !options.is_empty() {
1546 self.word_space(":")?;
1547 self.commasep(Inconsistent, &options, |s, &co| {
1548 s.print_string(co, ast::StrStyle::Cooked)?;
1555 hir::ExprKind::Yield(ref expr) => {
1556 self.word_space("yield")?;
1557 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1560 self.ann.post(self, AnnNode::Expr(expr))?;
1564 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1565 self.print_pat(&loc.pat)?;
1566 if let Some(ref ty) = loc.ty {
1567 self.word_space(":")?;
1568 self.print_type(&ty)?;
1573 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1574 self.maybe_print_comment(decl.span.lo())?;
1576 hir::DeclKind::Local(ref loc) => {
1577 self.space_if_not_bol()?;
1578 self.ibox(indent_unit)?;
1579 self.word_nbsp("let")?;
1581 self.ibox(indent_unit)?;
1582 self.print_local_decl(&loc)?;
1584 if let Some(ref init) = loc.init {
1586 self.word_space("=")?;
1587 self.print_expr(&init)?;
1591 hir::DeclKind::Item(item) => {
1592 self.ann.nested(self, Nested::Item(item))
1597 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1598 self.s.word(&i.to_string())
1601 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
1602 if ident.is_raw_guess() {
1603 self.s.word(&format!("r#{}", ident.name))?;
1605 self.s.word(&ident.as_str())?;
1607 self.ann.post(self, AnnNode::Name(&ident.name))
1610 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1611 self.print_ident(ast::Ident::with_empty_ctxt(name))
1614 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1615 self.print_local_decl(loc)?;
1617 self.word_space("in")?;
1618 self.print_expr(coll)
1621 pub fn print_path(&mut self,
1623 colons_before_params: bool)
1625 self.maybe_print_comment(path.span.lo())?;
1627 for (i, segment) in path.segments.iter().enumerate() {
1631 if segment.ident.name != keywords::CrateRoot.name() &&
1632 segment.ident.name != keywords::DollarCrate.name() {
1633 self.print_ident(segment.ident)?;
1634 segment.with_generic_args(|generic_args| {
1635 self.print_generic_args(generic_args, segment.infer_types,
1636 colons_before_params)
1644 pub fn print_qpath(&mut self,
1646 colons_before_params: bool)
1649 hir::QPath::Resolved(None, ref path) => {
1650 self.print_path(path, colons_before_params)
1652 hir::QPath::Resolved(Some(ref qself), ref path) => {
1654 self.print_type(qself)?;
1656 self.word_space("as")?;
1658 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1662 if segment.ident.name != keywords::CrateRoot.name() &&
1663 segment.ident.name != keywords::DollarCrate.name() {
1664 self.print_ident(segment.ident)?;
1665 segment.with_generic_args(|generic_args| {
1666 self.print_generic_args(generic_args,
1667 segment.infer_types,
1668 colons_before_params)
1675 let item_segment = path.segments.last().unwrap();
1676 self.print_ident(item_segment.ident)?;
1677 item_segment.with_generic_args(|generic_args| {
1678 self.print_generic_args(generic_args,
1679 item_segment.infer_types,
1680 colons_before_params)
1683 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1685 self.print_type(qself)?;
1688 self.print_ident(item_segment.ident)?;
1689 item_segment.with_generic_args(|generic_args| {
1690 self.print_generic_args(generic_args,
1691 item_segment.infer_types,
1692 colons_before_params)
1698 fn print_generic_args(&mut self,
1699 generic_args: &hir::GenericArgs,
1701 colons_before_params: bool)
1703 if generic_args.parenthesized {
1705 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty))?;
1708 self.space_if_not_bol()?;
1709 self.word_space("->")?;
1710 self.print_type(&generic_args.bindings[0].ty)?;
1712 let start = if colons_before_params { "::<" } else { "<" };
1713 let empty = Cell::new(true);
1714 let start_or_comma = |this: &mut Self| {
1719 this.word_space(",")
1723 let mut types = vec![];
1724 let mut elide_lifetimes = true;
1725 for arg in &generic_args.args {
1727 GenericArg::Lifetime(lt) => {
1728 if !lt.is_elided() {
1729 elide_lifetimes = false;
1732 GenericArg::Type(ty) => {
1737 if !elide_lifetimes {
1738 start_or_comma(self)?;
1739 self.commasep(Inconsistent, &generic_args.args, |s, generic_arg| {
1741 GenericArg::Lifetime(lt) => s.print_lifetime(lt),
1742 GenericArg::Type(ty) => s.print_type(ty),
1745 } else if !types.is_empty() {
1746 start_or_comma(self)?;
1747 self.commasep(Inconsistent, &types, |s, ty| s.print_type(&ty))?;
1750 // FIXME(eddyb) This would leak into error messages, e.g.:
1751 // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1752 if infer_types && false {
1753 start_or_comma(self)?;
1757 for binding in generic_args.bindings.iter() {
1758 start_or_comma(self)?;
1759 self.print_ident(binding.ident)?;
1761 self.word_space("=")?;
1762 self.print_type(&binding.ty)?;
1773 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1774 self.maybe_print_comment(pat.span.lo())?;
1775 self.ann.pre(self, AnnNode::Pat(pat))?;
1776 // Pat isn't normalized, but the beauty of it
1777 // is that it doesn't matter
1779 PatKind::Wild => self.s.word("_")?,
1780 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1781 match binding_mode {
1782 hir::BindingAnnotation::Ref => {
1783 self.word_nbsp("ref")?;
1784 self.print_mutability(hir::MutImmutable)?;
1786 hir::BindingAnnotation::RefMut => {
1787 self.word_nbsp("ref")?;
1788 self.print_mutability(hir::MutMutable)?;
1790 hir::BindingAnnotation::Unannotated => {}
1791 hir::BindingAnnotation::Mutable => {
1792 self.word_nbsp("mut")?;
1795 self.print_ident(ident)?;
1796 if let Some(ref p) = *sub {
1798 self.print_pat(&p)?;
1801 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1802 self.print_qpath(qpath, true)?;
1804 if let Some(ddpos) = ddpos {
1805 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1807 self.word_space(",")?;
1810 if ddpos != elts.len() {
1812 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1815 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1819 PatKind::Path(ref qpath) => {
1820 self.print_qpath(qpath, true)?;
1822 PatKind::Struct(ref qpath, ref fields, etc) => {
1823 self.print_qpath(qpath, true)?;
1825 self.word_space("{")?;
1826 self.commasep_cmnt(Consistent,
1829 s.cbox(indent_unit)?;
1830 if !f.node.is_shorthand {
1831 s.print_ident(f.node.ident)?;
1834 s.print_pat(&f.node.pat)?;
1837 |f| f.node.pat.span)?;
1839 if !fields.is_empty() {
1840 self.word_space(",")?;
1847 PatKind::Tuple(ref elts, ddpos) => {
1849 if let Some(ddpos) = ddpos {
1850 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1852 self.word_space(",")?;
1855 if ddpos != elts.len() {
1857 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1860 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1861 if elts.len() == 1 {
1867 PatKind::Box(ref inner) => {
1868 let is_range_inner = match inner.node {
1869 PatKind::Range(..) => true,
1872 self.s.word("box ")?;
1876 self.print_pat(&inner)?;
1881 PatKind::Ref(ref inner, mutbl) => {
1882 let is_range_inner = match inner.node {
1883 PatKind::Range(..) => true,
1887 if mutbl == hir::MutMutable {
1888 self.s.word("mut ")?;
1893 self.print_pat(&inner)?;
1898 PatKind::Lit(ref e) => self.print_expr(&e)?,
1899 PatKind::Range(ref begin, ref end, ref end_kind) => {
1900 self.print_expr(&begin)?;
1903 RangeEnd::Included => self.s.word("...")?,
1904 RangeEnd::Excluded => self.s.word("..")?,
1906 self.print_expr(&end)?;
1908 PatKind::Slice(ref before, ref slice, ref after) => {
1910 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1911 if let Some(ref p) = *slice {
1912 if !before.is_empty() {
1913 self.word_space(",")?;
1915 if let PatKind::Wild = p.node {
1918 self.print_pat(&p)?;
1921 if !after.is_empty() {
1922 self.word_space(",")?;
1925 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1929 self.ann.post(self, AnnNode::Pat(pat))
1932 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1933 // I have no idea why this check is necessary, but here it
1935 if arm.attrs.is_empty() {
1938 self.cbox(indent_unit)?;
1940 self.print_outer_attributes(&arm.attrs)?;
1941 let mut first = true;
1942 for p in &arm.pats {
1947 self.word_space("|")?;
1949 self.print_pat(&p)?;
1952 if let Some(ref g) = arm.guard {
1954 hir::Guard::If(e) => {
1955 self.word_space("if")?;
1956 self.print_expr(&e)?;
1961 self.word_space("=>")?;
1963 match arm.body.node {
1964 hir::ExprKind::Block(ref blk, opt_label) => {
1965 if let Some(label) = opt_label {
1966 self.print_ident(label.ident)?;
1967 self.word_space(":")?;
1969 // the block will close the pattern's ibox
1970 self.print_block_unclosed_indent(&blk, indent_unit)?;
1972 // If it is a user-provided unsafe block, print a comma after it
1973 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1978 self.end()?; // close the ibox for the pattern
1979 self.print_expr(&arm.body)?;
1983 self.end() // close enclosing cbox
1986 pub fn print_fn(&mut self,
1988 header: hir::FnHeader,
1989 name: Option<ast::Name>,
1990 generics: &hir::Generics,
1991 vis: &hir::Visibility,
1992 arg_names: &[ast::Ident],
1993 body_id: Option<hir::BodyId>)
1995 self.print_fn_header_info(header, vis)?;
1997 if let Some(name) = name {
1999 self.print_name(name)?;
2001 self.print_generic_params(&generics.params)?;
2005 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2006 assert!(arg_names.is_empty() || body_id.is_none());
2007 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2008 s.ibox(indent_unit)?;
2009 if let Some(arg_name) = arg_names.get(i) {
2010 s.s.word(&arg_name.as_str())?;
2013 } else if let Some(body_id) = body_id {
2014 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2023 self.s.word(", ...")?;
2027 self.print_fn_output(decl)?;
2028 self.print_where_clause(&generics.where_clause)
2031 fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
2034 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2035 s.ibox(indent_unit)?;
2037 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2040 if let hir::TyKind::Infer = ty.node {
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,
2271 node: hir::VisibilityKind::Inherited },
2277 pub fn maybe_print_trailing_comment(&mut self,
2278 span: syntax_pos::Span,
2279 next_pos: Option<BytePos>)
2281 let cm = match self.cm {
2285 if let Some(ref cmnt) = self.next_comment() {
2286 if (*cmnt).style != comments::Trailing {
2289 let span_line = cm.lookup_char_pos(span.hi());
2290 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2291 let mut next = (*cmnt).pos + BytePos(1);
2292 if let Some(p) = next_pos {
2295 if span.hi() < (*cmnt).pos && (*cmnt).pos < next &&
2296 span_line.line == comment_line.line {
2297 self.print_comment(cmnt)?;
2303 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2304 // If there aren't any remaining comments, then we need to manually
2305 // make sure there is a line break at the end.
2306 if self.next_comment().is_none() {
2307 self.s.hardbreak()?;
2309 while let Some(ref cmnt) = self.next_comment() {
2310 self.print_comment(cmnt)?
2315 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2316 opt_abi: Option<Abi>)
2319 Some(Abi::Rust) => Ok(()),
2321 self.word_nbsp("extern")?;
2322 self.word_nbsp(&abi.to_string())
2328 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2331 self.word_nbsp("extern")?;
2332 self.word_nbsp(&abi.to_string())
2338 pub fn print_fn_header_info(&mut self,
2339 header: hir::FnHeader,
2340 vis: &hir::Visibility)
2342 self.s.word(&visibility_qualified(vis, ""))?;
2344 match header.constness {
2345 hir::Constness::NotConst => {}
2346 hir::Constness::Const => self.word_nbsp("const")?,
2349 match header.asyncness {
2350 hir::IsAsync::NotAsync => {}
2351 hir::IsAsync::Async => self.word_nbsp("async")?,
2354 self.print_unsafety(header.unsafety)?;
2356 if header.abi != Abi::Rust {
2357 self.word_nbsp("extern")?;
2358 self.word_nbsp(&header.abi.to_string())?;
2364 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2366 hir::Unsafety::Normal => Ok(()),
2367 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2371 pub fn print_is_auto(&mut self, s: hir::IsAuto) -> io::Result<()> {
2373 hir::IsAuto::Yes => self.word_nbsp("auto"),
2374 hir::IsAuto::No => Ok(()),
2379 // Dup'ed from parse::classify, but adapted for the HIR.
2380 /// Does this expression require a semicolon to be treated
2381 /// as a statement? The negation of this: 'can this expression
2382 /// be used as a statement without a semicolon' -- is used
2383 /// as an early-bail-out in the parser so that, for instance,
2384 /// if true {...} else {...}
2386 /// isn't parsed as (if true {...} else {...} | x) | 5
2387 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2389 hir::ExprKind::If(..) |
2390 hir::ExprKind::Match(..) |
2391 hir::ExprKind::Block(..) |
2392 hir::ExprKind::While(..) |
2393 hir::ExprKind::Loop(..) => false,
2398 /// this statement requires a semicolon after it.
2399 /// note that in one case (stmt_semi), we've already
2400 /// seen the semicolon, and thus don't need another.
2401 fn stmt_ends_with_semi(stmt: &hir::StmtKind) -> bool {
2403 hir::StmtKind::Decl(ref d, _) => {
2405 hir::DeclKind::Local(_) => true,
2406 hir::DeclKind::Item(_) => false,
2409 hir::StmtKind::Expr(ref e, _) => {
2410 expr_requires_semi_to_be_stmt(&e)
2412 hir::StmtKind::Semi(..) => {
2418 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2419 use hir::BinOpKind::*;
2421 Add => AssocOp::Add,
2422 Sub => AssocOp::Subtract,
2423 Mul => AssocOp::Multiply,
2424 Div => AssocOp::Divide,
2425 Rem => AssocOp::Modulus,
2427 And => AssocOp::LAnd,
2430 BitXor => AssocOp::BitXor,
2431 BitAnd => AssocOp::BitAnd,
2432 BitOr => AssocOp::BitOr,
2433 Shl => AssocOp::ShiftLeft,
2434 Shr => AssocOp::ShiftRight,
2436 Eq => AssocOp::Equal,
2437 Lt => AssocOp::Less,
2438 Le => AssocOp::LessEqual,
2439 Ne => AssocOp::NotEqual,
2440 Ge => AssocOp::GreaterEqual,
2441 Gt => AssocOp::Greater,
2445 /// Expressions that syntactically contain an "exterior" struct literal i.e. not surrounded by any
2446 /// parens or other delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2447 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2448 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
2450 hir::ExprKind::Struct(..) => true,
2452 hir::ExprKind::Assign(ref lhs, ref rhs) |
2453 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) |
2454 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2455 // X { y: 1 } + X { y: 2 }
2456 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2458 hir::ExprKind::Unary(_, ref x) |
2459 hir::ExprKind::Cast(ref x, _) |
2460 hir::ExprKind::Type(ref x, _) |
2461 hir::ExprKind::Field(ref x, _) |
2462 hir::ExprKind::Index(ref x, _) => {
2463 // &X { y: 1 }, X { y: 1 }.y
2464 contains_exterior_struct_lit(&x)
2467 hir::ExprKind::MethodCall(.., ref exprs) => {
2468 // X { y: 1 }.bar(...)
2469 contains_exterior_struct_lit(&exprs[0])