1 use rustc_target::spec::abi::Abi;
3 use syntax::source_map::{SourceMap, Spanned};
4 use syntax::parse::ParseSess;
5 use syntax::parse::lexer::comments;
6 use syntax::print::pp::{self, Breaks};
7 use syntax::print::pp::Breaks::{Consistent, Inconsistent};
8 use syntax::print::pprust::PrintState;
10 use syntax::symbol::keywords;
11 use syntax::util::parser::{self, AssocOp, Fixity};
12 use syntax_pos::{self, BytePos, FileName};
15 use crate::hir::{PatKind, GenericBound, TraitBoundModifier, RangeEnd};
16 use crate::hir::{GenericParam, GenericParamKind, GenericArg};
20 use std::io::{self, Write, Read};
21 use std::iter::Peekable;
24 pub enum AnnNode<'a> {
26 Block(&'a hir::Block),
35 TraitItem(hir::TraitItemId),
36 ImplItem(hir::ImplItemId),
38 BodyArgPat(hir::BodyId, usize)
42 fn nested(&self, _state: &mut State<'_>, _nested: Nested) -> io::Result<()> {
45 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) -> io::Result<()> {
48 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) -> io::Result<()> {
51 fn try_fetch_item(&self, _: ast::NodeId) -> Option<&hir::Item> {
57 impl PpAnn for NoAnn {}
58 pub const NO_ANN: &dyn PpAnn = &NoAnn;
60 impl PpAnn for hir::Crate {
61 fn try_fetch_item(&self, item: ast::NodeId) -> Option<&hir::Item> {
64 fn nested(&self, state: &mut State<'_>, nested: Nested) -> io::Result<()> {
66 Nested::Item(id) => state.print_item(self.item(id.id)),
67 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
68 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
69 Nested::Body(id) => state.print_expr(&self.body(id).value),
70 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
75 pub struct State<'a> {
76 pub s: pp::Printer<'a>,
77 cm: Option<&'a SourceMap>,
78 comments: Option<Vec<comments::Comment>>,
79 literals: Peekable<vec::IntoIter<comments::Literal>>,
81 boxes: Vec<pp::Breaks>,
82 ann: &'a (dyn PpAnn + 'a),
85 impl<'a> PrintState<'a> for State<'a> {
86 fn writer(&mut self) -> &mut pp::Printer<'a> {
90 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
94 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
98 fn cur_cmnt(&mut self) -> &mut usize {
102 fn cur_lit(&mut self) -> Option<&comments::Literal> {
106 fn bump_lit(&mut self) -> Option<comments::Literal> {
111 #[allow(non_upper_case_globals)]
112 pub const indent_unit: usize = 4;
114 #[allow(non_upper_case_globals)]
115 pub const default_columns: usize = 78;
118 /// Requires you to pass an input filename and reader so that
119 /// it can scan the input text for comments and literals to
121 pub fn print_crate<'a>(cm: &'a SourceMap,
125 input: &mut dyn Read,
126 out: Box<dyn Write + 'a>,
130 let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
132 // When printing the AST, we sometimes need to inject `#[no_std]` here.
133 // Since you can't compile the HIR, it's not necessary.
135 s.print_mod(&krate.module, &krate.attrs)?;
136 s.print_remaining_comments()?;
141 pub fn new_from_input(cm: &'a SourceMap,
144 input: &mut dyn Read,
145 out: Box<dyn Write + 'a>,
149 let (cmnts, lits) = comments::gather_comments_and_literals(sess, filename, input);
155 // If the code is post expansion, don't use the table of
156 // literals, since it doesn't correspond with the literals
157 // in the AST anymore.
165 pub fn new(cm: &'a SourceMap,
166 out: Box<dyn Write + 'a>,
168 comments: Option<Vec<comments::Comment>>,
169 literals: Option<Vec<comments::Literal>>)
172 s: pp::mk_printer(out, default_columns),
175 literals: literals.unwrap_or_default().into_iter().peekable(),
183 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
184 where F: FnOnce(&mut State<'_>) -> io::Result<()>
186 let mut wr = Vec::new();
188 let mut printer = State {
189 s: pp::mk_printer(Box::new(&mut wr), default_columns),
192 literals: vec![].into_iter().peekable(),
197 f(&mut printer).unwrap();
198 printer.s.eof().unwrap();
200 String::from_utf8(wr).unwrap()
203 pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility, w: S) -> String {
204 to_string(NO_ANN, |s| {
205 s.print_visibility(vis)?;
211 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
212 self.boxes.push(pp::Breaks::Consistent);
216 pub fn nbsp(&mut self) -> io::Result<()> {
220 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
225 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
227 // outer-box is consistent
228 self.cbox(indent_unit)?;
229 // head-box is inconsistent
230 self.ibox(w.len() + 1)?;
231 // keyword that starts the head
238 pub fn bopen(&mut self) -> io::Result<()> {
240 self.end() // close the head-box
243 pub fn bclose_(&mut self, span: syntax_pos::Span, indented: usize) -> io::Result<()> {
244 self.bclose_maybe_open(span, indented, true)
247 pub fn bclose_maybe_open(&mut self,
248 span: syntax_pos::Span,
252 self.maybe_print_comment(span.hi())?;
253 self.break_offset_if_not_bol(1, -(indented as isize))?;
256 self.end()?; // close the outer-box
261 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
262 self.bclose_(span, indent_unit)
265 pub fn in_cbox(&self) -> bool {
266 match self.boxes.last() {
267 Some(&last_box) => last_box == pp::Breaks::Consistent,
272 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
279 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
281 self.s.break_offset(n, off)
283 if off != 0 && self.s.last_token().is_hardbreak_tok() {
284 // We do something pretty sketchy here: tuck the nonzero
285 // offset-adjustment we were going to deposit along with the
286 // break into the previous hardbreak.
287 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
293 // Synthesizes a comment that was not textually present in the original source
295 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
303 pub fn commasep_cmnt<T, F, G>(&mut self,
309 where F: FnMut(&mut State<'_>, &T) -> io::Result<()>,
310 G: FnMut(&T) -> syntax_pos::Span
313 let len = elts.len();
316 self.maybe_print_comment(get_span(elt).hi())?;
321 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()))?;
322 self.space_if_not_bol()?;
328 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr]) -> io::Result<()> {
329 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
332 pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
333 self.print_inner_attributes(attrs)?;
334 for &item_id in &_mod.item_ids {
335 self.ann.nested(self, Nested::Item(item_id))?;
340 pub fn print_foreign_mod(&mut self,
341 nmod: &hir::ForeignMod,
342 attrs: &[ast::Attribute])
344 self.print_inner_attributes(attrs)?;
345 for item in &nmod.items {
346 self.print_foreign_item(item)?;
351 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
352 if !lifetime.is_elided() {
353 self.print_lifetime(lifetime)?;
359 pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
360 self.maybe_print_comment(ty.span.lo())?;
363 hir::TyKind::Slice(ref ty) => {
365 self.print_type(&ty)?;
368 hir::TyKind::Ptr(ref mt) => {
371 hir::MutMutable => self.word_nbsp("mut")?,
372 hir::MutImmutable => self.word_nbsp("const")?,
374 self.print_type(&mt.ty)?;
376 hir::TyKind::Rptr(ref lifetime, ref mt) => {
378 self.print_opt_lifetime(lifetime)?;
381 hir::TyKind::Never => {
384 hir::TyKind::Tup(ref elts) => {
386 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty))?;
392 hir::TyKind::BareFn(ref f) => {
393 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &f.generic_params,
396 hir::TyKind::Def(..) => {},
397 hir::TyKind::Path(ref qpath) => {
398 self.print_qpath(qpath, false)?
400 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
401 let mut first = true;
402 for bound in bounds {
407 self.word_space("+")?;
409 self.print_poly_trait_ref(bound)?;
411 if !lifetime.is_elided() {
413 self.word_space("+")?;
414 self.print_lifetime(lifetime)?;
417 hir::TyKind::Array(ref ty, ref length) => {
419 self.print_type(&ty)?;
421 self.print_anon_const(length)?;
424 hir::TyKind::Typeof(ref e) => {
425 self.s.word("typeof(")?;
426 self.print_anon_const(e)?;
429 hir::TyKind::Infer => {
432 hir::TyKind::Err => {
434 self.s.word("/*ERROR*/")?;
441 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
442 self.hardbreak_if_not_bol()?;
443 self.maybe_print_comment(item.span.lo())?;
444 self.print_outer_attributes(&item.attrs)?;
446 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
450 unsafety: hir::Unsafety::Normal,
451 constness: hir::Constness::NotConst,
453 asyncness: hir::IsAsync::NotAsync,
455 Some(item.ident.name),
460 self.end()?; // end head-ibox
462 self.end() // end the outer fn box
464 hir::ForeignItemKind::Static(ref t, m) => {
465 self.head(visibility_qualified(&item.vis, "static"))?;
467 self.word_space("mut")?;
469 self.print_ident(item.ident)?;
470 self.word_space(":")?;
471 self.print_type(&t)?;
473 self.end()?; // end the head-ibox
474 self.end() // end the outer cbox
476 hir::ForeignItemKind::Type => {
477 self.head(visibility_qualified(&item.vis, "type"))?;
478 self.print_ident(item.ident)?;
480 self.end()?; // end the head-ibox
481 self.end() // end the outer cbox
486 fn print_associated_const(&mut self,
489 default: Option<hir::BodyId>,
490 vis: &hir::Visibility)
492 self.s.word(visibility_qualified(vis, ""))?;
493 self.word_space("const")?;
494 self.print_ident(ident)?;
495 self.word_space(":")?;
496 self.print_type(ty)?;
497 if let Some(expr) = default {
499 self.word_space("=")?;
500 self.ann.nested(self, Nested::Body(expr))?;
505 fn print_associated_type(&mut self,
507 bounds: Option<&hir::GenericBounds>,
508 ty: Option<&hir::Ty>)
510 self.word_space("type")?;
511 self.print_ident(ident)?;
512 if let Some(bounds) = bounds {
513 self.print_bounds(":", bounds)?;
515 if let Some(ty) = ty {
517 self.word_space("=")?;
518 self.print_type(ty)?;
523 /// Pretty-print an item
524 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
525 self.hardbreak_if_not_bol()?;
526 self.maybe_print_comment(item.span.lo())?;
527 self.print_outer_attributes(&item.attrs)?;
528 self.ann.pre(self, AnnNode::Item(item))?;
530 hir::ItemKind::ExternCrate(orig_name) => {
531 self.head(visibility_qualified(&item.vis, "extern crate"))?;
532 if let Some(orig_name) = orig_name {
533 self.print_name(orig_name)?;
538 self.print_ident(item.ident)?;
540 self.end()?; // end inner head-block
541 self.end()?; // end outer head-block
543 hir::ItemKind::Use(ref path, kind) => {
544 self.head(visibility_qualified(&item.vis, "use"))?;
545 self.print_path(path, false)?;
548 hir::UseKind::Single => {
549 if path.segments.last().unwrap().ident != item.ident {
551 self.word_space("as")?;
552 self.print_ident(item.ident)?;
556 hir::UseKind::Glob => self.s.word("::*;")?,
557 hir::UseKind::ListStem => self.s.word("::{};")?
559 self.end()?; // end inner head-block
560 self.end()?; // end outer head-block
562 hir::ItemKind::Static(ref ty, m, expr) => {
563 self.head(visibility_qualified(&item.vis, "static"))?;
564 if m == hir::MutMutable {
565 self.word_space("mut")?;
567 self.print_ident(item.ident)?;
568 self.word_space(":")?;
569 self.print_type(&ty)?;
571 self.end()?; // end the head-ibox
573 self.word_space("=")?;
574 self.ann.nested(self, Nested::Body(expr))?;
576 self.end()?; // end the outer cbox
578 hir::ItemKind::Const(ref ty, expr) => {
579 self.head(visibility_qualified(&item.vis, "const"))?;
580 self.print_ident(item.ident)?;
581 self.word_space(":")?;
582 self.print_type(&ty)?;
584 self.end()?; // end the head-ibox
586 self.word_space("=")?;
587 self.ann.nested(self, Nested::Body(expr))?;
589 self.end()?; // end the outer cbox
591 hir::ItemKind::Fn(ref decl, header, ref typarams, body) => {
595 Some(item.ident.name),
601 self.end()?; // need to close a box
602 self.end()?; // need to close a box
603 self.ann.nested(self, Nested::Body(body))?;
605 hir::ItemKind::Mod(ref _mod) => {
606 self.head(visibility_qualified(&item.vis, "mod"))?;
607 self.print_ident(item.ident)?;
610 self.print_mod(_mod, &item.attrs)?;
611 self.bclose(item.span)?;
613 hir::ItemKind::ForeignMod(ref nmod) => {
614 self.head("extern")?;
615 self.word_nbsp(nmod.abi.to_string())?;
617 self.print_foreign_mod(nmod, &item.attrs)?;
618 self.bclose(item.span)?;
620 hir::ItemKind::GlobalAsm(ref ga) => {
621 self.head(visibility_qualified(&item.vis, "global asm"))?;
622 self.s.word(ga.asm.as_str().get())?;
625 hir::ItemKind::Ty(ref ty, ref generics) => {
626 self.head(visibility_qualified(&item.vis, "type"))?;
627 self.print_ident(item.ident)?;
628 self.print_generic_params(&generics.params)?;
629 self.end()?; // end the inner ibox
631 self.print_where_clause(&generics.where_clause)?;
633 self.word_space("=")?;
634 self.print_type(&ty)?;
636 self.end()?; // end the outer ibox
638 hir::ItemKind::Existential(ref exist) => {
639 self.head(visibility_qualified(&item.vis, "existential type"))?;
640 self.print_ident(item.ident)?;
641 self.print_generic_params(&exist.generics.params)?;
642 self.end()?; // end the inner ibox
644 self.print_where_clause(&exist.generics.where_clause)?;
646 self.word_space(":")?;
647 let mut real_bounds = Vec::with_capacity(exist.bounds.len());
648 for b in exist.bounds.iter() {
649 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
651 self.word_space("for ?")?;
652 self.print_trait_ref(&ptr.trait_ref)?;
654 real_bounds.push(b.clone());
657 self.print_bounds(":", &real_bounds[..])?;
659 self.end()?; // end the outer ibox
661 hir::ItemKind::Enum(ref enum_definition, ref params) => {
662 self.print_enum_def(enum_definition, params, item.ident.name, item.span,
665 hir::ItemKind::Struct(ref struct_def, ref generics) => {
666 self.head(visibility_qualified(&item.vis, "struct"))?;
667 self.print_struct(struct_def, generics, item.ident.name, item.span, true)?;
669 hir::ItemKind::Union(ref struct_def, ref generics) => {
670 self.head(visibility_qualified(&item.vis, "union"))?;
671 self.print_struct(struct_def, generics, item.ident.name, item.span, true)?;
673 hir::ItemKind::Impl(unsafety,
681 self.print_visibility(&item.vis)?;
682 self.print_defaultness(defaultness)?;
683 self.print_unsafety(unsafety)?;
684 self.word_nbsp("impl")?;
686 if !generics.params.is_empty() {
687 self.print_generic_params(&generics.params)?;
691 if let hir::ImplPolarity::Negative = polarity {
695 if let Some(ref t) = opt_trait {
696 self.print_trait_ref(t)?;
698 self.word_space("for")?;
701 self.print_type(&ty)?;
702 self.print_where_clause(&generics.where_clause)?;
706 self.print_inner_attributes(&item.attrs)?;
707 for impl_item in impl_items {
708 self.ann.nested(self, Nested::ImplItem(impl_item.id))?;
710 self.bclose(item.span)?;
712 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
714 self.print_visibility(&item.vis)?;
715 self.print_is_auto(is_auto)?;
716 self.print_unsafety(unsafety)?;
717 self.word_nbsp("trait")?;
718 self.print_ident(item.ident)?;
719 self.print_generic_params(&generics.params)?;
720 let mut real_bounds = Vec::with_capacity(bounds.len());
721 for b in bounds.iter() {
722 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
724 self.word_space("for ?")?;
725 self.print_trait_ref(&ptr.trait_ref)?;
727 real_bounds.push(b.clone());
730 self.print_bounds(":", &real_bounds[..])?;
731 self.print_where_clause(&generics.where_clause)?;
734 for trait_item in trait_items {
735 self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
737 self.bclose(item.span)?;
739 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
741 self.print_visibility(&item.vis)?;
742 self.word_nbsp("trait")?;
743 self.print_ident(item.ident)?;
744 self.print_generic_params(&generics.params)?;
745 let mut real_bounds = Vec::with_capacity(bounds.len());
746 // FIXME(durka) this seems to be some quite outdated syntax
747 for b in bounds.iter() {
748 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
750 self.word_space("for ?")?;
751 self.print_trait_ref(&ptr.trait_ref)?;
753 real_bounds.push(b.clone());
757 self.print_bounds("=", &real_bounds[..])?;
758 self.print_where_clause(&generics.where_clause)?;
762 self.ann.post(self, AnnNode::Item(item))
765 pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
766 self.print_path(&t.path, false)
769 fn print_formal_generic_params(
771 generic_params: &[hir::GenericParam]
772 ) -> io::Result<()> {
773 if !generic_params.is_empty() {
775 self.print_generic_params(generic_params)?;
781 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
782 self.print_formal_generic_params(&t.bound_generic_params)?;
783 self.print_trait_ref(&t.trait_ref)
786 pub fn print_enum_def(&mut self,
787 enum_definition: &hir::EnumDef,
788 generics: &hir::Generics,
790 span: syntax_pos::Span,
791 visibility: &hir::Visibility)
793 self.head(visibility_qualified(visibility, "enum"))?;
794 self.print_name(name)?;
795 self.print_generic_params(&generics.params)?;
796 self.print_where_clause(&generics.where_clause)?;
798 self.print_variants(&enum_definition.variants, span)
801 pub fn print_variants(&mut self,
802 variants: &[hir::Variant],
803 span: syntax_pos::Span)
807 self.space_if_not_bol()?;
808 self.maybe_print_comment(v.span.lo())?;
809 self.print_outer_attributes(&v.node.attrs)?;
810 self.ibox(indent_unit)?;
811 self.print_variant(v)?;
814 self.maybe_print_trailing_comment(v.span, None)?;
819 pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
821 hir::VisibilityKind::Public => self.word_nbsp("pub")?,
822 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate")?,
823 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)")?,
824 hir::VisibilityKind::Restricted { ref path, .. } => {
825 self.s.word("pub(")?;
826 if path.segments.len() == 1 &&
827 path.segments[0].ident.name == keywords::Super.name() {
828 // Special case: `super` can print like `pub(super)`.
829 self.s.word("super")?;
831 // Everything else requires `in` at present.
832 self.word_nbsp("in")?;
833 self.print_path(path, false)?;
835 self.word_nbsp(")")?;
837 hir::VisibilityKind::Inherited => ()
843 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) -> io::Result<()> {
845 hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
846 hir::Defaultness::Final => (),
851 pub fn print_struct(&mut self,
852 struct_def: &hir::VariantData,
853 generics: &hir::Generics,
855 span: syntax_pos::Span,
856 print_finalizer: bool)
858 self.print_name(name)?;
859 self.print_generic_params(&generics.params)?;
860 if !struct_def.is_struct() {
861 if struct_def.is_tuple() {
863 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
864 s.maybe_print_comment(field.span.lo())?;
865 s.print_outer_attributes(&field.attrs)?;
866 s.print_visibility(&field.vis)?;
867 s.print_type(&field.ty)
871 self.print_where_clause(&generics.where_clause)?;
876 self.end() // close the outer-box
878 self.print_where_clause(&generics.where_clause)?;
881 self.hardbreak_if_not_bol()?;
883 for field in struct_def.fields() {
884 self.hardbreak_if_not_bol()?;
885 self.maybe_print_comment(field.span.lo())?;
886 self.print_outer_attributes(&field.attrs)?;
887 self.print_visibility(&field.vis)?;
888 self.print_ident(field.ident)?;
889 self.word_nbsp(":")?;
890 self.print_type(&field.ty)?;
898 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
900 let generics = hir::Generics::empty();
901 self.print_struct(&v.node.data, &generics, v.node.ident.name, v.span, false)?;
902 if let Some(ref d) = v.node.disr_expr {
904 self.word_space("=")?;
905 self.print_anon_const(d)?;
909 pub fn print_method_sig(&mut self,
912 generics: &hir::Generics,
913 vis: &hir::Visibility,
914 arg_names: &[ast::Ident],
915 body_id: Option<hir::BodyId>)
917 self.print_fn(&m.decl,
926 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
927 self.ann.pre(self, AnnNode::SubItem(ti.id))?;
928 self.hardbreak_if_not_bol()?;
929 self.maybe_print_comment(ti.span.lo())?;
930 self.print_outer_attributes(&ti.attrs)?;
932 hir::TraitItemKind::Const(ref ty, default) => {
933 let vis = Spanned { span: syntax_pos::DUMMY_SP,
934 node: hir::VisibilityKind::Inherited };
935 self.print_associated_const(ti.ident, &ty, default, &vis)?;
937 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
938 let vis = Spanned { span: syntax_pos::DUMMY_SP,
939 node: hir::VisibilityKind::Inherited };
940 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None)?;
943 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
944 let vis = Spanned { span: syntax_pos::DUMMY_SP,
945 node: hir::VisibilityKind::Inherited };
947 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body))?;
949 self.end()?; // need to close a box
950 self.end()?; // need to close a box
951 self.ann.nested(self, Nested::Body(body))?;
953 hir::TraitItemKind::Type(ref bounds, ref default) => {
954 self.print_associated_type(ti.ident,
956 default.as_ref().map(|ty| &**ty))?;
959 self.ann.post(self, AnnNode::SubItem(ti.id))
962 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
963 self.ann.pre(self, AnnNode::SubItem(ii.id))?;
964 self.hardbreak_if_not_bol()?;
965 self.maybe_print_comment(ii.span.lo())?;
966 self.print_outer_attributes(&ii.attrs)?;
967 self.print_defaultness(ii.defaultness)?;
970 hir::ImplItemKind::Const(ref ty, expr) => {
971 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis)?;
973 hir::ImplItemKind::Method(ref sig, body) => {
975 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body))?;
977 self.end()?; // need to close a box
978 self.end()?; // need to close a box
979 self.ann.nested(self, Nested::Body(body))?;
981 hir::ImplItemKind::Type(ref ty) => {
982 self.print_associated_type(ii.ident, None, Some(ty))?;
984 hir::ImplItemKind::Existential(ref bounds) => {
985 self.word_space("existential")?;
986 self.print_associated_type(ii.ident, Some(bounds), None)?;
989 self.ann.post(self, AnnNode::SubItem(ii.id))
992 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
993 self.maybe_print_comment(st.span.lo())?;
995 hir::StmtKind::Local(ref loc) => {
996 self.space_if_not_bol()?;
997 self.ibox(indent_unit)?;
998 self.word_nbsp("let")?;
1000 self.ibox(indent_unit)?;
1001 self.print_local_decl(&loc)?;
1003 if let Some(ref init) = loc.init {
1005 self.word_space("=")?;
1006 self.print_expr(&init)?;
1010 hir::StmtKind::Item(item) => {
1011 self.ann.nested(self, Nested::Item(item))?
1013 hir::StmtKind::Expr(ref expr) => {
1014 self.space_if_not_bol()?;
1015 self.print_expr(&expr)?;
1017 hir::StmtKind::Semi(ref expr) => {
1018 self.space_if_not_bol()?;
1019 self.print_expr(&expr)?;
1023 if stmt_ends_with_semi(&st.node) {
1026 self.maybe_print_trailing_comment(st.span, None)
1029 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1030 self.print_block_with_attrs(blk, &[])
1033 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1034 self.print_block_unclosed_indent(blk, indent_unit)
1037 pub fn print_block_unclosed_indent(&mut self,
1041 self.print_block_maybe_unclosed(blk, indented, &[], false)
1044 pub fn print_block_with_attrs(&mut self,
1046 attrs: &[ast::Attribute])
1048 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1051 pub fn print_block_maybe_unclosed(&mut self,
1054 attrs: &[ast::Attribute],
1058 hir::UnsafeBlock(..) => self.word_space("unsafe")?,
1059 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
1060 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
1061 hir::DefaultBlock => (),
1063 self.maybe_print_comment(blk.span.lo())?;
1064 self.ann.pre(self, AnnNode::Block(blk))?;
1067 self.print_inner_attributes(attrs)?;
1069 for st in &blk.stmts {
1070 self.print_stmt(st)?;
1072 if let Some(ref expr) = blk.expr {
1073 self.space_if_not_bol()?;
1074 self.print_expr(&expr)?;
1075 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1077 self.bclose_maybe_open(blk.span, indented, close_box)?;
1078 self.ann.post(self, AnnNode::Block(blk))
1081 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1085 // "another else-if"
1086 hir::ExprKind::If(ref i, ref then, ref e) => {
1087 self.cbox(indent_unit - 1)?;
1089 self.s.word(" else if ")?;
1090 self.print_expr_as_cond(&i)?;
1092 self.print_expr(&then)?;
1093 self.print_else(e.as_ref().map(|e| &**e))
1096 hir::ExprKind::Block(ref b, _) => {
1097 self.cbox(indent_unit - 1)?;
1099 self.s.word(" else ")?;
1100 self.print_block(&b)
1102 // BLEAH, constraints would be great here
1104 panic!("print_if saw if with weird alternative");
1112 pub fn print_if(&mut self,
1115 elseopt: Option<&hir::Expr>)
1118 self.print_expr_as_cond(test)?;
1120 self.print_expr(blk)?;
1121 self.print_else(elseopt)
1124 pub fn print_if_let(&mut self,
1128 elseopt: Option<&hir::Expr>)
1130 self.head("if let")?;
1131 self.print_pat(pat)?;
1133 self.word_space("=")?;
1134 self.print_expr_as_cond(expr)?;
1136 self.print_block(blk)?;
1137 self.print_else(elseopt)
1140 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) -> io::Result<()> {
1141 self.ann.nested(self, Nested::Body(constant.body))
1144 fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
1146 self.commasep_exprs(Inconsistent, args)?;
1150 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr, prec: i8) -> io::Result<()> {
1151 let needs_par = expr.precedence().order() < prec;
1155 self.print_expr(expr)?;
1162 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1163 /// `if cond { ... }`.
1164 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr) -> io::Result<()> {
1165 let needs_par = match expr.node {
1166 // These cases need parens due to the parse error observed in #26461: `if return {}`
1167 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1168 hir::ExprKind::Closure(..) |
1169 hir::ExprKind::Ret(..) |
1170 hir::ExprKind::Break(..) => true,
1172 _ => contains_exterior_struct_lit(expr),
1178 self.print_expr(expr)?;
1185 fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1186 self.ibox(indent_unit)?;
1188 self.commasep_exprs(Inconsistent, exprs)?;
1193 fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::AnonConst) -> io::Result<()> {
1194 self.ibox(indent_unit)?;
1196 self.print_expr(element)?;
1197 self.word_space(";")?;
1198 self.print_anon_const(count)?;
1203 fn print_expr_struct(&mut self,
1205 fields: &[hir::Field],
1206 wth: &Option<P<hir::Expr>>)
1208 self.print_qpath(qpath, true)?;
1210 self.commasep_cmnt(Consistent,
1213 s.ibox(indent_unit)?;
1214 if !field.is_shorthand {
1215 s.print_ident(field.ident)?;
1218 s.print_expr(&field.expr)?;
1224 self.ibox(indent_unit)?;
1225 if !fields.is_empty() {
1230 self.print_expr(&expr)?;
1233 _ => if !fields.is_empty() {
1241 fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1243 self.commasep_exprs(Inconsistent, exprs)?;
1244 if exprs.len() == 1 {
1250 fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1253 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1254 _ => parser::PREC_POSTFIX,
1257 self.print_expr_maybe_paren(func, prec)?;
1258 self.print_call_post(args)
1261 fn print_expr_method_call(&mut self,
1262 segment: &hir::PathSegment,
1265 let base_args = &args[1..];
1266 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
1268 self.print_ident(segment.ident)?;
1270 segment.with_generic_args(|generic_args| {
1271 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1272 return self.print_generic_args(&generic_args, segment.infer_types, true);
1276 self.print_call_post(base_args)
1279 fn print_expr_binary(&mut self,
1284 let assoc_op = bin_op_to_assoc_op(op.node);
1285 let prec = assoc_op.precedence() as i8;
1286 let fixity = assoc_op.fixity();
1288 let (left_prec, right_prec) = match fixity {
1289 Fixity::Left => (prec, prec + 1),
1290 Fixity::Right => (prec + 1, prec),
1291 Fixity::None => (prec + 1, prec + 1),
1294 let left_prec = match (&lhs.node, op.node) {
1295 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1296 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1297 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1298 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt) |
1299 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1303 self.print_expr_maybe_paren(lhs, left_prec)?;
1305 self.word_space(op.node.as_str())?;
1306 self.print_expr_maybe_paren(rhs, right_prec)
1309 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1310 self.s.word(op.as_str())?;
1311 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1314 fn print_expr_addr_of(&mut self,
1315 mutability: hir::Mutability,
1319 self.print_mutability(mutability)?;
1320 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1323 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1324 self.maybe_print_comment(expr.span.lo())?;
1325 self.print_outer_attributes(&expr.attrs)?;
1326 self.ibox(indent_unit)?;
1327 self.ann.pre(self, AnnNode::Expr(expr))?;
1329 hir::ExprKind::Box(ref expr) => {
1330 self.word_space("box")?;
1331 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
1333 hir::ExprKind::Array(ref exprs) => {
1334 self.print_expr_vec(exprs)?;
1336 hir::ExprKind::Repeat(ref element, ref count) => {
1337 self.print_expr_repeat(&element, count)?;
1339 hir::ExprKind::Struct(ref qpath, ref fields, ref wth) => {
1340 self.print_expr_struct(qpath, &fields[..], wth)?;
1342 hir::ExprKind::Tup(ref exprs) => {
1343 self.print_expr_tup(exprs)?;
1345 hir::ExprKind::Call(ref func, ref args) => {
1346 self.print_expr_call(&func, args)?;
1348 hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1349 self.print_expr_method_call(segment, args)?;
1351 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1352 self.print_expr_binary(op, &lhs, &rhs)?;
1354 hir::ExprKind::Unary(op, ref expr) => {
1355 self.print_expr_unary(op, &expr)?;
1357 hir::ExprKind::AddrOf(m, ref expr) => {
1358 self.print_expr_addr_of(m, &expr)?;
1360 hir::ExprKind::Lit(ref lit) => {
1361 self.print_literal(&lit)?;
1363 hir::ExprKind::Cast(ref expr, ref ty) => {
1364 let prec = AssocOp::As.precedence() as i8;
1365 self.print_expr_maybe_paren(&expr, prec)?;
1367 self.word_space("as")?;
1368 self.print_type(&ty)?;
1370 hir::ExprKind::Type(ref expr, ref ty) => {
1371 let prec = AssocOp::Colon.precedence() as i8;
1372 self.print_expr_maybe_paren(&expr, prec)?;
1373 self.word_space(":")?;
1374 self.print_type(&ty)?;
1376 hir::ExprKind::If(ref test, ref blk, ref elseopt) => {
1377 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1379 hir::ExprKind::While(ref test, ref blk, opt_label) => {
1380 if let Some(label) = opt_label {
1381 self.print_ident(label.ident)?;
1382 self.word_space(":")?;
1384 self.head("while")?;
1385 self.print_expr_as_cond(&test)?;
1387 self.print_block(&blk)?;
1389 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1390 if let Some(label) = opt_label {
1391 self.print_ident(label.ident)?;
1392 self.word_space(":")?;
1396 self.print_block(&blk)?;
1398 hir::ExprKind::Match(ref expr, ref arms, _) => {
1399 self.cbox(indent_unit)?;
1401 self.word_nbsp("match")?;
1402 self.print_expr_as_cond(&expr)?;
1406 self.print_arm(arm)?;
1408 self.bclose_(expr.span, indent_unit)?;
1410 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1411 self.print_capture_clause(capture_clause)?;
1413 self.print_closure_args(&decl, body)?;
1416 // this is a bare expression
1417 self.ann.nested(self, Nested::Body(body))?;
1418 self.end()?; // need to close a box
1420 // a box will be closed by print_expr, but we didn't want an overall
1421 // wrapper so we closed the corresponding opening. so create an
1422 // empty box to satisfy the close.
1425 hir::ExprKind::Block(ref blk, opt_label) => {
1426 if let Some(label) = opt_label {
1427 self.print_ident(label.ident)?;
1428 self.word_space(":")?;
1430 // containing cbox, will be closed by print-block at }
1431 self.cbox(indent_unit)?;
1432 // head-box, will be closed by print-block after {
1434 self.print_block(&blk)?;
1436 hir::ExprKind::Assign(ref lhs, ref rhs) => {
1437 let prec = AssocOp::Assign.precedence() as i8;
1438 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1440 self.word_space("=")?;
1441 self.print_expr_maybe_paren(&rhs, prec)?;
1443 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1444 let prec = AssocOp::Assign.precedence() as i8;
1445 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1447 self.s.word(op.node.as_str())?;
1448 self.word_space("=")?;
1449 self.print_expr_maybe_paren(&rhs, prec)?;
1451 hir::ExprKind::Field(ref expr, ident) => {
1452 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
1454 self.print_ident(ident)?;
1456 hir::ExprKind::Index(ref expr, ref index) => {
1457 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1459 self.print_expr(&index)?;
1462 hir::ExprKind::Path(ref qpath) => {
1463 self.print_qpath(qpath, true)?
1465 hir::ExprKind::Break(destination, ref opt_expr) => {
1466 self.s.word("break")?;
1468 if let Some(label) = destination.label {
1469 self.print_ident(label.ident)?;
1472 if let Some(ref expr) = *opt_expr {
1473 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
1477 hir::ExprKind::Continue(destination) => {
1478 self.s.word("continue")?;
1480 if let Some(label) = destination.label {
1481 self.print_ident(label.ident)?;
1485 hir::ExprKind::Ret(ref result) => {
1486 self.s.word("return")?;
1487 if let Some(ref expr) = *result {
1489 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1492 hir::ExprKind::InlineAsm(ref a, ref outputs, ref inputs) => {
1493 self.s.word("asm!")?;
1495 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
1496 self.word_space(":")?;
1498 let mut out_idx = 0;
1499 self.commasep(Inconsistent, &a.outputs, |s, out| {
1500 let constraint = out.constraint.as_str();
1501 let mut ch = constraint.chars();
1503 Some('=') if out.is_rw => {
1504 s.print_string(&format!("+{}", ch.as_str()),
1505 ast::StrStyle::Cooked)?
1507 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
1510 s.print_expr(&outputs[out_idx])?;
1516 self.word_space(":")?;
1519 self.commasep(Inconsistent, &a.inputs, |s, co| {
1520 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1522 s.print_expr(&inputs[in_idx])?;
1528 self.word_space(":")?;
1530 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1531 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1535 let mut options = vec![];
1537 options.push("volatile");
1540 options.push("alignstack");
1542 if a.dialect == ast::AsmDialect::Intel {
1543 options.push("intel");
1546 if !options.is_empty() {
1548 self.word_space(":")?;
1549 self.commasep(Inconsistent, &options, |s, &co| {
1550 s.print_string(co, ast::StrStyle::Cooked)?;
1557 hir::ExprKind::Yield(ref expr) => {
1558 self.word_space("yield")?;
1559 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1561 hir::ExprKind::Err => {
1563 self.s.word("/*ERROR*/")?;
1567 self.ann.post(self, AnnNode::Expr(expr))?;
1571 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1572 self.print_pat(&loc.pat)?;
1573 if let Some(ref ty) = loc.ty {
1574 self.word_space(":")?;
1575 self.print_type(&ty)?;
1580 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1581 self.s.word(i.to_string())
1584 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
1585 if ident.is_raw_guess() {
1586 self.s.word(format!("r#{}", ident.name))?;
1588 self.s.word(ident.as_str().get())?;
1590 self.ann.post(self, AnnNode::Name(&ident.name))
1593 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1594 self.print_ident(ast::Ident::with_empty_ctxt(name))
1597 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1598 self.print_local_decl(loc)?;
1600 self.word_space("in")?;
1601 self.print_expr(coll)
1604 pub fn print_path(&mut self,
1606 colons_before_params: bool)
1608 self.maybe_print_comment(path.span.lo())?;
1610 for (i, segment) in path.segments.iter().enumerate() {
1614 if segment.ident.name != keywords::PathRoot.name() {
1615 self.print_ident(segment.ident)?;
1616 segment.with_generic_args(|generic_args| {
1617 self.print_generic_args(generic_args, segment.infer_types,
1618 colons_before_params)
1626 pub fn print_path_segment(&mut self, segment: &hir::PathSegment) -> io::Result<()> {
1627 if segment.ident.name != keywords::PathRoot.name() {
1628 self.print_ident(segment.ident)?;
1629 segment.with_generic_args(|generic_args| {
1630 self.print_generic_args(generic_args, segment.infer_types, false)
1636 pub fn print_qpath(&mut self,
1638 colons_before_params: bool)
1641 hir::QPath::Resolved(None, ref path) => {
1642 self.print_path(path, colons_before_params)
1644 hir::QPath::Resolved(Some(ref qself), ref path) => {
1646 self.print_type(qself)?;
1648 self.word_space("as")?;
1650 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1654 if segment.ident.name != keywords::PathRoot.name() {
1655 self.print_ident(segment.ident)?;
1656 segment.with_generic_args(|generic_args| {
1657 self.print_generic_args(generic_args,
1658 segment.infer_types,
1659 colons_before_params)
1666 let item_segment = path.segments.last().unwrap();
1667 self.print_ident(item_segment.ident)?;
1668 item_segment.with_generic_args(|generic_args| {
1669 self.print_generic_args(generic_args,
1670 item_segment.infer_types,
1671 colons_before_params)
1674 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1676 self.print_type(qself)?;
1679 self.print_ident(item_segment.ident)?;
1680 item_segment.with_generic_args(|generic_args| {
1681 self.print_generic_args(generic_args,
1682 item_segment.infer_types,
1683 colons_before_params)
1689 fn print_generic_args(&mut self,
1690 generic_args: &hir::GenericArgs,
1692 colons_before_params: bool)
1694 if generic_args.parenthesized {
1696 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty))?;
1699 self.space_if_not_bol()?;
1700 self.word_space("->")?;
1701 self.print_type(&generic_args.bindings[0].ty)?;
1703 let start = if colons_before_params { "::<" } else { "<" };
1704 let empty = Cell::new(true);
1705 let start_or_comma = |this: &mut Self| {
1710 this.word_space(",")
1714 let mut nonelided_generic_args: bool = false;
1715 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1716 GenericArg::Lifetime(lt) => lt.is_elided(),
1718 nonelided_generic_args = true;
1723 if nonelided_generic_args {
1724 start_or_comma(self)?;
1725 self.commasep(Inconsistent, &generic_args.args, |s, generic_arg| {
1727 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1728 GenericArg::Lifetime(_) => Ok(()),
1729 GenericArg::Type(ty) => s.print_type(ty),
1730 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1735 // FIXME(eddyb) This would leak into error messages, e.g.:
1736 // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1737 if infer_types && false {
1738 start_or_comma(self)?;
1742 for binding in generic_args.bindings.iter() {
1743 start_or_comma(self)?;
1744 self.print_ident(binding.ident)?;
1746 self.word_space("=")?;
1747 self.print_type(&binding.ty)?;
1758 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1759 self.maybe_print_comment(pat.span.lo())?;
1760 self.ann.pre(self, AnnNode::Pat(pat))?;
1761 // Pat isn't normalized, but the beauty of it
1762 // is that it doesn't matter
1764 PatKind::Wild => self.s.word("_")?,
1765 PatKind::Binding(binding_mode, _, _, ident, ref sub) => {
1766 match binding_mode {
1767 hir::BindingAnnotation::Ref => {
1768 self.word_nbsp("ref")?;
1769 self.print_mutability(hir::MutImmutable)?;
1771 hir::BindingAnnotation::RefMut => {
1772 self.word_nbsp("ref")?;
1773 self.print_mutability(hir::MutMutable)?;
1775 hir::BindingAnnotation::Unannotated => {}
1776 hir::BindingAnnotation::Mutable => {
1777 self.word_nbsp("mut")?;
1780 self.print_ident(ident)?;
1781 if let Some(ref p) = *sub {
1783 self.print_pat(&p)?;
1786 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1787 self.print_qpath(qpath, true)?;
1789 if let Some(ddpos) = ddpos {
1790 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1792 self.word_space(",")?;
1795 if ddpos != elts.len() {
1797 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1800 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1804 PatKind::Path(ref qpath) => {
1805 self.print_qpath(qpath, true)?;
1807 PatKind::Struct(ref qpath, ref fields, etc) => {
1808 self.print_qpath(qpath, true)?;
1810 self.word_space("{")?;
1811 self.commasep_cmnt(Consistent,
1814 s.cbox(indent_unit)?;
1815 if !f.node.is_shorthand {
1816 s.print_ident(f.node.ident)?;
1819 s.print_pat(&f.node.pat)?;
1822 |f| f.node.pat.span)?;
1824 if !fields.is_empty() {
1825 self.word_space(",")?;
1832 PatKind::Tuple(ref elts, ddpos) => {
1834 if let Some(ddpos) = ddpos {
1835 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1837 self.word_space(",")?;
1840 if ddpos != elts.len() {
1842 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1845 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1846 if elts.len() == 1 {
1852 PatKind::Box(ref inner) => {
1853 let is_range_inner = match inner.node {
1854 PatKind::Range(..) => true,
1857 self.s.word("box ")?;
1861 self.print_pat(&inner)?;
1866 PatKind::Ref(ref inner, mutbl) => {
1867 let is_range_inner = match inner.node {
1868 PatKind::Range(..) => true,
1872 if mutbl == hir::MutMutable {
1873 self.s.word("mut ")?;
1878 self.print_pat(&inner)?;
1883 PatKind::Lit(ref e) => self.print_expr(&e)?,
1884 PatKind::Range(ref begin, ref end, ref end_kind) => {
1885 self.print_expr(&begin)?;
1888 RangeEnd::Included => self.s.word("...")?,
1889 RangeEnd::Excluded => self.s.word("..")?,
1891 self.print_expr(&end)?;
1893 PatKind::Slice(ref before, ref slice, ref after) => {
1895 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1896 if let Some(ref p) = *slice {
1897 if !before.is_empty() {
1898 self.word_space(",")?;
1900 if let PatKind::Wild = p.node {
1903 self.print_pat(&p)?;
1906 if !after.is_empty() {
1907 self.word_space(",")?;
1910 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1914 self.ann.post(self, AnnNode::Pat(pat))
1917 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1918 // I have no idea why this check is necessary, but here it
1920 if arm.attrs.is_empty() {
1923 self.cbox(indent_unit)?;
1925 self.print_outer_attributes(&arm.attrs)?;
1926 let mut first = true;
1927 for p in &arm.pats {
1932 self.word_space("|")?;
1934 self.print_pat(&p)?;
1937 if let Some(ref g) = arm.guard {
1939 hir::Guard::If(e) => {
1940 self.word_space("if")?;
1941 self.print_expr(&e)?;
1946 self.word_space("=>")?;
1948 match arm.body.node {
1949 hir::ExprKind::Block(ref blk, opt_label) => {
1950 if let Some(label) = opt_label {
1951 self.print_ident(label.ident)?;
1952 self.word_space(":")?;
1954 // the block will close the pattern's ibox
1955 self.print_block_unclosed_indent(&blk, indent_unit)?;
1957 // If it is a user-provided unsafe block, print a comma after it
1958 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1963 self.end()?; // close the ibox for the pattern
1964 self.print_expr(&arm.body)?;
1968 self.end() // close enclosing cbox
1971 pub fn print_fn(&mut self,
1973 header: hir::FnHeader,
1974 name: Option<ast::Name>,
1975 generics: &hir::Generics,
1976 vis: &hir::Visibility,
1977 arg_names: &[ast::Ident],
1978 body_id: Option<hir::BodyId>)
1980 self.print_fn_header_info(header, vis)?;
1982 if let Some(name) = name {
1984 self.print_name(name)?;
1986 self.print_generic_params(&generics.params)?;
1990 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1991 assert!(arg_names.is_empty() || body_id.is_none());
1992 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1993 s.ibox(indent_unit)?;
1994 if let Some(arg_name) = arg_names.get(i) {
1995 s.s.word(arg_name.as_str().get())?;
1998 } else if let Some(body_id) = body_id {
1999 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2008 self.s.word(", ...")?;
2012 self.print_fn_output(decl)?;
2013 self.print_where_clause(&generics.where_clause)
2016 fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
2019 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2020 s.ibox(indent_unit)?;
2022 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2025 if let hir::TyKind::Infer = ty.node {
2036 if let hir::DefaultReturn(..) = decl.output {
2040 self.space_if_not_bol()?;
2041 self.word_space("->")?;
2043 hir::Return(ref ty) => {
2044 self.print_type(&ty)?;
2045 self.maybe_print_comment(ty.span.lo())
2047 hir::DefaultReturn(..) => unreachable!(),
2051 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
2052 match capture_clause {
2053 hir::CaptureByValue => self.word_space("move"),
2054 hir::CaptureByRef => Ok(()),
2058 pub fn print_bounds(&mut self, prefix: &'static str, bounds: &[hir::GenericBound])
2060 if !bounds.is_empty() {
2061 self.s.word(prefix)?;
2062 let mut first = true;
2063 for bound in bounds {
2064 if !(first && prefix.is_empty()) {
2070 self.word_space("+")?;
2074 GenericBound::Trait(tref, modifier) => {
2075 if modifier == &TraitBoundModifier::Maybe {
2078 self.print_poly_trait_ref(tref)?;
2080 GenericBound::Outlives(lt) => {
2081 self.print_lifetime(lt)?;
2089 pub fn print_generic_params(&mut self, generic_params: &[GenericParam]) -> io::Result<()> {
2090 if !generic_params.is_empty() {
2093 self.commasep(Inconsistent, generic_params, |s, param| {
2094 s.print_generic_param(param)
2102 pub fn print_generic_param(&mut self, param: &GenericParam) -> io::Result<()> {
2103 if let GenericParamKind::Const { .. } = param.kind {
2104 self.word_space("const")?;
2107 self.print_ident(param.name.ident())?;
2110 GenericParamKind::Lifetime { .. } => {
2112 for bound in ¶m.bounds {
2114 GenericBound::Outlives(lt) => {
2116 self.print_lifetime(lt)?;
2124 GenericParamKind::Type { ref default, .. } => {
2125 self.print_bounds(":", ¶m.bounds)?;
2129 self.word_space("=")?;
2130 self.print_type(&default)
2135 GenericParamKind::Const { ref ty } => {
2136 self.word_space(":")?;
2142 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2143 self.print_ident(lifetime.name.ident())
2146 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2147 if where_clause.predicates.is_empty() {
2152 self.word_space("where")?;
2154 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2156 self.word_space(",")?;
2160 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2161 ref bound_generic_params,
2166 self.print_formal_generic_params(bound_generic_params)?;
2167 self.print_type(&bounded_ty)?;
2168 self.print_bounds(":", bounds)?;
2170 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2173 self.print_lifetime(lifetime)?;
2176 for (i, bound) in bounds.iter().enumerate() {
2178 GenericBound::Outlives(lt) => {
2179 self.print_lifetime(lt)?;
2189 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
2192 self.print_type(lhs_ty)?;
2194 self.word_space("=")?;
2195 self.print_type(rhs_ty)?;
2203 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2205 hir::MutMutable => self.word_nbsp("mut"),
2206 hir::MutImmutable => Ok(()),
2210 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2211 self.print_mutability(mt.mutbl)?;
2212 self.print_type(&mt.ty)
2215 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2216 if let hir::DefaultReturn(..) = decl.output {
2220 self.space_if_not_bol()?;
2221 self.ibox(indent_unit)?;
2222 self.word_space("->")?;
2224 hir::DefaultReturn(..) => unreachable!(),
2225 hir::Return(ref ty) => self.print_type(&ty)?,
2230 hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2235 pub fn print_ty_fn(&mut self,
2237 unsafety: hir::Unsafety,
2239 name: Option<ast::Name>,
2240 generic_params: &[hir::GenericParam],
2241 arg_names: &[ast::Ident])
2243 self.ibox(indent_unit)?;
2244 if !generic_params.is_empty() {
2245 self.s.word("for")?;
2246 self.print_generic_params(generic_params)?;
2248 let generics = hir::Generics {
2249 params: hir::HirVec::new(),
2250 where_clause: hir::WhereClause {
2251 hir_id: hir::DUMMY_HIR_ID,
2252 predicates: hir::HirVec::new(),
2254 span: syntax_pos::DUMMY_SP,
2260 constness: hir::Constness::NotConst,
2261 asyncness: hir::IsAsync::NotAsync,
2265 &Spanned { span: syntax_pos::DUMMY_SP,
2266 node: hir::VisibilityKind::Inherited },
2272 pub fn maybe_print_trailing_comment(&mut self,
2273 span: syntax_pos::Span,
2274 next_pos: Option<BytePos>)
2276 let cm = match self.cm {
2280 if let Some(ref cmnt) = self.next_comment() {
2281 if (*cmnt).style != comments::Trailing {
2284 let span_line = cm.lookup_char_pos(span.hi());
2285 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2286 let mut next = (*cmnt).pos + BytePos(1);
2287 if let Some(p) = next_pos {
2290 if span.hi() < (*cmnt).pos && (*cmnt).pos < next &&
2291 span_line.line == comment_line.line {
2292 self.print_comment(cmnt)?;
2298 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2299 // If there aren't any remaining comments, then we need to manually
2300 // make sure there is a line break at the end.
2301 if self.next_comment().is_none() {
2302 self.s.hardbreak()?;
2304 while let Some(ref cmnt) = self.next_comment() {
2305 self.print_comment(cmnt)?
2310 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2311 opt_abi: Option<Abi>)
2314 Some(Abi::Rust) => Ok(()),
2316 self.word_nbsp("extern")?;
2317 self.word_nbsp(abi.to_string())
2323 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2326 self.word_nbsp("extern")?;
2327 self.word_nbsp(abi.to_string())
2333 pub fn print_fn_header_info(&mut self,
2334 header: hir::FnHeader,
2335 vis: &hir::Visibility)
2337 self.s.word(visibility_qualified(vis, ""))?;
2339 match header.constness {
2340 hir::Constness::NotConst => {}
2341 hir::Constness::Const => self.word_nbsp("const")?,
2344 match header.asyncness {
2345 hir::IsAsync::NotAsync => {}
2346 hir::IsAsync::Async => self.word_nbsp("async")?,
2349 self.print_unsafety(header.unsafety)?;
2351 if header.abi != Abi::Rust {
2352 self.word_nbsp("extern")?;
2353 self.word_nbsp(header.abi.to_string())?;
2359 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2361 hir::Unsafety::Normal => Ok(()),
2362 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2366 pub fn print_is_auto(&mut self, s: hir::IsAuto) -> io::Result<()> {
2368 hir::IsAuto::Yes => self.word_nbsp("auto"),
2369 hir::IsAuto::No => Ok(()),
2374 // Dup'ed from parse::classify, but adapted for the HIR.
2375 /// Does this expression require a semicolon to be treated
2376 /// as a statement? The negation of this: 'can this expression
2377 /// be used as a statement without a semicolon' -- is used
2378 /// as an early-bail-out in the parser so that, for instance,
2379 /// if true {...} else {...}
2381 /// isn't parsed as (if true {...} else {...} | x) | 5
2382 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2384 hir::ExprKind::If(..) |
2385 hir::ExprKind::Match(..) |
2386 hir::ExprKind::Block(..) |
2387 hir::ExprKind::While(..) |
2388 hir::ExprKind::Loop(..) => false,
2393 /// this statement requires a semicolon after it.
2394 /// note that in one case (stmt_semi), we've already
2395 /// seen the semicolon, and thus don't need another.
2396 fn stmt_ends_with_semi(stmt: &hir::StmtKind) -> bool {
2398 hir::StmtKind::Local(_) => true,
2399 hir::StmtKind::Item(_) => false,
2400 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2401 hir::StmtKind::Semi(..) => false,
2405 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2406 use crate::hir::BinOpKind::*;
2408 Add => AssocOp::Add,
2409 Sub => AssocOp::Subtract,
2410 Mul => AssocOp::Multiply,
2411 Div => AssocOp::Divide,
2412 Rem => AssocOp::Modulus,
2414 And => AssocOp::LAnd,
2417 BitXor => AssocOp::BitXor,
2418 BitAnd => AssocOp::BitAnd,
2419 BitOr => AssocOp::BitOr,
2420 Shl => AssocOp::ShiftLeft,
2421 Shr => AssocOp::ShiftRight,
2423 Eq => AssocOp::Equal,
2424 Lt => AssocOp::Less,
2425 Le => AssocOp::LessEqual,
2426 Ne => AssocOp::NotEqual,
2427 Ge => AssocOp::GreaterEqual,
2428 Gt => AssocOp::Greater,
2432 /// Expressions that syntactically contain an "exterior" struct literal i.e., not surrounded by any
2433 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2434 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2435 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
2437 hir::ExprKind::Struct(..) => true,
2439 hir::ExprKind::Assign(ref lhs, ref rhs) |
2440 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) |
2441 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2442 // X { y: 1 } + X { y: 2 }
2443 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2445 hir::ExprKind::Unary(_, ref x) |
2446 hir::ExprKind::Cast(ref x, _) |
2447 hir::ExprKind::Type(ref x, _) |
2448 hir::ExprKind::Field(ref x, _) |
2449 hir::ExprKind::Index(ref x, _) => {
2450 // &X { y: 1 }, X { y: 1 }.y
2451 contains_exterior_struct_lit(&x)
2454 hir::ExprKind::MethodCall(.., ref exprs) => {
2455 // X { y: 1 }.bar(...)
2456 contains_exterior_struct_lit(&exprs[0])