1 use crate::ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax};
2 use crate::ast::{SelfKind, GenericBound, TraitBoundModifier};
3 use crate::ast::{Attribute, GenericArg, MacArgs};
4 use crate::util::parser::{self, AssocOp, Fixity};
5 use crate::util::comments;
7 use crate::source_map::{self, SourceMap, Spanned};
8 use crate::token::{self, BinOpToken, DelimToken, Nonterminal, Token, TokenKind};
9 use crate::print::pp::{self, Breaks};
10 use crate::print::pp::Breaks::{Consistent, Inconsistent};
12 use crate::util::classify;
13 use crate::sess::ParseSess;
14 use crate::symbol::{kw, sym};
15 use crate::tokenstream::{self, TokenStream, TokenTree};
17 use syntax_pos::{self, BytePos};
18 use syntax_pos::{FileName, Span};
25 pub enum MacHeader<'a> {
27 Keyword(&'static str),
30 pub enum AnnNode<'a> {
31 Ident(&'a ast::Ident),
33 Block(&'a ast::Block),
38 Crate(&'a ast::Crate),
42 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) { }
43 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) { }
46 #[derive(Copy, Clone)]
49 impl PpAnn for NoAnn {}
51 pub struct Comments<'a> {
53 comments: Vec<comments::Comment>,
57 impl<'a> Comments<'a> {
64 let comments = comments::gather_comments(sess, filename, input);
72 pub fn next(&self) -> Option<comments::Comment> {
73 self.comments.get(self.current).cloned()
76 pub fn trailing_comment(
78 span: syntax_pos::Span,
79 next_pos: Option<BytePos>,
80 ) -> Option<comments::Comment> {
81 if let Some(cmnt) = self.next() {
82 if cmnt.style != comments::Trailing { return None; }
83 let span_line = self.cm.lookup_char_pos(span.hi());
84 let comment_line = self.cm.lookup_char_pos(cmnt.pos);
85 let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1));
86 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
95 pub struct State<'a> {
97 comments: Option<Comments<'a>>,
98 ann: &'a (dyn PpAnn+'a),
102 crate const INDENT_UNIT: usize = 4;
104 /// Requires you to pass an input filename and reader so that
105 /// it can scan the input text for comments to copy forward.
106 pub fn print_crate<'a>(cm: &'a SourceMap,
112 is_expanded: bool) -> String {
115 comments: Some(Comments::new(cm, sess, filename, input)),
120 if is_expanded && sess.injected_crate_name.try_get().is_some() {
121 // We need to print `#![no_std]` (and its feature gate) so that
122 // compiling pretty-printed source won't inject libstd again.
123 // However, we don't want these attributes in the AST because
124 // of the feature gate, so we fake them up here.
126 // `#![feature(prelude_import)]`
127 let pi_nested = attr::mk_nested_word_item(ast::Ident::with_dummy_span(sym::prelude_import));
128 let list = attr::mk_list_item(ast::Ident::with_dummy_span(sym::feature), vec![pi_nested]);
129 let fake_attr = attr::mk_attr_inner(list);
130 s.print_attribute(&fake_attr);
132 // Currently, in Rust 2018 we don't have `extern crate std;` at the crate
133 // root, so this is not needed, and actually breaks things.
134 if sess.edition == syntax_pos::edition::Edition::Edition2015 {
136 let no_std_meta = attr::mk_word_item(ast::Ident::with_dummy_span(sym::no_std));
137 let fake_attr = attr::mk_attr_inner(no_std_meta);
138 s.print_attribute(&fake_attr);
142 s.print_mod(&krate.module, &krate.attrs);
143 s.print_remaining_comments();
144 s.ann.post(&mut s, AnnNode::Crate(krate));
148 pub fn to_string<F>(f: F) -> String where
149 F: FnOnce(&mut State<'_>),
151 let mut printer = State {
161 // This makes comma-separated lists look slightly nicer,
162 // and also addresses a specific regression described in issue #63896.
163 fn tt_prepend_space(tt: &TokenTree) -> bool {
165 TokenTree::Token(token) => match token.kind {
166 token::Comma => false,
173 fn binop_to_string(op: BinOpToken) -> &'static str {
179 token::Percent => "%",
188 pub fn literal_to_string(lit: token::Lit) -> String {
189 let token::Lit { kind, symbol, suffix } = lit;
190 let mut out = match kind {
191 token::Byte => format!("b'{}'", symbol),
192 token::Char => format!("'{}'", symbol),
193 token::Str => format!("\"{}\"", symbol),
194 token::StrRaw(n) => format!("r{delim}\"{string}\"{delim}",
195 delim="#".repeat(n as usize),
197 token::ByteStr => format!("b\"{}\"", symbol),
198 token::ByteStrRaw(n) => format!("br{delim}\"{string}\"{delim}",
199 delim="#".repeat(n as usize),
204 token::Err => symbol.to_string(),
207 if let Some(suffix) = suffix {
208 out.push_str(&suffix.as_str())
214 /// Print an ident from AST, `$crate` is converted into its respective crate name.
215 pub fn ast_ident_to_string(ident: ast::Ident, is_raw: bool) -> String {
216 ident_to_string(ident.name, is_raw, Some(ident.span))
219 // AST pretty-printer is used as a fallback for turning AST structures into token streams for
220 // proc macros. Additionally, proc macros may stringify their input and expect it survive the
221 // stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
222 // So we need to somehow pretty-print `$crate` in a way preserving at least some of its
223 // hygiene data, most importantly name of the crate it refers to.
224 // As a result we print `$crate` as `crate` if it refers to the local crate
225 // and as `::other_crate_name` if it refers to some other crate.
226 // Note, that this is only done if the ident token is printed from inside of AST pretty-pringing,
227 // but not otherwise. Pretty-printing is the only way for proc macros to discover token contents,
228 // so we should not perform this lossy conversion if the top level call to the pretty-printer was
229 // done for a token stream or a single token.
230 fn ident_to_string(name: ast::Name, is_raw: bool, convert_dollar_crate: Option<Span>) -> String {
232 format!("r#{}", name)
234 if name == kw::DollarCrate {
235 if let Some(span) = convert_dollar_crate {
236 let converted = span.ctxt().dollar_crate_name();
237 return if converted.is_path_segment_keyword() {
238 converted.to_string()
240 format!("::{}", converted)
248 /// Print the token kind precisely, without converting `$crate` into its respective crate name.
249 pub fn token_kind_to_string(tok: &TokenKind) -> String {
250 token_kind_to_string_ext(tok, None)
253 fn token_kind_to_string_ext(tok: &TokenKind, convert_dollar_crate: Option<Span>) -> String {
255 token::Eq => "=".to_string(),
256 token::Lt => "<".to_string(),
257 token::Le => "<=".to_string(),
258 token::EqEq => "==".to_string(),
259 token::Ne => "!=".to_string(),
260 token::Ge => ">=".to_string(),
261 token::Gt => ">".to_string(),
262 token::Not => "!".to_string(),
263 token::Tilde => "~".to_string(),
264 token::OrOr => "||".to_string(),
265 token::AndAnd => "&&".to_string(),
266 token::BinOp(op) => binop_to_string(op).to_string(),
267 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
269 /* Structural symbols */
270 token::At => "@".to_string(),
271 token::Dot => ".".to_string(),
272 token::DotDot => "..".to_string(),
273 token::DotDotDot => "...".to_string(),
274 token::DotDotEq => "..=".to_string(),
275 token::Comma => ",".to_string(),
276 token::Semi => ";".to_string(),
277 token::Colon => ":".to_string(),
278 token::ModSep => "::".to_string(),
279 token::RArrow => "->".to_string(),
280 token::LArrow => "<-".to_string(),
281 token::FatArrow => "=>".to_string(),
282 token::OpenDelim(token::Paren) => "(".to_string(),
283 token::CloseDelim(token::Paren) => ")".to_string(),
284 token::OpenDelim(token::Bracket) => "[".to_string(),
285 token::CloseDelim(token::Bracket) => "]".to_string(),
286 token::OpenDelim(token::Brace) => "{".to_string(),
287 token::CloseDelim(token::Brace) => "}".to_string(),
288 token::OpenDelim(token::NoDelim) |
289 token::CloseDelim(token::NoDelim) => " ".to_string(),
290 token::Pound => "#".to_string(),
291 token::Dollar => "$".to_string(),
292 token::Question => "?".to_string(),
293 token::SingleQuote => "'".to_string(),
296 token::Literal(lit) => literal_to_string(lit),
298 /* Name components */
299 token::Ident(s, is_raw) => ident_to_string(s, is_raw, convert_dollar_crate),
300 token::Lifetime(s) => s.to_string(),
303 token::DocComment(s) => s.to_string(),
304 token::Eof => "<eof>".to_string(),
305 token::Whitespace => " ".to_string(),
306 token::Comment => "/* */".to_string(),
307 token::Shebang(s) => format!("/* shebang: {}*/", s),
308 token::Unknown(s) => s.to_string(),
310 token::Interpolated(ref nt) => nonterminal_to_string(nt),
314 /// Print the token precisely, without converting `$crate` into its respective crate name.
315 pub fn token_to_string(token: &Token) -> String {
316 token_to_string_ext(token, false)
319 fn token_to_string_ext(token: &Token, convert_dollar_crate: bool) -> String {
320 let convert_dollar_crate = convert_dollar_crate.then_some(token.span);
321 token_kind_to_string_ext(&token.kind, convert_dollar_crate)
324 pub fn nonterminal_to_string(nt: &Nonterminal) -> String {
326 token::NtExpr(ref e) => expr_to_string(e),
327 token::NtMeta(ref e) => attr_item_to_string(e),
328 token::NtTy(ref e) => ty_to_string(e),
329 token::NtPath(ref e) => path_to_string(e),
330 token::NtItem(ref e) => item_to_string(e),
331 token::NtBlock(ref e) => block_to_string(e),
332 token::NtStmt(ref e) => stmt_to_string(e),
333 token::NtPat(ref e) => pat_to_string(e),
334 token::NtIdent(e, is_raw) => ast_ident_to_string(e, is_raw),
335 token::NtLifetime(e) => e.to_string(),
336 token::NtLiteral(ref e) => expr_to_string(e),
337 token::NtTT(ref tree) => tt_to_string(tree.clone()),
338 token::NtImplItem(ref e) => impl_item_to_string(e),
339 token::NtTraitItem(ref e) => trait_item_to_string(e),
340 token::NtVis(ref e) => vis_to_string(e),
341 token::NtForeignItem(ref e) => foreign_item_to_string(e),
345 pub fn ty_to_string(ty: &ast::Ty) -> String {
346 to_string(|s| s.print_type(ty))
349 pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
350 to_string(|s| s.print_type_bounds("", bounds))
353 pub fn pat_to_string(pat: &ast::Pat) -> String {
354 to_string(|s| s.print_pat(pat))
357 pub fn expr_to_string(e: &ast::Expr) -> String {
358 to_string(|s| s.print_expr(e))
361 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
362 to_string(|s| s.print_tt(tt, false))
365 pub fn tts_to_string(tokens: TokenStream) -> String {
366 to_string(|s| s.print_tts(tokens, false))
369 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
370 to_string(|s| s.print_stmt(stmt))
373 pub fn item_to_string(i: &ast::Item) -> String {
374 to_string(|s| s.print_item(i))
377 fn impl_item_to_string(i: &ast::ImplItem) -> String {
378 to_string(|s| s.print_impl_item(i))
381 fn trait_item_to_string(i: &ast::TraitItem) -> String {
382 to_string(|s| s.print_trait_item(i))
385 pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String {
386 to_string(|s| s.print_generic_params(generic_params))
389 pub fn path_to_string(p: &ast::Path) -> String {
390 to_string(|s| s.print_path(p, false, 0))
393 pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
394 to_string(|s| s.print_path_segment(p, false))
397 pub fn vis_to_string(v: &ast::Visibility) -> String {
398 to_string(|s| s.print_visibility(v))
401 fn block_to_string(blk: &ast::Block) -> String {
403 // Containing cbox, will be closed by `print_block` at `}`.
405 // Head-ibox, will be closed by `print_block` after `{`.
411 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
412 to_string(|s| s.print_meta_list_item(li))
415 fn attr_item_to_string(ai: &ast::AttrItem) -> String {
416 to_string(|s| s.print_attr_item(ai, ai.path.span))
419 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
420 to_string(|s| s.print_attribute(attr))
423 pub fn param_to_string(arg: &ast::Param) -> String {
424 to_string(|s| s.print_param(arg, false))
427 fn foreign_item_to_string(arg: &ast::ForeignItem) -> String {
428 to_string(|s| s.print_foreign_item(arg))
431 fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
432 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
435 impl std::ops::Deref for State<'_> {
436 type Target = pp::Printer;
437 fn deref(&self) -> &Self::Target {
442 impl std::ops::DerefMut for State<'_> {
443 fn deref_mut(&mut self) -> &mut Self::Target {
448 pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::DerefMut {
449 fn comments(&mut self) -> &mut Option<Comments<'a>>;
450 fn print_ident(&mut self, ident: ast::Ident);
451 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool);
453 fn strsep<T, F>(&mut self, sep: &'static str, space_before: bool,
454 b: Breaks, elts: &[T], mut op: F)
455 where F: FnMut(&mut Self, &T),
458 if let Some((first, rest)) = elts.split_first() {
464 self.word_space(sep);
471 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], op: F)
472 where F: FnMut(&mut Self, &T),
474 self.strsep(",", false, b, elts, op)
477 fn maybe_print_comment(&mut self, pos: BytePos) {
478 while let Some(ref cmnt) = self.next_comment() {
480 self.print_comment(cmnt);
487 fn print_comment(&mut self,
488 cmnt: &comments::Comment) {
491 assert_eq!(cmnt.lines.len(), 1);
493 self.word(cmnt.lines[0].clone());
496 comments::Isolated => {
497 self.hardbreak_if_not_bol();
498 for line in &cmnt.lines {
499 // Don't print empty lines because they will end up as trailing
501 if !line.is_empty() {
502 self.word(line.clone());
507 comments::Trailing => {
508 if !self.is_beginning_of_line() {
511 if cmnt.lines.len() == 1 {
512 self.word(cmnt.lines[0].clone());
516 for line in &cmnt.lines {
517 if !line.is_empty() {
518 self.word(line.clone());
525 comments::BlankLine => {
526 // We need to do at least one, possibly two hardbreaks.
527 let twice = match self.last_token() {
528 pp::Token::String(s) => ";" == s,
529 pp::Token::Begin(_) => true,
530 pp::Token::End => true,
539 if let Some(cm) = self.comments() {
544 fn next_comment(&mut self) -> Option<comments::Comment> {
545 self.comments().as_mut().and_then(|c| c.next())
548 fn print_literal(&mut self, lit: &ast::Lit) {
549 self.maybe_print_comment(lit.span.lo());
550 self.word(lit.token.to_string())
553 fn print_string(&mut self, st: &str,
554 style: ast::StrStyle) {
555 let st = match style {
556 ast::StrStyle::Cooked => {
557 (format!("\"{}\"", st.escape_debug()))
559 ast::StrStyle::Raw(n) => {
560 (format!("r{delim}\"{string}\"{delim}",
561 delim="#".repeat(n as usize),
568 fn print_inner_attributes(&mut self,
569 attrs: &[ast::Attribute]) {
570 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
573 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
574 attrs: &[ast::Attribute])
576 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
579 fn print_outer_attributes(&mut self,
580 attrs: &[ast::Attribute]) {
581 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
584 fn print_inner_attributes_inline(&mut self,
585 attrs: &[ast::Attribute]) {
586 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
589 fn print_outer_attributes_inline(&mut self,
590 attrs: &[ast::Attribute]) {
591 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
594 fn print_either_attributes(&mut self,
595 attrs: &[ast::Attribute],
596 kind: ast::AttrStyle,
598 trailing_hardbreak: bool) {
601 if attr.style == kind {
602 self.print_attribute_inline(attr, is_inline);
609 if count > 0 && trailing_hardbreak && !is_inline {
610 self.hardbreak_if_not_bol();
614 fn print_attribute(&mut self, attr: &ast::Attribute) {
615 self.print_attribute_inline(attr, false)
618 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
621 self.hardbreak_if_not_bol();
623 self.maybe_print_comment(attr.span.lo());
625 ast::AttrKind::Normal(ref item) => {
627 ast::AttrStyle::Inner => self.word("#!["),
628 ast::AttrStyle::Outer => self.word("#["),
630 self.print_attr_item(&item, attr.span);
633 ast::AttrKind::DocComment(comment) => {
634 self.word(comment.to_string());
640 fn print_attr_item(&mut self, item: &ast::AttrItem, span: Span) {
643 MacArgs::Delimited(_, delim, tokens) => self.print_mac_common(
644 Some(MacHeader::Path(&item.path)),
652 MacArgs::Empty | MacArgs::Eq(..) => {
653 self.print_path(&item.path, false, 0);
654 if let MacArgs::Eq(_, tokens) = &item.args {
656 self.word_space("=");
657 self.print_tts(tokens.clone(), true);
664 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) {
666 ast::NestedMetaItem::MetaItem(ref mi) => {
667 self.print_meta_item(mi)
669 ast::NestedMetaItem::Literal(ref lit) => {
670 self.print_literal(lit)
675 fn print_meta_item(&mut self, item: &ast::MetaItem) {
676 self.ibox(INDENT_UNIT);
678 ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
679 ast::MetaItemKind::NameValue(ref value) => {
680 self.print_path(&item.path, false, 0);
682 self.word_space("=");
683 self.print_literal(value);
685 ast::MetaItemKind::List(ref items) => {
686 self.print_path(&item.path, false, 0);
688 self.commasep(Consistent,
690 |s, i| s.print_meta_list_item(i));
697 /// This doesn't deserve to be called "pretty" printing, but it should be
698 /// meaning-preserving. A quick hack that might help would be to look at the
699 /// spans embedded in the TTs to decide where to put spaces and newlines.
700 /// But it'd be better to parse these according to the grammar of the
701 /// appropriate macro, transcribe back into the grammar we just parsed from,
702 /// and then pretty-print the resulting AST nodes (so, e.g., we print
703 /// expression arguments as expressions). It can be done! I think.
704 fn print_tt(&mut self, tt: tokenstream::TokenTree, convert_dollar_crate: bool) {
706 TokenTree::Token(ref token) => {
707 self.word(token_to_string_ext(&token, convert_dollar_crate));
709 token::DocComment(..) => {
715 TokenTree::Delimited(dspan, delim, tts) => {
716 self.print_mac_common(
717 None, false, None, delim, tts, convert_dollar_crate, dspan.entire()
723 fn print_tts(&mut self, tts: tokenstream::TokenStream, convert_dollar_crate: bool) {
724 for (i, tt) in tts.into_trees().enumerate() {
725 if i != 0 && tt_prepend_space(&tt) {
728 self.print_tt(tt, convert_dollar_crate);
734 header: Option<MacHeader<'_>>,
736 ident: Option<ast::Ident>,
739 convert_dollar_crate: bool,
742 if delim == DelimToken::Brace {
743 self.cbox(INDENT_UNIT);
746 Some(MacHeader::Path(path)) => self.print_path(path, false, 0),
747 Some(MacHeader::Keyword(kw)) => self.word(kw),
753 if let Some(ident) = ident {
755 self.print_ident(ident);
758 DelimToken::Brace => {
759 if header.is_some() || has_bang || ident.is_some() {
767 _ => self.word(token_kind_to_string(&token::OpenDelim(delim))),
770 self.print_tts(tts, convert_dollar_crate);
773 DelimToken::Brace => self.bclose(span),
774 _ => self.word(token_kind_to_string(&token::CloseDelim(delim))),
778 fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
779 self.maybe_print_comment(path.span.lo());
781 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
785 self.print_path_segment(segment, colons_before_params);
789 fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
790 if segment.ident.name != kw::PathRoot {
791 self.print_ident(segment.ident);
792 if let Some(ref args) = segment.args {
793 self.print_generic_args(args, colons_before_params);
798 fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
800 // Outer-box is consistent.
801 self.cbox(INDENT_UNIT);
802 // Head-box is inconsistent.
803 self.ibox(w.len() + 1);
804 // Keyword that starts the head.
810 fn bopen(&mut self) {
812 self.end(); // Close the head-box.
815 fn bclose_maybe_open(&mut self, span: syntax_pos::Span, close_box: bool) {
816 self.maybe_print_comment(span.hi());
817 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
820 self.end(); // Close the outer-box.
824 fn bclose(&mut self, span: syntax_pos::Span) {
825 self.bclose_maybe_open(span, true)
828 fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
829 if !self.is_beginning_of_line() {
830 self.break_offset(n, off)
832 if off != 0 && self.last_token().is_hardbreak_tok() {
833 // We do something pretty sketchy here: tuck the nonzero
834 // offset-adjustment we were going to deposit along with the
835 // break into the previous hardbreak.
836 self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
842 impl<'a> PrintState<'a> for State<'a> {
843 fn comments(&mut self) -> &mut Option<Comments<'a>> {
847 fn print_ident(&mut self, ident: ast::Ident) {
848 self.s.word(ast_ident_to_string(ident, ident.is_raw_guess()));
849 self.ann.post(self, AnnNode::Ident(&ident))
852 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
853 if colons_before_params {
858 ast::GenericArgs::AngleBracketed(ref data) => {
861 self.commasep(Inconsistent, &data.args, |s, generic_arg| {
862 s.print_generic_arg(generic_arg)
865 let mut comma = data.args.len() != 0;
867 for constraint in data.constraints.iter() {
871 self.print_ident(constraint.ident);
873 match constraint.kind {
874 ast::AssocTyConstraintKind::Equality { ref ty } => {
875 self.word_space("=");
878 ast::AssocTyConstraintKind::Bound { ref bounds } => {
879 self.print_type_bounds(":", &*bounds);
888 ast::GenericArgs::Parenthesized(ref data) => {
893 |s, ty| s.print_type(ty));
896 if let Some(ref ty) = data.output {
897 self.space_if_not_bol();
898 self.word_space("->");
907 // Synthesizes a comment that was not textually present in the original source
909 pub fn synth_comment(&mut self, text: String) {
917 crate fn commasep_cmnt<T, F, G>(&mut self,
921 mut get_span: G) where
922 F: FnMut(&mut State<'_>, &T),
923 G: FnMut(&T) -> syntax_pos::Span,
926 let len = elts.len();
929 self.maybe_print_comment(get_span(elt).hi());
934 self.maybe_print_trailing_comment(get_span(elt),
935 Some(get_span(&elts[i]).hi()));
936 self.space_if_not_bol();
942 crate fn commasep_exprs(&mut self, b: Breaks,
943 exprs: &[P<ast::Expr>]) {
944 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
950 attrs: &[ast::Attribute],
952 self.print_inner_attributes(attrs);
953 for item in &_mod.items {
954 self.print_item(item);
958 crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
959 attrs: &[ast::Attribute]) {
960 self.print_inner_attributes(attrs);
961 for item in &nmod.items {
962 self.print_foreign_item(item);
966 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
967 if let Some(lt) = *lifetime {
968 self.print_lifetime(lt);
973 crate fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
975 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
976 GenericArg::Type(ty) => self.print_type(ty),
977 GenericArg::Const(ct) => self.print_expr(&ct.value),
981 pub fn print_type(&mut self, ty: &ast::Ty) {
982 self.maybe_print_comment(ty.span.lo());
985 ast::TyKind::Slice(ref ty) => {
990 ast::TyKind::Ptr(ref mt) => {
992 self.print_mt(mt, true);
994 ast::TyKind::Rptr(ref lifetime, ref mt) => {
996 self.print_opt_lifetime(lifetime);
997 self.print_mt(mt, false);
999 ast::TyKind::Never => {
1002 ast::TyKind::Tup(ref elts) => {
1004 self.commasep(Inconsistent, &elts[..],
1005 |s, ty| s.print_type(ty));
1006 if elts.len() == 1 {
1011 ast::TyKind::Paren(ref typ) => {
1013 self.print_type(typ);
1016 ast::TyKind::BareFn(ref f) => {
1017 self.print_ty_fn(f.ext,
1023 ast::TyKind::Path(None, ref path) => {
1024 self.print_path(path, false, 0);
1026 ast::TyKind::Path(Some(ref qself), ref path) => {
1027 self.print_qpath(path, qself, false)
1029 ast::TyKind::TraitObject(ref bounds, syntax) => {
1030 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
1031 self.print_type_bounds(prefix, &bounds[..]);
1033 ast::TyKind::ImplTrait(_, ref bounds) => {
1034 self.print_type_bounds("impl", &bounds[..]);
1036 ast::TyKind::Array(ref ty, ref length) => {
1038 self.print_type(ty);
1040 self.print_expr(&length.value);
1043 ast::TyKind::Typeof(ref e) => {
1044 self.s.word("typeof(");
1045 self.print_expr(&e.value);
1048 ast::TyKind::Infer => {
1051 ast::TyKind::Err => {
1053 self.s.word("/*ERROR*/");
1056 ast::TyKind::ImplicitSelf => {
1057 self.s.word("Self");
1059 ast::TyKind::Mac(ref m) => {
1062 ast::TyKind::CVarArgs => {
1069 crate fn print_foreign_item(&mut self,
1070 item: &ast::ForeignItem) {
1071 self.hardbreak_if_not_bol();
1072 self.maybe_print_comment(item.span.lo());
1073 self.print_outer_attributes(&item.attrs);
1075 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1077 self.print_fn(decl, ast::FnHeader::default(),
1079 generics, &item.vis);
1080 self.end(); // end head-ibox
1082 self.end(); // end the outer fn box
1084 ast::ForeignItemKind::Static(ref t, m) => {
1085 self.head(visibility_qualified(&item.vis, "static"));
1086 if m == ast::Mutability::Mutable {
1087 self.word_space("mut");
1089 self.print_ident(item.ident);
1090 self.word_space(":");
1093 self.end(); // end the head-ibox
1094 self.end(); // end the outer cbox
1096 ast::ForeignItemKind::Ty => {
1097 self.head(visibility_qualified(&item.vis, "type"));
1098 self.print_ident(item.ident);
1100 self.end(); // end the head-ibox
1101 self.end(); // end the outer cbox
1103 ast::ForeignItemKind::Macro(ref m) => {
1105 if m.args.need_semicolon() {
1112 fn print_associated_const(&mut self,
1115 default: Option<&ast::Expr>,
1116 vis: &ast::Visibility)
1118 self.s.word(visibility_qualified(vis, ""));
1119 self.word_space("const");
1120 self.print_ident(ident);
1121 self.word_space(":");
1122 self.print_type(ty);
1123 if let Some(expr) = default {
1125 self.word_space("=");
1126 self.print_expr(expr);
1131 fn print_associated_type(&mut self,
1133 bounds: Option<&ast::GenericBounds>,
1134 ty: Option<&ast::Ty>)
1136 self.word_space("type");
1137 self.print_ident(ident);
1138 if let Some(bounds) = bounds {
1139 self.print_type_bounds(":", bounds);
1141 if let Some(ty) = ty {
1143 self.word_space("=");
1144 self.print_type(ty);
1149 /// Pretty-prints an item.
1150 crate fn print_item(&mut self, item: &ast::Item) {
1151 self.hardbreak_if_not_bol();
1152 self.maybe_print_comment(item.span.lo());
1153 self.print_outer_attributes(&item.attrs);
1154 self.ann.pre(self, AnnNode::Item(item));
1156 ast::ItemKind::ExternCrate(orig_name) => {
1157 self.head(visibility_qualified(&item.vis, "extern crate"));
1158 if let Some(orig_name) = orig_name {
1159 self.print_name(orig_name);
1164 self.print_ident(item.ident);
1166 self.end(); // end inner head-block
1167 self.end(); // end outer head-block
1169 ast::ItemKind::Use(ref tree) => {
1170 self.head(visibility_qualified(&item.vis, "use"));
1171 self.print_use_tree(tree);
1173 self.end(); // end inner head-block
1174 self.end(); // end outer head-block
1176 ast::ItemKind::Static(ref ty, m, ref expr) => {
1177 self.head(visibility_qualified(&item.vis, "static"));
1178 if m == ast::Mutability::Mutable {
1179 self.word_space("mut");
1181 self.print_ident(item.ident);
1182 self.word_space(":");
1183 self.print_type(ty);
1185 self.end(); // end the head-ibox
1187 self.word_space("=");
1188 self.print_expr(expr);
1190 self.end(); // end the outer cbox
1192 ast::ItemKind::Const(ref ty, ref expr) => {
1193 self.head(visibility_qualified(&item.vis, "const"));
1194 self.print_ident(item.ident);
1195 self.word_space(":");
1196 self.print_type(ty);
1198 self.end(); // end the head-ibox
1200 self.word_space("=");
1201 self.print_expr(expr);
1203 self.end(); // end the outer cbox
1205 ast::ItemKind::Fn(ref sig, ref param_names, ref body) => {
1215 self.print_block_with_attrs(body, &item.attrs);
1217 ast::ItemKind::Mod(ref _mod) => {
1218 self.head(visibility_qualified(&item.vis, "mod"));
1219 self.print_ident(item.ident);
1221 if _mod.inline || self.is_expanded {
1224 self.print_mod(_mod, &item.attrs);
1225 self.bclose(item.span);
1228 self.end(); // end inner head-block
1229 self.end(); // end outer head-block
1233 ast::ItemKind::ForeignMod(ref nmod) => {
1234 self.head("extern");
1235 if let Some(abi) = nmod.abi {
1236 self.print_literal(&abi.as_lit());
1240 self.print_foreign_mod(nmod, &item.attrs);
1241 self.bclose(item.span);
1243 ast::ItemKind::GlobalAsm(ref ga) => {
1244 self.head(visibility_qualified(&item.vis, "global_asm!"));
1245 self.s.word(ga.asm.to_string());
1248 ast::ItemKind::TyAlias(ref ty, ref generics) => {
1249 self.head(visibility_qualified(&item.vis, "type"));
1250 self.print_ident(item.ident);
1251 self.print_generic_params(&generics.params);
1252 self.end(); // end the inner ibox
1254 self.print_where_clause(&generics.where_clause);
1256 self.word_space("=");
1257 self.print_type(ty);
1259 self.end(); // end the outer ibox
1261 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1262 self.print_enum_def(
1270 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1271 self.head(visibility_qualified(&item.vis, "struct"));
1272 self.print_struct(struct_def, generics, item.ident, item.span, true);
1274 ast::ItemKind::Union(ref struct_def, ref generics) => {
1275 self.head(visibility_qualified(&item.vis, "union"));
1276 self.print_struct(struct_def, generics, item.ident, item.span, true);
1278 ast::ItemKind::Impl(unsafety,
1284 ref impl_items) => {
1286 self.print_visibility(&item.vis);
1287 self.print_defaultness(defaultness);
1288 self.print_unsafety(unsafety);
1289 self.word_nbsp("impl");
1291 if !generics.params.is_empty() {
1292 self.print_generic_params(&generics.params);
1296 if polarity == ast::ImplPolarity::Negative {
1300 if let Some(ref t) = *opt_trait {
1301 self.print_trait_ref(t);
1303 self.word_space("for");
1306 self.print_type(ty);
1307 self.print_where_clause(&generics.where_clause);
1311 self.print_inner_attributes(&item.attrs);
1312 for impl_item in impl_items {
1313 self.print_impl_item(impl_item);
1315 self.bclose(item.span);
1317 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1319 self.print_visibility(&item.vis);
1320 self.print_unsafety(unsafety);
1321 self.print_is_auto(is_auto);
1322 self.word_nbsp("trait");
1323 self.print_ident(item.ident);
1324 self.print_generic_params(&generics.params);
1325 let mut real_bounds = Vec::with_capacity(bounds.len());
1326 for b in bounds.iter() {
1327 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1329 self.word_space("for ?");
1330 self.print_trait_ref(&ptr.trait_ref);
1332 real_bounds.push(b.clone());
1335 self.print_type_bounds(":", &real_bounds[..]);
1336 self.print_where_clause(&generics.where_clause);
1339 for trait_item in trait_items {
1340 self.print_trait_item(trait_item);
1342 self.bclose(item.span);
1344 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1346 self.print_visibility(&item.vis);
1347 self.word_nbsp("trait");
1348 self.print_ident(item.ident);
1349 self.print_generic_params(&generics.params);
1350 let mut real_bounds = Vec::with_capacity(bounds.len());
1351 // FIXME(durka) this seems to be some quite outdated syntax
1352 for b in bounds.iter() {
1353 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1355 self.word_space("for ?");
1356 self.print_trait_ref(&ptr.trait_ref);
1358 real_bounds.push(b.clone());
1362 self.print_type_bounds("=", &real_bounds[..]);
1363 self.print_where_clause(&generics.where_clause);
1366 ast::ItemKind::Mac(ref mac) => {
1367 self.print_mac(mac);
1368 if mac.args.need_semicolon() {
1372 ast::ItemKind::MacroDef(ref macro_def) => {
1373 let (kw, has_bang) = if macro_def.legacy {
1374 ("macro_rules", true)
1376 self.print_visibility(&item.vis);
1379 self.print_mac_common(
1380 Some(MacHeader::Keyword(kw)),
1383 macro_def.body.delim(),
1384 macro_def.body.inner_tokens(),
1390 self.ann.post(self, AnnNode::Item(item))
1393 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1394 self.print_path(&t.path, false, 0)
1397 fn print_formal_generic_params(
1399 generic_params: &[ast::GenericParam]
1401 if !generic_params.is_empty() {
1403 self.print_generic_params(generic_params);
1408 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1409 self.print_formal_generic_params(&t.bound_generic_params);
1410 self.print_trait_ref(&t.trait_ref)
1413 crate fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1414 generics: &ast::Generics, ident: ast::Ident,
1415 span: syntax_pos::Span,
1416 visibility: &ast::Visibility) {
1417 self.head(visibility_qualified(visibility, "enum"));
1418 self.print_ident(ident);
1419 self.print_generic_params(&generics.params);
1420 self.print_where_clause(&generics.where_clause);
1422 self.print_variants(&enum_definition.variants, span)
1425 crate fn print_variants(&mut self,
1426 variants: &[ast::Variant],
1427 span: syntax_pos::Span) {
1430 self.space_if_not_bol();
1431 self.maybe_print_comment(v.span.lo());
1432 self.print_outer_attributes(&v.attrs);
1433 self.ibox(INDENT_UNIT);
1434 self.print_variant(v);
1437 self.maybe_print_trailing_comment(v.span, None);
1442 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1444 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1445 ast::VisibilityKind::Crate(sugar) => match sugar {
1446 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1447 ast::CrateSugar::JustCrate => self.word_nbsp("crate")
1449 ast::VisibilityKind::Restricted { ref path, .. } => {
1450 let path = to_string(|s| s.print_path(path, false, 0));
1451 if path == "self" || path == "super" {
1452 self.word_nbsp(format!("pub({})", path))
1454 self.word_nbsp(format!("pub(in {})", path))
1457 ast::VisibilityKind::Inherited => {}
1461 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1462 if let ast::Defaultness::Default = defaultness {
1463 self.word_nbsp("default");
1467 crate fn print_struct(&mut self,
1468 struct_def: &ast::VariantData,
1469 generics: &ast::Generics,
1471 span: syntax_pos::Span,
1472 print_finalizer: bool) {
1473 self.print_ident(ident);
1474 self.print_generic_params(&generics.params);
1476 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1477 if let ast::VariantData::Tuple(..) = struct_def {
1480 Inconsistent, struct_def.fields(),
1482 s.maybe_print_comment(field.span.lo());
1483 s.print_outer_attributes(&field.attrs);
1484 s.print_visibility(&field.vis);
1485 s.print_type(&field.ty)
1490 self.print_where_clause(&generics.where_clause);
1491 if print_finalizer {
1495 self.end(); // Close the outer-box.
1497 ast::VariantData::Struct(..) => {
1498 self.print_where_clause(&generics.where_clause);
1501 self.hardbreak_if_not_bol();
1503 for field in struct_def.fields() {
1504 self.hardbreak_if_not_bol();
1505 self.maybe_print_comment(field.span.lo());
1506 self.print_outer_attributes(&field.attrs);
1507 self.print_visibility(&field.vis);
1508 self.print_ident(field.ident.unwrap());
1509 self.word_nbsp(":");
1510 self.print_type(&field.ty);
1519 crate fn print_variant(&mut self, v: &ast::Variant) {
1521 let generics = ast::Generics::default();
1522 self.print_struct(&v.data, &generics, v.ident, v.span, false);
1526 self.word_space("=");
1527 self.print_expr(&d.value)
1533 crate fn print_method_sig(&mut self,
1535 generics: &ast::Generics,
1537 vis: &ast::Visibility)
1539 self.print_fn(&m.decl,
1546 crate fn print_trait_item(&mut self, ti: &ast::TraitItem)
1548 self.ann.pre(self, AnnNode::SubItem(ti.id));
1549 self.hardbreak_if_not_bol();
1550 self.maybe_print_comment(ti.span.lo());
1551 self.print_outer_attributes(&ti.attrs);
1553 ast::TraitItemKind::Const(ref ty, ref default) => {
1554 self.print_associated_const(
1557 default.as_ref().map(|expr| &**expr),
1558 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1561 ast::TraitItemKind::Method(ref sig, ref body) => {
1565 self.print_method_sig(
1569 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1571 if let Some(ref body) = *body {
1573 self.print_block_with_attrs(body, &ti.attrs);
1578 ast::TraitItemKind::Type(ref bounds, ref default) => {
1579 self.print_associated_type(ti.ident, Some(bounds),
1580 default.as_ref().map(|ty| &**ty));
1582 ast::TraitItemKind::Macro(ref mac) => {
1583 self.print_mac(mac);
1584 if mac.args.need_semicolon() {
1589 self.ann.post(self, AnnNode::SubItem(ti.id))
1592 crate fn print_impl_item(&mut self, ii: &ast::ImplItem) {
1593 self.ann.pre(self, AnnNode::SubItem(ii.id));
1594 self.hardbreak_if_not_bol();
1595 self.maybe_print_comment(ii.span.lo());
1596 self.print_outer_attributes(&ii.attrs);
1597 self.print_defaultness(ii.defaultness);
1599 ast::ImplItemKind::Const(ref ty, ref expr) => {
1600 self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis);
1602 ast::ImplItemKind::Method(ref sig, ref body) => {
1604 self.print_method_sig(ii.ident, &ii.generics, sig, &ii.vis);
1606 self.print_block_with_attrs(body, &ii.attrs);
1608 ast::ImplItemKind::TyAlias(ref ty) => {
1609 self.print_associated_type(ii.ident, None, Some(ty));
1611 ast::ImplItemKind::Macro(ref mac) => {
1612 self.print_mac(mac);
1613 if mac.args.need_semicolon() {
1618 self.ann.post(self, AnnNode::SubItem(ii.id))
1621 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1622 self.maybe_print_comment(st.span.lo());
1624 ast::StmtKind::Local(ref loc) => {
1625 self.print_outer_attributes(&loc.attrs);
1626 self.space_if_not_bol();
1627 self.ibox(INDENT_UNIT);
1628 self.word_nbsp("let");
1630 self.ibox(INDENT_UNIT);
1631 self.print_local_decl(loc);
1633 if let Some(ref init) = loc.init {
1635 self.word_space("=");
1636 self.print_expr(init);
1641 ast::StmtKind::Item(ref item) => self.print_item(item),
1642 ast::StmtKind::Expr(ref expr) => {
1643 self.space_if_not_bol();
1644 self.print_expr_outer_attr_style(expr, false);
1645 if classify::expr_requires_semi_to_be_stmt(expr) {
1649 ast::StmtKind::Semi(ref expr) => {
1651 // Filter out empty `Tup` exprs created for the `redundant_semicolon`
1652 // lint, as they shouldn't be visible and interact poorly
1653 // with proc macros.
1654 ast::ExprKind::Tup(ref exprs) if exprs.is_empty()
1655 && expr.attrs.is_empty() => (),
1657 self.space_if_not_bol();
1658 self.print_expr_outer_attr_style(expr, false);
1663 ast::StmtKind::Mac(ref mac) => {
1664 let (ref mac, style, ref attrs) = **mac;
1665 self.space_if_not_bol();
1666 self.print_outer_attributes(attrs);
1667 self.print_mac(mac);
1668 if style == ast::MacStmtStyle::Semicolon {
1673 self.maybe_print_trailing_comment(st.span, None)
1676 crate fn print_block(&mut self, blk: &ast::Block) {
1677 self.print_block_with_attrs(blk, &[])
1680 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1681 self.print_block_maybe_unclosed(blk, &[], false)
1684 crate fn print_block_with_attrs(&mut self,
1686 attrs: &[ast::Attribute]) {
1687 self.print_block_maybe_unclosed(blk, attrs, true)
1690 crate fn print_block_maybe_unclosed(&mut self,
1692 attrs: &[ast::Attribute],
1695 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1696 BlockCheckMode::Default => ()
1698 self.maybe_print_comment(blk.span.lo());
1699 self.ann.pre(self, AnnNode::Block(blk));
1702 self.print_inner_attributes(attrs);
1704 for (i, st) in blk.stmts.iter().enumerate() {
1706 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1707 self.maybe_print_comment(st.span.lo());
1708 self.space_if_not_bol();
1709 self.print_expr_outer_attr_style(expr, false);
1710 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1712 _ => self.print_stmt(st),
1716 self.bclose_maybe_open(blk.span, close_box);
1717 self.ann.post(self, AnnNode::Block(blk))
1720 /// Print a `let pat = scrutinee` expression.
1721 crate fn print_let(&mut self, pat: &ast::Pat, scrutinee: &ast::Expr) {
1722 self.s.word("let ");
1724 self.print_pat(pat);
1727 self.word_space("=");
1728 self.print_expr_cond_paren(
1730 Self::cond_needs_par(scrutinee)
1731 || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order())
1735 fn print_else(&mut self, els: Option<&ast::Expr>) {
1736 if let Some(_else) = els {
1738 // Another `else if` block.
1739 ast::ExprKind::If(ref i, ref then, ref e) => {
1740 self.cbox(INDENT_UNIT - 1);
1742 self.s.word(" else if ");
1743 self.print_expr_as_cond(i);
1745 self.print_block(then);
1746 self.print_else(e.as_ref().map(|e| &**e))
1748 // Final `else` block.
1749 ast::ExprKind::Block(ref b, _) => {
1750 self.cbox(INDENT_UNIT - 1);
1752 self.s.word(" else ");
1755 // Constraints would be great here!
1757 panic!("print_if saw if with weird alternative");
1763 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1764 elseopt: Option<&ast::Expr>) {
1767 self.print_expr_as_cond(test);
1770 self.print_block(blk);
1771 self.print_else(elseopt)
1774 crate fn print_mac(&mut self, m: &ast::Mac) {
1775 self.print_mac_common(
1776 Some(MacHeader::Path(&m.path)),
1780 m.args.inner_tokens(),
1786 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1788 self.commasep_exprs(Inconsistent, args);
1792 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1793 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1796 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1797 /// `if cond { ... }`.
1798 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1799 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1802 /// Does `expr` need parenthesis when printed in a condition position?
1803 fn cond_needs_par(expr: &ast::Expr) -> bool {
1805 // These cases need parens due to the parse error observed in #26461: `if return {}`
1806 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1807 ast::ExprKind::Closure(..) |
1808 ast::ExprKind::Ret(..) |
1809 ast::ExprKind::Break(..) => true,
1811 _ => parser::contains_exterior_struct_lit(expr),
1815 /// Prints `expr` or `(expr)` when `needs_par` holds.
1816 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1820 self.print_expr(expr);
1826 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1827 attrs: &[Attribute]) {
1828 self.ibox(INDENT_UNIT);
1830 self.print_inner_attributes_inline(attrs);
1831 self.commasep_exprs(Inconsistent, &exprs[..]);
1836 fn print_expr_repeat(&mut self,
1837 element: &ast::Expr,
1838 count: &ast::AnonConst,
1839 attrs: &[Attribute]) {
1840 self.ibox(INDENT_UNIT);
1842 self.print_inner_attributes_inline(attrs);
1843 self.print_expr(element);
1844 self.word_space(";");
1845 self.print_expr(&count.value);
1850 fn print_expr_struct(&mut self,
1852 fields: &[ast::Field],
1853 wth: &Option<P<ast::Expr>>,
1854 attrs: &[Attribute]) {
1855 self.print_path(path, true, 0);
1857 self.print_inner_attributes_inline(attrs);
1862 s.ibox(INDENT_UNIT);
1863 if !field.is_shorthand {
1864 s.print_ident(field.ident);
1867 s.print_expr(&field.expr);
1873 self.ibox(INDENT_UNIT);
1874 if !fields.is_empty() {
1879 self.print_expr(expr);
1882 _ => if !fields.is_empty() {
1889 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1890 attrs: &[Attribute]) {
1892 self.print_inner_attributes_inline(attrs);
1893 self.commasep_exprs(Inconsistent, &exprs[..]);
1894 if exprs.len() == 1 {
1900 fn print_expr_call(&mut self,
1902 args: &[P<ast::Expr>]) {
1905 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1906 _ => parser::PREC_POSTFIX,
1909 self.print_expr_maybe_paren(func, prec);
1910 self.print_call_post(args)
1913 fn print_expr_method_call(&mut self,
1914 segment: &ast::PathSegment,
1915 args: &[P<ast::Expr>]) {
1916 let base_args = &args[1..];
1917 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1919 self.print_ident(segment.ident);
1920 if let Some(ref args) = segment.args {
1921 self.print_generic_args(args, true);
1923 self.print_call_post(base_args)
1926 fn print_expr_binary(&mut self,
1930 let assoc_op = AssocOp::from_ast_binop(op.node);
1931 let prec = assoc_op.precedence() as i8;
1932 let fixity = assoc_op.fixity();
1934 let (left_prec, right_prec) = match fixity {
1935 Fixity::Left => (prec, prec + 1),
1936 Fixity::Right => (prec + 1, prec),
1937 Fixity::None => (prec + 1, prec + 1),
1940 let left_prec = match (&lhs.kind, op.node) {
1941 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1942 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1943 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1944 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) |
1945 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1946 // We are given `(let _ = a) OP b`.
1948 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1949 // as the parser will interpret this as `(let _ = a) OP b`.
1951 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1952 // parens are required since the parser would interpret `let a = b < c` as
1953 // `let a = (b < c)`. To achieve this, we force parens.
1954 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1955 parser::PREC_FORCE_PAREN
1960 self.print_expr_maybe_paren(lhs, left_prec);
1962 self.word_space(op.node.to_string());
1963 self.print_expr_maybe_paren(rhs, right_prec)
1966 fn print_expr_unary(&mut self,
1969 self.s.word(ast::UnOp::to_string(op));
1970 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1973 fn print_expr_addr_of(&mut self,
1974 kind: ast::BorrowKind,
1975 mutability: ast::Mutability,
1979 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
1980 ast::BorrowKind::Raw => {
1981 self.word_nbsp("raw");
1982 self.print_mutability(mutability, true);
1985 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1988 pub fn print_expr(&mut self, expr: &ast::Expr) {
1989 self.print_expr_outer_attr_style(expr, true)
1992 fn print_expr_outer_attr_style(&mut self,
1995 self.maybe_print_comment(expr.span.lo());
1997 let attrs = &expr.attrs;
1999 self.print_outer_attributes_inline(attrs);
2001 self.print_outer_attributes(attrs);
2004 self.ibox(INDENT_UNIT);
2005 self.ann.pre(self, AnnNode::Expr(expr));
2007 ast::ExprKind::Box(ref expr) => {
2008 self.word_space("box");
2009 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
2011 ast::ExprKind::Array(ref exprs) => {
2012 self.print_expr_vec(&exprs[..], attrs);
2014 ast::ExprKind::Repeat(ref element, ref count) => {
2015 self.print_expr_repeat(element, count, attrs);
2017 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2018 self.print_expr_struct(path, &fields[..], wth, attrs);
2020 ast::ExprKind::Tup(ref exprs) => {
2021 self.print_expr_tup(&exprs[..], attrs);
2023 ast::ExprKind::Call(ref func, ref args) => {
2024 self.print_expr_call(func, &args[..]);
2026 ast::ExprKind::MethodCall(ref segment, ref args) => {
2027 self.print_expr_method_call(segment, &args[..]);
2029 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2030 self.print_expr_binary(op, lhs, rhs);
2032 ast::ExprKind::Unary(op, ref expr) => {
2033 self.print_expr_unary(op, expr);
2035 ast::ExprKind::AddrOf(k, m, ref expr) => {
2036 self.print_expr_addr_of(k, m, expr);
2038 ast::ExprKind::Lit(ref lit) => {
2039 self.print_literal(lit);
2041 ast::ExprKind::Cast(ref expr, ref ty) => {
2042 let prec = AssocOp::As.precedence() as i8;
2043 self.print_expr_maybe_paren(expr, prec);
2045 self.word_space("as");
2046 self.print_type(ty);
2048 ast::ExprKind::Type(ref expr, ref ty) => {
2049 let prec = AssocOp::Colon.precedence() as i8;
2050 self.print_expr_maybe_paren(expr, prec);
2051 self.word_space(":");
2052 self.print_type(ty);
2054 ast::ExprKind::Let(ref pat, ref scrutinee) => {
2055 self.print_let(pat, scrutinee);
2057 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2058 self.print_if(test, blk, elseopt.as_ref().map(|e| &**e));
2060 ast::ExprKind::While(ref test, ref blk, opt_label) => {
2061 if let Some(label) = opt_label {
2062 self.print_ident(label.ident);
2063 self.word_space(":");
2066 self.print_expr_as_cond(test);
2068 self.print_block_with_attrs(blk, attrs);
2070 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2071 if let Some(label) = opt_label {
2072 self.print_ident(label.ident);
2073 self.word_space(":");
2076 self.print_pat(pat);
2078 self.word_space("in");
2079 self.print_expr_as_cond(iter);
2081 self.print_block_with_attrs(blk, attrs);
2083 ast::ExprKind::Loop(ref blk, opt_label) => {
2084 if let Some(label) = opt_label {
2085 self.print_ident(label.ident);
2086 self.word_space(":");
2090 self.print_block_with_attrs(blk, attrs);
2092 ast::ExprKind::Match(ref expr, ref arms) => {
2093 self.cbox(INDENT_UNIT);
2094 self.ibox(INDENT_UNIT);
2095 self.word_nbsp("match");
2096 self.print_expr_as_cond(expr);
2099 self.print_inner_attributes_no_trailing_hardbreak(attrs);
2101 self.print_arm(arm);
2103 self.bclose(expr.span);
2105 ast::ExprKind::Closure(
2106 capture_clause, asyncness, movability, ref decl, ref body, _) => {
2107 self.print_movability(movability);
2108 self.print_asyncness(asyncness);
2109 self.print_capture_clause(capture_clause);
2111 self.print_fn_block_params(decl);
2113 self.print_expr(body);
2114 self.end(); // need to close a box
2116 // a box will be closed by print_expr, but we didn't want an overall
2117 // wrapper so we closed the corresponding opening. so create an
2118 // empty box to satisfy the close.
2121 ast::ExprKind::Block(ref blk, opt_label) => {
2122 if let Some(label) = opt_label {
2123 self.print_ident(label.ident);
2124 self.word_space(":");
2126 // containing cbox, will be closed by print-block at }
2127 self.cbox(INDENT_UNIT);
2128 // head-box, will be closed by print-block after {
2130 self.print_block_with_attrs(blk, attrs);
2132 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2133 self.word_nbsp("async");
2134 self.print_capture_clause(capture_clause);
2136 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2137 self.cbox(INDENT_UNIT);
2139 self.print_block_with_attrs(blk, attrs);
2141 ast::ExprKind::Await(ref expr) => {
2142 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2143 self.s.word(".await");
2145 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2146 let prec = AssocOp::Assign.precedence() as i8;
2147 self.print_expr_maybe_paren(lhs, prec + 1);
2149 self.word_space("=");
2150 self.print_expr_maybe_paren(rhs, prec);
2152 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2153 let prec = AssocOp::Assign.precedence() as i8;
2154 self.print_expr_maybe_paren(lhs, prec + 1);
2156 self.s.word(op.node.to_string());
2157 self.word_space("=");
2158 self.print_expr_maybe_paren(rhs, prec);
2160 ast::ExprKind::Field(ref expr, ident) => {
2161 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2163 self.print_ident(ident);
2165 ast::ExprKind::Index(ref expr, ref index) => {
2166 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2168 self.print_expr(index);
2171 ast::ExprKind::Range(ref start, ref end, limits) => {
2172 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2173 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2174 // Here we use a fake precedence value so that any child with lower precedence than
2175 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2176 let fake_prec = AssocOp::LOr.precedence() as i8;
2177 if let Some(ref e) = *start {
2178 self.print_expr_maybe_paren(e, fake_prec);
2180 if limits == ast::RangeLimits::HalfOpen {
2185 if let Some(ref e) = *end {
2186 self.print_expr_maybe_paren(e, fake_prec);
2189 ast::ExprKind::Path(None, ref path) => {
2190 self.print_path(path, true, 0)
2192 ast::ExprKind::Path(Some(ref qself), ref path) => {
2193 self.print_qpath(path, qself, true)
2195 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2196 self.s.word("break");
2198 if let Some(label) = opt_label {
2199 self.print_ident(label.ident);
2202 if let Some(ref expr) = *opt_expr {
2203 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2207 ast::ExprKind::Continue(opt_label) => {
2208 self.s.word("continue");
2210 if let Some(label) = opt_label {
2211 self.print_ident(label.ident);
2215 ast::ExprKind::Ret(ref result) => {
2216 self.s.word("return");
2217 if let Some(ref expr) = *result {
2219 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2222 ast::ExprKind::InlineAsm(ref a) => {
2223 self.s.word("asm!");
2225 self.print_string(&a.asm.as_str(), a.asm_str_style);
2226 self.word_space(":");
2228 self.commasep(Inconsistent, &a.outputs, |s, out| {
2229 let constraint = out.constraint.as_str();
2230 let mut ch = constraint.chars();
2232 Some('=') if out.is_rw => {
2233 s.print_string(&format!("+{}", ch.as_str()),
2234 ast::StrStyle::Cooked)
2236 _ => s.print_string(&constraint, ast::StrStyle::Cooked)
2239 s.print_expr(&out.expr);
2243 self.word_space(":");
2245 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2246 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2252 self.word_space(":");
2254 self.commasep(Inconsistent, &a.clobbers,
2256 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2259 let mut options = vec![];
2261 options.push("volatile");
2264 options.push("alignstack");
2266 if a.dialect == ast::AsmDialect::Intel {
2267 options.push("intel");
2270 if !options.is_empty() {
2272 self.word_space(":");
2273 self.commasep(Inconsistent, &options,
2275 s.print_string(co, ast::StrStyle::Cooked);
2281 ast::ExprKind::Mac(ref m) => self.print_mac(m),
2282 ast::ExprKind::Paren(ref e) => {
2284 self.print_inner_attributes_inline(attrs);
2288 ast::ExprKind::Yield(ref e) => {
2289 self.s.word("yield");
2293 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2298 ast::ExprKind::Try(ref e) => {
2299 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2302 ast::ExprKind::TryBlock(ref blk) => {
2305 self.print_block_with_attrs(blk, attrs)
2307 ast::ExprKind::Err => {
2309 self.s.word("/*ERROR*/");
2313 self.ann.post(self, AnnNode::Expr(expr));
2317 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2318 self.print_pat(&loc.pat);
2319 if let Some(ref ty) = loc.ty {
2320 self.word_space(":");
2321 self.print_type(ty);
2325 pub fn print_usize(&mut self, i: usize) {
2326 self.s.word(i.to_string())
2329 crate fn print_name(&mut self, name: ast::Name) {
2330 self.s.word(name.to_string());
2331 self.ann.post(self, AnnNode::Name(&name))
2334 fn print_qpath(&mut self,
2337 colons_before_params: bool)
2340 self.print_type(&qself.ty);
2341 if qself.position > 0 {
2343 self.word_space("as");
2344 let depth = path.segments.len() - qself.position;
2345 self.print_path(path, false, depth);
2349 let item_segment = path.segments.last().unwrap();
2350 self.print_ident(item_segment.ident);
2351 match item_segment.args {
2352 Some(ref args) => self.print_generic_args(args, colons_before_params),
2357 crate fn print_pat(&mut self, pat: &ast::Pat) {
2358 self.maybe_print_comment(pat.span.lo());
2359 self.ann.pre(self, AnnNode::Pat(pat));
2360 /* Pat isn't normalized, but the beauty of it
2361 is that it doesn't matter */
2363 PatKind::Wild => self.s.word("_"),
2364 PatKind::Ident(binding_mode, ident, ref sub) => {
2365 match binding_mode {
2366 ast::BindingMode::ByRef(mutbl) => {
2367 self.word_nbsp("ref");
2368 self.print_mutability(mutbl, false);
2370 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2371 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2372 self.word_nbsp("mut");
2375 self.print_ident(ident);
2376 if let Some(ref p) = *sub {
2378 self.s.word_space("@");
2382 PatKind::TupleStruct(ref path, ref elts) => {
2383 self.print_path(path, true, 0);
2385 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2388 PatKind::Or(ref pats) => {
2389 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(p));
2391 PatKind::Path(None, ref path) => {
2392 self.print_path(path, true, 0);
2394 PatKind::Path(Some(ref qself), ref path) => {
2395 self.print_qpath(path, qself, false);
2397 PatKind::Struct(ref path, ref fields, etc) => {
2398 self.print_path(path, true, 0);
2400 self.word_space("{");
2402 Consistent, &fields[..],
2404 s.cbox(INDENT_UNIT);
2405 if !f.is_shorthand {
2406 s.print_ident(f.ident);
2409 s.print_pat(&f.pat);
2414 if !fields.is_empty() { self.word_space(","); }
2420 PatKind::Tuple(ref elts) => {
2422 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2423 if elts.len() == 1 {
2428 PatKind::Box(ref inner) => {
2429 self.s.word("box ");
2430 self.print_pat(inner);
2432 PatKind::Ref(ref inner, mutbl) => {
2434 if mutbl == ast::Mutability::Mutable {
2435 self.s.word("mut ");
2437 self.print_pat(inner);
2439 PatKind::Lit(ref e) => self.print_expr(&**e),
2440 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2441 self.print_expr(begin);
2444 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("..."),
2445 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..="),
2446 RangeEnd::Excluded => self.s.word(".."),
2448 self.print_expr(end);
2450 PatKind::Slice(ref elts) => {
2452 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2455 PatKind::Rest => self.s.word(".."),
2456 PatKind::Paren(ref inner) => {
2458 self.print_pat(inner);
2461 PatKind::Mac(ref m) => self.print_mac(m),
2463 self.ann.post(self, AnnNode::Pat(pat))
2466 fn print_arm(&mut self, arm: &ast::Arm) {
2467 // Note, I have no idea why this check is necessary, but here it is.
2468 if arm.attrs.is_empty() {
2471 self.cbox(INDENT_UNIT);
2473 self.maybe_print_comment(arm.pat.span.lo());
2474 self.print_outer_attributes(&arm.attrs);
2475 self.print_pat(&arm.pat);
2477 if let Some(ref e) = arm.guard {
2478 self.word_space("if");
2482 self.word_space("=>");
2484 match arm.body.kind {
2485 ast::ExprKind::Block(ref blk, opt_label) => {
2486 if let Some(label) = opt_label {
2487 self.print_ident(label.ident);
2488 self.word_space(":");
2491 // The block will close the pattern's ibox.
2492 self.print_block_unclosed_indent(blk);
2494 // If it is a user-provided unsafe block, print a comma after it.
2495 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2500 self.end(); // Close the ibox for the pattern.
2501 self.print_expr(&arm.body);
2505 self.end(); // Close enclosing cbox.
2508 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2509 match explicit_self.node {
2510 SelfKind::Value(m) => {
2511 self.print_mutability(m, false);
2514 SelfKind::Region(ref lt, m) => {
2516 self.print_opt_lifetime(lt);
2517 self.print_mutability(m, false);
2520 SelfKind::Explicit(ref typ, m) => {
2521 self.print_mutability(m, false);
2522 self.s.word("self");
2523 self.word_space(":");
2524 self.print_type(typ)
2529 crate fn print_fn(&mut self,
2531 header: ast::FnHeader,
2532 name: Option<ast::Ident>,
2533 generics: &ast::Generics,
2534 vis: &ast::Visibility) {
2535 self.print_fn_header_info(header, vis);
2537 if let Some(name) = name {
2539 self.print_ident(name);
2541 self.print_generic_params(&generics.params);
2542 self.print_fn_params_and_ret(decl);
2543 self.print_where_clause(&generics.where_clause)
2546 crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl) {
2548 self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, false));
2551 self.print_fn_output(decl)
2554 crate fn print_fn_block_params(&mut self, decl: &ast::FnDecl) {
2556 self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, true));
2559 if let ast::FunctionRetTy::Default(..) = decl.output {
2563 self.space_if_not_bol();
2564 self.word_space("->");
2566 ast::FunctionRetTy::Ty(ref ty) => {
2567 self.print_type(ty);
2568 self.maybe_print_comment(ty.span.lo())
2570 ast::FunctionRetTy::Default(..) => unreachable!(),
2574 crate fn print_movability(&mut self, movability: ast::Movability) {
2576 ast::Movability::Static => self.word_space("static"),
2577 ast::Movability::Movable => {},
2581 crate fn print_asyncness(&mut self, asyncness: ast::IsAsync) {
2582 if asyncness.is_async() {
2583 self.word_nbsp("async");
2587 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2588 match capture_clause {
2589 ast::CaptureBy::Value => self.word_space("move"),
2590 ast::CaptureBy::Ref => {},
2594 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2595 if !bounds.is_empty() {
2596 self.s.word(prefix);
2597 let mut first = true;
2598 for bound in bounds {
2599 if !(first && prefix.is_empty()) {
2605 self.word_space("+");
2609 GenericBound::Trait(tref, modifier) => {
2610 if modifier == &TraitBoundModifier::Maybe {
2613 self.print_poly_trait_ref(tref);
2615 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2621 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2622 self.print_name(lifetime.ident.name)
2625 crate fn print_lifetime_bounds(
2626 &mut self, lifetime: ast::Lifetime, bounds: &ast::GenericBounds) {
2627 self.print_lifetime(lifetime);
2628 if !bounds.is_empty() {
2630 for (i, bound) in bounds.iter().enumerate() {
2635 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2642 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2643 if generic_params.is_empty() {
2649 self.commasep(Inconsistent, &generic_params, |s, param| {
2650 s.print_outer_attributes_inline(¶m.attrs);
2653 ast::GenericParamKind::Lifetime => {
2654 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2655 s.print_lifetime_bounds(lt, ¶m.bounds)
2657 ast::GenericParamKind::Type { ref default } => {
2658 s.print_ident(param.ident);
2659 s.print_type_bounds(":", ¶m.bounds);
2660 if let Some(ref default) = default {
2663 s.print_type(default)
2666 ast::GenericParamKind::Const { ref ty } => {
2667 s.word_space("const");
2668 s.print_ident(param.ident);
2672 s.print_type_bounds(":", ¶m.bounds)
2680 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2681 if where_clause.predicates.is_empty() {
2686 self.word_space("where");
2688 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2690 self.word_space(",");
2694 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2695 ref bound_generic_params,
2700 self.print_formal_generic_params(bound_generic_params);
2701 self.print_type(bounded_ty);
2702 self.print_type_bounds(":", bounds);
2704 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2707 self.print_lifetime_bounds(*lifetime, bounds);
2709 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2712 self.print_type(lhs_ty);
2714 self.word_space("=");
2715 self.print_type(rhs_ty);
2721 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2723 ast::UseTreeKind::Simple(rename, ..) => {
2724 self.print_path(&tree.prefix, false, 0);
2725 if let Some(rename) = rename {
2727 self.word_space("as");
2728 self.print_ident(rename);
2731 ast::UseTreeKind::Glob => {
2732 if !tree.prefix.segments.is_empty() {
2733 self.print_path(&tree.prefix, false, 0);
2738 ast::UseTreeKind::Nested(ref items) => {
2739 if tree.prefix.segments.is_empty() {
2742 self.print_path(&tree.prefix, false, 0);
2745 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2746 this.print_use_tree(tree)
2753 pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2755 ast::Mutability::Mutable => self.word_nbsp("mut"),
2756 ast::Mutability::Immutable => if print_const { self.word_nbsp("const"); },
2760 crate fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2761 self.print_mutability(mt.mutbl, print_const);
2762 self.print_type(&mt.ty)
2765 crate fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2766 self.ibox(INDENT_UNIT);
2768 self.print_outer_attributes_inline(&input.attrs);
2770 match input.ty.kind {
2771 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2773 if let Some(eself) = input.to_self() {
2774 self.print_explicit_self(&eself);
2776 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.kind {
2777 ident.name == kw::Invalid
2782 self.print_pat(&input.pat);
2786 self.print_type(&input.ty);
2793 crate fn print_fn_output(&mut self, decl: &ast::FnDecl) {
2794 if let ast::FunctionRetTy::Default(..) = decl.output {
2798 self.space_if_not_bol();
2799 self.ibox(INDENT_UNIT);
2800 self.word_space("->");
2802 ast::FunctionRetTy::Default(..) => unreachable!(),
2803 ast::FunctionRetTy::Ty(ref ty) =>
2804 self.print_type(ty),
2809 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo()),
2814 crate fn print_ty_fn(&mut self,
2816 unsafety: ast::Unsafety,
2818 name: Option<ast::Ident>,
2819 generic_params: &[ast::GenericParam])
2821 self.ibox(INDENT_UNIT);
2822 if !generic_params.is_empty() {
2824 self.print_generic_params(generic_params);
2826 let generics = ast::Generics {
2828 where_clause: ast::WhereClause {
2829 predicates: Vec::new(),
2830 span: syntax_pos::DUMMY_SP,
2832 span: syntax_pos::DUMMY_SP,
2835 ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() },
2838 &source_map::dummy_spanned(ast::VisibilityKind::Inherited));
2842 crate fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
2843 next_pos: Option<BytePos>)
2845 if let Some(cmnts) = self.comments() {
2846 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2847 self.print_comment(&cmnt);
2852 crate fn print_remaining_comments(&mut self) {
2853 // If there aren't any remaining comments, then we need to manually
2854 // make sure there is a line break at the end.
2855 if self.next_comment().is_none() {
2858 while let Some(ref cmnt) = self.next_comment() {
2859 self.print_comment(cmnt);
2863 crate fn print_fn_header_info(&mut self,
2864 header: ast::FnHeader,
2865 vis: &ast::Visibility) {
2866 self.s.word(visibility_qualified(vis, ""));
2868 match header.constness.node {
2869 ast::Constness::NotConst => {}
2870 ast::Constness::Const => self.word_nbsp("const")
2873 self.print_asyncness(header.asyncness.node);
2874 self.print_unsafety(header.unsafety);
2877 ast::Extern::None => {}
2878 ast::Extern::Implicit => {
2879 self.word_nbsp("extern");
2881 ast::Extern::Explicit(abi) => {
2882 self.word_nbsp("extern");
2883 self.print_literal(&abi.as_lit());
2891 crate fn print_unsafety(&mut self, s: ast::Unsafety) {
2893 ast::Unsafety::Normal => {},
2894 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2898 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2900 ast::IsAuto::Yes => self.word_nbsp("auto"),
2901 ast::IsAuto::No => {}