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::std_inject;
14 use crate::symbol::{kw, sym};
15 use crate::tokenstream::{self, TokenStream, TokenTree};
17 use rustc_target::spec::abi::{self, Abi};
18 use syntax_pos::{self, BytePos};
19 use syntax_pos::{DUMMY_SP, FileName, Span};
23 pub enum MacHeader<'a> {
25 Keyword(&'static str),
28 pub enum AnnNode<'a> {
29 Ident(&'a ast::Ident),
31 Block(&'a ast::Block),
39 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) { }
40 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) { }
43 #[derive(Copy, Clone)]
46 impl PpAnn for NoAnn {}
48 pub struct Comments<'a> {
50 comments: Vec<comments::Comment>,
54 impl<'a> Comments<'a> {
61 let comments = comments::gather_comments(sess, filename, input);
69 pub fn next(&self) -> Option<comments::Comment> {
70 self.comments.get(self.current).cloned()
73 pub fn trailing_comment(
75 span: syntax_pos::Span,
76 next_pos: Option<BytePos>,
77 ) -> Option<comments::Comment> {
78 if let Some(cmnt) = self.next() {
79 if cmnt.style != comments::Trailing { return None; }
80 let span_line = self.cm.lookup_char_pos(span.hi());
81 let comment_line = self.cm.lookup_char_pos(cmnt.pos);
82 let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1));
83 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
92 pub struct State<'a> {
94 comments: Option<Comments<'a>>,
95 ann: &'a (dyn PpAnn+'a),
99 crate const INDENT_UNIT: usize = 4;
101 /// Requires you to pass an input filename and reader so that
102 /// it can scan the input text for comments to copy forward.
103 pub fn print_crate<'a>(cm: &'a SourceMap,
109 is_expanded: bool) -> String {
112 comments: Some(Comments::new(cm, sess, filename, input)),
117 if is_expanded && std_inject::injected_crate_name().is_some() {
118 // We need to print `#![no_std]` (and its feature gate) so that
119 // compiling pretty-printed source won't inject libstd again.
120 // However we don't want these attributes in the AST because
121 // of the feature gate, so we fake them up here.
123 // #![feature(prelude_import)]
124 let pi_nested = attr::mk_nested_word_item(ast::Ident::with_empty_ctxt(sym::prelude_import));
125 let list = attr::mk_list_item(
126 DUMMY_SP, ast::Ident::with_empty_ctxt(sym::feature), vec![pi_nested]);
127 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), list);
128 s.print_attribute(&fake_attr);
131 let no_std_meta = attr::mk_word_item(ast::Ident::with_empty_ctxt(sym::no_std));
132 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), no_std_meta);
133 s.print_attribute(&fake_attr);
136 s.print_mod(&krate.module, &krate.attrs);
137 s.print_remaining_comments();
141 pub fn to_string<F>(f: F) -> String where
142 F: FnOnce(&mut State<'_>),
144 let mut printer = State {
154 fn binop_to_string(op: BinOpToken) -> &'static str {
160 token::Percent => "%",
169 pub fn literal_to_string(lit: token::Lit) -> String {
170 let token::Lit { kind, symbol, suffix } = lit;
171 let mut out = match kind {
172 token::Byte => format!("b'{}'", symbol),
173 token::Char => format!("'{}'", symbol),
174 token::Str => format!("\"{}\"", symbol),
175 token::StrRaw(n) => format!("r{delim}\"{string}\"{delim}",
176 delim="#".repeat(n as usize),
178 token::ByteStr => format!("b\"{}\"", symbol),
179 token::ByteStrRaw(n) => format!("br{delim}\"{string}\"{delim}",
180 delim="#".repeat(n as usize),
185 token::Err => symbol.to_string(),
188 if let Some(suffix) = suffix {
189 out.push_str(&suffix.as_str())
195 /// Print an ident from AST, `$crate` is converted into its respective crate name.
196 pub fn ast_ident_to_string(ident: ast::Ident, is_raw: bool) -> String {
197 ident_to_string(ident.name, is_raw, Some(ident.span))
200 // AST pretty-printer is used as a fallback for turning AST structures into token streams for
201 // proc macros. Additionally, proc macros may stringify their input and expect it survive the
202 // stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
203 // So we need to somehow pretty-print `$crate` in a way preserving at least some of its
204 // hygiene data, most importantly name of the crate it refers to.
205 // As a result we print `$crate` as `crate` if it refers to the local crate
206 // and as `::other_crate_name` if it refers to some other crate.
207 // Note, that this is only done if the ident token is printed from inside of AST pretty-pringing,
208 // but not otherwise. Pretty-printing is the only way for proc macros to discover token contents,
209 // so we should not perform this lossy conversion if the top level call to the pretty-printer was
210 // done for a token stream or a single token.
211 fn ident_to_string(name: ast::Name, is_raw: bool, convert_dollar_crate: Option<Span>) -> String {
213 format!("r#{}", name)
215 if name == kw::DollarCrate {
216 if let Some(span) = convert_dollar_crate {
217 let converted = span.ctxt().dollar_crate_name();
218 return if converted.is_path_segment_keyword() {
219 converted.to_string()
221 format!("::{}", converted)
229 /// Print the token kind precisely, without converting `$crate` into its respective crate name.
230 pub fn token_kind_to_string(tok: &TokenKind) -> String {
231 token_kind_to_string_ext(tok, None)
234 fn token_kind_to_string_ext(tok: &TokenKind, convert_dollar_crate: Option<Span>) -> String {
236 token::Eq => "=".to_string(),
237 token::Lt => "<".to_string(),
238 token::Le => "<=".to_string(),
239 token::EqEq => "==".to_string(),
240 token::Ne => "!=".to_string(),
241 token::Ge => ">=".to_string(),
242 token::Gt => ">".to_string(),
243 token::Not => "!".to_string(),
244 token::Tilde => "~".to_string(),
245 token::OrOr => "||".to_string(),
246 token::AndAnd => "&&".to_string(),
247 token::BinOp(op) => binop_to_string(op).to_string(),
248 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
250 /* Structural symbols */
251 token::At => "@".to_string(),
252 token::Dot => ".".to_string(),
253 token::DotDot => "..".to_string(),
254 token::DotDotDot => "...".to_string(),
255 token::DotDotEq => "..=".to_string(),
256 token::Comma => ",".to_string(),
257 token::Semi => ";".to_string(),
258 token::Colon => ":".to_string(),
259 token::ModSep => "::".to_string(),
260 token::RArrow => "->".to_string(),
261 token::LArrow => "<-".to_string(),
262 token::FatArrow => "=>".to_string(),
263 token::OpenDelim(token::Paren) => "(".to_string(),
264 token::CloseDelim(token::Paren) => ")".to_string(),
265 token::OpenDelim(token::Bracket) => "[".to_string(),
266 token::CloseDelim(token::Bracket) => "]".to_string(),
267 token::OpenDelim(token::Brace) => "{".to_string(),
268 token::CloseDelim(token::Brace) => "}".to_string(),
269 token::OpenDelim(token::NoDelim) |
270 token::CloseDelim(token::NoDelim) => " ".to_string(),
271 token::Pound => "#".to_string(),
272 token::Dollar => "$".to_string(),
273 token::Question => "?".to_string(),
274 token::SingleQuote => "'".to_string(),
277 token::Literal(lit) => literal_to_string(lit),
279 /* Name components */
280 token::Ident(s, is_raw) => ident_to_string(s, is_raw, convert_dollar_crate),
281 token::Lifetime(s) => s.to_string(),
284 token::DocComment(s) => s.to_string(),
285 token::Eof => "<eof>".to_string(),
286 token::Whitespace => " ".to_string(),
287 token::Comment => "/* */".to_string(),
288 token::Shebang(s) => format!("/* shebang: {}*/", s),
290 token::Interpolated(ref nt) => nonterminal_to_string(nt),
294 /// Print the token precisely, without converting `$crate` into its respective crate name.
295 pub fn token_to_string(token: &Token) -> String {
296 token_to_string_ext(token, false)
299 fn token_to_string_ext(token: &Token, convert_dollar_crate: bool) -> String {
300 let convert_dollar_crate = if convert_dollar_crate { Some(token.span) } else { None };
301 token_kind_to_string_ext(&token.kind, convert_dollar_crate)
304 crate fn nonterminal_to_string(nt: &Nonterminal) -> String {
306 token::NtExpr(ref e) => expr_to_string(e),
307 token::NtMeta(ref e) => meta_item_to_string(e),
308 token::NtTy(ref e) => ty_to_string(e),
309 token::NtPath(ref e) => path_to_string(e),
310 token::NtItem(ref e) => item_to_string(e),
311 token::NtBlock(ref e) => block_to_string(e),
312 token::NtStmt(ref e) => stmt_to_string(e),
313 token::NtPat(ref e) => pat_to_string(e),
314 token::NtIdent(e, is_raw) => ast_ident_to_string(e, is_raw),
315 token::NtLifetime(e) => e.to_string(),
316 token::NtLiteral(ref e) => expr_to_string(e),
317 token::NtTT(ref tree) => tt_to_string(tree.clone()),
318 token::NtImplItem(ref e) => impl_item_to_string(e),
319 token::NtTraitItem(ref e) => trait_item_to_string(e),
320 token::NtVis(ref e) => vis_to_string(e),
321 token::NtForeignItem(ref e) => foreign_item_to_string(e),
325 pub fn ty_to_string(ty: &ast::Ty) -> String {
326 to_string(|s| s.print_type(ty))
329 pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
330 to_string(|s| s.print_type_bounds("", bounds))
333 pub fn pat_to_string(pat: &ast::Pat) -> String {
334 to_string(|s| s.print_pat(pat))
337 pub fn expr_to_string(e: &ast::Expr) -> String {
338 to_string(|s| s.print_expr(e))
341 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
342 to_string(|s| s.print_tt(tt, false))
345 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
346 tokens_to_string(tts.iter().cloned().collect())
349 pub fn tokens_to_string(tokens: TokenStream) -> String {
350 to_string(|s| s.print_tts(tokens, false))
353 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
354 to_string(|s| s.print_stmt(stmt))
357 pub fn item_to_string(i: &ast::Item) -> String {
358 to_string(|s| s.print_item(i))
361 fn impl_item_to_string(i: &ast::ImplItem) -> String {
362 to_string(|s| s.print_impl_item(i))
365 fn trait_item_to_string(i: &ast::TraitItem) -> String {
366 to_string(|s| s.print_trait_item(i))
369 pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String {
370 to_string(|s| s.print_generic_params(generic_params))
373 pub fn path_to_string(p: &ast::Path) -> String {
374 to_string(|s| s.print_path(p, false, 0))
377 pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
378 to_string(|s| s.print_path_segment(p, false))
381 pub fn vis_to_string(v: &ast::Visibility) -> String {
382 to_string(|s| s.print_visibility(v))
386 fn fun_to_string(decl: &ast::FnDecl,
387 header: ast::FnHeader,
389 generics: &ast::Generics)
393 s.print_fn(decl, header, Some(name),
394 generics, &source_map::dummy_spanned(ast::VisibilityKind::Inherited));
395 s.end(); // Close the head box
396 s.end(); // Close the outer box
400 fn block_to_string(blk: &ast::Block) -> String {
402 // containing cbox, will be closed by print-block at }
404 // head-ibox, will be closed by print-block after {
410 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
411 to_string(|s| s.print_meta_list_item(li))
414 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
415 to_string(|s| s.print_meta_item(mi))
418 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
419 to_string(|s| s.print_attribute(attr))
423 fn variant_to_string(var: &ast::Variant) -> String {
424 to_string(|s| s.print_variant(var))
427 pub fn arg_to_string(arg: &ast::Arg) -> String {
428 to_string(|s| s.print_arg(arg, false))
431 fn foreign_item_to_string(arg: &ast::ForeignItem) -> String {
432 to_string(|s| s.print_foreign_item(arg))
435 fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
436 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
439 impl std::ops::Deref for State<'_> {
440 type Target = pp::Printer;
441 fn deref(&self) -> &Self::Target {
446 impl std::ops::DerefMut for State<'_> {
447 fn deref_mut(&mut self) -> &mut Self::Target {
452 pub trait PrintState<'a>: std::ops::Deref<Target=pp::Printer> + std::ops::DerefMut {
453 fn comments(&mut self) -> &mut Option<Comments<'a>>;
454 fn print_ident(&mut self, ident: ast::Ident);
455 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool);
457 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F)
458 where F: FnMut(&mut Self, &T),
461 let mut first = true;
463 if first { first = false; } else { self.word_space(","); }
469 fn maybe_print_comment(&mut self, pos: BytePos) {
470 while let Some(ref cmnt) = self.next_comment() {
472 self.print_comment(cmnt);
479 fn print_comment(&mut self,
480 cmnt: &comments::Comment) {
483 assert_eq!(cmnt.lines.len(), 1);
485 self.word(cmnt.lines[0].clone());
488 comments::Isolated => {
489 self.hardbreak_if_not_bol();
490 for line in &cmnt.lines {
491 // Don't print empty lines because they will end up as trailing
493 if !line.is_empty() {
494 self.word(line.clone());
499 comments::Trailing => {
500 if !self.is_beginning_of_line() {
503 if cmnt.lines.len() == 1 {
504 self.word(cmnt.lines[0].clone());
508 for line in &cmnt.lines {
509 if !line.is_empty() {
510 self.word(line.clone());
517 comments::BlankLine => {
518 // We need to do at least one, possibly two hardbreaks.
519 let twice = match self.last_token() {
520 pp::Token::String(s) => ";" == s,
521 pp::Token::Begin(_) => true,
522 pp::Token::End => true,
531 if let Some(cm) = self.comments() {
536 fn next_comment(&mut self) -> Option<comments::Comment> {
537 self.comments().as_mut().and_then(|c| c.next())
540 fn print_literal(&mut self, lit: &ast::Lit) {
541 self.maybe_print_comment(lit.span.lo());
542 self.word(lit.token.to_string())
545 fn print_string(&mut self, st: &str,
546 style: ast::StrStyle) {
547 let st = match style {
548 ast::StrStyle::Cooked => {
549 (format!("\"{}\"", st.escape_debug()))
551 ast::StrStyle::Raw(n) => {
552 (format!("r{delim}\"{string}\"{delim}",
553 delim="#".repeat(n as usize),
560 fn print_inner_attributes(&mut self,
561 attrs: &[ast::Attribute]) {
562 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
565 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
566 attrs: &[ast::Attribute])
568 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
571 fn print_outer_attributes(&mut self,
572 attrs: &[ast::Attribute]) {
573 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
576 fn print_inner_attributes_inline(&mut self,
577 attrs: &[ast::Attribute]) {
578 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
581 fn print_outer_attributes_inline(&mut self,
582 attrs: &[ast::Attribute]) {
583 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
586 fn print_either_attributes(&mut self,
587 attrs: &[ast::Attribute],
588 kind: ast::AttrStyle,
590 trailing_hardbreak: bool) {
593 if attr.style == kind {
594 self.print_attribute_inline(attr, is_inline);
601 if count > 0 && trailing_hardbreak && !is_inline {
602 self.hardbreak_if_not_bol();
606 fn print_attribute(&mut self, attr: &ast::Attribute) {
607 self.print_attribute_inline(attr, false)
610 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
613 self.hardbreak_if_not_bol();
615 self.maybe_print_comment(attr.span.lo());
616 if attr.is_sugared_doc {
617 self.word(attr.value_str().unwrap().as_str().to_string());
621 ast::AttrStyle::Inner => self.word("#!["),
622 ast::AttrStyle::Outer => self.word("#["),
625 match attr.tokens.trees().next() {
626 Some(TokenTree::Delimited(_, delim, tts)) => {
627 self.print_mac_common(
628 Some(MacHeader::Path(&attr.path)), false, None, delim, tts, true, attr.span
632 self.print_path(&attr.path, false, 0);
635 self.print_tts(attr.tokens.clone(), true);
644 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) {
646 ast::NestedMetaItem::MetaItem(ref mi) => {
647 self.print_meta_item(mi)
649 ast::NestedMetaItem::Literal(ref lit) => {
650 self.print_literal(lit)
655 fn print_meta_item(&mut self, item: &ast::MetaItem) {
656 self.ibox(INDENT_UNIT);
658 ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
659 ast::MetaItemKind::NameValue(ref value) => {
660 self.print_path(&item.path, false, 0);
662 self.word_space("=");
663 self.print_literal(value);
665 ast::MetaItemKind::List(ref items) => {
666 self.print_path(&item.path, false, 0);
668 self.commasep(Consistent,
670 |s, i| s.print_meta_list_item(i));
677 /// This doesn't deserve to be called "pretty" printing, but it should be
678 /// meaning-preserving. A quick hack that might help would be to look at the
679 /// spans embedded in the TTs to decide where to put spaces and newlines.
680 /// But it'd be better to parse these according to the grammar of the
681 /// appropriate macro, transcribe back into the grammar we just parsed from,
682 /// and then pretty-print the resulting AST nodes (so, e.g., we print
683 /// expression arguments as expressions). It can be done! I think.
684 fn print_tt(&mut self, tt: tokenstream::TokenTree, convert_dollar_crate: bool) {
686 TokenTree::Token(ref token) => {
687 self.word(token_to_string_ext(&token, convert_dollar_crate));
689 token::DocComment(..) => {
695 TokenTree::Delimited(dspan, delim, tts) => {
696 self.print_mac_common(
697 None, false, None, delim, tts, convert_dollar_crate, dspan.entire()
703 fn print_tts(&mut self, tts: tokenstream::TokenStream, convert_dollar_crate: bool) {
704 for (i, tt) in tts.into_trees().enumerate() {
708 self.print_tt(tt, convert_dollar_crate);
714 header: Option<MacHeader<'_>>,
716 ident: Option<ast::Ident>,
719 convert_dollar_crate: bool,
722 if delim == DelimToken::Brace {
723 self.cbox(INDENT_UNIT);
726 Some(MacHeader::Path(path)) => self.print_path(path, false, 0),
727 Some(MacHeader::Keyword(kw)) => self.word(kw),
733 if let Some(ident) = ident {
735 self.print_ident(ident);
738 DelimToken::Brace => {
739 if header.is_some() || has_bang || ident.is_some() {
747 _ => self.word(token_kind_to_string(&token::OpenDelim(delim))),
750 self.print_tts(tts, convert_dollar_crate);
753 DelimToken::Brace => self.bclose(span),
754 _ => self.word(token_kind_to_string(&token::CloseDelim(delim))),
758 fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
759 self.maybe_print_comment(path.span.lo());
761 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
765 self.print_path_segment(segment, colons_before_params);
769 fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
770 if segment.ident.name != kw::PathRoot {
771 self.print_ident(segment.ident);
772 if let Some(ref args) = segment.args {
773 self.print_generic_args(args, colons_before_params);
778 fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
780 // outer-box is consistent
781 self.cbox(INDENT_UNIT);
782 // head-box is inconsistent
783 self.ibox(w.len() + 1);
784 // keyword that starts the head
790 fn bopen(&mut self) {
792 self.end(); // close the head-box
795 fn bclose_maybe_open(&mut self, span: syntax_pos::Span, close_box: bool) {
796 self.maybe_print_comment(span.hi());
797 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
800 self.end(); // close the outer-box
804 fn bclose(&mut self, span: syntax_pos::Span) {
805 self.bclose_maybe_open(span, true)
808 fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
809 if !self.is_beginning_of_line() {
810 self.break_offset(n, off)
812 if off != 0 && self.last_token().is_hardbreak_tok() {
813 // We do something pretty sketchy here: tuck the nonzero
814 // offset-adjustment we were going to deposit along with the
815 // break into the previous hardbreak.
816 self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
822 impl<'a> PrintState<'a> for State<'a> {
823 fn comments(&mut self) -> &mut Option<Comments<'a>> {
827 fn print_ident(&mut self, ident: ast::Ident) {
828 self.s.word(ast_ident_to_string(ident, ident.is_raw_guess()));
829 self.ann.post(self, AnnNode::Ident(&ident))
832 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
833 if colons_before_params {
838 ast::GenericArgs::AngleBracketed(ref data) => {
841 self.commasep(Inconsistent, &data.args, |s, generic_arg| {
842 s.print_generic_arg(generic_arg)
845 let mut comma = data.args.len() != 0;
847 for constraint in data.constraints.iter() {
851 self.print_ident(constraint.ident);
853 match constraint.kind {
854 ast::AssocTyConstraintKind::Equality { ref ty } => {
855 self.word_space("=");
858 ast::AssocTyConstraintKind::Bound { ref bounds } => {
859 self.print_type_bounds(":", &*bounds);
868 ast::GenericArgs::Parenthesized(ref data) => {
873 |s, ty| s.print_type(ty));
876 if let Some(ref ty) = data.output {
877 self.space_if_not_bol();
878 self.word_space("->");
887 // Synthesizes a comment that was not textually present in the original source
889 pub fn synth_comment(&mut self, text: String) {
899 crate fn commasep_cmnt<T, F, G>(&mut self,
903 mut get_span: G) where
904 F: FnMut(&mut State<'_>, &T),
905 G: FnMut(&T) -> syntax_pos::Span,
908 let len = elts.len();
911 self.maybe_print_comment(get_span(elt).hi());
916 self.maybe_print_trailing_comment(get_span(elt),
917 Some(get_span(&elts[i]).hi()));
918 self.space_if_not_bol();
924 crate fn commasep_exprs(&mut self, b: Breaks,
925 exprs: &[P<ast::Expr>]) {
926 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
929 crate fn print_mod(&mut self, _mod: &ast::Mod,
930 attrs: &[ast::Attribute]) {
931 self.print_inner_attributes(attrs);
932 for item in &_mod.items {
933 self.print_item(item);
937 crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
938 attrs: &[ast::Attribute]) {
939 self.print_inner_attributes(attrs);
940 for item in &nmod.items {
941 self.print_foreign_item(item);
945 crate fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
946 if let Some(lt) = *lifetime {
947 self.print_lifetime(lt);
952 crate fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
954 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
955 GenericArg::Type(ty) => self.print_type(ty),
956 GenericArg::Const(ct) => self.print_expr(&ct.value),
960 crate fn print_type(&mut self, ty: &ast::Ty) {
961 self.maybe_print_comment(ty.span.lo());
964 ast::TyKind::Slice(ref ty) => {
969 ast::TyKind::Ptr(ref mt) => {
972 ast::Mutability::Mutable => self.word_nbsp("mut"),
973 ast::Mutability::Immutable => self.word_nbsp("const"),
975 self.print_type(&mt.ty);
977 ast::TyKind::Rptr(ref lifetime, ref mt) => {
979 self.print_opt_lifetime(lifetime);
982 ast::TyKind::Never => {
985 ast::TyKind::Tup(ref elts) => {
987 self.commasep(Inconsistent, &elts[..],
988 |s, ty| s.print_type(ty));
994 ast::TyKind::Paren(ref typ) => {
996 self.print_type(typ);
999 ast::TyKind::BareFn(ref f) => {
1000 self.print_ty_fn(f.abi,
1006 ast::TyKind::Path(None, ref path) => {
1007 self.print_path(path, false, 0);
1009 ast::TyKind::Path(Some(ref qself), ref path) => {
1010 self.print_qpath(path, qself, false)
1012 ast::TyKind::TraitObject(ref bounds, syntax) => {
1013 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
1014 self.print_type_bounds(prefix, &bounds[..]);
1016 ast::TyKind::ImplTrait(_, ref bounds) => {
1017 self.print_type_bounds("impl", &bounds[..]);
1019 ast::TyKind::Array(ref ty, ref length) => {
1021 self.print_type(ty);
1023 self.print_expr(&length.value);
1026 ast::TyKind::Typeof(ref e) => {
1027 self.s.word("typeof(");
1028 self.print_expr(&e.value);
1031 ast::TyKind::Infer => {
1034 ast::TyKind::Err => {
1036 self.s.word("/*ERROR*/");
1039 ast::TyKind::ImplicitSelf => {
1040 self.s.word("Self");
1042 ast::TyKind::Mac(ref m) => {
1045 ast::TyKind::CVarArgs => {
1052 crate fn print_foreign_item(&mut self,
1053 item: &ast::ForeignItem) {
1054 self.hardbreak_if_not_bol();
1055 self.maybe_print_comment(item.span.lo());
1056 self.print_outer_attributes(&item.attrs);
1058 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1060 self.print_fn(decl, ast::FnHeader::default(),
1062 generics, &item.vis);
1063 self.end(); // end head-ibox
1065 self.end(); // end the outer fn box
1067 ast::ForeignItemKind::Static(ref t, m) => {
1068 self.head(visibility_qualified(&item.vis, "static"));
1069 if m == ast::Mutability::Mutable {
1070 self.word_space("mut");
1072 self.print_ident(item.ident);
1073 self.word_space(":");
1076 self.end(); // end the head-ibox
1077 self.end(); // end the outer cbox
1079 ast::ForeignItemKind::Ty => {
1080 self.head(visibility_qualified(&item.vis, "type"));
1081 self.print_ident(item.ident);
1083 self.end(); // end the head-ibox
1084 self.end(); // end the outer cbox
1086 ast::ForeignItemKind::Macro(ref m) => {
1088 match m.node.delim {
1089 MacDelimiter::Brace => {},
1090 _ => self.s.word(";")
1096 fn print_associated_const(&mut self,
1099 default: Option<&ast::Expr>,
1100 vis: &ast::Visibility)
1102 self.s.word(visibility_qualified(vis, ""));
1103 self.word_space("const");
1104 self.print_ident(ident);
1105 self.word_space(":");
1106 self.print_type(ty);
1107 if let Some(expr) = default {
1109 self.word_space("=");
1110 self.print_expr(expr);
1115 fn print_associated_type(&mut self,
1117 bounds: Option<&ast::GenericBounds>,
1118 ty: Option<&ast::Ty>)
1120 self.word_space("type");
1121 self.print_ident(ident);
1122 if let Some(bounds) = bounds {
1123 self.print_type_bounds(":", bounds);
1125 if let Some(ty) = ty {
1127 self.word_space("=");
1128 self.print_type(ty);
1133 /// Pretty-print an item
1134 crate fn print_item(&mut self, item: &ast::Item) {
1135 self.hardbreak_if_not_bol();
1136 self.maybe_print_comment(item.span.lo());
1137 self.print_outer_attributes(&item.attrs);
1138 self.ann.pre(self, AnnNode::Item(item));
1140 ast::ItemKind::ExternCrate(orig_name) => {
1141 self.head(visibility_qualified(&item.vis, "extern crate"));
1142 if let Some(orig_name) = orig_name {
1143 self.print_name(orig_name);
1148 self.print_ident(item.ident);
1150 self.end(); // end inner head-block
1151 self.end(); // end outer head-block
1153 ast::ItemKind::Use(ref tree) => {
1154 self.head(visibility_qualified(&item.vis, "use"));
1155 self.print_use_tree(tree);
1157 self.end(); // end inner head-block
1158 self.end(); // end outer head-block
1160 ast::ItemKind::Static(ref ty, m, ref expr) => {
1161 self.head(visibility_qualified(&item.vis, "static"));
1162 if m == ast::Mutability::Mutable {
1163 self.word_space("mut");
1165 self.print_ident(item.ident);
1166 self.word_space(":");
1167 self.print_type(ty);
1169 self.end(); // end the head-ibox
1171 self.word_space("=");
1172 self.print_expr(expr);
1174 self.end(); // end the outer cbox
1176 ast::ItemKind::Const(ref ty, ref expr) => {
1177 self.head(visibility_qualified(&item.vis, "const"));
1178 self.print_ident(item.ident);
1179 self.word_space(":");
1180 self.print_type(ty);
1182 self.end(); // end the head-ibox
1184 self.word_space("=");
1185 self.print_expr(expr);
1187 self.end(); // end the outer cbox
1189 ast::ItemKind::Fn(ref decl, header, ref param_names, ref body) => {
1199 self.print_block_with_attrs(body, &item.attrs);
1201 ast::ItemKind::Mod(ref _mod) => {
1202 self.head(visibility_qualified(&item.vis, "mod"));
1203 self.print_ident(item.ident);
1205 if _mod.inline || self.is_expanded {
1208 self.print_mod(_mod, &item.attrs);
1209 self.bclose(item.span);
1212 self.end(); // end inner head-block
1213 self.end(); // end outer head-block
1217 ast::ItemKind::ForeignMod(ref nmod) => {
1218 self.head("extern");
1219 self.word_nbsp(nmod.abi.to_string());
1221 self.print_foreign_mod(nmod, &item.attrs);
1222 self.bclose(item.span);
1224 ast::ItemKind::GlobalAsm(ref ga) => {
1225 self.head(visibility_qualified(&item.vis, "global_asm!"));
1226 self.s.word(ga.asm.as_str().to_string());
1229 ast::ItemKind::Ty(ref ty, ref generics) => {
1230 self.head(visibility_qualified(&item.vis, "type"));
1231 self.print_ident(item.ident);
1232 self.print_generic_params(&generics.params);
1233 self.end(); // end the inner ibox
1235 self.print_where_clause(&generics.where_clause);
1237 self.word_space("=");
1238 self.print_type(ty);
1240 self.end(); // end the outer ibox
1242 ast::ItemKind::Existential(ref bounds, ref generics) => {
1243 self.head(visibility_qualified(&item.vis, "existential type"));
1244 self.print_ident(item.ident);
1245 self.print_generic_params(&generics.params);
1246 self.end(); // end the inner ibox
1248 self.print_where_clause(&generics.where_clause);
1250 self.print_type_bounds(":", bounds);
1252 self.end(); // end the outer ibox
1254 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1255 self.print_enum_def(
1263 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1264 self.head(visibility_qualified(&item.vis, "struct"));
1265 self.print_struct(struct_def, generics, item.ident, item.span, true);
1267 ast::ItemKind::Union(ref struct_def, ref generics) => {
1268 self.head(visibility_qualified(&item.vis, "union"));
1269 self.print_struct(struct_def, generics, item.ident, item.span, true);
1271 ast::ItemKind::Impl(unsafety,
1277 ref impl_items) => {
1279 self.print_visibility(&item.vis);
1280 self.print_defaultness(defaultness);
1281 self.print_unsafety(unsafety);
1282 self.word_nbsp("impl");
1284 if !generics.params.is_empty() {
1285 self.print_generic_params(&generics.params);
1289 if polarity == ast::ImplPolarity::Negative {
1293 if let Some(ref t) = *opt_trait {
1294 self.print_trait_ref(t);
1296 self.word_space("for");
1299 self.print_type(ty);
1300 self.print_where_clause(&generics.where_clause);
1304 self.print_inner_attributes(&item.attrs);
1305 for impl_item in impl_items {
1306 self.print_impl_item(impl_item);
1308 self.bclose(item.span);
1310 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1312 self.print_visibility(&item.vis);
1313 self.print_unsafety(unsafety);
1314 self.print_is_auto(is_auto);
1315 self.word_nbsp("trait");
1316 self.print_ident(item.ident);
1317 self.print_generic_params(&generics.params);
1318 let mut real_bounds = Vec::with_capacity(bounds.len());
1319 for b in bounds.iter() {
1320 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1322 self.word_space("for ?");
1323 self.print_trait_ref(&ptr.trait_ref);
1325 real_bounds.push(b.clone());
1328 self.print_type_bounds(":", &real_bounds[..]);
1329 self.print_where_clause(&generics.where_clause);
1332 for trait_item in trait_items {
1333 self.print_trait_item(trait_item);
1335 self.bclose(item.span);
1337 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1339 self.print_visibility(&item.vis);
1340 self.word_nbsp("trait");
1341 self.print_ident(item.ident);
1342 self.print_generic_params(&generics.params);
1343 let mut real_bounds = Vec::with_capacity(bounds.len());
1344 // FIXME(durka) this seems to be some quite outdated syntax
1345 for b in bounds.iter() {
1346 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1348 self.word_space("for ?");
1349 self.print_trait_ref(&ptr.trait_ref);
1351 real_bounds.push(b.clone());
1355 self.print_type_bounds("=", &real_bounds[..]);
1356 self.print_where_clause(&generics.where_clause);
1359 ast::ItemKind::Mac(ref mac) => {
1360 self.print_mac(mac);
1361 match mac.node.delim {
1362 MacDelimiter::Brace => {}
1363 _ => self.s.word(";"),
1366 ast::ItemKind::MacroDef(ref macro_def) => {
1367 let (kw, has_bang) =
1368 if macro_def.legacy { ("macro_rules", true) } else { ("macro", false) };
1369 self.print_mac_common(
1370 Some(MacHeader::Keyword(kw)),
1380 self.ann.post(self, AnnNode::Item(item))
1383 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1384 self.print_path(&t.path, false, 0)
1387 fn print_formal_generic_params(
1389 generic_params: &[ast::GenericParam]
1391 if !generic_params.is_empty() {
1393 self.print_generic_params(generic_params);
1398 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1399 self.print_formal_generic_params(&t.bound_generic_params);
1400 self.print_trait_ref(&t.trait_ref)
1403 crate fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1404 generics: &ast::Generics, ident: ast::Ident,
1405 span: syntax_pos::Span,
1406 visibility: &ast::Visibility) {
1407 self.head(visibility_qualified(visibility, "enum"));
1408 self.print_ident(ident);
1409 self.print_generic_params(&generics.params);
1410 self.print_where_clause(&generics.where_clause);
1412 self.print_variants(&enum_definition.variants, span)
1415 crate fn print_variants(&mut self,
1416 variants: &[ast::Variant],
1417 span: syntax_pos::Span) {
1420 self.space_if_not_bol();
1421 self.maybe_print_comment(v.span.lo());
1422 self.print_outer_attributes(&v.node.attrs);
1423 self.ibox(INDENT_UNIT);
1424 self.print_variant(v);
1427 self.maybe_print_trailing_comment(v.span, None);
1432 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1434 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1435 ast::VisibilityKind::Crate(sugar) => match sugar {
1436 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1437 ast::CrateSugar::JustCrate => self.word_nbsp("crate")
1439 ast::VisibilityKind::Restricted { ref path, .. } => {
1440 let path = to_string(|s| s.print_path(path, false, 0));
1441 if path == "self" || path == "super" {
1442 self.word_nbsp(format!("pub({})", path))
1444 self.word_nbsp(format!("pub(in {})", path))
1447 ast::VisibilityKind::Inherited => {}
1451 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1452 if let ast::Defaultness::Default = defaultness {
1453 self.word_nbsp("default");
1457 crate fn print_struct(&mut self,
1458 struct_def: &ast::VariantData,
1459 generics: &ast::Generics,
1461 span: syntax_pos::Span,
1462 print_finalizer: bool) {
1463 self.print_ident(ident);
1464 self.print_generic_params(&generics.params);
1466 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1467 if let ast::VariantData::Tuple(..) = struct_def {
1470 Inconsistent, struct_def.fields(),
1472 s.maybe_print_comment(field.span.lo());
1473 s.print_outer_attributes(&field.attrs);
1474 s.print_visibility(&field.vis);
1475 s.print_type(&field.ty)
1480 self.print_where_clause(&generics.where_clause);
1481 if print_finalizer {
1485 self.end(); // close the outer-box
1487 ast::VariantData::Struct(..) => {
1488 self.print_where_clause(&generics.where_clause);
1491 self.hardbreak_if_not_bol();
1493 for field in struct_def.fields() {
1494 self.hardbreak_if_not_bol();
1495 self.maybe_print_comment(field.span.lo());
1496 self.print_outer_attributes(&field.attrs);
1497 self.print_visibility(&field.vis);
1498 self.print_ident(field.ident.unwrap());
1499 self.word_nbsp(":");
1500 self.print_type(&field.ty);
1509 crate fn print_variant(&mut self, v: &ast::Variant) {
1511 let generics = ast::Generics::default();
1512 self.print_struct(&v.node.data, &generics, v.node.ident, v.span, false);
1513 match v.node.disr_expr {
1516 self.word_space("=");
1517 self.print_expr(&d.value)
1523 crate fn print_method_sig(&mut self,
1525 generics: &ast::Generics,
1527 vis: &ast::Visibility)
1529 self.print_fn(&m.decl,
1536 crate fn print_trait_item(&mut self, ti: &ast::TraitItem)
1538 self.ann.pre(self, AnnNode::SubItem(ti.id));
1539 self.hardbreak_if_not_bol();
1540 self.maybe_print_comment(ti.span.lo());
1541 self.print_outer_attributes(&ti.attrs);
1543 ast::TraitItemKind::Const(ref ty, ref default) => {
1544 self.print_associated_const(
1547 default.as_ref().map(|expr| &**expr),
1548 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1551 ast::TraitItemKind::Method(ref sig, ref body) => {
1555 self.print_method_sig(
1559 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1561 if let Some(ref body) = *body {
1563 self.print_block_with_attrs(body, &ti.attrs);
1568 ast::TraitItemKind::Type(ref bounds, ref default) => {
1569 self.print_associated_type(ti.ident, Some(bounds),
1570 default.as_ref().map(|ty| &**ty));
1572 ast::TraitItemKind::Macro(ref mac) => {
1573 self.print_mac(mac);
1574 match mac.node.delim {
1575 MacDelimiter::Brace => {}
1576 _ => self.s.word(";"),
1580 self.ann.post(self, AnnNode::SubItem(ti.id))
1583 crate fn print_impl_item(&mut self, ii: &ast::ImplItem) {
1584 self.ann.pre(self, AnnNode::SubItem(ii.id));
1585 self.hardbreak_if_not_bol();
1586 self.maybe_print_comment(ii.span.lo());
1587 self.print_outer_attributes(&ii.attrs);
1588 self.print_defaultness(ii.defaultness);
1590 ast::ImplItemKind::Const(ref ty, ref expr) => {
1591 self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis);
1593 ast::ImplItemKind::Method(ref sig, ref body) => {
1595 self.print_method_sig(ii.ident, &ii.generics, sig, &ii.vis);
1597 self.print_block_with_attrs(body, &ii.attrs);
1599 ast::ImplItemKind::Type(ref ty) => {
1600 self.print_associated_type(ii.ident, None, Some(ty));
1602 ast::ImplItemKind::Existential(ref bounds) => {
1603 self.word_space("existential");
1604 self.print_associated_type(ii.ident, Some(bounds), None);
1606 ast::ImplItemKind::Macro(ref mac) => {
1607 self.print_mac(mac);
1608 match mac.node.delim {
1609 MacDelimiter::Brace => {}
1610 _ => self.s.word(";"),
1614 self.ann.post(self, AnnNode::SubItem(ii.id))
1617 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1618 self.maybe_print_comment(st.span.lo());
1620 ast::StmtKind::Local(ref loc) => {
1621 self.print_outer_attributes(&loc.attrs);
1622 self.space_if_not_bol();
1623 self.ibox(INDENT_UNIT);
1624 self.word_nbsp("let");
1626 self.ibox(INDENT_UNIT);
1627 self.print_local_decl(loc);
1629 if let Some(ref init) = loc.init {
1631 self.word_space("=");
1632 self.print_expr(init);
1637 ast::StmtKind::Item(ref item) => self.print_item(item),
1638 ast::StmtKind::Expr(ref expr) => {
1639 self.space_if_not_bol();
1640 self.print_expr_outer_attr_style(expr, false);
1641 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1645 ast::StmtKind::Semi(ref expr) => {
1646 self.space_if_not_bol();
1647 self.print_expr_outer_attr_style(expr, false);
1650 ast::StmtKind::Mac(ref mac) => {
1651 let (ref mac, style, ref attrs) = **mac;
1652 self.space_if_not_bol();
1653 self.print_outer_attributes(attrs);
1654 self.print_mac(mac);
1655 if style == ast::MacStmtStyle::Semicolon {
1660 self.maybe_print_trailing_comment(st.span, None)
1663 crate fn print_block(&mut self, blk: &ast::Block) {
1664 self.print_block_with_attrs(blk, &[])
1667 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1668 self.print_block_maybe_unclosed(blk, &[], false)
1671 crate fn print_block_with_attrs(&mut self,
1673 attrs: &[ast::Attribute]) {
1674 self.print_block_maybe_unclosed(blk, attrs, true)
1677 crate fn print_block_maybe_unclosed(&mut self,
1679 attrs: &[ast::Attribute],
1682 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1683 BlockCheckMode::Default => ()
1685 self.maybe_print_comment(blk.span.lo());
1686 self.ann.pre(self, AnnNode::Block(blk));
1689 self.print_inner_attributes(attrs);
1691 for (i, st) in blk.stmts.iter().enumerate() {
1693 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1694 self.maybe_print_comment(st.span.lo());
1695 self.space_if_not_bol();
1696 self.print_expr_outer_attr_style(expr, false);
1697 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1699 _ => self.print_stmt(st),
1703 self.bclose_maybe_open(blk.span, close_box);
1704 self.ann.post(self, AnnNode::Block(blk))
1707 /// Print a `let pats = scrutinee` expression.
1708 crate fn print_let(&mut self, pats: &[P<ast::Pat>], scrutinee: &ast::Expr) {
1709 self.s.word("let ");
1711 self.print_pats(pats);
1714 self.word_space("=");
1715 self.print_expr_cond_paren(
1717 Self::cond_needs_par(scrutinee)
1718 || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order())
1722 fn print_else(&mut self, els: Option<&ast::Expr>) {
1726 // Another `else if` block.
1727 ast::ExprKind::If(ref i, ref then, ref e) => {
1728 self.cbox(INDENT_UNIT - 1);
1730 self.s.word(" else if ");
1731 self.print_expr_as_cond(i);
1733 self.print_block(then);
1734 self.print_else(e.as_ref().map(|e| &**e))
1736 // Final `else` block.
1737 ast::ExprKind::Block(ref b, _) => {
1738 self.cbox(INDENT_UNIT - 1);
1740 self.s.word(" else ");
1743 // Constraints would be great here!
1745 panic!("print_if saw if with weird alternative");
1753 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1754 elseopt: Option<&ast::Expr>) {
1757 self.print_expr_as_cond(test);
1760 self.print_block(blk);
1761 self.print_else(elseopt)
1764 crate fn print_mac(&mut self, m: &ast::Mac) {
1765 self.print_mac_common(
1766 Some(MacHeader::Path(&m.node.path)),
1769 m.node.delim.to_token(),
1776 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1778 self.commasep_exprs(Inconsistent, args);
1782 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1783 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1786 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1787 /// `if cond { ... }`.
1788 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1789 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1792 /// Does `expr` need parenthesis when printed in a condition position?
1793 fn cond_needs_par(expr: &ast::Expr) -> bool {
1795 // These cases need parens due to the parse error observed in #26461: `if return {}`
1796 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1797 ast::ExprKind::Closure(..) |
1798 ast::ExprKind::Ret(..) |
1799 ast::ExprKind::Break(..) => true,
1801 _ => parser::contains_exterior_struct_lit(expr),
1805 /// Print `expr` or `(expr)` when `needs_par` holds.
1806 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1810 self.print_expr(expr);
1816 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1817 attrs: &[Attribute]) {
1818 self.ibox(INDENT_UNIT);
1820 self.print_inner_attributes_inline(attrs);
1821 self.commasep_exprs(Inconsistent, &exprs[..]);
1826 fn print_expr_repeat(&mut self,
1827 element: &ast::Expr,
1828 count: &ast::AnonConst,
1829 attrs: &[Attribute]) {
1830 self.ibox(INDENT_UNIT);
1832 self.print_inner_attributes_inline(attrs);
1833 self.print_expr(element);
1834 self.word_space(";");
1835 self.print_expr(&count.value);
1840 fn print_expr_struct(&mut self,
1842 fields: &[ast::Field],
1843 wth: &Option<P<ast::Expr>>,
1844 attrs: &[Attribute]) {
1845 self.print_path(path, true, 0);
1847 self.print_inner_attributes_inline(attrs);
1852 s.ibox(INDENT_UNIT);
1853 if !field.is_shorthand {
1854 s.print_ident(field.ident);
1857 s.print_expr(&field.expr);
1863 self.ibox(INDENT_UNIT);
1864 if !fields.is_empty() {
1869 self.print_expr(expr);
1872 _ => if !fields.is_empty() {
1879 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1880 attrs: &[Attribute]) {
1882 self.print_inner_attributes_inline(attrs);
1883 self.commasep_exprs(Inconsistent, &exprs[..]);
1884 if exprs.len() == 1 {
1890 fn print_expr_call(&mut self,
1892 args: &[P<ast::Expr>]) {
1895 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1896 _ => parser::PREC_POSTFIX,
1899 self.print_expr_maybe_paren(func, prec);
1900 self.print_call_post(args)
1903 fn print_expr_method_call(&mut self,
1904 segment: &ast::PathSegment,
1905 args: &[P<ast::Expr>]) {
1906 let base_args = &args[1..];
1907 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1909 self.print_ident(segment.ident);
1910 if let Some(ref args) = segment.args {
1911 self.print_generic_args(args, true);
1913 self.print_call_post(base_args)
1916 fn print_expr_binary(&mut self,
1920 let assoc_op = AssocOp::from_ast_binop(op.node);
1921 let prec = assoc_op.precedence() as i8;
1922 let fixity = assoc_op.fixity();
1924 let (left_prec, right_prec) = match fixity {
1925 Fixity::Left => (prec, prec + 1),
1926 Fixity::Right => (prec + 1, prec),
1927 Fixity::None => (prec + 1, prec + 1),
1930 let left_prec = match (&lhs.node, op.node) {
1931 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1932 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1933 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1934 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) |
1935 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1936 // We are given `(let _ = a) OP b`.
1938 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1939 // as the parser will interpret this as `(let _ = a) OP b`.
1941 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1942 // parens are required since the parser would interpret `let a = b < c` as
1943 // `let a = (b < c)`. To achieve this, we force parens.
1944 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1945 parser::PREC_FORCE_PAREN
1950 self.print_expr_maybe_paren(lhs, left_prec);
1952 self.word_space(op.node.to_string());
1953 self.print_expr_maybe_paren(rhs, right_prec)
1956 fn print_expr_unary(&mut self,
1959 self.s.word(ast::UnOp::to_string(op));
1960 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1963 fn print_expr_addr_of(&mut self,
1964 mutability: ast::Mutability,
1967 self.print_mutability(mutability);
1968 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1971 crate fn print_expr(&mut self, expr: &ast::Expr) {
1972 self.print_expr_outer_attr_style(expr, true)
1975 fn print_expr_outer_attr_style(&mut self,
1978 self.maybe_print_comment(expr.span.lo());
1980 let attrs = &expr.attrs;
1982 self.print_outer_attributes_inline(attrs);
1984 self.print_outer_attributes(attrs);
1987 self.ibox(INDENT_UNIT);
1988 self.ann.pre(self, AnnNode::Expr(expr));
1990 ast::ExprKind::Box(ref expr) => {
1991 self.word_space("box");
1992 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1994 ast::ExprKind::Array(ref exprs) => {
1995 self.print_expr_vec(&exprs[..], attrs);
1997 ast::ExprKind::Repeat(ref element, ref count) => {
1998 self.print_expr_repeat(element, count, attrs);
2000 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2001 self.print_expr_struct(path, &fields[..], wth, attrs);
2003 ast::ExprKind::Tup(ref exprs) => {
2004 self.print_expr_tup(&exprs[..], attrs);
2006 ast::ExprKind::Call(ref func, ref args) => {
2007 self.print_expr_call(func, &args[..]);
2009 ast::ExprKind::MethodCall(ref segment, ref args) => {
2010 self.print_expr_method_call(segment, &args[..]);
2012 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2013 self.print_expr_binary(op, lhs, rhs);
2015 ast::ExprKind::Unary(op, ref expr) => {
2016 self.print_expr_unary(op, expr);
2018 ast::ExprKind::AddrOf(m, ref expr) => {
2019 self.print_expr_addr_of(m, expr);
2021 ast::ExprKind::Lit(ref lit) => {
2022 self.print_literal(lit);
2024 ast::ExprKind::Cast(ref expr, ref ty) => {
2025 let prec = AssocOp::As.precedence() as i8;
2026 self.print_expr_maybe_paren(expr, prec);
2028 self.word_space("as");
2029 self.print_type(ty);
2031 ast::ExprKind::Type(ref expr, ref ty) => {
2032 let prec = AssocOp::Colon.precedence() as i8;
2033 self.print_expr_maybe_paren(expr, prec);
2034 self.word_space(":");
2035 self.print_type(ty);
2037 ast::ExprKind::Let(ref pats, ref scrutinee) => {
2038 self.print_let(pats, scrutinee);
2040 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2041 self.print_if(test, blk, elseopt.as_ref().map(|e| &**e));
2043 ast::ExprKind::While(ref test, ref blk, opt_label) => {
2044 if let Some(label) = opt_label {
2045 self.print_ident(label.ident);
2046 self.word_space(":");
2049 self.print_expr_as_cond(test);
2051 self.print_block_with_attrs(blk, attrs);
2053 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2054 if let Some(label) = opt_label {
2055 self.print_ident(label.ident);
2056 self.word_space(":");
2059 self.print_pat(pat);
2061 self.word_space("in");
2062 self.print_expr_as_cond(iter);
2064 self.print_block_with_attrs(blk, attrs);
2066 ast::ExprKind::Loop(ref blk, opt_label) => {
2067 if let Some(label) = opt_label {
2068 self.print_ident(label.ident);
2069 self.word_space(":");
2073 self.print_block_with_attrs(blk, attrs);
2075 ast::ExprKind::Match(ref expr, ref arms) => {
2076 self.cbox(INDENT_UNIT);
2077 self.ibox(INDENT_UNIT);
2078 self.word_nbsp("match");
2079 self.print_expr_as_cond(expr);
2082 self.print_inner_attributes_no_trailing_hardbreak(attrs);
2084 self.print_arm(arm);
2086 self.bclose(expr.span);
2088 ast::ExprKind::Closure(
2089 capture_clause, asyncness, movability, ref decl, ref body, _) => {
2090 self.print_movability(movability);
2091 self.print_asyncness(asyncness);
2092 self.print_capture_clause(capture_clause);
2094 self.print_fn_block_args(decl);
2096 self.print_expr(body);
2097 self.end(); // need to close a box
2099 // a box will be closed by print_expr, but we didn't want an overall
2100 // wrapper so we closed the corresponding opening. so create an
2101 // empty box to satisfy the close.
2104 ast::ExprKind::Block(ref blk, opt_label) => {
2105 if let Some(label) = opt_label {
2106 self.print_ident(label.ident);
2107 self.word_space(":");
2109 // containing cbox, will be closed by print-block at }
2110 self.cbox(INDENT_UNIT);
2111 // head-box, will be closed by print-block after {
2113 self.print_block_with_attrs(blk, attrs);
2115 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2116 self.word_nbsp("async");
2117 self.print_capture_clause(capture_clause);
2119 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2120 self.cbox(INDENT_UNIT);
2122 self.print_block_with_attrs(blk, attrs);
2124 ast::ExprKind::Await(origin, ref expr) => {
2126 ast::AwaitOrigin::MacroLike => {
2127 self.s.word("await!");
2128 self.print_expr_maybe_paren(expr, parser::PREC_FORCE_PAREN);
2130 ast::AwaitOrigin::FieldLike => {
2131 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2132 self.s.word(".await");
2136 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2137 let prec = AssocOp::Assign.precedence() as i8;
2138 self.print_expr_maybe_paren(lhs, prec + 1);
2140 self.word_space("=");
2141 self.print_expr_maybe_paren(rhs, prec);
2143 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2144 let prec = AssocOp::Assign.precedence() as i8;
2145 self.print_expr_maybe_paren(lhs, prec + 1);
2147 self.s.word(op.node.to_string());
2148 self.word_space("=");
2149 self.print_expr_maybe_paren(rhs, prec);
2151 ast::ExprKind::Field(ref expr, ident) => {
2152 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2154 self.print_ident(ident);
2156 ast::ExprKind::Index(ref expr, ref index) => {
2157 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2159 self.print_expr(index);
2162 ast::ExprKind::Range(ref start, ref end, limits) => {
2163 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2164 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2165 // Here we use a fake precedence value so that any child with lower precedence than
2166 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2167 let fake_prec = AssocOp::LOr.precedence() as i8;
2168 if let Some(ref e) = *start {
2169 self.print_expr_maybe_paren(e, fake_prec);
2171 if limits == ast::RangeLimits::HalfOpen {
2176 if let Some(ref e) = *end {
2177 self.print_expr_maybe_paren(e, fake_prec);
2180 ast::ExprKind::Path(None, ref path) => {
2181 self.print_path(path, true, 0)
2183 ast::ExprKind::Path(Some(ref qself), ref path) => {
2184 self.print_qpath(path, qself, true)
2186 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2187 self.s.word("break");
2189 if let Some(label) = opt_label {
2190 self.print_ident(label.ident);
2193 if let Some(ref expr) = *opt_expr {
2194 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2198 ast::ExprKind::Continue(opt_label) => {
2199 self.s.word("continue");
2201 if let Some(label) = opt_label {
2202 self.print_ident(label.ident);
2206 ast::ExprKind::Ret(ref result) => {
2207 self.s.word("return");
2208 if let Some(ref expr) = *result {
2210 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2213 ast::ExprKind::InlineAsm(ref a) => {
2214 self.s.word("asm!");
2216 self.print_string(&a.asm.as_str(), a.asm_str_style);
2217 self.word_space(":");
2219 self.commasep(Inconsistent, &a.outputs, |s, out| {
2220 let constraint = out.constraint.as_str();
2221 let mut ch = constraint.chars();
2223 Some('=') if out.is_rw => {
2224 s.print_string(&format!("+{}", ch.as_str()),
2225 ast::StrStyle::Cooked)
2227 _ => s.print_string(&constraint, ast::StrStyle::Cooked)
2230 s.print_expr(&out.expr);
2234 self.word_space(":");
2236 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2237 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2243 self.word_space(":");
2245 self.commasep(Inconsistent, &a.clobbers,
2247 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2250 let mut options = vec![];
2252 options.push("volatile");
2255 options.push("alignstack");
2257 if a.dialect == ast::AsmDialect::Intel {
2258 options.push("intel");
2261 if !options.is_empty() {
2263 self.word_space(":");
2264 self.commasep(Inconsistent, &options,
2266 s.print_string(co, ast::StrStyle::Cooked);
2272 ast::ExprKind::Mac(ref m) => self.print_mac(m),
2273 ast::ExprKind::Paren(ref e) => {
2275 self.print_inner_attributes_inline(attrs);
2279 ast::ExprKind::Yield(ref e) => {
2280 self.s.word("yield");
2284 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2289 ast::ExprKind::Try(ref e) => {
2290 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2293 ast::ExprKind::TryBlock(ref blk) => {
2296 self.print_block_with_attrs(blk, attrs)
2298 ast::ExprKind::Err => {
2300 self.s.word("/*ERROR*/");
2304 self.ann.post(self, AnnNode::Expr(expr));
2308 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2309 self.print_pat(&loc.pat);
2310 if let Some(ref ty) = loc.ty {
2311 self.word_space(":");
2312 self.print_type(ty);
2316 crate fn print_usize(&mut self, i: usize) {
2317 self.s.word(i.to_string())
2320 crate fn print_name(&mut self, name: ast::Name) {
2321 self.s.word(name.as_str().to_string());
2322 self.ann.post(self, AnnNode::Name(&name))
2325 fn print_qpath(&mut self,
2328 colons_before_params: bool)
2331 self.print_type(&qself.ty);
2332 if qself.position > 0 {
2334 self.word_space("as");
2335 let depth = path.segments.len() - qself.position;
2336 self.print_path(path, false, depth);
2340 let item_segment = path.segments.last().unwrap();
2341 self.print_ident(item_segment.ident);
2342 match item_segment.args {
2343 Some(ref args) => self.print_generic_args(args, colons_before_params),
2348 crate fn print_pat(&mut self, pat: &ast::Pat) {
2349 self.maybe_print_comment(pat.span.lo());
2350 self.ann.pre(self, AnnNode::Pat(pat));
2351 /* Pat isn't normalized, but the beauty of it
2352 is that it doesn't matter */
2354 PatKind::Wild => self.s.word("_"),
2355 PatKind::Ident(binding_mode, ident, ref sub) => {
2356 match binding_mode {
2357 ast::BindingMode::ByRef(mutbl) => {
2358 self.word_nbsp("ref");
2359 self.print_mutability(mutbl);
2361 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2362 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2363 self.word_nbsp("mut");
2366 self.print_ident(ident);
2367 if let Some(ref p) = *sub {
2372 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2373 self.print_path(path, true, 0);
2375 if let Some(ddpos) = ddpos {
2376 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
2378 self.word_space(",");
2381 if ddpos != elts.len() {
2383 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
2386 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2390 PatKind::Path(None, ref path) => {
2391 self.print_path(path, true, 0);
2393 PatKind::Path(Some(ref qself), ref path) => {
2394 self.print_qpath(path, qself, false);
2396 PatKind::Struct(ref path, ref fields, etc) => {
2397 self.print_path(path, true, 0);
2399 self.word_space("{");
2401 Consistent, &fields[..],
2403 s.cbox(INDENT_UNIT);
2404 if !f.node.is_shorthand {
2405 s.print_ident(f.node.ident);
2408 s.print_pat(&f.node.pat);
2411 |f| f.node.pat.span);
2413 if !fields.is_empty() { self.word_space(","); }
2419 PatKind::Tuple(ref elts, ddpos) => {
2421 if let Some(ddpos) = ddpos {
2422 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
2424 self.word_space(",");
2427 if ddpos != elts.len() {
2429 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
2432 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2433 if elts.len() == 1 {
2439 PatKind::Box(ref inner) => {
2440 self.s.word("box ");
2441 self.print_pat(inner);
2443 PatKind::Ref(ref inner, mutbl) => {
2445 if mutbl == ast::Mutability::Mutable {
2446 self.s.word("mut ");
2448 self.print_pat(inner);
2450 PatKind::Lit(ref e) => self.print_expr(&**e),
2451 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2452 self.print_expr(begin);
2455 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("..."),
2456 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..="),
2457 RangeEnd::Excluded => self.s.word(".."),
2459 self.print_expr(end);
2461 PatKind::Slice(ref before, ref slice, ref after) => {
2463 self.commasep(Inconsistent,
2465 |s, p| s.print_pat(p));
2466 if let Some(ref p) = *slice {
2467 if !before.is_empty() { self.word_space(","); }
2468 if let PatKind::Wild = p.node {
2474 if !after.is_empty() { self.word_space(","); }
2476 self.commasep(Inconsistent,
2478 |s, p| s.print_pat(p));
2481 PatKind::Paren(ref inner) => {
2483 self.print_pat(inner);
2486 PatKind::Mac(ref m) => self.print_mac(m),
2488 self.ann.post(self, AnnNode::Pat(pat))
2491 fn print_pats(&mut self, pats: &[P<ast::Pat>]) {
2492 let mut first = true;
2498 self.word_space("|");
2504 fn print_arm(&mut self, arm: &ast::Arm) {
2505 // I have no idea why this check is necessary, but here it
2507 if arm.attrs.is_empty() {
2510 self.cbox(INDENT_UNIT);
2512 self.maybe_print_comment(arm.pats[0].span.lo());
2513 self.print_outer_attributes(&arm.attrs);
2514 self.print_pats(&arm.pats);
2516 if let Some(ref e) = arm.guard {
2517 self.word_space("if");
2521 self.word_space("=>");
2523 match arm.body.node {
2524 ast::ExprKind::Block(ref blk, opt_label) => {
2525 if let Some(label) = opt_label {
2526 self.print_ident(label.ident);
2527 self.word_space(":");
2530 // the block will close the pattern's ibox
2531 self.print_block_unclosed_indent(blk);
2533 // If it is a user-provided unsafe block, print a comma after it
2534 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2539 self.end(); // close the ibox for the pattern
2540 self.print_expr(&arm.body);
2544 self.end(); // close enclosing cbox
2547 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2548 match explicit_self.node {
2549 SelfKind::Value(m) => {
2550 self.print_mutability(m);
2553 SelfKind::Region(ref lt, m) => {
2555 self.print_opt_lifetime(lt);
2556 self.print_mutability(m);
2559 SelfKind::Explicit(ref typ, m) => {
2560 self.print_mutability(m);
2561 self.s.word("self");
2562 self.word_space(":");
2563 self.print_type(typ)
2568 crate fn print_fn(&mut self,
2570 header: ast::FnHeader,
2571 name: Option<ast::Ident>,
2572 generics: &ast::Generics,
2573 vis: &ast::Visibility) {
2574 self.print_fn_header_info(header, vis);
2576 if let Some(name) = name {
2578 self.print_ident(name);
2580 self.print_generic_params(&generics.params);
2581 self.print_fn_args_and_ret(decl);
2582 self.print_where_clause(&generics.where_clause)
2585 crate fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl) {
2587 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false));
2590 self.print_fn_output(decl)
2593 crate fn print_fn_block_args(&mut self, decl: &ast::FnDecl) {
2595 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true));
2598 if let ast::FunctionRetTy::Default(..) = decl.output {
2602 self.space_if_not_bol();
2603 self.word_space("->");
2605 ast::FunctionRetTy::Ty(ref ty) => {
2606 self.print_type(ty);
2607 self.maybe_print_comment(ty.span.lo())
2609 ast::FunctionRetTy::Default(..) => unreachable!(),
2613 crate fn print_movability(&mut self, movability: ast::Movability) {
2615 ast::Movability::Static => self.word_space("static"),
2616 ast::Movability::Movable => {},
2620 crate fn print_asyncness(&mut self, asyncness: ast::IsAsync) {
2621 if asyncness.is_async() {
2622 self.word_nbsp("async");
2626 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2627 match capture_clause {
2628 ast::CaptureBy::Value => self.word_space("move"),
2629 ast::CaptureBy::Ref => {},
2633 crate fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2634 if !bounds.is_empty() {
2635 self.s.word(prefix);
2636 let mut first = true;
2637 for bound in bounds {
2638 if !(first && prefix.is_empty()) {
2644 self.word_space("+");
2648 GenericBound::Trait(tref, modifier) => {
2649 if modifier == &TraitBoundModifier::Maybe {
2652 self.print_poly_trait_ref(tref);
2654 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2660 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2661 self.print_name(lifetime.ident.name)
2664 crate fn print_lifetime_bounds(
2665 &mut self, lifetime: ast::Lifetime, bounds: &ast::GenericBounds) {
2666 self.print_lifetime(lifetime);
2667 if !bounds.is_empty() {
2669 for (i, bound) in bounds.iter().enumerate() {
2674 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2681 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2682 if generic_params.is_empty() {
2688 self.commasep(Inconsistent, &generic_params, |s, param| {
2690 ast::GenericParamKind::Lifetime => {
2691 s.print_outer_attributes_inline(¶m.attrs);
2692 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2693 s.print_lifetime_bounds(lt, ¶m.bounds)
2695 ast::GenericParamKind::Type { ref default } => {
2696 s.print_outer_attributes_inline(¶m.attrs);
2697 s.print_ident(param.ident);
2698 s.print_type_bounds(":", ¶m.bounds);
2700 Some(ref default) => {
2703 s.print_type(default)
2708 ast::GenericParamKind::Const { ref ty } => {
2709 s.print_outer_attributes_inline(¶m.attrs);
2710 s.word_space("const");
2711 s.print_ident(param.ident);
2715 s.print_type_bounds(":", ¶m.bounds)
2723 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2724 if where_clause.predicates.is_empty() {
2729 self.word_space("where");
2731 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2733 self.word_space(",");
2737 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2738 ref bound_generic_params,
2743 self.print_formal_generic_params(bound_generic_params);
2744 self.print_type(bounded_ty);
2745 self.print_type_bounds(":", bounds);
2747 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2750 self.print_lifetime_bounds(*lifetime, bounds);
2752 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2755 self.print_type(lhs_ty);
2757 self.word_space("=");
2758 self.print_type(rhs_ty);
2764 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2766 ast::UseTreeKind::Simple(rename, ..) => {
2767 self.print_path(&tree.prefix, false, 0);
2768 if let Some(rename) = rename {
2770 self.word_space("as");
2771 self.print_ident(rename);
2774 ast::UseTreeKind::Glob => {
2775 if !tree.prefix.segments.is_empty() {
2776 self.print_path(&tree.prefix, false, 0);
2781 ast::UseTreeKind::Nested(ref items) => {
2782 if tree.prefix.segments.is_empty() {
2785 self.print_path(&tree.prefix, false, 0);
2788 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2789 this.print_use_tree(tree)
2796 crate fn print_mutability(&mut self, mutbl: ast::Mutability) {
2798 ast::Mutability::Mutable => self.word_nbsp("mut"),
2799 ast::Mutability::Immutable => {},
2803 crate fn print_mt(&mut self, mt: &ast::MutTy) {
2804 self.print_mutability(mt.mutbl);
2805 self.print_type(&mt.ty)
2808 crate fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) {
2809 self.ibox(INDENT_UNIT);
2810 match input.ty.node {
2811 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2813 if let Some(eself) = input.to_self() {
2814 self.print_explicit_self(&eself);
2816 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
2817 ident.name == kw::Invalid
2822 self.print_pat(&input.pat);
2826 self.print_type(&input.ty);
2833 crate fn print_fn_output(&mut self, decl: &ast::FnDecl) {
2834 if let ast::FunctionRetTy::Default(..) = decl.output {
2838 self.space_if_not_bol();
2839 self.ibox(INDENT_UNIT);
2840 self.word_space("->");
2842 ast::FunctionRetTy::Default(..) => unreachable!(),
2843 ast::FunctionRetTy::Ty(ref ty) =>
2844 self.print_type(ty),
2849 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo()),
2854 crate fn print_ty_fn(&mut self,
2856 unsafety: ast::Unsafety,
2858 name: Option<ast::Ident>,
2859 generic_params: &[ast::GenericParam])
2861 self.ibox(INDENT_UNIT);
2862 if !generic_params.is_empty() {
2864 self.print_generic_params(generic_params);
2866 let generics = ast::Generics {
2868 where_clause: ast::WhereClause {
2869 predicates: Vec::new(),
2870 span: syntax_pos::DUMMY_SP,
2872 span: syntax_pos::DUMMY_SP,
2875 ast::FnHeader { unsafety, abi, ..ast::FnHeader::default() },
2878 &source_map::dummy_spanned(ast::VisibilityKind::Inherited));
2882 crate fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
2883 next_pos: Option<BytePos>)
2885 if let Some(cmnts) = self.comments() {
2886 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2887 self.print_comment(&cmnt);
2892 crate fn print_remaining_comments(&mut self) {
2893 // If there aren't any remaining comments, then we need to manually
2894 // make sure there is a line break at the end.
2895 if self.next_comment().is_none() {
2898 while let Some(ref cmnt) = self.next_comment() {
2899 self.print_comment(cmnt);
2903 crate fn print_fn_header_info(&mut self,
2904 header: ast::FnHeader,
2905 vis: &ast::Visibility) {
2906 self.s.word(visibility_qualified(vis, ""));
2908 match header.constness.node {
2909 ast::Constness::NotConst => {}
2910 ast::Constness::Const => self.word_nbsp("const")
2913 self.print_asyncness(header.asyncness.node);
2914 self.print_unsafety(header.unsafety);
2916 if header.abi != Abi::Rust {
2917 self.word_nbsp("extern");
2918 self.word_nbsp(header.abi.to_string());
2924 crate fn print_unsafety(&mut self, s: ast::Unsafety) {
2926 ast::Unsafety::Normal => {},
2927 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2931 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2933 ast::IsAuto::Yes => self.word_nbsp("auto"),
2934 ast::IsAuto::No => {}
2944 use crate::source_map;
2945 use crate::with_default_globals;
2949 fn test_fun_to_string() {
2950 with_default_globals(|| {
2951 let abba_ident = ast::Ident::from_str("abba");
2953 let decl = ast::FnDecl {
2955 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
2958 let generics = ast::Generics::default();
2963 unsafety: ast::Unsafety::Normal,
2964 constness: source_map::dummy_spanned(ast::Constness::NotConst),
2965 asyncness: source_map::dummy_spanned(ast::IsAsync::NotAsync),
2977 fn test_variant_to_string() {
2978 with_default_globals(|| {
2979 let ident = ast::Ident::from_str("principal_skinner");
2981 let var = source_map::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
2984 id: ast::DUMMY_NODE_ID,
2985 // making this up as I go.... ?
2986 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
2990 let varstr = variant_to_string(&var);
2991 assert_eq!(varstr, "principal_skinner");