1 use crate::ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax};
2 use crate::ast::{SelfKind, GenericBound, TraitBoundModifier};
3 use crate::ast::{Attribute, MacDelimiter, GenericArg};
4 use crate::util::parser::{self, AssocOp, Fixity};
6 use crate::source_map::{self, SourceMap, Spanned};
7 use crate::parse::token::{self, BinOpToken, DelimToken, Nonterminal, Token, TokenKind};
8 use crate::parse::lexer::comments;
9 use crate::parse::{self, ParseSess};
10 use crate::print::pp::{self, Breaks};
11 use crate::print::pp::Breaks::{Consistent, Inconsistent};
13 use crate::symbol::{kw, sym};
14 use crate::tokenstream::{self, TokenStream, TokenTree};
16 use rustc_target::spec::abi::{self, Abi};
17 use syntax_pos::{self, BytePos};
18 use syntax_pos::{DUMMY_SP, FileName, Span};
22 pub enum MacHeader<'a> {
24 Keyword(&'static str),
27 pub enum AnnNode<'a> {
28 Ident(&'a ast::Ident),
30 Block(&'a ast::Block),
38 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) { }
39 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) { }
42 #[derive(Copy, Clone)]
45 impl PpAnn for NoAnn {}
47 pub struct Comments<'a> {
49 comments: Vec<comments::Comment>,
53 impl<'a> Comments<'a> {
60 let comments = comments::gather_comments(sess, filename, input);
68 pub fn next(&self) -> Option<comments::Comment> {
69 self.comments.get(self.current).cloned()
72 pub fn trailing_comment(
74 span: syntax_pos::Span,
75 next_pos: Option<BytePos>,
76 ) -> Option<comments::Comment> {
77 if let Some(cmnt) = self.next() {
78 if cmnt.style != comments::Trailing { return None; }
79 let span_line = self.cm.lookup_char_pos(span.hi());
80 let comment_line = self.cm.lookup_char_pos(cmnt.pos);
81 let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1));
82 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
91 pub struct State<'a> {
93 comments: Option<Comments<'a>>,
94 ann: &'a (dyn PpAnn+'a),
98 crate const INDENT_UNIT: usize = 4;
100 /// Requires you to pass an input filename and reader so that
101 /// it can scan the input text for comments to copy forward.
102 pub fn print_crate<'a>(cm: &'a SourceMap,
108 is_expanded: bool) -> String {
111 comments: Some(Comments::new(cm, sess, filename, input)),
116 if is_expanded && sess.injected_crate_name.try_get().is_some() {
117 // We need to print `#![no_std]` (and its feature gate) so that
118 // compiling pretty-printed source won't inject libstd again.
119 // However we don't want these attributes in the AST because
120 // of the feature gate, so we fake them up here.
122 // #![feature(prelude_import)]
123 let pi_nested = attr::mk_nested_word_item(ast::Ident::with_empty_ctxt(sym::prelude_import));
124 let list = attr::mk_list_item(
125 DUMMY_SP, ast::Ident::with_empty_ctxt(sym::feature), vec![pi_nested]);
126 let fake_attr = attr::mk_attr_inner(DUMMY_SP, list);
127 s.print_attribute(&fake_attr);
130 let no_std_meta = attr::mk_word_item(ast::Ident::with_empty_ctxt(sym::no_std));
131 let fake_attr = attr::mk_attr_inner(DUMMY_SP, no_std_meta);
132 s.print_attribute(&fake_attr);
135 s.print_mod(&krate.module, &krate.attrs);
136 s.print_remaining_comments();
140 pub fn to_string<F>(f: F) -> String where
141 F: FnOnce(&mut State<'_>),
143 let mut printer = State {
153 fn binop_to_string(op: BinOpToken) -> &'static str {
159 token::Percent => "%",
168 pub fn literal_to_string(lit: token::Lit) -> String {
169 let token::Lit { kind, symbol, suffix } = lit;
170 let mut out = match kind {
171 token::Byte => format!("b'{}'", symbol),
172 token::Char => format!("'{}'", symbol),
173 token::Str => format!("\"{}\"", symbol),
174 token::StrRaw(n) => format!("r{delim}\"{string}\"{delim}",
175 delim="#".repeat(n as usize),
177 token::ByteStr => format!("b\"{}\"", symbol),
178 token::ByteStrRaw(n) => format!("br{delim}\"{string}\"{delim}",
179 delim="#".repeat(n as usize),
184 token::Err => symbol.to_string(),
187 if let Some(suffix) = suffix {
188 out.push_str(&suffix.as_str())
194 /// Print an ident from AST, `$crate` is converted into its respective crate name.
195 pub fn ast_ident_to_string(ident: ast::Ident, is_raw: bool) -> String {
196 ident_to_string(ident.name, is_raw, Some(ident.span))
199 // AST pretty-printer is used as a fallback for turning AST structures into token streams for
200 // proc macros. Additionally, proc macros may stringify their input and expect it survive the
201 // stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
202 // So we need to somehow pretty-print `$crate` in a way preserving at least some of its
203 // hygiene data, most importantly name of the crate it refers to.
204 // As a result we print `$crate` as `crate` if it refers to the local crate
205 // and as `::other_crate_name` if it refers to some other crate.
206 // Note, that this is only done if the ident token is printed from inside of AST pretty-pringing,
207 // but not otherwise. Pretty-printing is the only way for proc macros to discover token contents,
208 // so we should not perform this lossy conversion if the top level call to the pretty-printer was
209 // done for a token stream or a single token.
210 fn ident_to_string(name: ast::Name, is_raw: bool, convert_dollar_crate: Option<Span>) -> String {
212 format!("r#{}", name)
214 if name == kw::DollarCrate {
215 if let Some(span) = convert_dollar_crate {
216 let converted = span.ctxt().dollar_crate_name();
217 return if converted.is_path_segment_keyword() {
218 converted.to_string()
220 format!("::{}", converted)
228 /// Print the token kind precisely, without converting `$crate` into its respective crate name.
229 pub fn token_kind_to_string(tok: &TokenKind) -> String {
230 token_kind_to_string_ext(tok, None)
233 fn token_kind_to_string_ext(tok: &TokenKind, convert_dollar_crate: Option<Span>) -> String {
235 token::Eq => "=".to_string(),
236 token::Lt => "<".to_string(),
237 token::Le => "<=".to_string(),
238 token::EqEq => "==".to_string(),
239 token::Ne => "!=".to_string(),
240 token::Ge => ">=".to_string(),
241 token::Gt => ">".to_string(),
242 token::Not => "!".to_string(),
243 token::Tilde => "~".to_string(),
244 token::OrOr => "||".to_string(),
245 token::AndAnd => "&&".to_string(),
246 token::BinOp(op) => binop_to_string(op).to_string(),
247 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
249 /* Structural symbols */
250 token::At => "@".to_string(),
251 token::Dot => ".".to_string(),
252 token::DotDot => "..".to_string(),
253 token::DotDotDot => "...".to_string(),
254 token::DotDotEq => "..=".to_string(),
255 token::Comma => ",".to_string(),
256 token::Semi => ";".to_string(),
257 token::Colon => ":".to_string(),
258 token::ModSep => "::".to_string(),
259 token::RArrow => "->".to_string(),
260 token::LArrow => "<-".to_string(),
261 token::FatArrow => "=>".to_string(),
262 token::OpenDelim(token::Paren) => "(".to_string(),
263 token::CloseDelim(token::Paren) => ")".to_string(),
264 token::OpenDelim(token::Bracket) => "[".to_string(),
265 token::CloseDelim(token::Bracket) => "]".to_string(),
266 token::OpenDelim(token::Brace) => "{".to_string(),
267 token::CloseDelim(token::Brace) => "}".to_string(),
268 token::OpenDelim(token::NoDelim) |
269 token::CloseDelim(token::NoDelim) => " ".to_string(),
270 token::Pound => "#".to_string(),
271 token::Dollar => "$".to_string(),
272 token::Question => "?".to_string(),
273 token::SingleQuote => "'".to_string(),
276 token::Literal(lit) => literal_to_string(lit),
278 /* Name components */
279 token::Ident(s, is_raw) => ident_to_string(s, is_raw, convert_dollar_crate),
280 token::Lifetime(s) => s.to_string(),
283 token::DocComment(s) => s.to_string(),
284 token::Eof => "<eof>".to_string(),
285 token::Whitespace => " ".to_string(),
286 token::Comment => "/* */".to_string(),
287 token::Shebang(s) => format!("/* shebang: {}*/", s),
289 token::Interpolated(ref nt) => nonterminal_to_string(nt),
293 /// Print the token precisely, without converting `$crate` into its respective crate name.
294 pub fn token_to_string(token: &Token) -> String {
295 token_to_string_ext(token, false)
298 fn token_to_string_ext(token: &Token, convert_dollar_crate: bool) -> String {
299 let convert_dollar_crate = if convert_dollar_crate { Some(token.span) } else { None };
300 token_kind_to_string_ext(&token.kind, convert_dollar_crate)
303 crate fn nonterminal_to_string(nt: &Nonterminal) -> String {
305 token::NtExpr(ref e) => expr_to_string(e),
306 token::NtMeta(ref e) => meta_item_to_string(e),
307 token::NtTy(ref e) => ty_to_string(e),
308 token::NtPath(ref e) => path_to_string(e),
309 token::NtItem(ref e) => item_to_string(e),
310 token::NtBlock(ref e) => block_to_string(e),
311 token::NtStmt(ref e) => stmt_to_string(e),
312 token::NtPat(ref e) => pat_to_string(e),
313 token::NtIdent(e, is_raw) => ast_ident_to_string(e, is_raw),
314 token::NtLifetime(e) => e.to_string(),
315 token::NtLiteral(ref e) => expr_to_string(e),
316 token::NtTT(ref tree) => tt_to_string(tree.clone()),
317 token::NtImplItem(ref e) => impl_item_to_string(e),
318 token::NtTraitItem(ref e) => trait_item_to_string(e),
319 token::NtVis(ref e) => vis_to_string(e),
320 token::NtForeignItem(ref e) => foreign_item_to_string(e),
324 pub fn ty_to_string(ty: &ast::Ty) -> String {
325 to_string(|s| s.print_type(ty))
328 pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
329 to_string(|s| s.print_type_bounds("", bounds))
332 pub fn pat_to_string(pat: &ast::Pat) -> String {
333 to_string(|s| s.print_pat(pat))
336 pub fn expr_to_string(e: &ast::Expr) -> String {
337 to_string(|s| s.print_expr(e))
340 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
341 to_string(|s| s.print_tt(tt, false))
344 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
345 tokens_to_string(tts.iter().cloned().collect())
348 pub fn tokens_to_string(tokens: TokenStream) -> String {
349 to_string(|s| s.print_tts(tokens, false))
352 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
353 to_string(|s| s.print_stmt(stmt))
356 pub fn item_to_string(i: &ast::Item) -> String {
357 to_string(|s| s.print_item(i))
360 fn impl_item_to_string(i: &ast::ImplItem) -> String {
361 to_string(|s| s.print_impl_item(i))
364 fn trait_item_to_string(i: &ast::TraitItem) -> String {
365 to_string(|s| s.print_trait_item(i))
368 pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String {
369 to_string(|s| s.print_generic_params(generic_params))
372 pub fn path_to_string(p: &ast::Path) -> String {
373 to_string(|s| s.print_path(p, false, 0))
376 pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
377 to_string(|s| s.print_path_segment(p, false))
380 pub fn vis_to_string(v: &ast::Visibility) -> String {
381 to_string(|s| s.print_visibility(v))
385 fn fun_to_string(decl: &ast::FnDecl,
386 header: ast::FnHeader,
388 generics: &ast::Generics)
392 s.print_fn(decl, header, Some(name),
393 generics, &source_map::dummy_spanned(ast::VisibilityKind::Inherited));
394 s.end(); // Close the head box
395 s.end(); // Close the outer box
399 fn block_to_string(blk: &ast::Block) -> String {
401 // containing cbox, will be closed by print-block at }
403 // head-ibox, will be closed by print-block after {
409 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
410 to_string(|s| s.print_meta_list_item(li))
413 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
414 to_string(|s| s.print_meta_item(mi))
417 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
418 to_string(|s| s.print_attribute(attr))
422 fn variant_to_string(var: &ast::Variant) -> String {
423 to_string(|s| s.print_variant(var))
426 pub fn arg_to_string(arg: &ast::Arg) -> String {
427 to_string(|s| s.print_arg(arg, false))
430 fn foreign_item_to_string(arg: &ast::ForeignItem) -> String {
431 to_string(|s| s.print_foreign_item(arg))
434 fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
435 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
438 impl std::ops::Deref for State<'_> {
439 type Target = pp::Printer;
440 fn deref(&self) -> &Self::Target {
445 impl std::ops::DerefMut for State<'_> {
446 fn deref_mut(&mut self) -> &mut Self::Target {
451 pub trait PrintState<'a>: std::ops::Deref<Target=pp::Printer> + std::ops::DerefMut {
452 fn comments(&mut self) -> &mut Option<Comments<'a>>;
453 fn print_ident(&mut self, ident: ast::Ident);
454 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool);
456 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F)
457 where F: FnMut(&mut Self, &T),
460 let mut first = true;
462 if first { first = false; } else { self.word_space(","); }
468 fn maybe_print_comment(&mut self, pos: BytePos) {
469 while let Some(ref cmnt) = self.next_comment() {
471 self.print_comment(cmnt);
478 fn print_comment(&mut self,
479 cmnt: &comments::Comment) {
482 assert_eq!(cmnt.lines.len(), 1);
484 self.word(cmnt.lines[0].clone());
487 comments::Isolated => {
488 self.hardbreak_if_not_bol();
489 for line in &cmnt.lines {
490 // Don't print empty lines because they will end up as trailing
492 if !line.is_empty() {
493 self.word(line.clone());
498 comments::Trailing => {
499 if !self.is_beginning_of_line() {
502 if cmnt.lines.len() == 1 {
503 self.word(cmnt.lines[0].clone());
507 for line in &cmnt.lines {
508 if !line.is_empty() {
509 self.word(line.clone());
516 comments::BlankLine => {
517 // We need to do at least one, possibly two hardbreaks.
518 let twice = match self.last_token() {
519 pp::Token::String(s) => ";" == s,
520 pp::Token::Begin(_) => true,
521 pp::Token::End => true,
530 if let Some(cm) = self.comments() {
535 fn next_comment(&mut self) -> Option<comments::Comment> {
536 self.comments().as_mut().and_then(|c| c.next())
539 fn print_literal(&mut self, lit: &ast::Lit) {
540 self.maybe_print_comment(lit.span.lo());
541 self.word(lit.token.to_string())
544 fn print_string(&mut self, st: &str,
545 style: ast::StrStyle) {
546 let st = match style {
547 ast::StrStyle::Cooked => {
548 (format!("\"{}\"", st.escape_debug()))
550 ast::StrStyle::Raw(n) => {
551 (format!("r{delim}\"{string}\"{delim}",
552 delim="#".repeat(n as usize),
559 fn print_inner_attributes(&mut self,
560 attrs: &[ast::Attribute]) {
561 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
564 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
565 attrs: &[ast::Attribute])
567 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
570 fn print_outer_attributes(&mut self,
571 attrs: &[ast::Attribute]) {
572 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
575 fn print_inner_attributes_inline(&mut self,
576 attrs: &[ast::Attribute]) {
577 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
580 fn print_outer_attributes_inline(&mut self,
581 attrs: &[ast::Attribute]) {
582 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
585 fn print_either_attributes(&mut self,
586 attrs: &[ast::Attribute],
587 kind: ast::AttrStyle,
589 trailing_hardbreak: bool) {
592 if attr.style == kind {
593 self.print_attribute_inline(attr, is_inline);
600 if count > 0 && trailing_hardbreak && !is_inline {
601 self.hardbreak_if_not_bol();
605 fn print_attribute(&mut self, attr: &ast::Attribute) {
606 self.print_attribute_inline(attr, false)
609 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
612 self.hardbreak_if_not_bol();
614 self.maybe_print_comment(attr.span.lo());
615 if attr.is_sugared_doc {
616 self.word(attr.value_str().unwrap().as_str().to_string());
620 ast::AttrStyle::Inner => self.word("#!["),
621 ast::AttrStyle::Outer => self.word("#["),
624 match attr.tokens.trees().next() {
625 Some(TokenTree::Delimited(_, delim, tts)) => {
626 self.print_mac_common(
627 Some(MacHeader::Path(&attr.path)), false, None, delim, tts, true, attr.span
631 self.print_path(&attr.path, false, 0);
634 self.print_tts(attr.tokens.clone(), true);
643 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) {
645 ast::NestedMetaItem::MetaItem(ref mi) => {
646 self.print_meta_item(mi)
648 ast::NestedMetaItem::Literal(ref lit) => {
649 self.print_literal(lit)
654 fn print_meta_item(&mut self, item: &ast::MetaItem) {
655 self.ibox(INDENT_UNIT);
657 ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
658 ast::MetaItemKind::NameValue(ref value) => {
659 self.print_path(&item.path, false, 0);
661 self.word_space("=");
662 self.print_literal(value);
664 ast::MetaItemKind::List(ref items) => {
665 self.print_path(&item.path, false, 0);
667 self.commasep(Consistent,
669 |s, i| s.print_meta_list_item(i));
676 /// This doesn't deserve to be called "pretty" printing, but it should be
677 /// meaning-preserving. A quick hack that might help would be to look at the
678 /// spans embedded in the TTs to decide where to put spaces and newlines.
679 /// But it'd be better to parse these according to the grammar of the
680 /// appropriate macro, transcribe back into the grammar we just parsed from,
681 /// and then pretty-print the resulting AST nodes (so, e.g., we print
682 /// expression arguments as expressions). It can be done! I think.
683 fn print_tt(&mut self, tt: tokenstream::TokenTree, convert_dollar_crate: bool) {
685 TokenTree::Token(ref token) => {
686 self.word(token_to_string_ext(&token, convert_dollar_crate));
688 token::DocComment(..) => {
694 TokenTree::Delimited(dspan, delim, tts) => {
695 self.print_mac_common(
696 None, false, None, delim, tts, convert_dollar_crate, dspan.entire()
702 fn print_tts(&mut self, tts: tokenstream::TokenStream, convert_dollar_crate: bool) {
703 for (i, tt) in tts.into_trees().enumerate() {
707 self.print_tt(tt, convert_dollar_crate);
713 header: Option<MacHeader<'_>>,
715 ident: Option<ast::Ident>,
718 convert_dollar_crate: bool,
721 if delim == DelimToken::Brace {
722 self.cbox(INDENT_UNIT);
725 Some(MacHeader::Path(path)) => self.print_path(path, false, 0),
726 Some(MacHeader::Keyword(kw)) => self.word(kw),
732 if let Some(ident) = ident {
734 self.print_ident(ident);
737 DelimToken::Brace => {
738 if header.is_some() || has_bang || ident.is_some() {
746 _ => self.word(token_kind_to_string(&token::OpenDelim(delim))),
749 self.print_tts(tts, convert_dollar_crate);
752 DelimToken::Brace => self.bclose(span),
753 _ => self.word(token_kind_to_string(&token::CloseDelim(delim))),
757 fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
758 self.maybe_print_comment(path.span.lo());
760 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
764 self.print_path_segment(segment, colons_before_params);
768 fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
769 if segment.ident.name != kw::PathRoot {
770 self.print_ident(segment.ident);
771 if let Some(ref args) = segment.args {
772 self.print_generic_args(args, colons_before_params);
777 fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
779 // outer-box is consistent
780 self.cbox(INDENT_UNIT);
781 // head-box is inconsistent
782 self.ibox(w.len() + 1);
783 // keyword that starts the head
789 fn bopen(&mut self) {
791 self.end(); // close the head-box
794 fn bclose_maybe_open(&mut self, span: syntax_pos::Span, close_box: bool) {
795 self.maybe_print_comment(span.hi());
796 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
799 self.end(); // close the outer-box
803 fn bclose(&mut self, span: syntax_pos::Span) {
804 self.bclose_maybe_open(span, true)
807 fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
808 if !self.is_beginning_of_line() {
809 self.break_offset(n, off)
811 if off != 0 && self.last_token().is_hardbreak_tok() {
812 // We do something pretty sketchy here: tuck the nonzero
813 // offset-adjustment we were going to deposit along with the
814 // break into the previous hardbreak.
815 self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
821 impl<'a> PrintState<'a> for State<'a> {
822 fn comments(&mut self) -> &mut Option<Comments<'a>> {
826 fn print_ident(&mut self, ident: ast::Ident) {
827 self.s.word(ast_ident_to_string(ident, ident.is_raw_guess()));
828 self.ann.post(self, AnnNode::Ident(&ident))
831 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
832 if colons_before_params {
837 ast::GenericArgs::AngleBracketed(ref data) => {
840 self.commasep(Inconsistent, &data.args, |s, generic_arg| {
841 s.print_generic_arg(generic_arg)
844 let mut comma = data.args.len() != 0;
846 for constraint in data.constraints.iter() {
850 self.print_ident(constraint.ident);
852 match constraint.kind {
853 ast::AssocTyConstraintKind::Equality { ref ty } => {
854 self.word_space("=");
857 ast::AssocTyConstraintKind::Bound { ref bounds } => {
858 self.print_type_bounds(":", &*bounds);
867 ast::GenericArgs::Parenthesized(ref data) => {
872 |s, ty| s.print_type(ty));
875 if let Some(ref ty) = data.output {
876 self.space_if_not_bol();
877 self.word_space("->");
886 // Synthesizes a comment that was not textually present in the original source
888 pub fn synth_comment(&mut self, text: String) {
898 crate fn commasep_cmnt<T, F, G>(&mut self,
902 mut get_span: G) where
903 F: FnMut(&mut State<'_>, &T),
904 G: FnMut(&T) -> syntax_pos::Span,
907 let len = elts.len();
910 self.maybe_print_comment(get_span(elt).hi());
915 self.maybe_print_trailing_comment(get_span(elt),
916 Some(get_span(&elts[i]).hi()));
917 self.space_if_not_bol();
923 crate fn commasep_exprs(&mut self, b: Breaks,
924 exprs: &[P<ast::Expr>]) {
925 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
928 crate fn print_mod(&mut self, _mod: &ast::Mod,
929 attrs: &[ast::Attribute]) {
930 self.print_inner_attributes(attrs);
931 for item in &_mod.items {
932 self.print_item(item);
936 crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
937 attrs: &[ast::Attribute]) {
938 self.print_inner_attributes(attrs);
939 for item in &nmod.items {
940 self.print_foreign_item(item);
944 crate fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
945 if let Some(lt) = *lifetime {
946 self.print_lifetime(lt);
951 crate fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
953 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
954 GenericArg::Type(ty) => self.print_type(ty),
955 GenericArg::Const(ct) => self.print_expr(&ct.value),
959 crate fn print_type(&mut self, ty: &ast::Ty) {
960 self.maybe_print_comment(ty.span.lo());
963 ast::TyKind::Slice(ref ty) => {
968 ast::TyKind::Ptr(ref mt) => {
971 ast::Mutability::Mutable => self.word_nbsp("mut"),
972 ast::Mutability::Immutable => self.word_nbsp("const"),
974 self.print_type(&mt.ty);
976 ast::TyKind::Rptr(ref lifetime, ref mt) => {
978 self.print_opt_lifetime(lifetime);
981 ast::TyKind::Never => {
984 ast::TyKind::Tup(ref elts) => {
986 self.commasep(Inconsistent, &elts[..],
987 |s, ty| s.print_type(ty));
993 ast::TyKind::Paren(ref typ) => {
995 self.print_type(typ);
998 ast::TyKind::BareFn(ref f) => {
999 self.print_ty_fn(f.abi,
1005 ast::TyKind::Path(None, ref path) => {
1006 self.print_path(path, false, 0);
1008 ast::TyKind::Path(Some(ref qself), ref path) => {
1009 self.print_qpath(path, qself, false)
1011 ast::TyKind::TraitObject(ref bounds, syntax) => {
1012 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
1013 self.print_type_bounds(prefix, &bounds[..]);
1015 ast::TyKind::ImplTrait(_, ref bounds) => {
1016 self.print_type_bounds("impl", &bounds[..]);
1018 ast::TyKind::Array(ref ty, ref length) => {
1020 self.print_type(ty);
1022 self.print_expr(&length.value);
1025 ast::TyKind::Typeof(ref e) => {
1026 self.s.word("typeof(");
1027 self.print_expr(&e.value);
1030 ast::TyKind::Infer => {
1033 ast::TyKind::Err => {
1035 self.s.word("/*ERROR*/");
1038 ast::TyKind::ImplicitSelf => {
1039 self.s.word("Self");
1041 ast::TyKind::Mac(ref m) => {
1044 ast::TyKind::CVarArgs => {
1051 crate fn print_foreign_item(&mut self,
1052 item: &ast::ForeignItem) {
1053 self.hardbreak_if_not_bol();
1054 self.maybe_print_comment(item.span.lo());
1055 self.print_outer_attributes(&item.attrs);
1057 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1059 self.print_fn(decl, ast::FnHeader::default(),
1061 generics, &item.vis);
1062 self.end(); // end head-ibox
1064 self.end(); // end the outer fn box
1066 ast::ForeignItemKind::Static(ref t, m) => {
1067 self.head(visibility_qualified(&item.vis, "static"));
1068 if m == ast::Mutability::Mutable {
1069 self.word_space("mut");
1071 self.print_ident(item.ident);
1072 self.word_space(":");
1075 self.end(); // end the head-ibox
1076 self.end(); // end the outer cbox
1078 ast::ForeignItemKind::Ty => {
1079 self.head(visibility_qualified(&item.vis, "type"));
1080 self.print_ident(item.ident);
1082 self.end(); // end the head-ibox
1083 self.end(); // end the outer cbox
1085 ast::ForeignItemKind::Macro(ref m) => {
1087 match m.node.delim {
1088 MacDelimiter::Brace => {},
1089 _ => self.s.word(";")
1095 fn print_associated_const(&mut self,
1098 default: Option<&ast::Expr>,
1099 vis: &ast::Visibility)
1101 self.s.word(visibility_qualified(vis, ""));
1102 self.word_space("const");
1103 self.print_ident(ident);
1104 self.word_space(":");
1105 self.print_type(ty);
1106 if let Some(expr) = default {
1108 self.word_space("=");
1109 self.print_expr(expr);
1114 fn print_associated_type(&mut self,
1116 bounds: Option<&ast::GenericBounds>,
1117 ty: Option<&ast::Ty>)
1119 self.word_space("type");
1120 self.print_ident(ident);
1121 if let Some(bounds) = bounds {
1122 self.print_type_bounds(":", bounds);
1124 if let Some(ty) = ty {
1126 self.word_space("=");
1127 self.print_type(ty);
1132 /// Pretty-print an item
1133 crate fn print_item(&mut self, item: &ast::Item) {
1134 self.hardbreak_if_not_bol();
1135 self.maybe_print_comment(item.span.lo());
1136 self.print_outer_attributes(&item.attrs);
1137 self.ann.pre(self, AnnNode::Item(item));
1139 ast::ItemKind::ExternCrate(orig_name) => {
1140 self.head(visibility_qualified(&item.vis, "extern crate"));
1141 if let Some(orig_name) = orig_name {
1142 self.print_name(orig_name);
1147 self.print_ident(item.ident);
1149 self.end(); // end inner head-block
1150 self.end(); // end outer head-block
1152 ast::ItemKind::Use(ref tree) => {
1153 self.head(visibility_qualified(&item.vis, "use"));
1154 self.print_use_tree(tree);
1156 self.end(); // end inner head-block
1157 self.end(); // end outer head-block
1159 ast::ItemKind::Static(ref ty, m, ref expr) => {
1160 self.head(visibility_qualified(&item.vis, "static"));
1161 if m == ast::Mutability::Mutable {
1162 self.word_space("mut");
1164 self.print_ident(item.ident);
1165 self.word_space(":");
1166 self.print_type(ty);
1168 self.end(); // end the head-ibox
1170 self.word_space("=");
1171 self.print_expr(expr);
1173 self.end(); // end the outer cbox
1175 ast::ItemKind::Const(ref ty, ref expr) => {
1176 self.head(visibility_qualified(&item.vis, "const"));
1177 self.print_ident(item.ident);
1178 self.word_space(":");
1179 self.print_type(ty);
1181 self.end(); // end the head-ibox
1183 self.word_space("=");
1184 self.print_expr(expr);
1186 self.end(); // end the outer cbox
1188 ast::ItemKind::Fn(ref decl, header, ref param_names, ref body) => {
1198 self.print_block_with_attrs(body, &item.attrs);
1200 ast::ItemKind::Mod(ref _mod) => {
1201 self.head(visibility_qualified(&item.vis, "mod"));
1202 self.print_ident(item.ident);
1204 if _mod.inline || self.is_expanded {
1207 self.print_mod(_mod, &item.attrs);
1208 self.bclose(item.span);
1211 self.end(); // end inner head-block
1212 self.end(); // end outer head-block
1216 ast::ItemKind::ForeignMod(ref nmod) => {
1217 self.head("extern");
1218 self.word_nbsp(nmod.abi.to_string());
1220 self.print_foreign_mod(nmod, &item.attrs);
1221 self.bclose(item.span);
1223 ast::ItemKind::GlobalAsm(ref ga) => {
1224 self.head(visibility_qualified(&item.vis, "global_asm!"));
1225 self.s.word(ga.asm.as_str().to_string());
1228 ast::ItemKind::Ty(ref ty, ref generics) => {
1229 self.head(visibility_qualified(&item.vis, "type"));
1230 self.print_ident(item.ident);
1231 self.print_generic_params(&generics.params);
1232 self.end(); // end the inner ibox
1234 self.print_where_clause(&generics.where_clause);
1236 self.word_space("=");
1237 self.print_type(ty);
1239 self.end(); // end the outer ibox
1241 ast::ItemKind::Existential(ref bounds, ref generics) => {
1242 self.head(visibility_qualified(&item.vis, "existential type"));
1243 self.print_ident(item.ident);
1244 self.print_generic_params(&generics.params);
1245 self.end(); // end the inner ibox
1247 self.print_where_clause(&generics.where_clause);
1249 self.print_type_bounds(":", bounds);
1251 self.end(); // end the outer ibox
1253 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1254 self.print_enum_def(
1262 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1263 self.head(visibility_qualified(&item.vis, "struct"));
1264 self.print_struct(struct_def, generics, item.ident, item.span, true);
1266 ast::ItemKind::Union(ref struct_def, ref generics) => {
1267 self.head(visibility_qualified(&item.vis, "union"));
1268 self.print_struct(struct_def, generics, item.ident, item.span, true);
1270 ast::ItemKind::Impl(unsafety,
1276 ref impl_items) => {
1278 self.print_visibility(&item.vis);
1279 self.print_defaultness(defaultness);
1280 self.print_unsafety(unsafety);
1281 self.word_nbsp("impl");
1283 if !generics.params.is_empty() {
1284 self.print_generic_params(&generics.params);
1288 if polarity == ast::ImplPolarity::Negative {
1292 if let Some(ref t) = *opt_trait {
1293 self.print_trait_ref(t);
1295 self.word_space("for");
1298 self.print_type(ty);
1299 self.print_where_clause(&generics.where_clause);
1303 self.print_inner_attributes(&item.attrs);
1304 for impl_item in impl_items {
1305 self.print_impl_item(impl_item);
1307 self.bclose(item.span);
1309 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1311 self.print_visibility(&item.vis);
1312 self.print_unsafety(unsafety);
1313 self.print_is_auto(is_auto);
1314 self.word_nbsp("trait");
1315 self.print_ident(item.ident);
1316 self.print_generic_params(&generics.params);
1317 let mut real_bounds = Vec::with_capacity(bounds.len());
1318 for b in bounds.iter() {
1319 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1321 self.word_space("for ?");
1322 self.print_trait_ref(&ptr.trait_ref);
1324 real_bounds.push(b.clone());
1327 self.print_type_bounds(":", &real_bounds[..]);
1328 self.print_where_clause(&generics.where_clause);
1331 for trait_item in trait_items {
1332 self.print_trait_item(trait_item);
1334 self.bclose(item.span);
1336 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1338 self.print_visibility(&item.vis);
1339 self.word_nbsp("trait");
1340 self.print_ident(item.ident);
1341 self.print_generic_params(&generics.params);
1342 let mut real_bounds = Vec::with_capacity(bounds.len());
1343 // FIXME(durka) this seems to be some quite outdated syntax
1344 for b in bounds.iter() {
1345 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1347 self.word_space("for ?");
1348 self.print_trait_ref(&ptr.trait_ref);
1350 real_bounds.push(b.clone());
1354 self.print_type_bounds("=", &real_bounds[..]);
1355 self.print_where_clause(&generics.where_clause);
1358 ast::ItemKind::Mac(ref mac) => {
1359 self.print_mac(mac);
1360 match mac.node.delim {
1361 MacDelimiter::Brace => {}
1362 _ => self.s.word(";"),
1365 ast::ItemKind::MacroDef(ref macro_def) => {
1366 let (kw, has_bang) =
1367 if macro_def.legacy { ("macro_rules", true) } else { ("macro", false) };
1368 self.print_mac_common(
1369 Some(MacHeader::Keyword(kw)),
1379 self.ann.post(self, AnnNode::Item(item))
1382 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1383 self.print_path(&t.path, false, 0)
1386 fn print_formal_generic_params(
1388 generic_params: &[ast::GenericParam]
1390 if !generic_params.is_empty() {
1392 self.print_generic_params(generic_params);
1397 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1398 self.print_formal_generic_params(&t.bound_generic_params);
1399 self.print_trait_ref(&t.trait_ref)
1402 crate fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1403 generics: &ast::Generics, ident: ast::Ident,
1404 span: syntax_pos::Span,
1405 visibility: &ast::Visibility) {
1406 self.head(visibility_qualified(visibility, "enum"));
1407 self.print_ident(ident);
1408 self.print_generic_params(&generics.params);
1409 self.print_where_clause(&generics.where_clause);
1411 self.print_variants(&enum_definition.variants, span)
1414 crate fn print_variants(&mut self,
1415 variants: &[ast::Variant],
1416 span: syntax_pos::Span) {
1419 self.space_if_not_bol();
1420 self.maybe_print_comment(v.span.lo());
1421 self.print_outer_attributes(&v.node.attrs);
1422 self.ibox(INDENT_UNIT);
1423 self.print_variant(v);
1426 self.maybe_print_trailing_comment(v.span, None);
1431 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1433 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1434 ast::VisibilityKind::Crate(sugar) => match sugar {
1435 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1436 ast::CrateSugar::JustCrate => self.word_nbsp("crate")
1438 ast::VisibilityKind::Restricted { ref path, .. } => {
1439 let path = to_string(|s| s.print_path(path, false, 0));
1440 if path == "self" || path == "super" {
1441 self.word_nbsp(format!("pub({})", path))
1443 self.word_nbsp(format!("pub(in {})", path))
1446 ast::VisibilityKind::Inherited => {}
1450 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1451 if let ast::Defaultness::Default = defaultness {
1452 self.word_nbsp("default");
1456 crate fn print_struct(&mut self,
1457 struct_def: &ast::VariantData,
1458 generics: &ast::Generics,
1460 span: syntax_pos::Span,
1461 print_finalizer: bool) {
1462 self.print_ident(ident);
1463 self.print_generic_params(&generics.params);
1465 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1466 if let ast::VariantData::Tuple(..) = struct_def {
1469 Inconsistent, struct_def.fields(),
1471 s.maybe_print_comment(field.span.lo());
1472 s.print_outer_attributes(&field.attrs);
1473 s.print_visibility(&field.vis);
1474 s.print_type(&field.ty)
1479 self.print_where_clause(&generics.where_clause);
1480 if print_finalizer {
1484 self.end(); // close the outer-box
1486 ast::VariantData::Struct(..) => {
1487 self.print_where_clause(&generics.where_clause);
1490 self.hardbreak_if_not_bol();
1492 for field in struct_def.fields() {
1493 self.hardbreak_if_not_bol();
1494 self.maybe_print_comment(field.span.lo());
1495 self.print_outer_attributes(&field.attrs);
1496 self.print_visibility(&field.vis);
1497 self.print_ident(field.ident.unwrap());
1498 self.word_nbsp(":");
1499 self.print_type(&field.ty);
1508 crate fn print_variant(&mut self, v: &ast::Variant) {
1510 let generics = ast::Generics::default();
1511 self.print_struct(&v.node.data, &generics, v.node.ident, v.span, false);
1512 match v.node.disr_expr {
1515 self.word_space("=");
1516 self.print_expr(&d.value)
1522 crate fn print_method_sig(&mut self,
1524 generics: &ast::Generics,
1526 vis: &ast::Visibility)
1528 self.print_fn(&m.decl,
1535 crate fn print_trait_item(&mut self, ti: &ast::TraitItem)
1537 self.ann.pre(self, AnnNode::SubItem(ti.id));
1538 self.hardbreak_if_not_bol();
1539 self.maybe_print_comment(ti.span.lo());
1540 self.print_outer_attributes(&ti.attrs);
1542 ast::TraitItemKind::Const(ref ty, ref default) => {
1543 self.print_associated_const(
1546 default.as_ref().map(|expr| &**expr),
1547 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1550 ast::TraitItemKind::Method(ref sig, ref body) => {
1554 self.print_method_sig(
1558 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1560 if let Some(ref body) = *body {
1562 self.print_block_with_attrs(body, &ti.attrs);
1567 ast::TraitItemKind::Type(ref bounds, ref default) => {
1568 self.print_associated_type(ti.ident, Some(bounds),
1569 default.as_ref().map(|ty| &**ty));
1571 ast::TraitItemKind::Macro(ref mac) => {
1572 self.print_mac(mac);
1573 match mac.node.delim {
1574 MacDelimiter::Brace => {}
1575 _ => self.s.word(";"),
1579 self.ann.post(self, AnnNode::SubItem(ti.id))
1582 crate fn print_impl_item(&mut self, ii: &ast::ImplItem) {
1583 self.ann.pre(self, AnnNode::SubItem(ii.id));
1584 self.hardbreak_if_not_bol();
1585 self.maybe_print_comment(ii.span.lo());
1586 self.print_outer_attributes(&ii.attrs);
1587 self.print_defaultness(ii.defaultness);
1589 ast::ImplItemKind::Const(ref ty, ref expr) => {
1590 self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis);
1592 ast::ImplItemKind::Method(ref sig, ref body) => {
1594 self.print_method_sig(ii.ident, &ii.generics, sig, &ii.vis);
1596 self.print_block_with_attrs(body, &ii.attrs);
1598 ast::ImplItemKind::Type(ref ty) => {
1599 self.print_associated_type(ii.ident, None, Some(ty));
1601 ast::ImplItemKind::Existential(ref bounds) => {
1602 self.word_space("existential");
1603 self.print_associated_type(ii.ident, Some(bounds), None);
1605 ast::ImplItemKind::Macro(ref mac) => {
1606 self.print_mac(mac);
1607 match mac.node.delim {
1608 MacDelimiter::Brace => {}
1609 _ => self.s.word(";"),
1613 self.ann.post(self, AnnNode::SubItem(ii.id))
1616 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1617 self.maybe_print_comment(st.span.lo());
1619 ast::StmtKind::Local(ref loc) => {
1620 self.print_outer_attributes(&loc.attrs);
1621 self.space_if_not_bol();
1622 self.ibox(INDENT_UNIT);
1623 self.word_nbsp("let");
1625 self.ibox(INDENT_UNIT);
1626 self.print_local_decl(loc);
1628 if let Some(ref init) = loc.init {
1630 self.word_space("=");
1631 self.print_expr(init);
1636 ast::StmtKind::Item(ref item) => self.print_item(item),
1637 ast::StmtKind::Expr(ref expr) => {
1638 self.space_if_not_bol();
1639 self.print_expr_outer_attr_style(expr, false);
1640 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1644 ast::StmtKind::Semi(ref expr) => {
1645 self.space_if_not_bol();
1646 self.print_expr_outer_attr_style(expr, false);
1649 ast::StmtKind::Mac(ref mac) => {
1650 let (ref mac, style, ref attrs) = **mac;
1651 self.space_if_not_bol();
1652 self.print_outer_attributes(attrs);
1653 self.print_mac(mac);
1654 if style == ast::MacStmtStyle::Semicolon {
1659 self.maybe_print_trailing_comment(st.span, None)
1662 crate fn print_block(&mut self, blk: &ast::Block) {
1663 self.print_block_with_attrs(blk, &[])
1666 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1667 self.print_block_maybe_unclosed(blk, &[], false)
1670 crate fn print_block_with_attrs(&mut self,
1672 attrs: &[ast::Attribute]) {
1673 self.print_block_maybe_unclosed(blk, attrs, true)
1676 crate fn print_block_maybe_unclosed(&mut self,
1678 attrs: &[ast::Attribute],
1681 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1682 BlockCheckMode::Default => ()
1684 self.maybe_print_comment(blk.span.lo());
1685 self.ann.pre(self, AnnNode::Block(blk));
1688 self.print_inner_attributes(attrs);
1690 for (i, st) in blk.stmts.iter().enumerate() {
1692 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1693 self.maybe_print_comment(st.span.lo());
1694 self.space_if_not_bol();
1695 self.print_expr_outer_attr_style(expr, false);
1696 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1698 _ => self.print_stmt(st),
1702 self.bclose_maybe_open(blk.span, close_box);
1703 self.ann.post(self, AnnNode::Block(blk))
1706 /// Print a `let pats = scrutinee` expression.
1707 crate fn print_let(&mut self, pats: &[P<ast::Pat>], scrutinee: &ast::Expr) {
1708 self.s.word("let ");
1710 self.print_pats(pats);
1713 self.word_space("=");
1714 self.print_expr_cond_paren(
1716 Self::cond_needs_par(scrutinee)
1717 || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order())
1721 fn print_else(&mut self, els: Option<&ast::Expr>) {
1725 // Another `else if` block.
1726 ast::ExprKind::If(ref i, ref then, ref e) => {
1727 self.cbox(INDENT_UNIT - 1);
1729 self.s.word(" else if ");
1730 self.print_expr_as_cond(i);
1732 self.print_block(then);
1733 self.print_else(e.as_ref().map(|e| &**e))
1735 // Final `else` block.
1736 ast::ExprKind::Block(ref b, _) => {
1737 self.cbox(INDENT_UNIT - 1);
1739 self.s.word(" else ");
1742 // Constraints would be great here!
1744 panic!("print_if saw if with weird alternative");
1752 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1753 elseopt: Option<&ast::Expr>) {
1756 self.print_expr_as_cond(test);
1759 self.print_block(blk);
1760 self.print_else(elseopt)
1763 crate fn print_mac(&mut self, m: &ast::Mac) {
1764 self.print_mac_common(
1765 Some(MacHeader::Path(&m.node.path)),
1768 m.node.delim.to_token(),
1775 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1777 self.commasep_exprs(Inconsistent, args);
1781 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1782 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1785 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1786 /// `if cond { ... }`.
1787 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1788 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1791 /// Does `expr` need parenthesis when printed in a condition position?
1792 fn cond_needs_par(expr: &ast::Expr) -> bool {
1794 // These cases need parens due to the parse error observed in #26461: `if return {}`
1795 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1796 ast::ExprKind::Closure(..) |
1797 ast::ExprKind::Ret(..) |
1798 ast::ExprKind::Break(..) => true,
1800 _ => parser::contains_exterior_struct_lit(expr),
1804 /// Print `expr` or `(expr)` when `needs_par` holds.
1805 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1809 self.print_expr(expr);
1815 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1816 attrs: &[Attribute]) {
1817 self.ibox(INDENT_UNIT);
1819 self.print_inner_attributes_inline(attrs);
1820 self.commasep_exprs(Inconsistent, &exprs[..]);
1825 fn print_expr_repeat(&mut self,
1826 element: &ast::Expr,
1827 count: &ast::AnonConst,
1828 attrs: &[Attribute]) {
1829 self.ibox(INDENT_UNIT);
1831 self.print_inner_attributes_inline(attrs);
1832 self.print_expr(element);
1833 self.word_space(";");
1834 self.print_expr(&count.value);
1839 fn print_expr_struct(&mut self,
1841 fields: &[ast::Field],
1842 wth: &Option<P<ast::Expr>>,
1843 attrs: &[Attribute]) {
1844 self.print_path(path, true, 0);
1846 self.print_inner_attributes_inline(attrs);
1851 s.ibox(INDENT_UNIT);
1852 if !field.is_shorthand {
1853 s.print_ident(field.ident);
1856 s.print_expr(&field.expr);
1862 self.ibox(INDENT_UNIT);
1863 if !fields.is_empty() {
1868 self.print_expr(expr);
1871 _ => if !fields.is_empty() {
1878 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1879 attrs: &[Attribute]) {
1881 self.print_inner_attributes_inline(attrs);
1882 self.commasep_exprs(Inconsistent, &exprs[..]);
1883 if exprs.len() == 1 {
1889 fn print_expr_call(&mut self,
1891 args: &[P<ast::Expr>]) {
1894 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1895 _ => parser::PREC_POSTFIX,
1898 self.print_expr_maybe_paren(func, prec);
1899 self.print_call_post(args)
1902 fn print_expr_method_call(&mut self,
1903 segment: &ast::PathSegment,
1904 args: &[P<ast::Expr>]) {
1905 let base_args = &args[1..];
1906 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1908 self.print_ident(segment.ident);
1909 if let Some(ref args) = segment.args {
1910 self.print_generic_args(args, true);
1912 self.print_call_post(base_args)
1915 fn print_expr_binary(&mut self,
1919 let assoc_op = AssocOp::from_ast_binop(op.node);
1920 let prec = assoc_op.precedence() as i8;
1921 let fixity = assoc_op.fixity();
1923 let (left_prec, right_prec) = match fixity {
1924 Fixity::Left => (prec, prec + 1),
1925 Fixity::Right => (prec + 1, prec),
1926 Fixity::None => (prec + 1, prec + 1),
1929 let left_prec = match (&lhs.node, op.node) {
1930 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1931 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1932 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1933 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) |
1934 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1935 // We are given `(let _ = a) OP b`.
1937 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1938 // as the parser will interpret this as `(let _ = a) OP b`.
1940 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1941 // parens are required since the parser would interpret `let a = b < c` as
1942 // `let a = (b < c)`. To achieve this, we force parens.
1943 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1944 parser::PREC_FORCE_PAREN
1949 self.print_expr_maybe_paren(lhs, left_prec);
1951 self.word_space(op.node.to_string());
1952 self.print_expr_maybe_paren(rhs, right_prec)
1955 fn print_expr_unary(&mut self,
1958 self.s.word(ast::UnOp::to_string(op));
1959 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1962 fn print_expr_addr_of(&mut self,
1963 mutability: ast::Mutability,
1966 self.print_mutability(mutability);
1967 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1970 crate fn print_expr(&mut self, expr: &ast::Expr) {
1971 self.print_expr_outer_attr_style(expr, true)
1974 fn print_expr_outer_attr_style(&mut self,
1977 self.maybe_print_comment(expr.span.lo());
1979 let attrs = &expr.attrs;
1981 self.print_outer_attributes_inline(attrs);
1983 self.print_outer_attributes(attrs);
1986 self.ibox(INDENT_UNIT);
1987 self.ann.pre(self, AnnNode::Expr(expr));
1989 ast::ExprKind::Box(ref expr) => {
1990 self.word_space("box");
1991 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1993 ast::ExprKind::Array(ref exprs) => {
1994 self.print_expr_vec(&exprs[..], attrs);
1996 ast::ExprKind::Repeat(ref element, ref count) => {
1997 self.print_expr_repeat(element, count, attrs);
1999 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2000 self.print_expr_struct(path, &fields[..], wth, attrs);
2002 ast::ExprKind::Tup(ref exprs) => {
2003 self.print_expr_tup(&exprs[..], attrs);
2005 ast::ExprKind::Call(ref func, ref args) => {
2006 self.print_expr_call(func, &args[..]);
2008 ast::ExprKind::MethodCall(ref segment, ref args) => {
2009 self.print_expr_method_call(segment, &args[..]);
2011 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2012 self.print_expr_binary(op, lhs, rhs);
2014 ast::ExprKind::Unary(op, ref expr) => {
2015 self.print_expr_unary(op, expr);
2017 ast::ExprKind::AddrOf(m, ref expr) => {
2018 self.print_expr_addr_of(m, expr);
2020 ast::ExprKind::Lit(ref lit) => {
2021 self.print_literal(lit);
2023 ast::ExprKind::Cast(ref expr, ref ty) => {
2024 let prec = AssocOp::As.precedence() as i8;
2025 self.print_expr_maybe_paren(expr, prec);
2027 self.word_space("as");
2028 self.print_type(ty);
2030 ast::ExprKind::Type(ref expr, ref ty) => {
2031 let prec = AssocOp::Colon.precedence() as i8;
2032 self.print_expr_maybe_paren(expr, prec);
2033 self.word_space(":");
2034 self.print_type(ty);
2036 ast::ExprKind::Let(ref pats, ref scrutinee) => {
2037 self.print_let(pats, scrutinee);
2039 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2040 self.print_if(test, blk, elseopt.as_ref().map(|e| &**e));
2042 ast::ExprKind::While(ref test, ref blk, opt_label) => {
2043 if let Some(label) = opt_label {
2044 self.print_ident(label.ident);
2045 self.word_space(":");
2048 self.print_expr_as_cond(test);
2050 self.print_block_with_attrs(blk, attrs);
2052 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2053 if let Some(label) = opt_label {
2054 self.print_ident(label.ident);
2055 self.word_space(":");
2058 self.print_pat(pat);
2060 self.word_space("in");
2061 self.print_expr_as_cond(iter);
2063 self.print_block_with_attrs(blk, attrs);
2065 ast::ExprKind::Loop(ref blk, opt_label) => {
2066 if let Some(label) = opt_label {
2067 self.print_ident(label.ident);
2068 self.word_space(":");
2072 self.print_block_with_attrs(blk, attrs);
2074 ast::ExprKind::Match(ref expr, ref arms) => {
2075 self.cbox(INDENT_UNIT);
2076 self.ibox(INDENT_UNIT);
2077 self.word_nbsp("match");
2078 self.print_expr_as_cond(expr);
2081 self.print_inner_attributes_no_trailing_hardbreak(attrs);
2083 self.print_arm(arm);
2085 self.bclose(expr.span);
2087 ast::ExprKind::Closure(
2088 capture_clause, asyncness, movability, ref decl, ref body, _) => {
2089 self.print_movability(movability);
2090 self.print_asyncness(asyncness);
2091 self.print_capture_clause(capture_clause);
2093 self.print_fn_block_args(decl);
2095 self.print_expr(body);
2096 self.end(); // need to close a box
2098 // a box will be closed by print_expr, but we didn't want an overall
2099 // wrapper so we closed the corresponding opening. so create an
2100 // empty box to satisfy the close.
2103 ast::ExprKind::Block(ref blk, opt_label) => {
2104 if let Some(label) = opt_label {
2105 self.print_ident(label.ident);
2106 self.word_space(":");
2108 // containing cbox, will be closed by print-block at }
2109 self.cbox(INDENT_UNIT);
2110 // head-box, will be closed by print-block after {
2112 self.print_block_with_attrs(blk, attrs);
2114 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2115 self.word_nbsp("async");
2116 self.print_capture_clause(capture_clause);
2118 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2119 self.cbox(INDENT_UNIT);
2121 self.print_block_with_attrs(blk, attrs);
2123 ast::ExprKind::Await(ref expr) => {
2124 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2125 self.s.word(".await");
2127 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2128 let prec = AssocOp::Assign.precedence() as i8;
2129 self.print_expr_maybe_paren(lhs, prec + 1);
2131 self.word_space("=");
2132 self.print_expr_maybe_paren(rhs, prec);
2134 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2135 let prec = AssocOp::Assign.precedence() as i8;
2136 self.print_expr_maybe_paren(lhs, prec + 1);
2138 self.s.word(op.node.to_string());
2139 self.word_space("=");
2140 self.print_expr_maybe_paren(rhs, prec);
2142 ast::ExprKind::Field(ref expr, ident) => {
2143 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2145 self.print_ident(ident);
2147 ast::ExprKind::Index(ref expr, ref index) => {
2148 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2150 self.print_expr(index);
2153 ast::ExprKind::Range(ref start, ref end, limits) => {
2154 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2155 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2156 // Here we use a fake precedence value so that any child with lower precedence than
2157 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2158 let fake_prec = AssocOp::LOr.precedence() as i8;
2159 if let Some(ref e) = *start {
2160 self.print_expr_maybe_paren(e, fake_prec);
2162 if limits == ast::RangeLimits::HalfOpen {
2167 if let Some(ref e) = *end {
2168 self.print_expr_maybe_paren(e, fake_prec);
2171 ast::ExprKind::Path(None, ref path) => {
2172 self.print_path(path, true, 0)
2174 ast::ExprKind::Path(Some(ref qself), ref path) => {
2175 self.print_qpath(path, qself, true)
2177 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2178 self.s.word("break");
2180 if let Some(label) = opt_label {
2181 self.print_ident(label.ident);
2184 if let Some(ref expr) = *opt_expr {
2185 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2189 ast::ExprKind::Continue(opt_label) => {
2190 self.s.word("continue");
2192 if let Some(label) = opt_label {
2193 self.print_ident(label.ident);
2197 ast::ExprKind::Ret(ref result) => {
2198 self.s.word("return");
2199 if let Some(ref expr) = *result {
2201 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2204 ast::ExprKind::InlineAsm(ref a) => {
2205 self.s.word("asm!");
2207 self.print_string(&a.asm.as_str(), a.asm_str_style);
2208 self.word_space(":");
2210 self.commasep(Inconsistent, &a.outputs, |s, out| {
2211 let constraint = out.constraint.as_str();
2212 let mut ch = constraint.chars();
2214 Some('=') if out.is_rw => {
2215 s.print_string(&format!("+{}", ch.as_str()),
2216 ast::StrStyle::Cooked)
2218 _ => s.print_string(&constraint, ast::StrStyle::Cooked)
2221 s.print_expr(&out.expr);
2225 self.word_space(":");
2227 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2228 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2234 self.word_space(":");
2236 self.commasep(Inconsistent, &a.clobbers,
2238 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2241 let mut options = vec![];
2243 options.push("volatile");
2246 options.push("alignstack");
2248 if a.dialect == ast::AsmDialect::Intel {
2249 options.push("intel");
2252 if !options.is_empty() {
2254 self.word_space(":");
2255 self.commasep(Inconsistent, &options,
2257 s.print_string(co, ast::StrStyle::Cooked);
2263 ast::ExprKind::Mac(ref m) => self.print_mac(m),
2264 ast::ExprKind::Paren(ref e) => {
2266 self.print_inner_attributes_inline(attrs);
2270 ast::ExprKind::Yield(ref e) => {
2271 self.s.word("yield");
2275 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2280 ast::ExprKind::Try(ref e) => {
2281 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2284 ast::ExprKind::TryBlock(ref blk) => {
2287 self.print_block_with_attrs(blk, attrs)
2289 ast::ExprKind::Err => {
2291 self.s.word("/*ERROR*/");
2295 self.ann.post(self, AnnNode::Expr(expr));
2299 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2300 self.print_pat(&loc.pat);
2301 if let Some(ref ty) = loc.ty {
2302 self.word_space(":");
2303 self.print_type(ty);
2307 crate fn print_usize(&mut self, i: usize) {
2308 self.s.word(i.to_string())
2311 crate fn print_name(&mut self, name: ast::Name) {
2312 self.s.word(name.as_str().to_string());
2313 self.ann.post(self, AnnNode::Name(&name))
2316 fn print_qpath(&mut self,
2319 colons_before_params: bool)
2322 self.print_type(&qself.ty);
2323 if qself.position > 0 {
2325 self.word_space("as");
2326 let depth = path.segments.len() - qself.position;
2327 self.print_path(path, false, depth);
2331 let item_segment = path.segments.last().unwrap();
2332 self.print_ident(item_segment.ident);
2333 match item_segment.args {
2334 Some(ref args) => self.print_generic_args(args, colons_before_params),
2339 crate fn print_pat(&mut self, pat: &ast::Pat) {
2340 self.maybe_print_comment(pat.span.lo());
2341 self.ann.pre(self, AnnNode::Pat(pat));
2342 /* Pat isn't normalized, but the beauty of it
2343 is that it doesn't matter */
2345 PatKind::Wild => self.s.word("_"),
2346 PatKind::Ident(binding_mode, ident, ref sub) => {
2347 match binding_mode {
2348 ast::BindingMode::ByRef(mutbl) => {
2349 self.word_nbsp("ref");
2350 self.print_mutability(mutbl);
2352 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2353 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2354 self.word_nbsp("mut");
2357 self.print_ident(ident);
2358 if let Some(ref p) = *sub {
2363 PatKind::TupleStruct(ref path, ref elts) => {
2364 self.print_path(path, true, 0);
2366 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2369 PatKind::Path(None, ref path) => {
2370 self.print_path(path, true, 0);
2372 PatKind::Path(Some(ref qself), ref path) => {
2373 self.print_qpath(path, qself, false);
2375 PatKind::Struct(ref path, ref fields, etc) => {
2376 self.print_path(path, true, 0);
2378 self.word_space("{");
2380 Consistent, &fields[..],
2382 s.cbox(INDENT_UNIT);
2383 if !f.node.is_shorthand {
2384 s.print_ident(f.node.ident);
2387 s.print_pat(&f.node.pat);
2390 |f| f.node.pat.span);
2392 if !fields.is_empty() { self.word_space(","); }
2398 PatKind::Tuple(ref elts) => {
2400 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2401 if elts.len() == 1 {
2406 PatKind::Box(ref inner) => {
2407 self.s.word("box ");
2408 self.print_pat(inner);
2410 PatKind::Ref(ref inner, mutbl) => {
2412 if mutbl == ast::Mutability::Mutable {
2413 self.s.word("mut ");
2415 self.print_pat(inner);
2417 PatKind::Lit(ref e) => self.print_expr(&**e),
2418 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2419 self.print_expr(begin);
2422 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("..."),
2423 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..="),
2424 RangeEnd::Excluded => self.s.word(".."),
2426 self.print_expr(end);
2428 PatKind::Slice(ref elts) => {
2430 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2433 PatKind::Rest => self.s.word(".."),
2434 PatKind::Paren(ref inner) => {
2436 self.print_pat(inner);
2439 PatKind::Mac(ref m) => self.print_mac(m),
2441 self.ann.post(self, AnnNode::Pat(pat))
2444 fn print_pats(&mut self, pats: &[P<ast::Pat>]) {
2445 let mut first = true;
2451 self.word_space("|");
2457 fn print_arm(&mut self, arm: &ast::Arm) {
2458 // I have no idea why this check is necessary, but here it
2460 if arm.attrs.is_empty() {
2463 self.cbox(INDENT_UNIT);
2465 self.maybe_print_comment(arm.pats[0].span.lo());
2466 self.print_outer_attributes(&arm.attrs);
2467 self.print_pats(&arm.pats);
2469 if let Some(ref e) = arm.guard {
2470 self.word_space("if");
2474 self.word_space("=>");
2476 match arm.body.node {
2477 ast::ExprKind::Block(ref blk, opt_label) => {
2478 if let Some(label) = opt_label {
2479 self.print_ident(label.ident);
2480 self.word_space(":");
2483 // the block will close the pattern's ibox
2484 self.print_block_unclosed_indent(blk);
2486 // If it is a user-provided unsafe block, print a comma after it
2487 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2492 self.end(); // close the ibox for the pattern
2493 self.print_expr(&arm.body);
2497 self.end(); // close enclosing cbox
2500 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2501 match explicit_self.node {
2502 SelfKind::Value(m) => {
2503 self.print_mutability(m);
2506 SelfKind::Region(ref lt, m) => {
2508 self.print_opt_lifetime(lt);
2509 self.print_mutability(m);
2512 SelfKind::Explicit(ref typ, m) => {
2513 self.print_mutability(m);
2514 self.s.word("self");
2515 self.word_space(":");
2516 self.print_type(typ)
2521 crate fn print_fn(&mut self,
2523 header: ast::FnHeader,
2524 name: Option<ast::Ident>,
2525 generics: &ast::Generics,
2526 vis: &ast::Visibility) {
2527 self.print_fn_header_info(header, vis);
2529 if let Some(name) = name {
2531 self.print_ident(name);
2533 self.print_generic_params(&generics.params);
2534 self.print_fn_args_and_ret(decl);
2535 self.print_where_clause(&generics.where_clause)
2538 crate fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl) {
2540 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false));
2543 self.print_fn_output(decl)
2546 crate fn print_fn_block_args(&mut self, decl: &ast::FnDecl) {
2548 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true));
2551 if let ast::FunctionRetTy::Default(..) = decl.output {
2555 self.space_if_not_bol();
2556 self.word_space("->");
2558 ast::FunctionRetTy::Ty(ref ty) => {
2559 self.print_type(ty);
2560 self.maybe_print_comment(ty.span.lo())
2562 ast::FunctionRetTy::Default(..) => unreachable!(),
2566 crate fn print_movability(&mut self, movability: ast::Movability) {
2568 ast::Movability::Static => self.word_space("static"),
2569 ast::Movability::Movable => {},
2573 crate fn print_asyncness(&mut self, asyncness: ast::IsAsync) {
2574 if asyncness.is_async() {
2575 self.word_nbsp("async");
2579 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2580 match capture_clause {
2581 ast::CaptureBy::Value => self.word_space("move"),
2582 ast::CaptureBy::Ref => {},
2586 crate fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2587 if !bounds.is_empty() {
2588 self.s.word(prefix);
2589 let mut first = true;
2590 for bound in bounds {
2591 if !(first && prefix.is_empty()) {
2597 self.word_space("+");
2601 GenericBound::Trait(tref, modifier) => {
2602 if modifier == &TraitBoundModifier::Maybe {
2605 self.print_poly_trait_ref(tref);
2607 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2613 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2614 self.print_name(lifetime.ident.name)
2617 crate fn print_lifetime_bounds(
2618 &mut self, lifetime: ast::Lifetime, bounds: &ast::GenericBounds) {
2619 self.print_lifetime(lifetime);
2620 if !bounds.is_empty() {
2622 for (i, bound) in bounds.iter().enumerate() {
2627 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2634 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2635 if generic_params.is_empty() {
2641 self.commasep(Inconsistent, &generic_params, |s, param| {
2643 ast::GenericParamKind::Lifetime => {
2644 s.print_outer_attributes_inline(¶m.attrs);
2645 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2646 s.print_lifetime_bounds(lt, ¶m.bounds)
2648 ast::GenericParamKind::Type { ref default } => {
2649 s.print_outer_attributes_inline(¶m.attrs);
2650 s.print_ident(param.ident);
2651 s.print_type_bounds(":", ¶m.bounds);
2653 Some(ref default) => {
2656 s.print_type(default)
2661 ast::GenericParamKind::Const { ref ty } => {
2662 s.print_outer_attributes_inline(¶m.attrs);
2663 s.word_space("const");
2664 s.print_ident(param.ident);
2668 s.print_type_bounds(":", ¶m.bounds)
2676 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2677 if where_clause.predicates.is_empty() {
2682 self.word_space("where");
2684 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2686 self.word_space(",");
2690 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2691 ref bound_generic_params,
2696 self.print_formal_generic_params(bound_generic_params);
2697 self.print_type(bounded_ty);
2698 self.print_type_bounds(":", bounds);
2700 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2703 self.print_lifetime_bounds(*lifetime, bounds);
2705 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2708 self.print_type(lhs_ty);
2710 self.word_space("=");
2711 self.print_type(rhs_ty);
2717 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2719 ast::UseTreeKind::Simple(rename, ..) => {
2720 self.print_path(&tree.prefix, false, 0);
2721 if let Some(rename) = rename {
2723 self.word_space("as");
2724 self.print_ident(rename);
2727 ast::UseTreeKind::Glob => {
2728 if !tree.prefix.segments.is_empty() {
2729 self.print_path(&tree.prefix, false, 0);
2734 ast::UseTreeKind::Nested(ref items) => {
2735 if tree.prefix.segments.is_empty() {
2738 self.print_path(&tree.prefix, false, 0);
2741 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2742 this.print_use_tree(tree)
2749 crate fn print_mutability(&mut self, mutbl: ast::Mutability) {
2751 ast::Mutability::Mutable => self.word_nbsp("mut"),
2752 ast::Mutability::Immutable => {},
2756 crate fn print_mt(&mut self, mt: &ast::MutTy) {
2757 self.print_mutability(mt.mutbl);
2758 self.print_type(&mt.ty)
2761 crate fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) {
2762 self.ibox(INDENT_UNIT);
2763 match input.ty.node {
2764 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2766 if let Some(eself) = input.to_self() {
2767 self.print_explicit_self(&eself);
2769 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
2770 ident.name == kw::Invalid
2775 self.print_pat(&input.pat);
2779 self.print_type(&input.ty);
2786 crate fn print_fn_output(&mut self, decl: &ast::FnDecl) {
2787 if let ast::FunctionRetTy::Default(..) = decl.output {
2791 self.space_if_not_bol();
2792 self.ibox(INDENT_UNIT);
2793 self.word_space("->");
2795 ast::FunctionRetTy::Default(..) => unreachable!(),
2796 ast::FunctionRetTy::Ty(ref ty) =>
2797 self.print_type(ty),
2802 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo()),
2807 crate fn print_ty_fn(&mut self,
2809 unsafety: ast::Unsafety,
2811 name: Option<ast::Ident>,
2812 generic_params: &[ast::GenericParam])
2814 self.ibox(INDENT_UNIT);
2815 if !generic_params.is_empty() {
2817 self.print_generic_params(generic_params);
2819 let generics = ast::Generics {
2821 where_clause: ast::WhereClause {
2822 predicates: Vec::new(),
2823 span: syntax_pos::DUMMY_SP,
2825 span: syntax_pos::DUMMY_SP,
2828 ast::FnHeader { unsafety, abi, ..ast::FnHeader::default() },
2831 &source_map::dummy_spanned(ast::VisibilityKind::Inherited));
2835 crate fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
2836 next_pos: Option<BytePos>)
2838 if let Some(cmnts) = self.comments() {
2839 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2840 self.print_comment(&cmnt);
2845 crate fn print_remaining_comments(&mut self) {
2846 // If there aren't any remaining comments, then we need to manually
2847 // make sure there is a line break at the end.
2848 if self.next_comment().is_none() {
2851 while let Some(ref cmnt) = self.next_comment() {
2852 self.print_comment(cmnt);
2856 crate fn print_fn_header_info(&mut self,
2857 header: ast::FnHeader,
2858 vis: &ast::Visibility) {
2859 self.s.word(visibility_qualified(vis, ""));
2861 match header.constness.node {
2862 ast::Constness::NotConst => {}
2863 ast::Constness::Const => self.word_nbsp("const")
2866 self.print_asyncness(header.asyncness.node);
2867 self.print_unsafety(header.unsafety);
2869 if header.abi != Abi::Rust {
2870 self.word_nbsp("extern");
2871 self.word_nbsp(header.abi.to_string());
2877 crate fn print_unsafety(&mut self, s: ast::Unsafety) {
2879 ast::Unsafety::Normal => {},
2880 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2884 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2886 ast::IsAuto::Yes => self.word_nbsp("auto"),
2887 ast::IsAuto::No => {}
2897 use crate::source_map;
2898 use crate::with_default_globals;
2902 fn test_fun_to_string() {
2903 with_default_globals(|| {
2904 let abba_ident = ast::Ident::from_str("abba");
2906 let decl = ast::FnDecl {
2908 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
2911 let generics = ast::Generics::default();
2916 unsafety: ast::Unsafety::Normal,
2917 constness: source_map::dummy_spanned(ast::Constness::NotConst),
2918 asyncness: source_map::dummy_spanned(ast::IsAsync::NotAsync),
2930 fn test_variant_to_string() {
2931 with_default_globals(|| {
2932 let ident = ast::Ident::from_str("principal_skinner");
2934 let var = source_map::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
2937 id: ast::DUMMY_NODE_ID,
2938 // making this up as I go.... ?
2939 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
2943 let varstr = variant_to_string(&var);
2944 assert_eq!(varstr, "principal_skinner");