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),
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::Def(..) => {},
405 hir::TyKind::Path(ref qpath) => {
406 self.print_qpath(qpath, false)?
408 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
409 let mut first = true;
410 for bound in bounds {
415 self.word_space("+")?;
417 self.print_poly_trait_ref(bound)?;
419 if !lifetime.is_elided() {
421 self.word_space("+")?;
422 self.print_lifetime(lifetime)?;
425 hir::TyKind::Array(ref ty, ref length) => {
427 self.print_type(&ty)?;
429 self.print_anon_const(length)?;
432 hir::TyKind::Typeof(ref e) => {
433 self.s.word("typeof(")?;
434 self.print_anon_const(e)?;
437 hir::TyKind::Infer => {
440 hir::TyKind::Err => {
447 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
448 self.hardbreak_if_not_bol()?;
449 self.maybe_print_comment(item.span.lo())?;
450 self.print_outer_attributes(&item.attrs)?;
452 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
456 unsafety: hir::Unsafety::Normal,
457 constness: hir::Constness::NotConst,
459 asyncness: hir::IsAsync::NotAsync,
466 self.end()?; // end head-ibox
468 self.end() // end the outer fn box
470 hir::ForeignItemKind::Static(ref t, m) => {
471 self.head(&visibility_qualified(&item.vis, "static"))?;
473 self.word_space("mut")?;
475 self.print_name(item.name)?;
476 self.word_space(":")?;
477 self.print_type(&t)?;
479 self.end()?; // end the head-ibox
480 self.end() // end the outer cbox
482 hir::ForeignItemKind::Type => {
483 self.head(&visibility_qualified(&item.vis, "type"))?;
484 self.print_name(item.name)?;
486 self.end()?; // end the head-ibox
487 self.end() // end the outer cbox
492 fn print_associated_const(&mut self,
495 default: Option<hir::BodyId>,
496 vis: &hir::Visibility)
498 self.s.word(&visibility_qualified(vis, ""))?;
499 self.word_space("const")?;
500 self.print_ident(ident)?;
501 self.word_space(":")?;
502 self.print_type(ty)?;
503 if let Some(expr) = default {
505 self.word_space("=")?;
506 self.ann.nested(self, Nested::Body(expr))?;
511 fn print_associated_type(&mut self,
513 bounds: Option<&hir::GenericBounds>,
514 ty: Option<&hir::Ty>)
516 self.word_space("type")?;
517 self.print_ident(ident)?;
518 if let Some(bounds) = bounds {
519 self.print_bounds(":", bounds)?;
521 if let Some(ty) = ty {
523 self.word_space("=")?;
524 self.print_type(ty)?;
529 /// Pretty-print an item
530 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
531 self.hardbreak_if_not_bol()?;
532 self.maybe_print_comment(item.span.lo())?;
533 self.print_outer_attributes(&item.attrs)?;
534 self.ann.pre(self, AnnNode::Item(item))?;
536 hir::ItemKind::ExternCrate(orig_name) => {
537 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
538 if let Some(orig_name) = orig_name {
539 self.print_name(orig_name)?;
544 self.print_name(item.name)?;
546 self.end()?; // end inner head-block
547 self.end()?; // end outer head-block
549 hir::ItemKind::Use(ref path, kind) => {
550 self.head(&visibility_qualified(&item.vis, "use"))?;
551 self.print_path(path, false)?;
554 hir::UseKind::Single => {
555 if path.segments.last().unwrap().ident.name != item.name {
557 self.word_space("as")?;
558 self.print_name(item.name)?;
562 hir::UseKind::Glob => self.s.word("::*;")?,
563 hir::UseKind::ListStem => self.s.word("::{};")?
565 self.end()?; // end inner head-block
566 self.end()?; // end outer head-block
568 hir::ItemKind::Static(ref ty, m, expr) => {
569 self.head(&visibility_qualified(&item.vis, "static"))?;
570 if m == hir::MutMutable {
571 self.word_space("mut")?;
573 self.print_name(item.name)?;
574 self.word_space(":")?;
575 self.print_type(&ty)?;
577 self.end()?; // end the head-ibox
579 self.word_space("=")?;
580 self.ann.nested(self, Nested::Body(expr))?;
582 self.end()?; // end the outer cbox
584 hir::ItemKind::Const(ref ty, expr) => {
585 self.head(&visibility_qualified(&item.vis, "const"))?;
586 self.print_name(item.name)?;
587 self.word_space(":")?;
588 self.print_type(&ty)?;
590 self.end()?; // end the head-ibox
592 self.word_space("=")?;
593 self.ann.nested(self, Nested::Body(expr))?;
595 self.end()?; // end the outer cbox
597 hir::ItemKind::Fn(ref decl, header, ref typarams, body) => {
607 self.end()?; // need to close a box
608 self.end()?; // need to close a box
609 self.ann.nested(self, Nested::Body(body))?;
611 hir::ItemKind::Mod(ref _mod) => {
612 self.head(&visibility_qualified(&item.vis, "mod"))?;
613 self.print_name(item.name)?;
616 self.print_mod(_mod, &item.attrs)?;
617 self.bclose(item.span)?;
619 hir::ItemKind::ForeignMod(ref nmod) => {
620 self.head("extern")?;
621 self.word_nbsp(&nmod.abi.to_string())?;
623 self.print_foreign_mod(nmod, &item.attrs)?;
624 self.bclose(item.span)?;
626 hir::ItemKind::GlobalAsm(ref ga) => {
627 self.head(&visibility_qualified(&item.vis, "global asm"))?;
628 self.s.word(&ga.asm.as_str())?;
631 hir::ItemKind::Ty(ref ty, ref generics) => {
632 self.head(&visibility_qualified(&item.vis, "type"))?;
633 self.print_name(item.name)?;
634 self.print_generic_params(&generics.params)?;
635 self.end()?; // end the inner ibox
637 self.print_where_clause(&generics.where_clause)?;
639 self.word_space("=")?;
640 self.print_type(&ty)?;
642 self.end()?; // end the outer ibox
644 hir::ItemKind::Existential(ref exist) => {
645 self.head(&visibility_qualified(&item.vis, "existential type"))?;
646 self.print_name(item.name)?;
647 self.print_generic_params(&exist.generics.params)?;
648 self.end()?; // end the inner ibox
650 self.print_where_clause(&exist.generics.where_clause)?;
652 self.word_space(":")?;
653 let mut real_bounds = Vec::with_capacity(exist.bounds.len());
654 for b in exist.bounds.iter() {
655 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
657 self.word_space("for ?")?;
658 self.print_trait_ref(&ptr.trait_ref)?;
660 real_bounds.push(b.clone());
663 self.print_bounds(":", &real_bounds[..])?;
665 self.end()?; // end the outer ibox
667 hir::ItemKind::Enum(ref enum_definition, ref params) => {
668 self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
670 hir::ItemKind::Struct(ref struct_def, ref generics) => {
671 self.head(&visibility_qualified(&item.vis, "struct"))?;
672 self.print_struct(struct_def, generics, item.name, item.span, true)?;
674 hir::ItemKind::Union(ref struct_def, ref generics) => {
675 self.head(&visibility_qualified(&item.vis, "union"))?;
676 self.print_struct(struct_def, generics, item.name, item.span, true)?;
678 hir::ItemKind::Impl(unsafety,
686 self.print_visibility(&item.vis)?;
687 self.print_defaultness(defaultness)?;
688 self.print_unsafety(unsafety)?;
689 self.word_nbsp("impl")?;
691 if !generics.params.is_empty() {
692 self.print_generic_params(&generics.params)?;
696 if let hir::ImplPolarity::Negative = polarity {
700 if let Some(ref t) = opt_trait {
701 self.print_trait_ref(t)?;
703 self.word_space("for")?;
706 self.print_type(&ty)?;
707 self.print_where_clause(&generics.where_clause)?;
711 self.print_inner_attributes(&item.attrs)?;
712 for impl_item in impl_items {
713 self.ann.nested(self, Nested::ImplItem(impl_item.id))?;
715 self.bclose(item.span)?;
717 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
719 self.print_visibility(&item.vis)?;
720 self.print_is_auto(is_auto)?;
721 self.print_unsafety(unsafety)?;
722 self.word_nbsp("trait")?;
723 self.print_name(item.name)?;
724 self.print_generic_params(&generics.params)?;
725 let mut real_bounds = Vec::with_capacity(bounds.len());
726 for b in bounds.iter() {
727 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
729 self.word_space("for ?")?;
730 self.print_trait_ref(&ptr.trait_ref)?;
732 real_bounds.push(b.clone());
735 self.print_bounds(":", &real_bounds[..])?;
736 self.print_where_clause(&generics.where_clause)?;
739 for trait_item in trait_items {
740 self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
742 self.bclose(item.span)?;
744 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
746 self.print_visibility(&item.vis)?;
747 self.word_nbsp("trait")?;
748 self.print_name(item.name)?;
749 self.print_generic_params(&generics.params)?;
750 let mut real_bounds = Vec::with_capacity(bounds.len());
751 // FIXME(durka) this seems to be some quite outdated syntax
752 for b in bounds.iter() {
753 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
755 self.word_space("for ?")?;
756 self.print_trait_ref(&ptr.trait_ref)?;
758 real_bounds.push(b.clone());
762 self.print_bounds("=", &real_bounds[..])?;
763 self.print_where_clause(&generics.where_clause)?;
767 self.ann.post(self, AnnNode::Item(item))
770 pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
771 self.print_path(&t.path, false)
774 fn print_formal_generic_params(
776 generic_params: &[hir::GenericParam]
777 ) -> io::Result<()> {
778 if !generic_params.is_empty() {
780 self.print_generic_params(generic_params)?;
786 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
787 self.print_formal_generic_params(&t.bound_generic_params)?;
788 self.print_trait_ref(&t.trait_ref)
791 pub fn print_enum_def(&mut self,
792 enum_definition: &hir::EnumDef,
793 generics: &hir::Generics,
795 span: syntax_pos::Span,
796 visibility: &hir::Visibility)
798 self.head(&visibility_qualified(visibility, "enum"))?;
799 self.print_name(name)?;
800 self.print_generic_params(&generics.params)?;
801 self.print_where_clause(&generics.where_clause)?;
803 self.print_variants(&enum_definition.variants, span)
806 pub fn print_variants(&mut self,
807 variants: &[hir::Variant],
808 span: syntax_pos::Span)
812 self.space_if_not_bol()?;
813 self.maybe_print_comment(v.span.lo())?;
814 self.print_outer_attributes(&v.node.attrs)?;
815 self.ibox(indent_unit)?;
816 self.print_variant(v)?;
819 self.maybe_print_trailing_comment(v.span, None)?;
824 pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
826 hir::VisibilityKind::Public => self.word_nbsp("pub")?,
827 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate")?,
828 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)")?,
829 hir::VisibilityKind::Restricted { ref path, .. } => {
830 self.s.word("pub(")?;
831 if path.segments.len() == 1 &&
832 path.segments[0].ident.name == keywords::Super.name() {
833 // Special case: `super` can print like `pub(super)`.
834 self.s.word("super")?;
836 // Everything else requires `in` at present.
837 self.word_nbsp("in")?;
838 self.print_path(path, false)?;
840 self.word_nbsp(")")?;
842 hir::VisibilityKind::Inherited => ()
848 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) -> io::Result<()> {
850 hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
851 hir::Defaultness::Final => (),
856 pub fn print_struct(&mut self,
857 struct_def: &hir::VariantData,
858 generics: &hir::Generics,
860 span: syntax_pos::Span,
861 print_finalizer: bool)
863 self.print_name(name)?;
864 self.print_generic_params(&generics.params)?;
865 if !struct_def.is_struct() {
866 if struct_def.is_tuple() {
868 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
869 s.maybe_print_comment(field.span.lo())?;
870 s.print_outer_attributes(&field.attrs)?;
871 s.print_visibility(&field.vis)?;
872 s.print_type(&field.ty)
876 self.print_where_clause(&generics.where_clause)?;
881 self.end() // close the outer-box
883 self.print_where_clause(&generics.where_clause)?;
886 self.hardbreak_if_not_bol()?;
888 for field in struct_def.fields() {
889 self.hardbreak_if_not_bol()?;
890 self.maybe_print_comment(field.span.lo())?;
891 self.print_outer_attributes(&field.attrs)?;
892 self.print_visibility(&field.vis)?;
893 self.print_ident(field.ident)?;
894 self.word_nbsp(":")?;
895 self.print_type(&field.ty)?;
903 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
905 let generics = hir::Generics::empty();
906 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
907 if let Some(ref d) = v.node.disr_expr {
909 self.word_space("=")?;
910 self.print_anon_const(d)?;
914 pub fn print_method_sig(&mut self,
917 generics: &hir::Generics,
918 vis: &hir::Visibility,
919 arg_names: &[ast::Ident],
920 body_id: Option<hir::BodyId>)
922 self.print_fn(&m.decl,
931 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
932 self.ann.pre(self, AnnNode::SubItem(ti.id))?;
933 self.hardbreak_if_not_bol()?;
934 self.maybe_print_comment(ti.span.lo())?;
935 self.print_outer_attributes(&ti.attrs)?;
937 hir::TraitItemKind::Const(ref ty, default) => {
938 let vis = Spanned { span: syntax_pos::DUMMY_SP,
939 node: hir::VisibilityKind::Inherited };
940 self.print_associated_const(ti.ident, &ty, default, &vis)?;
942 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
943 let vis = Spanned { span: syntax_pos::DUMMY_SP,
944 node: hir::VisibilityKind::Inherited };
945 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None)?;
948 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
949 let vis = Spanned { span: syntax_pos::DUMMY_SP,
950 node: hir::VisibilityKind::Inherited };
952 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body))?;
954 self.end()?; // need to close a box
955 self.end()?; // need to close a box
956 self.ann.nested(self, Nested::Body(body))?;
958 hir::TraitItemKind::Type(ref bounds, ref default) => {
959 self.print_associated_type(ti.ident,
961 default.as_ref().map(|ty| &**ty))?;
964 self.ann.post(self, AnnNode::SubItem(ti.id))
967 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
968 self.ann.pre(self, AnnNode::SubItem(ii.id))?;
969 self.hardbreak_if_not_bol()?;
970 self.maybe_print_comment(ii.span.lo())?;
971 self.print_outer_attributes(&ii.attrs)?;
972 self.print_defaultness(ii.defaultness)?;
975 hir::ImplItemKind::Const(ref ty, expr) => {
976 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis)?;
978 hir::ImplItemKind::Method(ref sig, body) => {
980 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body))?;
982 self.end()?; // need to close a box
983 self.end()?; // need to close a box
984 self.ann.nested(self, Nested::Body(body))?;
986 hir::ImplItemKind::Type(ref ty) => {
987 self.print_associated_type(ii.ident, None, Some(ty))?;
989 hir::ImplItemKind::Existential(ref bounds) => {
990 self.word_space("existential")?;
991 self.print_associated_type(ii.ident, Some(bounds), None)?;
994 self.ann.post(self, AnnNode::SubItem(ii.id))
997 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
998 self.maybe_print_comment(st.span.lo())?;
1000 hir::StmtKind::Decl(ref decl, _) => {
1001 self.print_decl(&decl)?;
1003 hir::StmtKind::Expr(ref expr, _) => {
1004 self.space_if_not_bol()?;
1005 self.print_expr(&expr)?;
1007 hir::StmtKind::Semi(ref expr, _) => {
1008 self.space_if_not_bol()?;
1009 self.print_expr(&expr)?;
1013 if stmt_ends_with_semi(&st.node) {
1016 self.maybe_print_trailing_comment(st.span, None)
1019 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1020 self.print_block_with_attrs(blk, &[])
1023 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1024 self.print_block_unclosed_indent(blk, indent_unit)
1027 pub fn print_block_unclosed_indent(&mut self,
1031 self.print_block_maybe_unclosed(blk, indented, &[], false)
1034 pub fn print_block_with_attrs(&mut self,
1036 attrs: &[ast::Attribute])
1038 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1041 pub fn print_block_maybe_unclosed(&mut self,
1044 attrs: &[ast::Attribute],
1048 hir::UnsafeBlock(..) => self.word_space("unsafe")?,
1049 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
1050 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
1051 hir::DefaultBlock => (),
1053 self.maybe_print_comment(blk.span.lo())?;
1054 self.ann.pre(self, AnnNode::Block(blk))?;
1057 self.print_inner_attributes(attrs)?;
1059 for st in &blk.stmts {
1060 self.print_stmt(st)?;
1062 if let Some(ref expr) = blk.expr {
1063 self.space_if_not_bol()?;
1064 self.print_expr(&expr)?;
1065 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1067 self.bclose_maybe_open(blk.span, indented, close_box)?;
1068 self.ann.post(self, AnnNode::Block(blk))
1071 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1075 // "another else-if"
1076 hir::ExprKind::If(ref i, ref then, ref e) => {
1077 self.cbox(indent_unit - 1)?;
1079 self.s.word(" else if ")?;
1080 self.print_expr_as_cond(&i)?;
1082 self.print_expr(&then)?;
1083 self.print_else(e.as_ref().map(|e| &**e))
1086 hir::ExprKind::Block(ref b, _) => {
1087 self.cbox(indent_unit - 1)?;
1089 self.s.word(" else ")?;
1090 self.print_block(&b)
1092 // BLEAH, constraints would be great here
1094 panic!("print_if saw if with weird alternative");
1102 pub fn print_if(&mut self,
1105 elseopt: Option<&hir::Expr>)
1108 self.print_expr_as_cond(test)?;
1110 self.print_expr(blk)?;
1111 self.print_else(elseopt)
1114 pub fn print_if_let(&mut self,
1118 elseopt: Option<&hir::Expr>)
1120 self.head("if let")?;
1121 self.print_pat(pat)?;
1123 self.word_space("=")?;
1124 self.print_expr_as_cond(expr)?;
1126 self.print_block(blk)?;
1127 self.print_else(elseopt)
1130 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) -> io::Result<()> {
1131 self.ann.nested(self, Nested::Body(constant.body))
1134 fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
1136 self.commasep_exprs(Inconsistent, args)?;
1140 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr, prec: i8) -> io::Result<()> {
1141 let needs_par = expr.precedence().order() < prec;
1145 self.print_expr(expr)?;
1152 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1153 /// `if cond { ... }`.
1154 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr) -> io::Result<()> {
1155 let needs_par = match expr.node {
1156 // These cases need parens due to the parse error observed in #26461: `if return {}`
1157 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1158 hir::ExprKind::Closure(..) |
1159 hir::ExprKind::Ret(..) |
1160 hir::ExprKind::Break(..) => true,
1162 _ => contains_exterior_struct_lit(expr),
1168 self.print_expr(expr)?;
1175 fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1176 self.ibox(indent_unit)?;
1178 self.commasep_exprs(Inconsistent, exprs)?;
1183 fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::AnonConst) -> io::Result<()> {
1184 self.ibox(indent_unit)?;
1186 self.print_expr(element)?;
1187 self.word_space(";")?;
1188 self.print_anon_const(count)?;
1193 fn print_expr_struct(&mut self,
1195 fields: &[hir::Field],
1196 wth: &Option<P<hir::Expr>>)
1198 self.print_qpath(qpath, true)?;
1200 self.commasep_cmnt(Consistent,
1203 s.ibox(indent_unit)?;
1204 if !field.is_shorthand {
1205 s.print_ident(field.ident)?;
1208 s.print_expr(&field.expr)?;
1214 self.ibox(indent_unit)?;
1215 if !fields.is_empty() {
1220 self.print_expr(&expr)?;
1223 _ => if !fields.is_empty() {
1231 fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1233 self.commasep_exprs(Inconsistent, exprs)?;
1234 if exprs.len() == 1 {
1240 fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1243 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1244 _ => parser::PREC_POSTFIX,
1247 self.print_expr_maybe_paren(func, prec)?;
1248 self.print_call_post(args)
1251 fn print_expr_method_call(&mut self,
1252 segment: &hir::PathSegment,
1255 let base_args = &args[1..];
1256 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
1258 self.print_ident(segment.ident)?;
1260 segment.with_generic_args(|generic_args| {
1261 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1262 return self.print_generic_args(&generic_args, segment.infer_types, true);
1266 self.print_call_post(base_args)
1269 fn print_expr_binary(&mut self,
1274 let assoc_op = bin_op_to_assoc_op(op.node);
1275 let prec = assoc_op.precedence() as i8;
1276 let fixity = assoc_op.fixity();
1278 let (left_prec, right_prec) = match fixity {
1279 Fixity::Left => (prec, prec + 1),
1280 Fixity::Right => (prec + 1, prec),
1281 Fixity::None => (prec + 1, prec + 1),
1284 let left_prec = match (&lhs.node, op.node) {
1285 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1286 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1287 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1288 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt) |
1289 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1293 self.print_expr_maybe_paren(lhs, left_prec)?;
1295 self.word_space(op.node.as_str())?;
1296 self.print_expr_maybe_paren(rhs, right_prec)
1299 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1300 self.s.word(op.as_str())?;
1301 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1304 fn print_expr_addr_of(&mut self,
1305 mutability: hir::Mutability,
1309 self.print_mutability(mutability)?;
1310 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1313 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1314 self.maybe_print_comment(expr.span.lo())?;
1315 self.print_outer_attributes(&expr.attrs)?;
1316 self.ibox(indent_unit)?;
1317 self.ann.pre(self, AnnNode::Expr(expr))?;
1319 hir::ExprKind::Box(ref expr) => {
1320 self.word_space("box")?;
1321 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
1323 hir::ExprKind::Array(ref exprs) => {
1324 self.print_expr_vec(exprs)?;
1326 hir::ExprKind::Repeat(ref element, ref count) => {
1327 self.print_expr_repeat(&element, count)?;
1329 hir::ExprKind::Struct(ref qpath, ref fields, ref wth) => {
1330 self.print_expr_struct(qpath, &fields[..], wth)?;
1332 hir::ExprKind::Tup(ref exprs) => {
1333 self.print_expr_tup(exprs)?;
1335 hir::ExprKind::Call(ref func, ref args) => {
1336 self.print_expr_call(&func, args)?;
1338 hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1339 self.print_expr_method_call(segment, args)?;
1341 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1342 self.print_expr_binary(op, &lhs, &rhs)?;
1344 hir::ExprKind::Unary(op, ref expr) => {
1345 self.print_expr_unary(op, &expr)?;
1347 hir::ExprKind::AddrOf(m, ref expr) => {
1348 self.print_expr_addr_of(m, &expr)?;
1350 hir::ExprKind::Lit(ref lit) => {
1351 self.print_literal(&lit)?;
1353 hir::ExprKind::Cast(ref expr, ref ty) => {
1354 let prec = AssocOp::As.precedence() as i8;
1355 self.print_expr_maybe_paren(&expr, prec)?;
1357 self.word_space("as")?;
1358 self.print_type(&ty)?;
1360 hir::ExprKind::Type(ref expr, ref ty) => {
1361 let prec = AssocOp::Colon.precedence() as i8;
1362 self.print_expr_maybe_paren(&expr, prec)?;
1363 self.word_space(":")?;
1364 self.print_type(&ty)?;
1366 hir::ExprKind::If(ref test, ref blk, ref elseopt) => {
1367 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1369 hir::ExprKind::While(ref test, ref blk, opt_label) => {
1370 if let Some(label) = opt_label {
1371 self.print_ident(label.ident)?;
1372 self.word_space(":")?;
1374 self.head("while")?;
1375 self.print_expr_as_cond(&test)?;
1377 self.print_block(&blk)?;
1379 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1380 if let Some(label) = opt_label {
1381 self.print_ident(label.ident)?;
1382 self.word_space(":")?;
1386 self.print_block(&blk)?;
1388 hir::ExprKind::Match(ref expr, ref arms, _) => {
1389 self.cbox(indent_unit)?;
1391 self.word_nbsp("match")?;
1392 self.print_expr_as_cond(&expr)?;
1396 self.print_arm(arm)?;
1398 self.bclose_(expr.span, indent_unit)?;
1400 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1401 self.print_capture_clause(capture_clause)?;
1403 self.print_closure_args(&decl, body)?;
1406 // this is a bare expression
1407 self.ann.nested(self, Nested::Body(body))?;
1408 self.end()?; // need to close a box
1410 // a box will be closed by print_expr, but we didn't want an overall
1411 // wrapper so we closed the corresponding opening. so create an
1412 // empty box to satisfy the close.
1415 hir::ExprKind::Block(ref blk, opt_label) => {
1416 if let Some(label) = opt_label {
1417 self.print_ident(label.ident)?;
1418 self.word_space(":")?;
1420 // containing cbox, will be closed by print-block at }
1421 self.cbox(indent_unit)?;
1422 // head-box, will be closed by print-block after {
1424 self.print_block(&blk)?;
1426 hir::ExprKind::Assign(ref lhs, ref rhs) => {
1427 let prec = AssocOp::Assign.precedence() as i8;
1428 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1430 self.word_space("=")?;
1431 self.print_expr_maybe_paren(&rhs, prec)?;
1433 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1434 let prec = AssocOp::Assign.precedence() as i8;
1435 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1437 self.s.word(op.node.as_str())?;
1438 self.word_space("=")?;
1439 self.print_expr_maybe_paren(&rhs, prec)?;
1441 hir::ExprKind::Field(ref expr, ident) => {
1442 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
1444 self.print_ident(ident)?;
1446 hir::ExprKind::Index(ref expr, ref index) => {
1447 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1449 self.print_expr(&index)?;
1452 hir::ExprKind::Path(ref qpath) => {
1453 self.print_qpath(qpath, true)?
1455 hir::ExprKind::Break(destination, ref opt_expr) => {
1456 self.s.word("break")?;
1458 if let Some(label) = destination.label {
1459 self.print_ident(label.ident)?;
1462 if let Some(ref expr) = *opt_expr {
1463 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
1467 hir::ExprKind::Continue(destination) => {
1468 self.s.word("continue")?;
1470 if let Some(label) = destination.label {
1471 self.print_ident(label.ident)?;
1475 hir::ExprKind::Ret(ref result) => {
1476 self.s.word("return")?;
1477 if let Some(ref expr) = *result {
1479 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1482 hir::ExprKind::InlineAsm(ref a, ref outputs, ref inputs) => {
1483 self.s.word("asm!")?;
1485 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
1486 self.word_space(":")?;
1488 let mut out_idx = 0;
1489 self.commasep(Inconsistent, &a.outputs, |s, out| {
1490 let constraint = out.constraint.as_str();
1491 let mut ch = constraint.chars();
1493 Some('=') if out.is_rw => {
1494 s.print_string(&format!("+{}", ch.as_str()),
1495 ast::StrStyle::Cooked)?
1497 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
1500 s.print_expr(&outputs[out_idx])?;
1506 self.word_space(":")?;
1509 self.commasep(Inconsistent, &a.inputs, |s, co| {
1510 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1512 s.print_expr(&inputs[in_idx])?;
1518 self.word_space(":")?;
1520 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1521 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1525 let mut options = vec![];
1527 options.push("volatile");
1530 options.push("alignstack");
1532 if a.dialect == ast::AsmDialect::Intel {
1533 options.push("intel");
1536 if !options.is_empty() {
1538 self.word_space(":")?;
1539 self.commasep(Inconsistent, &options, |s, &co| {
1540 s.print_string(co, ast::StrStyle::Cooked)?;
1547 hir::ExprKind::Yield(ref expr) => {
1548 self.word_space("yield")?;
1549 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1552 self.ann.post(self, AnnNode::Expr(expr))?;
1556 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1557 self.print_pat(&loc.pat)?;
1558 if let Some(ref ty) = loc.ty {
1559 self.word_space(":")?;
1560 self.print_type(&ty)?;
1565 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1566 self.maybe_print_comment(decl.span.lo())?;
1568 hir::DeclKind::Local(ref loc) => {
1569 self.space_if_not_bol()?;
1570 self.ibox(indent_unit)?;
1571 self.word_nbsp("let")?;
1573 self.ibox(indent_unit)?;
1574 self.print_local_decl(&loc)?;
1576 if let Some(ref init) = loc.init {
1578 self.word_space("=")?;
1579 self.print_expr(&init)?;
1583 hir::DeclKind::Item(item) => {
1584 self.ann.nested(self, Nested::Item(item))
1589 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1590 self.s.word(&i.to_string())
1593 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
1594 if ident.is_raw_guess() {
1595 self.s.word(&format!("r#{}", ident.name))?;
1597 self.s.word(&ident.as_str())?;
1599 self.ann.post(self, AnnNode::Name(&ident.name))
1602 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1603 self.print_ident(ast::Ident::with_empty_ctxt(name))
1606 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1607 self.print_local_decl(loc)?;
1609 self.word_space("in")?;
1610 self.print_expr(coll)
1613 pub fn print_path(&mut self,
1615 colons_before_params: bool)
1617 self.maybe_print_comment(path.span.lo())?;
1619 for (i, segment) in path.segments.iter().enumerate() {
1623 if segment.ident.name != keywords::CrateRoot.name() &&
1624 segment.ident.name != keywords::DollarCrate.name() {
1625 self.print_ident(segment.ident)?;
1626 segment.with_generic_args(|generic_args| {
1627 self.print_generic_args(generic_args, segment.infer_types,
1628 colons_before_params)
1636 pub fn print_path_segment(&mut self, segment: &hir::PathSegment) -> io::Result<()> {
1637 if segment.ident.name != keywords::CrateRoot.name() &&
1638 segment.ident.name != keywords::DollarCrate.name() {
1639 self.print_ident(segment.ident)?;
1640 segment.with_generic_args(|generic_args| {
1641 self.print_generic_args(generic_args, segment.infer_types, false)
1647 pub fn print_qpath(&mut self,
1649 colons_before_params: bool)
1652 hir::QPath::Resolved(None, ref path) => {
1653 self.print_path(path, colons_before_params)
1655 hir::QPath::Resolved(Some(ref qself), ref path) => {
1657 self.print_type(qself)?;
1659 self.word_space("as")?;
1661 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1665 if segment.ident.name != keywords::CrateRoot.name() &&
1666 segment.ident.name != keywords::DollarCrate.name() {
1667 self.print_ident(segment.ident)?;
1668 segment.with_generic_args(|generic_args| {
1669 self.print_generic_args(generic_args,
1670 segment.infer_types,
1671 colons_before_params)
1678 let item_segment = path.segments.last().unwrap();
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)
1686 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1688 self.print_type(qself)?;
1691 self.print_ident(item_segment.ident)?;
1692 item_segment.with_generic_args(|generic_args| {
1693 self.print_generic_args(generic_args,
1694 item_segment.infer_types,
1695 colons_before_params)
1701 fn print_generic_args(&mut self,
1702 generic_args: &hir::GenericArgs,
1704 colons_before_params: bool)
1706 if generic_args.parenthesized {
1708 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty))?;
1711 self.space_if_not_bol()?;
1712 self.word_space("->")?;
1713 self.print_type(&generic_args.bindings[0].ty)?;
1715 let start = if colons_before_params { "::<" } else { "<" };
1716 let empty = Cell::new(true);
1717 let start_or_comma = |this: &mut Self| {
1722 this.word_space(",")
1726 let mut types = vec![];
1727 let mut elide_lifetimes = true;
1728 for arg in &generic_args.args {
1730 GenericArg::Lifetime(lt) => {
1731 if !lt.is_elided() {
1732 elide_lifetimes = false;
1735 GenericArg::Type(ty) => {
1740 if !elide_lifetimes {
1741 start_or_comma(self)?;
1742 self.commasep(Inconsistent, &generic_args.args, |s, generic_arg| {
1744 GenericArg::Lifetime(lt) => s.print_lifetime(lt),
1745 GenericArg::Type(ty) => s.print_type(ty),
1748 } else if !types.is_empty() {
1749 start_or_comma(self)?;
1750 self.commasep(Inconsistent, &types, |s, ty| s.print_type(&ty))?;
1753 // FIXME(eddyb) This would leak into error messages, e.g.:
1754 // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1755 if infer_types && false {
1756 start_or_comma(self)?;
1760 for binding in generic_args.bindings.iter() {
1761 start_or_comma(self)?;
1762 self.print_ident(binding.ident)?;
1764 self.word_space("=")?;
1765 self.print_type(&binding.ty)?;
1776 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1777 self.maybe_print_comment(pat.span.lo())?;
1778 self.ann.pre(self, AnnNode::Pat(pat))?;
1779 // Pat isn't normalized, but the beauty of it
1780 // is that it doesn't matter
1782 PatKind::Wild => self.s.word("_")?,
1783 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1784 match binding_mode {
1785 hir::BindingAnnotation::Ref => {
1786 self.word_nbsp("ref")?;
1787 self.print_mutability(hir::MutImmutable)?;
1789 hir::BindingAnnotation::RefMut => {
1790 self.word_nbsp("ref")?;
1791 self.print_mutability(hir::MutMutable)?;
1793 hir::BindingAnnotation::Unannotated => {}
1794 hir::BindingAnnotation::Mutable => {
1795 self.word_nbsp("mut")?;
1798 self.print_ident(ident)?;
1799 if let Some(ref p) = *sub {
1801 self.print_pat(&p)?;
1804 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1805 self.print_qpath(qpath, true)?;
1807 if let Some(ddpos) = ddpos {
1808 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1810 self.word_space(",")?;
1813 if ddpos != elts.len() {
1815 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1818 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1822 PatKind::Path(ref qpath) => {
1823 self.print_qpath(qpath, true)?;
1825 PatKind::Struct(ref qpath, ref fields, etc) => {
1826 self.print_qpath(qpath, true)?;
1828 self.word_space("{")?;
1829 self.commasep_cmnt(Consistent,
1832 s.cbox(indent_unit)?;
1833 if !f.node.is_shorthand {
1834 s.print_ident(f.node.ident)?;
1837 s.print_pat(&f.node.pat)?;
1840 |f| f.node.pat.span)?;
1842 if !fields.is_empty() {
1843 self.word_space(",")?;
1850 PatKind::Tuple(ref elts, ddpos) => {
1852 if let Some(ddpos) = ddpos {
1853 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1855 self.word_space(",")?;
1858 if ddpos != elts.len() {
1860 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1863 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1864 if elts.len() == 1 {
1870 PatKind::Box(ref inner) => {
1871 let is_range_inner = match inner.node {
1872 PatKind::Range(..) => true,
1875 self.s.word("box ")?;
1879 self.print_pat(&inner)?;
1884 PatKind::Ref(ref inner, mutbl) => {
1885 let is_range_inner = match inner.node {
1886 PatKind::Range(..) => true,
1890 if mutbl == hir::MutMutable {
1891 self.s.word("mut ")?;
1896 self.print_pat(&inner)?;
1901 PatKind::Lit(ref e) => self.print_expr(&e)?,
1902 PatKind::Range(ref begin, ref end, ref end_kind) => {
1903 self.print_expr(&begin)?;
1906 RangeEnd::Included => self.s.word("...")?,
1907 RangeEnd::Excluded => self.s.word("..")?,
1909 self.print_expr(&end)?;
1911 PatKind::Slice(ref before, ref slice, ref after) => {
1913 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1914 if let Some(ref p) = *slice {
1915 if !before.is_empty() {
1916 self.word_space(",")?;
1918 if let PatKind::Wild = p.node {
1921 self.print_pat(&p)?;
1924 if !after.is_empty() {
1925 self.word_space(",")?;
1928 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1932 self.ann.post(self, AnnNode::Pat(pat))
1935 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1936 // I have no idea why this check is necessary, but here it
1938 if arm.attrs.is_empty() {
1941 self.cbox(indent_unit)?;
1943 self.print_outer_attributes(&arm.attrs)?;
1944 let mut first = true;
1945 for p in &arm.pats {
1950 self.word_space("|")?;
1952 self.print_pat(&p)?;
1955 if let Some(ref g) = arm.guard {
1957 hir::Guard::If(e) => {
1958 self.word_space("if")?;
1959 self.print_expr(&e)?;
1964 self.word_space("=>")?;
1966 match arm.body.node {
1967 hir::ExprKind::Block(ref blk, opt_label) => {
1968 if let Some(label) = opt_label {
1969 self.print_ident(label.ident)?;
1970 self.word_space(":")?;
1972 // the block will close the pattern's ibox
1973 self.print_block_unclosed_indent(&blk, indent_unit)?;
1975 // If it is a user-provided unsafe block, print a comma after it
1976 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1981 self.end()?; // close the ibox for the pattern
1982 self.print_expr(&arm.body)?;
1986 self.end() // close enclosing cbox
1989 pub fn print_fn(&mut self,
1991 header: hir::FnHeader,
1992 name: Option<ast::Name>,
1993 generics: &hir::Generics,
1994 vis: &hir::Visibility,
1995 arg_names: &[ast::Ident],
1996 body_id: Option<hir::BodyId>)
1998 self.print_fn_header_info(header, vis)?;
2000 if let Some(name) = name {
2002 self.print_name(name)?;
2004 self.print_generic_params(&generics.params)?;
2008 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2009 assert!(arg_names.is_empty() || body_id.is_none());
2010 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2011 s.ibox(indent_unit)?;
2012 if let Some(arg_name) = arg_names.get(i) {
2013 s.s.word(&arg_name.as_str())?;
2016 } else if let Some(body_id) = body_id {
2017 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2026 self.s.word(", ...")?;
2030 self.print_fn_output(decl)?;
2031 self.print_where_clause(&generics.where_clause)
2034 fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
2037 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2038 s.ibox(indent_unit)?;
2040 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2043 if let hir::TyKind::Infer = ty.node {
2054 if let hir::DefaultReturn(..) = decl.output {
2058 self.space_if_not_bol()?;
2059 self.word_space("->")?;
2061 hir::Return(ref ty) => {
2062 self.print_type(&ty)?;
2063 self.maybe_print_comment(ty.span.lo())
2065 hir::DefaultReturn(..) => unreachable!(),
2069 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
2070 match capture_clause {
2071 hir::CaptureByValue => self.word_space("move"),
2072 hir::CaptureByRef => Ok(()),
2076 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::GenericBound]) -> io::Result<()> {
2077 if !bounds.is_empty() {
2078 self.s.word(prefix)?;
2079 let mut first = true;
2080 for bound in bounds {
2081 if !(first && prefix.is_empty()) {
2087 self.word_space("+")?;
2091 GenericBound::Trait(tref, modifier) => {
2092 if modifier == &TraitBoundModifier::Maybe {
2095 self.print_poly_trait_ref(tref)?;
2097 GenericBound::Outlives(lt) => {
2098 self.print_lifetime(lt)?;
2106 pub fn print_generic_params(&mut self, generic_params: &[GenericParam]) -> io::Result<()> {
2107 if !generic_params.is_empty() {
2110 self.commasep(Inconsistent, generic_params, |s, param| {
2111 s.print_generic_param(param)
2119 pub fn print_generic_param(&mut self, param: &GenericParam) -> io::Result<()> {
2120 self.print_ident(param.name.ident())?;
2122 GenericParamKind::Lifetime { .. } => {
2124 for bound in ¶m.bounds {
2126 GenericBound::Outlives(lt) => {
2128 self.print_lifetime(lt)?;
2136 GenericParamKind::Type { ref default, .. } => {
2137 self.print_bounds(":", ¶m.bounds)?;
2141 self.word_space("=")?;
2142 self.print_type(&default)
2150 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2151 self.print_ident(lifetime.name.ident())
2154 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2155 if where_clause.predicates.is_empty() {
2160 self.word_space("where")?;
2162 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2164 self.word_space(",")?;
2168 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2169 ref bound_generic_params,
2174 self.print_formal_generic_params(bound_generic_params)?;
2175 self.print_type(&bounded_ty)?;
2176 self.print_bounds(":", bounds)?;
2178 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2181 self.print_lifetime(lifetime)?;
2184 for (i, bound) in bounds.iter().enumerate() {
2186 GenericBound::Outlives(lt) => {
2187 self.print_lifetime(lt)?;
2197 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
2200 self.print_type(lhs_ty)?;
2202 self.word_space("=")?;
2203 self.print_type(rhs_ty)?;
2211 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2213 hir::MutMutable => self.word_nbsp("mut"),
2214 hir::MutImmutable => Ok(()),
2218 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2219 self.print_mutability(mt.mutbl)?;
2220 self.print_type(&mt.ty)
2223 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2224 if let hir::DefaultReturn(..) = decl.output {
2228 self.space_if_not_bol()?;
2229 self.ibox(indent_unit)?;
2230 self.word_space("->")?;
2232 hir::DefaultReturn(..) => unreachable!(),
2233 hir::Return(ref ty) => self.print_type(&ty)?,
2238 hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2243 pub fn print_ty_fn(&mut self,
2245 unsafety: hir::Unsafety,
2247 name: Option<ast::Name>,
2248 generic_params: &[hir::GenericParam],
2249 arg_names: &[ast::Ident])
2251 self.ibox(indent_unit)?;
2252 if !generic_params.is_empty() {
2253 self.s.word("for")?;
2254 self.print_generic_params(generic_params)?;
2256 let generics = hir::Generics {
2257 params: hir::HirVec::new(),
2258 where_clause: hir::WhereClause {
2259 id: ast::DUMMY_NODE_ID,
2260 predicates: hir::HirVec::new(),
2262 span: syntax_pos::DUMMY_SP,
2268 constness: hir::Constness::NotConst,
2269 asyncness: hir::IsAsync::NotAsync,
2273 &Spanned { span: syntax_pos::DUMMY_SP,
2274 node: hir::VisibilityKind::Inherited },
2280 pub fn maybe_print_trailing_comment(&mut self,
2281 span: syntax_pos::Span,
2282 next_pos: Option<BytePos>)
2284 let cm = match self.cm {
2288 if let Some(ref cmnt) = self.next_comment() {
2289 if (*cmnt).style != comments::Trailing {
2292 let span_line = cm.lookup_char_pos(span.hi());
2293 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2294 let mut next = (*cmnt).pos + BytePos(1);
2295 if let Some(p) = next_pos {
2298 if span.hi() < (*cmnt).pos && (*cmnt).pos < next &&
2299 span_line.line == comment_line.line {
2300 self.print_comment(cmnt)?;
2306 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2307 // If there aren't any remaining comments, then we need to manually
2308 // make sure there is a line break at the end.
2309 if self.next_comment().is_none() {
2310 self.s.hardbreak()?;
2312 while let Some(ref cmnt) = self.next_comment() {
2313 self.print_comment(cmnt)?
2318 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2319 opt_abi: Option<Abi>)
2322 Some(Abi::Rust) => Ok(()),
2324 self.word_nbsp("extern")?;
2325 self.word_nbsp(&abi.to_string())
2331 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2334 self.word_nbsp("extern")?;
2335 self.word_nbsp(&abi.to_string())
2341 pub fn print_fn_header_info(&mut self,
2342 header: hir::FnHeader,
2343 vis: &hir::Visibility)
2345 self.s.word(&visibility_qualified(vis, ""))?;
2347 match header.constness {
2348 hir::Constness::NotConst => {}
2349 hir::Constness::Const => self.word_nbsp("const")?,
2352 match header.asyncness {
2353 hir::IsAsync::NotAsync => {}
2354 hir::IsAsync::Async => self.word_nbsp("async")?,
2357 self.print_unsafety(header.unsafety)?;
2359 if header.abi != Abi::Rust {
2360 self.word_nbsp("extern")?;
2361 self.word_nbsp(&header.abi.to_string())?;
2367 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2369 hir::Unsafety::Normal => Ok(()),
2370 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2374 pub fn print_is_auto(&mut self, s: hir::IsAuto) -> io::Result<()> {
2376 hir::IsAuto::Yes => self.word_nbsp("auto"),
2377 hir::IsAuto::No => Ok(()),
2382 // Dup'ed from parse::classify, but adapted for the HIR.
2383 /// Does this expression require a semicolon to be treated
2384 /// as a statement? The negation of this: 'can this expression
2385 /// be used as a statement without a semicolon' -- is used
2386 /// as an early-bail-out in the parser so that, for instance,
2387 /// if true {...} else {...}
2389 /// isn't parsed as (if true {...} else {...} | x) | 5
2390 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2392 hir::ExprKind::If(..) |
2393 hir::ExprKind::Match(..) |
2394 hir::ExprKind::Block(..) |
2395 hir::ExprKind::While(..) |
2396 hir::ExprKind::Loop(..) => false,
2401 /// this statement requires a semicolon after it.
2402 /// note that in one case (stmt_semi), we've already
2403 /// seen the semicolon, and thus don't need another.
2404 fn stmt_ends_with_semi(stmt: &hir::StmtKind) -> bool {
2406 hir::StmtKind::Decl(ref d, _) => {
2408 hir::DeclKind::Local(_) => true,
2409 hir::DeclKind::Item(_) => false,
2412 hir::StmtKind::Expr(ref e, _) => {
2413 expr_requires_semi_to_be_stmt(&e)
2415 hir::StmtKind::Semi(..) => {
2421 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2422 use hir::BinOpKind::*;
2424 Add => AssocOp::Add,
2425 Sub => AssocOp::Subtract,
2426 Mul => AssocOp::Multiply,
2427 Div => AssocOp::Divide,
2428 Rem => AssocOp::Modulus,
2430 And => AssocOp::LAnd,
2433 BitXor => AssocOp::BitXor,
2434 BitAnd => AssocOp::BitAnd,
2435 BitOr => AssocOp::BitOr,
2436 Shl => AssocOp::ShiftLeft,
2437 Shr => AssocOp::ShiftRight,
2439 Eq => AssocOp::Equal,
2440 Lt => AssocOp::Less,
2441 Le => AssocOp::LessEqual,
2442 Ne => AssocOp::NotEqual,
2443 Ge => AssocOp::GreaterEqual,
2444 Gt => AssocOp::Greater,
2448 /// Expressions that syntactically contain an "exterior" struct literal i.e. not surrounded by any
2449 /// parens or other delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2450 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2451 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
2453 hir::ExprKind::Struct(..) => true,
2455 hir::ExprKind::Assign(ref lhs, ref rhs) |
2456 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) |
2457 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2458 // X { y: 1 } + X { y: 2 }
2459 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2461 hir::ExprKind::Unary(_, ref x) |
2462 hir::ExprKind::Cast(ref x, _) |
2463 hir::ExprKind::Type(ref x, _) |
2464 hir::ExprKind::Field(ref x, _) |
2465 hir::ExprKind::Index(ref x, _) => {
2466 // &X { y: 1 }, X { y: 1 }.y
2467 contains_exterior_struct_lit(&x)
2470 hir::ExprKind::MethodCall(.., ref exprs) => {
2471 // X { y: 1 }.bar(...)
2472 contains_exterior_struct_lit(&exprs[0])