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 AnnNode<'a> {
24 Ident(&'a ast::Ident),
26 Block(&'a ast::Block),
34 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) { }
35 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) { }
38 #[derive(Copy, Clone)]
41 impl PpAnn for NoAnn {}
43 pub struct Comments<'a> {
45 comments: Vec<comments::Comment>,
49 impl<'a> Comments<'a> {
56 let comments = comments::gather_comments(sess, filename, input);
64 pub fn next(&self) -> Option<comments::Comment> {
65 self.comments.get(self.current).cloned()
68 pub fn trailing_comment(
70 span: syntax_pos::Span,
71 next_pos: Option<BytePos>,
72 ) -> Option<comments::Comment> {
73 if let Some(cmnt) = self.next() {
74 if cmnt.style != comments::Trailing { return None; }
75 let span_line = self.cm.lookup_char_pos(span.hi());
76 let comment_line = self.cm.lookup_char_pos(cmnt.pos);
77 let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1));
78 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
87 pub struct State<'a> {
89 comments: Option<Comments<'a>>,
90 ann: &'a (dyn PpAnn+'a),
94 crate const INDENT_UNIT: usize = 4;
96 /// Requires you to pass an input filename and reader so that
97 /// it can scan the input text for comments to copy forward.
98 pub fn print_crate<'a>(cm: &'a SourceMap,
104 is_expanded: bool) -> String {
107 comments: Some(Comments::new(cm, sess, filename, input)),
112 if is_expanded && std_inject::injected_crate_name().is_some() {
113 // We need to print `#![no_std]` (and its feature gate) so that
114 // compiling pretty-printed source won't inject libstd again.
115 // However we don't want these attributes in the AST because
116 // of the feature gate, so we fake them up here.
118 // #![feature(prelude_import)]
119 let pi_nested = attr::mk_nested_word_item(ast::Ident::with_empty_ctxt(sym::prelude_import));
120 let list = attr::mk_list_item(
121 DUMMY_SP, ast::Ident::with_empty_ctxt(sym::feature), vec![pi_nested]);
122 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), list);
123 s.print_attribute(&fake_attr);
126 let no_std_meta = attr::mk_word_item(ast::Ident::with_empty_ctxt(sym::no_std));
127 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), no_std_meta);
128 s.print_attribute(&fake_attr);
131 s.print_mod(&krate.module, &krate.attrs);
132 s.print_remaining_comments();
136 pub fn to_string<F>(f: F) -> String where
137 F: FnOnce(&mut State<'_>),
139 let mut printer = State {
149 fn binop_to_string(op: BinOpToken) -> &'static str {
155 token::Percent => "%",
164 pub fn literal_to_string(lit: token::Lit) -> String {
165 let token::Lit { kind, symbol, suffix } = lit;
166 let mut out = match kind {
167 token::Byte => format!("b'{}'", symbol),
168 token::Char => format!("'{}'", symbol),
169 token::Str => format!("\"{}\"", symbol),
170 token::StrRaw(n) => format!("r{delim}\"{string}\"{delim}",
171 delim="#".repeat(n as usize),
173 token::ByteStr => format!("b\"{}\"", symbol),
174 token::ByteStrRaw(n) => format!("br{delim}\"{string}\"{delim}",
175 delim="#".repeat(n as usize),
180 token::Err => symbol.to_string(),
183 if let Some(suffix) = suffix {
184 out.push_str(&suffix.as_str())
190 /// Print an ident from AST, `$crate` is converted into its respective crate name.
191 pub fn ast_ident_to_string(ident: ast::Ident, is_raw: bool) -> String {
192 ident_to_string(ident.name, is_raw, Some(ident.span))
195 // AST pretty-printer is used as a fallback for turning AST structures into token streams for
196 // proc macros. Additionally, proc macros may stringify their input and expect it survive the
197 // stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
198 // So we need to somehow pretty-print `$crate` in a way preserving at least some of its
199 // hygiene data, most importantly name of the crate it refers to.
200 // As a result we print `$crate` as `crate` if it refers to the local crate
201 // and as `::other_crate_name` if it refers to some other crate.
202 // Note, that this is only done if the ident token is printed from inside of AST pretty-pringing,
203 // but not otherwise. Pretty-printing is the only way for proc macros to discover token contents,
204 // so we should not perform this lossy conversion if the top level call to the pretty-printer was
205 // done for a token stream or a single token.
206 fn ident_to_string(name: ast::Name, is_raw: bool, convert_dollar_crate: Option<Span>) -> String {
208 format!("r#{}", name)
210 if name == kw::DollarCrate {
211 if let Some(span) = convert_dollar_crate {
212 let converted = span.ctxt().dollar_crate_name();
213 return if converted.is_path_segment_keyword() {
214 converted.to_string()
216 format!("::{}", converted)
224 /// Print the token kind precisely, without converting `$crate` into its respective crate name.
225 pub fn token_kind_to_string(tok: &TokenKind) -> String {
226 token_kind_to_string_ext(tok, None)
229 fn token_kind_to_string_ext(tok: &TokenKind, convert_dollar_crate: Option<Span>) -> String {
231 token::Eq => "=".to_string(),
232 token::Lt => "<".to_string(),
233 token::Le => "<=".to_string(),
234 token::EqEq => "==".to_string(),
235 token::Ne => "!=".to_string(),
236 token::Ge => ">=".to_string(),
237 token::Gt => ">".to_string(),
238 token::Not => "!".to_string(),
239 token::Tilde => "~".to_string(),
240 token::OrOr => "||".to_string(),
241 token::AndAnd => "&&".to_string(),
242 token::BinOp(op) => binop_to_string(op).to_string(),
243 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
245 /* Structural symbols */
246 token::At => "@".to_string(),
247 token::Dot => ".".to_string(),
248 token::DotDot => "..".to_string(),
249 token::DotDotDot => "...".to_string(),
250 token::DotDotEq => "..=".to_string(),
251 token::Comma => ",".to_string(),
252 token::Semi => ";".to_string(),
253 token::Colon => ":".to_string(),
254 token::ModSep => "::".to_string(),
255 token::RArrow => "->".to_string(),
256 token::LArrow => "<-".to_string(),
257 token::FatArrow => "=>".to_string(),
258 token::OpenDelim(token::Paren) => "(".to_string(),
259 token::CloseDelim(token::Paren) => ")".to_string(),
260 token::OpenDelim(token::Bracket) => "[".to_string(),
261 token::CloseDelim(token::Bracket) => "]".to_string(),
262 token::OpenDelim(token::Brace) => "{".to_string(),
263 token::CloseDelim(token::Brace) => "}".to_string(),
264 token::OpenDelim(token::NoDelim) |
265 token::CloseDelim(token::NoDelim) => " ".to_string(),
266 token::Pound => "#".to_string(),
267 token::Dollar => "$".to_string(),
268 token::Question => "?".to_string(),
269 token::SingleQuote => "'".to_string(),
272 token::Literal(lit) => literal_to_string(lit),
274 /* Name components */
275 token::Ident(s, is_raw) => ident_to_string(s, is_raw, convert_dollar_crate),
276 token::Lifetime(s) => s.to_string(),
279 token::DocComment(s) => s.to_string(),
280 token::Eof => "<eof>".to_string(),
281 token::Whitespace => " ".to_string(),
282 token::Comment => "/* */".to_string(),
283 token::Shebang(s) => format!("/* shebang: {}*/", s),
285 token::Interpolated(ref nt) => nonterminal_to_string(nt),
289 /// Print the token precisely, without converting `$crate` into its respective crate name.
290 pub fn token_to_string(token: &Token) -> String {
291 token_to_string_ext(token, false)
294 fn token_to_string_ext(token: &Token, convert_dollar_crate: bool) -> String {
295 let convert_dollar_crate = if convert_dollar_crate { Some(token.span) } else { None };
296 token_kind_to_string_ext(&token.kind, convert_dollar_crate)
299 crate fn nonterminal_to_string(nt: &Nonterminal) -> String {
301 token::NtExpr(ref e) => expr_to_string(e),
302 token::NtMeta(ref e) => meta_item_to_string(e),
303 token::NtTy(ref e) => ty_to_string(e),
304 token::NtPath(ref e) => path_to_string(e),
305 token::NtItem(ref e) => item_to_string(e),
306 token::NtBlock(ref e) => block_to_string(e),
307 token::NtStmt(ref e) => stmt_to_string(e),
308 token::NtPat(ref e) => pat_to_string(e),
309 token::NtIdent(e, is_raw) => ast_ident_to_string(e, is_raw),
310 token::NtLifetime(e) => e.to_string(),
311 token::NtLiteral(ref e) => expr_to_string(e),
312 token::NtTT(ref tree) => tt_to_string(tree.clone()),
313 token::NtImplItem(ref e) => impl_item_to_string(e),
314 token::NtTraitItem(ref e) => trait_item_to_string(e),
315 token::NtVis(ref e) => vis_to_string(e),
316 token::NtForeignItem(ref e) => foreign_item_to_string(e),
320 pub fn ty_to_string(ty: &ast::Ty) -> String {
321 to_string(|s| s.print_type(ty))
324 pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
325 to_string(|s| s.print_type_bounds("", bounds))
328 pub fn pat_to_string(pat: &ast::Pat) -> String {
329 to_string(|s| s.print_pat(pat))
332 pub fn expr_to_string(e: &ast::Expr) -> String {
333 to_string(|s| s.print_expr(e))
336 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
337 to_string(|s| s.print_tt(tt, false))
340 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
341 tokens_to_string(tts.iter().cloned().collect())
344 pub fn tokens_to_string(tokens: TokenStream) -> String {
345 to_string(|s| s.print_tts(tokens, false))
348 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
349 to_string(|s| s.print_stmt(stmt))
352 pub fn item_to_string(i: &ast::Item) -> String {
353 to_string(|s| s.print_item(i))
356 fn impl_item_to_string(i: &ast::ImplItem) -> String {
357 to_string(|s| s.print_impl_item(i))
360 fn trait_item_to_string(i: &ast::TraitItem) -> String {
361 to_string(|s| s.print_trait_item(i))
364 pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String {
365 to_string(|s| s.print_generic_params(generic_params))
368 pub fn path_to_string(p: &ast::Path) -> String {
369 to_string(|s| s.print_path(p, false, 0))
372 pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
373 to_string(|s| s.print_path_segment(p, false))
376 pub fn vis_to_string(v: &ast::Visibility) -> String {
377 to_string(|s| s.print_visibility(v))
381 fn fun_to_string(decl: &ast::FnDecl,
382 header: ast::FnHeader,
384 generics: &ast::Generics)
388 s.print_fn(decl, header, Some(name),
389 generics, &source_map::dummy_spanned(ast::VisibilityKind::Inherited));
390 s.end(); // Close the head box
391 s.end(); // Close the outer box
395 fn block_to_string(blk: &ast::Block) -> String {
397 // containing cbox, will be closed by print-block at }
399 // head-ibox, will be closed by print-block after {
405 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
406 to_string(|s| s.print_meta_list_item(li))
409 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
410 to_string(|s| s.print_meta_item(mi))
413 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
414 to_string(|s| s.print_attribute(attr))
418 fn variant_to_string(var: &ast::Variant) -> String {
419 to_string(|s| s.print_variant(var))
422 pub fn arg_to_string(arg: &ast::Arg) -> String {
423 to_string(|s| s.print_arg(arg, false))
426 fn foreign_item_to_string(arg: &ast::ForeignItem) -> String {
427 to_string(|s| s.print_foreign_item(arg))
430 fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
431 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
434 impl std::ops::Deref for State<'_> {
435 type Target = pp::Printer;
436 fn deref(&self) -> &Self::Target {
441 impl std::ops::DerefMut for State<'_> {
442 fn deref_mut(&mut self) -> &mut Self::Target {
447 pub trait PrintState<'a>: std::ops::Deref<Target=pp::Printer> + std::ops::DerefMut {
448 fn comments(&mut self) -> &mut Option<Comments<'a>>;
449 fn print_ident(&mut self, ident: ast::Ident);
450 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool);
452 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F)
453 where F: FnMut(&mut Self, &T),
456 let mut first = true;
458 if first { first = false; } else { self.word_space(","); }
464 fn maybe_print_comment(&mut self, pos: BytePos) {
465 while let Some(ref cmnt) = self.next_comment() {
467 self.print_comment(cmnt);
474 fn print_comment(&mut self,
475 cmnt: &comments::Comment) {
478 assert_eq!(cmnt.lines.len(), 1);
480 self.word(cmnt.lines[0].clone());
483 comments::Isolated => {
484 self.hardbreak_if_not_bol();
485 for line in &cmnt.lines {
486 // Don't print empty lines because they will end up as trailing
488 if !line.is_empty() {
489 self.word(line.clone());
494 comments::Trailing => {
495 if !self.is_beginning_of_line() {
498 if cmnt.lines.len() == 1 {
499 self.word(cmnt.lines[0].clone());
503 for line in &cmnt.lines {
504 if !line.is_empty() {
505 self.word(line.clone());
512 comments::BlankLine => {
513 // We need to do at least one, possibly two hardbreaks.
514 let twice = match self.last_token() {
515 pp::Token::String(s) => ";" == s,
516 pp::Token::Begin(_) => true,
517 pp::Token::End => true,
526 if let Some(cm) = self.comments() {
531 fn next_comment(&mut self) -> Option<comments::Comment> {
532 self.comments().as_mut().and_then(|c| c.next())
535 fn print_literal(&mut self, lit: &ast::Lit) {
536 self.maybe_print_comment(lit.span.lo());
537 self.word(lit.token.to_string())
540 fn print_string(&mut self, st: &str,
541 style: ast::StrStyle) {
542 let st = match style {
543 ast::StrStyle::Cooked => {
544 (format!("\"{}\"", st.escape_debug()))
546 ast::StrStyle::Raw(n) => {
547 (format!("r{delim}\"{string}\"{delim}",
548 delim="#".repeat(n as usize),
555 fn print_inner_attributes(&mut self,
556 attrs: &[ast::Attribute]) {
557 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
560 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
561 attrs: &[ast::Attribute])
563 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
566 fn print_outer_attributes(&mut self,
567 attrs: &[ast::Attribute]) {
568 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
571 fn print_inner_attributes_inline(&mut self,
572 attrs: &[ast::Attribute]) {
573 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
576 fn print_outer_attributes_inline(&mut self,
577 attrs: &[ast::Attribute]) {
578 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
581 fn print_either_attributes(&mut self,
582 attrs: &[ast::Attribute],
583 kind: ast::AttrStyle,
585 trailing_hardbreak: bool) {
588 if attr.style == kind {
589 self.print_attribute_inline(attr, is_inline);
596 if count > 0 && trailing_hardbreak && !is_inline {
597 self.hardbreak_if_not_bol();
601 fn print_attribute(&mut self, attr: &ast::Attribute) {
602 self.print_attribute_inline(attr, false)
605 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
608 self.hardbreak_if_not_bol();
610 self.maybe_print_comment(attr.span.lo());
611 if attr.is_sugared_doc {
612 self.word(attr.value_str().unwrap().as_str().to_string());
616 ast::AttrStyle::Inner => self.word("#!["),
617 ast::AttrStyle::Outer => self.word("#["),
620 match attr.tokens.trees().next() {
621 Some(TokenTree::Delimited(_, delim, tts)) => {
622 self.print_mac_common(
623 Some(&attr.path), false, None, delim, tts, true, attr.span
627 self.print_path(&attr.path, false, 0);
630 self.print_tts(attr.tokens.clone(), true);
639 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) {
641 ast::NestedMetaItem::MetaItem(ref mi) => {
642 self.print_meta_item(mi)
644 ast::NestedMetaItem::Literal(ref lit) => {
645 self.print_literal(lit)
650 fn print_meta_item(&mut self, item: &ast::MetaItem) {
651 self.ibox(INDENT_UNIT);
653 ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
654 ast::MetaItemKind::NameValue(ref value) => {
655 self.print_path(&item.path, false, 0);
657 self.word_space("=");
658 self.print_literal(value);
660 ast::MetaItemKind::List(ref items) => {
661 self.print_path(&item.path, false, 0);
663 self.commasep(Consistent,
665 |s, i| s.print_meta_list_item(i));
672 /// This doesn't deserve to be called "pretty" printing, but it should be
673 /// meaning-preserving. A quick hack that might help would be to look at the
674 /// spans embedded in the TTs to decide where to put spaces and newlines.
675 /// But it'd be better to parse these according to the grammar of the
676 /// appropriate macro, transcribe back into the grammar we just parsed from,
677 /// and then pretty-print the resulting AST nodes (so, e.g., we print
678 /// expression arguments as expressions). It can be done! I think.
679 fn print_tt(&mut self, tt: tokenstream::TokenTree, convert_dollar_crate: bool) {
681 TokenTree::Token(ref token) => {
682 self.word(token_to_string_ext(&token, convert_dollar_crate));
684 token::DocComment(..) => {
690 TokenTree::Delimited(dspan, delim, tts) => {
691 self.print_mac_common(
692 None, false, None, delim, tts, convert_dollar_crate, dspan.entire()
698 fn print_tts(&mut self, tts: tokenstream::TokenStream, convert_dollar_crate: bool) {
699 for (i, tt) in tts.into_trees().enumerate() {
703 self.print_tt(tt, convert_dollar_crate);
709 path: Option<&ast::Path>,
711 ident: Option<ast::Ident>,
714 convert_dollar_crate: bool,
717 if delim == DelimToken::Brace {
718 self.cbox(INDENT_UNIT);
720 if let Some(path) = path {
721 self.print_path(path, false, 0);
726 if let Some(ident) = ident {
728 self.print_ident(ident);
731 DelimToken::Brace => {
732 if path.is_some() || has_bang || ident.is_some() {
740 _ => self.word(token_kind_to_string(&token::OpenDelim(delim))),
743 self.print_tts(tts, convert_dollar_crate);
746 DelimToken::Brace => self.bclose(span),
747 _ => self.word(token_kind_to_string(&token::CloseDelim(delim))),
751 fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
752 self.maybe_print_comment(path.span.lo());
754 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
758 self.print_path_segment(segment, colons_before_params);
762 fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
763 if segment.ident.name != kw::PathRoot {
764 self.print_ident(segment.ident);
765 if let Some(ref args) = segment.args {
766 self.print_generic_args(args, colons_before_params);
771 fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
773 // outer-box is consistent
774 self.cbox(INDENT_UNIT);
775 // head-box is inconsistent
776 self.ibox(w.len() + 1);
777 // keyword that starts the head
783 fn bopen(&mut self) {
785 self.end(); // close the head-box
788 fn bclose_maybe_open(&mut self, span: syntax_pos::Span, close_box: bool) {
789 self.maybe_print_comment(span.hi());
790 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
793 self.end(); // close the outer-box
797 fn bclose(&mut self, span: syntax_pos::Span) {
798 self.bclose_maybe_open(span, true)
801 fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
802 if !self.is_beginning_of_line() {
803 self.break_offset(n, off)
805 if off != 0 && self.last_token().is_hardbreak_tok() {
806 // We do something pretty sketchy here: tuck the nonzero
807 // offset-adjustment we were going to deposit along with the
808 // break into the previous hardbreak.
809 self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
815 impl<'a> PrintState<'a> for State<'a> {
816 fn comments(&mut self) -> &mut Option<Comments<'a>> {
820 fn print_ident(&mut self, ident: ast::Ident) {
821 self.s.word(ast_ident_to_string(ident, ident.is_raw_guess()));
822 self.ann.post(self, AnnNode::Ident(&ident))
825 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
826 if colons_before_params {
831 ast::GenericArgs::AngleBracketed(ref data) => {
834 self.commasep(Inconsistent, &data.args, |s, generic_arg| {
835 s.print_generic_arg(generic_arg)
838 let mut comma = data.args.len() != 0;
840 for constraint in data.constraints.iter() {
844 self.print_ident(constraint.ident);
846 match constraint.kind {
847 ast::AssocTyConstraintKind::Equality { ref ty } => {
848 self.word_space("=");
851 ast::AssocTyConstraintKind::Bound { ref bounds } => {
852 self.print_type_bounds(":", &*bounds);
861 ast::GenericArgs::Parenthesized(ref data) => {
866 |s, ty| s.print_type(ty));
869 if let Some(ref ty) = data.output {
870 self.space_if_not_bol();
871 self.word_space("->");
880 // Synthesizes a comment that was not textually present in the original source
882 pub fn synth_comment(&mut self, text: String) {
892 crate fn commasep_cmnt<T, F, G>(&mut self,
896 mut get_span: G) where
897 F: FnMut(&mut State<'_>, &T),
898 G: FnMut(&T) -> syntax_pos::Span,
901 let len = elts.len();
904 self.maybe_print_comment(get_span(elt).hi());
909 self.maybe_print_trailing_comment(get_span(elt),
910 Some(get_span(&elts[i]).hi()));
911 self.space_if_not_bol();
917 crate fn commasep_exprs(&mut self, b: Breaks,
918 exprs: &[P<ast::Expr>]) {
919 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
922 crate fn print_mod(&mut self, _mod: &ast::Mod,
923 attrs: &[ast::Attribute]) {
924 self.print_inner_attributes(attrs);
925 for item in &_mod.items {
926 self.print_item(item);
930 crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
931 attrs: &[ast::Attribute]) {
932 self.print_inner_attributes(attrs);
933 for item in &nmod.items {
934 self.print_foreign_item(item);
938 crate fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
939 if let Some(lt) = *lifetime {
940 self.print_lifetime(lt);
945 crate fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
947 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
948 GenericArg::Type(ty) => self.print_type(ty),
949 GenericArg::Const(ct) => self.print_expr(&ct.value),
953 crate fn print_type(&mut self, ty: &ast::Ty) {
954 self.maybe_print_comment(ty.span.lo());
957 ast::TyKind::Slice(ref ty) => {
962 ast::TyKind::Ptr(ref mt) => {
965 ast::Mutability::Mutable => self.word_nbsp("mut"),
966 ast::Mutability::Immutable => self.word_nbsp("const"),
968 self.print_type(&mt.ty);
970 ast::TyKind::Rptr(ref lifetime, ref mt) => {
972 self.print_opt_lifetime(lifetime);
975 ast::TyKind::Never => {
978 ast::TyKind::Tup(ref elts) => {
980 self.commasep(Inconsistent, &elts[..],
981 |s, ty| s.print_type(ty));
987 ast::TyKind::Paren(ref typ) => {
989 self.print_type(typ);
992 ast::TyKind::BareFn(ref f) => {
993 self.print_ty_fn(f.abi,
999 ast::TyKind::Path(None, ref path) => {
1000 self.print_path(path, false, 0);
1002 ast::TyKind::Path(Some(ref qself), ref path) => {
1003 self.print_qpath(path, qself, false)
1005 ast::TyKind::TraitObject(ref bounds, syntax) => {
1006 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
1007 self.print_type_bounds(prefix, &bounds[..]);
1009 ast::TyKind::ImplTrait(_, ref bounds) => {
1010 self.print_type_bounds("impl", &bounds[..]);
1012 ast::TyKind::Array(ref ty, ref length) => {
1014 self.print_type(ty);
1016 self.print_expr(&length.value);
1019 ast::TyKind::Typeof(ref e) => {
1020 self.s.word("typeof(");
1021 self.print_expr(&e.value);
1024 ast::TyKind::Infer => {
1027 ast::TyKind::Err => {
1029 self.s.word("/*ERROR*/");
1032 ast::TyKind::ImplicitSelf => {
1033 self.s.word("Self");
1035 ast::TyKind::Mac(ref m) => {
1038 ast::TyKind::CVarArgs => {
1045 crate fn print_foreign_item(&mut self,
1046 item: &ast::ForeignItem) {
1047 self.hardbreak_if_not_bol();
1048 self.maybe_print_comment(item.span.lo());
1049 self.print_outer_attributes(&item.attrs);
1051 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1053 self.print_fn(decl, ast::FnHeader::default(),
1055 generics, &item.vis);
1056 self.end(); // end head-ibox
1058 self.end(); // end the outer fn box
1060 ast::ForeignItemKind::Static(ref t, m) => {
1061 self.head(visibility_qualified(&item.vis, "static"));
1062 if m == ast::Mutability::Mutable {
1063 self.word_space("mut");
1065 self.print_ident(item.ident);
1066 self.word_space(":");
1069 self.end(); // end the head-ibox
1070 self.end(); // end the outer cbox
1072 ast::ForeignItemKind::Ty => {
1073 self.head(visibility_qualified(&item.vis, "type"));
1074 self.print_ident(item.ident);
1076 self.end(); // end the head-ibox
1077 self.end(); // end the outer cbox
1079 ast::ForeignItemKind::Macro(ref m) => {
1081 match m.node.delim {
1082 MacDelimiter::Brace => {},
1083 _ => self.s.word(";")
1089 fn print_associated_const(&mut self,
1092 default: Option<&ast::Expr>,
1093 vis: &ast::Visibility)
1095 self.s.word(visibility_qualified(vis, ""));
1096 self.word_space("const");
1097 self.print_ident(ident);
1098 self.word_space(":");
1099 self.print_type(ty);
1100 if let Some(expr) = default {
1102 self.word_space("=");
1103 self.print_expr(expr);
1108 fn print_associated_type(&mut self,
1110 bounds: Option<&ast::GenericBounds>,
1111 ty: Option<&ast::Ty>)
1113 self.word_space("type");
1114 self.print_ident(ident);
1115 if let Some(bounds) = bounds {
1116 self.print_type_bounds(":", bounds);
1118 if let Some(ty) = ty {
1120 self.word_space("=");
1121 self.print_type(ty);
1126 /// Pretty-print an item
1127 crate fn print_item(&mut self, item: &ast::Item) {
1128 self.hardbreak_if_not_bol();
1129 self.maybe_print_comment(item.span.lo());
1130 self.print_outer_attributes(&item.attrs);
1131 self.ann.pre(self, AnnNode::Item(item));
1133 ast::ItemKind::ExternCrate(orig_name) => {
1134 self.head(visibility_qualified(&item.vis, "extern crate"));
1135 if let Some(orig_name) = orig_name {
1136 self.print_name(orig_name);
1141 self.print_ident(item.ident);
1143 self.end(); // end inner head-block
1144 self.end(); // end outer head-block
1146 ast::ItemKind::Use(ref tree) => {
1147 self.head(visibility_qualified(&item.vis, "use"));
1148 self.print_use_tree(tree);
1150 self.end(); // end inner head-block
1151 self.end(); // end outer head-block
1153 ast::ItemKind::Static(ref ty, m, ref expr) => {
1154 self.head(visibility_qualified(&item.vis, "static"));
1155 if m == ast::Mutability::Mutable {
1156 self.word_space("mut");
1158 self.print_ident(item.ident);
1159 self.word_space(":");
1160 self.print_type(ty);
1162 self.end(); // end the head-ibox
1164 self.word_space("=");
1165 self.print_expr(expr);
1167 self.end(); // end the outer cbox
1169 ast::ItemKind::Const(ref ty, ref expr) => {
1170 self.head(visibility_qualified(&item.vis, "const"));
1171 self.print_ident(item.ident);
1172 self.word_space(":");
1173 self.print_type(ty);
1175 self.end(); // end the head-ibox
1177 self.word_space("=");
1178 self.print_expr(expr);
1180 self.end(); // end the outer cbox
1182 ast::ItemKind::Fn(ref decl, header, ref param_names, ref body) => {
1192 self.print_block_with_attrs(body, &item.attrs);
1194 ast::ItemKind::Mod(ref _mod) => {
1195 self.head(visibility_qualified(&item.vis, "mod"));
1196 self.print_ident(item.ident);
1198 if _mod.inline || self.is_expanded {
1201 self.print_mod(_mod, &item.attrs);
1202 self.bclose(item.span);
1205 self.end(); // end inner head-block
1206 self.end(); // end outer head-block
1210 ast::ItemKind::ForeignMod(ref nmod) => {
1211 self.head("extern");
1212 self.word_nbsp(nmod.abi.to_string());
1214 self.print_foreign_mod(nmod, &item.attrs);
1215 self.bclose(item.span);
1217 ast::ItemKind::GlobalAsm(ref ga) => {
1218 self.head(visibility_qualified(&item.vis, "global_asm!"));
1219 self.s.word(ga.asm.as_str().to_string());
1222 ast::ItemKind::Ty(ref ty, ref generics) => {
1223 self.head(visibility_qualified(&item.vis, "type"));
1224 self.print_ident(item.ident);
1225 self.print_generic_params(&generics.params);
1226 self.end(); // end the inner ibox
1228 self.print_where_clause(&generics.where_clause);
1230 self.word_space("=");
1231 self.print_type(ty);
1233 self.end(); // end the outer ibox
1235 ast::ItemKind::Existential(ref bounds, ref generics) => {
1236 self.head(visibility_qualified(&item.vis, "existential type"));
1237 self.print_ident(item.ident);
1238 self.print_generic_params(&generics.params);
1239 self.end(); // end the inner ibox
1241 self.print_where_clause(&generics.where_clause);
1243 self.print_type_bounds(":", bounds);
1245 self.end(); // end the outer ibox
1247 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1248 self.print_enum_def(
1256 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1257 self.head(visibility_qualified(&item.vis, "struct"));
1258 self.print_struct(struct_def, generics, item.ident, item.span, true);
1260 ast::ItemKind::Union(ref struct_def, ref generics) => {
1261 self.head(visibility_qualified(&item.vis, "union"));
1262 self.print_struct(struct_def, generics, item.ident, item.span, true);
1264 ast::ItemKind::Impl(unsafety,
1270 ref impl_items) => {
1272 self.print_visibility(&item.vis);
1273 self.print_defaultness(defaultness);
1274 self.print_unsafety(unsafety);
1275 self.word_nbsp("impl");
1277 if !generics.params.is_empty() {
1278 self.print_generic_params(&generics.params);
1282 if polarity == ast::ImplPolarity::Negative {
1286 if let Some(ref t) = *opt_trait {
1287 self.print_trait_ref(t);
1289 self.word_space("for");
1292 self.print_type(ty);
1293 self.print_where_clause(&generics.where_clause);
1297 self.print_inner_attributes(&item.attrs);
1298 for impl_item in impl_items {
1299 self.print_impl_item(impl_item);
1301 self.bclose(item.span);
1303 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1305 self.print_visibility(&item.vis);
1306 self.print_unsafety(unsafety);
1307 self.print_is_auto(is_auto);
1308 self.word_nbsp("trait");
1309 self.print_ident(item.ident);
1310 self.print_generic_params(&generics.params);
1311 let mut real_bounds = Vec::with_capacity(bounds.len());
1312 for b in bounds.iter() {
1313 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1315 self.word_space("for ?");
1316 self.print_trait_ref(&ptr.trait_ref);
1318 real_bounds.push(b.clone());
1321 self.print_type_bounds(":", &real_bounds[..]);
1322 self.print_where_clause(&generics.where_clause);
1325 for trait_item in trait_items {
1326 self.print_trait_item(trait_item);
1328 self.bclose(item.span);
1330 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1332 self.print_visibility(&item.vis);
1333 self.word_nbsp("trait");
1334 self.print_ident(item.ident);
1335 self.print_generic_params(&generics.params);
1336 let mut real_bounds = Vec::with_capacity(bounds.len());
1337 // FIXME(durka) this seems to be some quite outdated syntax
1338 for b in bounds.iter() {
1339 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1341 self.word_space("for ?");
1342 self.print_trait_ref(&ptr.trait_ref);
1344 real_bounds.push(b.clone());
1348 self.print_type_bounds("=", &real_bounds[..]);
1349 self.print_where_clause(&generics.where_clause);
1352 ast::ItemKind::Mac(ref mac) => {
1353 self.print_mac(mac);
1354 match mac.node.delim {
1355 MacDelimiter::Brace => {}
1356 _ => self.s.word(";"),
1359 ast::ItemKind::MacroDef(ref macro_def) => {
1360 self.print_mac_common(
1361 Some(&ast::Path::from_ident(ast::Ident::with_empty_ctxt(sym::macro_rules))),
1371 self.ann.post(self, AnnNode::Item(item))
1374 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1375 self.print_path(&t.path, false, 0)
1378 fn print_formal_generic_params(
1380 generic_params: &[ast::GenericParam]
1382 if !generic_params.is_empty() {
1384 self.print_generic_params(generic_params);
1389 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1390 self.print_formal_generic_params(&t.bound_generic_params);
1391 self.print_trait_ref(&t.trait_ref)
1394 crate fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1395 generics: &ast::Generics, ident: ast::Ident,
1396 span: syntax_pos::Span,
1397 visibility: &ast::Visibility) {
1398 self.head(visibility_qualified(visibility, "enum"));
1399 self.print_ident(ident);
1400 self.print_generic_params(&generics.params);
1401 self.print_where_clause(&generics.where_clause);
1403 self.print_variants(&enum_definition.variants, span)
1406 crate fn print_variants(&mut self,
1407 variants: &[ast::Variant],
1408 span: syntax_pos::Span) {
1411 self.space_if_not_bol();
1412 self.maybe_print_comment(v.span.lo());
1413 self.print_outer_attributes(&v.node.attrs);
1414 self.ibox(INDENT_UNIT);
1415 self.print_variant(v);
1418 self.maybe_print_trailing_comment(v.span, None);
1423 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1425 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1426 ast::VisibilityKind::Crate(sugar) => match sugar {
1427 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1428 ast::CrateSugar::JustCrate => self.word_nbsp("crate")
1430 ast::VisibilityKind::Restricted { ref path, .. } => {
1431 let path = to_string(|s| s.print_path(path, false, 0));
1432 if path == "self" || path == "super" {
1433 self.word_nbsp(format!("pub({})", path))
1435 self.word_nbsp(format!("pub(in {})", path))
1438 ast::VisibilityKind::Inherited => {}
1442 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1443 if let ast::Defaultness::Default = defaultness {
1444 self.word_nbsp("default");
1448 crate fn print_struct(&mut self,
1449 struct_def: &ast::VariantData,
1450 generics: &ast::Generics,
1452 span: syntax_pos::Span,
1453 print_finalizer: bool) {
1454 self.print_ident(ident);
1455 self.print_generic_params(&generics.params);
1457 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1458 if let ast::VariantData::Tuple(..) = struct_def {
1461 Inconsistent, struct_def.fields(),
1463 s.maybe_print_comment(field.span.lo());
1464 s.print_outer_attributes(&field.attrs);
1465 s.print_visibility(&field.vis);
1466 s.print_type(&field.ty)
1471 self.print_where_clause(&generics.where_clause);
1472 if print_finalizer {
1476 self.end(); // close the outer-box
1478 ast::VariantData::Struct(..) => {
1479 self.print_where_clause(&generics.where_clause);
1482 self.hardbreak_if_not_bol();
1484 for field in struct_def.fields() {
1485 self.hardbreak_if_not_bol();
1486 self.maybe_print_comment(field.span.lo());
1487 self.print_outer_attributes(&field.attrs);
1488 self.print_visibility(&field.vis);
1489 self.print_ident(field.ident.unwrap());
1490 self.word_nbsp(":");
1491 self.print_type(&field.ty);
1500 crate fn print_variant(&mut self, v: &ast::Variant) {
1502 let generics = ast::Generics::default();
1503 self.print_struct(&v.node.data, &generics, v.node.ident, v.span, false);
1504 match v.node.disr_expr {
1507 self.word_space("=");
1508 self.print_expr(&d.value)
1514 crate fn print_method_sig(&mut self,
1516 generics: &ast::Generics,
1518 vis: &ast::Visibility)
1520 self.print_fn(&m.decl,
1527 crate fn print_trait_item(&mut self, ti: &ast::TraitItem)
1529 self.ann.pre(self, AnnNode::SubItem(ti.id));
1530 self.hardbreak_if_not_bol();
1531 self.maybe_print_comment(ti.span.lo());
1532 self.print_outer_attributes(&ti.attrs);
1534 ast::TraitItemKind::Const(ref ty, ref default) => {
1535 self.print_associated_const(
1538 default.as_ref().map(|expr| &**expr),
1539 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1542 ast::TraitItemKind::Method(ref sig, ref body) => {
1546 self.print_method_sig(
1550 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1552 if let Some(ref body) = *body {
1554 self.print_block_with_attrs(body, &ti.attrs);
1559 ast::TraitItemKind::Type(ref bounds, ref default) => {
1560 self.print_associated_type(ti.ident, Some(bounds),
1561 default.as_ref().map(|ty| &**ty));
1563 ast::TraitItemKind::Macro(ref mac) => {
1564 self.print_mac(mac);
1565 match mac.node.delim {
1566 MacDelimiter::Brace => {}
1567 _ => self.s.word(";"),
1571 self.ann.post(self, AnnNode::SubItem(ti.id))
1574 crate fn print_impl_item(&mut self, ii: &ast::ImplItem) {
1575 self.ann.pre(self, AnnNode::SubItem(ii.id));
1576 self.hardbreak_if_not_bol();
1577 self.maybe_print_comment(ii.span.lo());
1578 self.print_outer_attributes(&ii.attrs);
1579 self.print_defaultness(ii.defaultness);
1581 ast::ImplItemKind::Const(ref ty, ref expr) => {
1582 self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis);
1584 ast::ImplItemKind::Method(ref sig, ref body) => {
1586 self.print_method_sig(ii.ident, &ii.generics, sig, &ii.vis);
1588 self.print_block_with_attrs(body, &ii.attrs);
1590 ast::ImplItemKind::Type(ref ty) => {
1591 self.print_associated_type(ii.ident, None, Some(ty));
1593 ast::ImplItemKind::Existential(ref bounds) => {
1594 self.word_space("existential");
1595 self.print_associated_type(ii.ident, Some(bounds), None);
1597 ast::ImplItemKind::Macro(ref mac) => {
1598 self.print_mac(mac);
1599 match mac.node.delim {
1600 MacDelimiter::Brace => {}
1601 _ => self.s.word(";"),
1605 self.ann.post(self, AnnNode::SubItem(ii.id))
1608 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1609 self.maybe_print_comment(st.span.lo());
1611 ast::StmtKind::Local(ref loc) => {
1612 self.print_outer_attributes(&loc.attrs);
1613 self.space_if_not_bol();
1614 self.ibox(INDENT_UNIT);
1615 self.word_nbsp("let");
1617 self.ibox(INDENT_UNIT);
1618 self.print_local_decl(loc);
1620 if let Some(ref init) = loc.init {
1622 self.word_space("=");
1623 self.print_expr(init);
1628 ast::StmtKind::Item(ref item) => self.print_item(item),
1629 ast::StmtKind::Expr(ref expr) => {
1630 self.space_if_not_bol();
1631 self.print_expr_outer_attr_style(expr, false);
1632 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1636 ast::StmtKind::Semi(ref expr) => {
1637 self.space_if_not_bol();
1638 self.print_expr_outer_attr_style(expr, false);
1641 ast::StmtKind::Mac(ref mac) => {
1642 let (ref mac, style, ref attrs) = **mac;
1643 self.space_if_not_bol();
1644 self.print_outer_attributes(attrs);
1645 self.print_mac(mac);
1646 if style == ast::MacStmtStyle::Semicolon {
1651 self.maybe_print_trailing_comment(st.span, None)
1654 crate fn print_block(&mut self, blk: &ast::Block) {
1655 self.print_block_with_attrs(blk, &[])
1658 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1659 self.print_block_maybe_unclosed(blk, &[], false)
1662 crate fn print_block_with_attrs(&mut self,
1664 attrs: &[ast::Attribute]) {
1665 self.print_block_maybe_unclosed(blk, attrs, true)
1668 crate fn print_block_maybe_unclosed(&mut self,
1670 attrs: &[ast::Attribute],
1673 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1674 BlockCheckMode::Default => ()
1676 self.maybe_print_comment(blk.span.lo());
1677 self.ann.pre(self, AnnNode::Block(blk));
1680 self.print_inner_attributes(attrs);
1682 for (i, st) in blk.stmts.iter().enumerate() {
1684 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1685 self.maybe_print_comment(st.span.lo());
1686 self.space_if_not_bol();
1687 self.print_expr_outer_attr_style(expr, false);
1688 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1690 _ => self.print_stmt(st),
1694 self.bclose_maybe_open(blk.span, close_box);
1695 self.ann.post(self, AnnNode::Block(blk))
1698 /// Print a `let pats = scrutinee` expression.
1699 crate fn print_let(&mut self, pats: &[P<ast::Pat>], scrutinee: &ast::Expr) {
1700 self.s.word("let ");
1702 self.print_pats(pats);
1705 self.word_space("=");
1706 self.print_expr_cond_paren(
1708 Self::cond_needs_par(scrutinee)
1709 || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order())
1713 fn print_else(&mut self, els: Option<&ast::Expr>) {
1717 // Another `else if` block.
1718 ast::ExprKind::If(ref i, ref then, ref e) => {
1719 self.cbox(INDENT_UNIT - 1);
1721 self.s.word(" else if ");
1722 self.print_expr_as_cond(i);
1724 self.print_block(then);
1725 self.print_else(e.as_ref().map(|e| &**e))
1727 // Final `else` block.
1728 ast::ExprKind::Block(ref b, _) => {
1729 self.cbox(INDENT_UNIT - 1);
1731 self.s.word(" else ");
1734 // Constraints would be great here!
1736 panic!("print_if saw if with weird alternative");
1744 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1745 elseopt: Option<&ast::Expr>) {
1748 self.print_expr_as_cond(test);
1751 self.print_block(blk);
1752 self.print_else(elseopt)
1755 crate fn print_mac(&mut self, m: &ast::Mac) {
1756 self.print_mac_common(
1757 Some(&m.node.path), true, None, m.node.delim.to_token(), m.node.stream(), true, m.span
1761 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1763 self.commasep_exprs(Inconsistent, args);
1767 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1768 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1771 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1772 /// `if cond { ... }`.
1773 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1774 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1777 /// Does `expr` need parenthesis when printed in a condition position?
1778 fn cond_needs_par(expr: &ast::Expr) -> bool {
1780 // These cases need parens due to the parse error observed in #26461: `if return {}`
1781 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1782 ast::ExprKind::Closure(..) |
1783 ast::ExprKind::Ret(..) |
1784 ast::ExprKind::Break(..) => true,
1786 _ => parser::contains_exterior_struct_lit(expr),
1790 /// Print `expr` or `(expr)` when `needs_par` holds.
1791 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1795 self.print_expr(expr);
1801 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1802 attrs: &[Attribute]) {
1803 self.ibox(INDENT_UNIT);
1805 self.print_inner_attributes_inline(attrs);
1806 self.commasep_exprs(Inconsistent, &exprs[..]);
1811 fn print_expr_repeat(&mut self,
1812 element: &ast::Expr,
1813 count: &ast::AnonConst,
1814 attrs: &[Attribute]) {
1815 self.ibox(INDENT_UNIT);
1817 self.print_inner_attributes_inline(attrs);
1818 self.print_expr(element);
1819 self.word_space(";");
1820 self.print_expr(&count.value);
1825 fn print_expr_struct(&mut self,
1827 fields: &[ast::Field],
1828 wth: &Option<P<ast::Expr>>,
1829 attrs: &[Attribute]) {
1830 self.print_path(path, true, 0);
1832 self.print_inner_attributes_inline(attrs);
1837 s.ibox(INDENT_UNIT);
1838 if !field.is_shorthand {
1839 s.print_ident(field.ident);
1842 s.print_expr(&field.expr);
1848 self.ibox(INDENT_UNIT);
1849 if !fields.is_empty() {
1854 self.print_expr(expr);
1857 _ => if !fields.is_empty() {
1864 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1865 attrs: &[Attribute]) {
1867 self.print_inner_attributes_inline(attrs);
1868 self.commasep_exprs(Inconsistent, &exprs[..]);
1869 if exprs.len() == 1 {
1875 fn print_expr_call(&mut self,
1877 args: &[P<ast::Expr>]) {
1880 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1881 _ => parser::PREC_POSTFIX,
1884 self.print_expr_maybe_paren(func, prec);
1885 self.print_call_post(args)
1888 fn print_expr_method_call(&mut self,
1889 segment: &ast::PathSegment,
1890 args: &[P<ast::Expr>]) {
1891 let base_args = &args[1..];
1892 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1894 self.print_ident(segment.ident);
1895 if let Some(ref args) = segment.args {
1896 self.print_generic_args(args, true);
1898 self.print_call_post(base_args)
1901 fn print_expr_binary(&mut self,
1905 let assoc_op = AssocOp::from_ast_binop(op.node);
1906 let prec = assoc_op.precedence() as i8;
1907 let fixity = assoc_op.fixity();
1909 let (left_prec, right_prec) = match fixity {
1910 Fixity::Left => (prec, prec + 1),
1911 Fixity::Right => (prec + 1, prec),
1912 Fixity::None => (prec + 1, prec + 1),
1915 let left_prec = match (&lhs.node, op.node) {
1916 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1917 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1918 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1919 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) |
1920 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1921 // We are given `(let _ = a) OP b`.
1923 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1924 // as the parser will interpret this as `(let _ = a) OP b`.
1926 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1927 // parens are required since the parser would interpret `let a = b < c` as
1928 // `let a = (b < c)`. To achieve this, we force parens.
1929 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1930 parser::PREC_FORCE_PAREN
1935 self.print_expr_maybe_paren(lhs, left_prec);
1937 self.word_space(op.node.to_string());
1938 self.print_expr_maybe_paren(rhs, right_prec)
1941 fn print_expr_unary(&mut self,
1944 self.s.word(ast::UnOp::to_string(op));
1945 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1948 fn print_expr_addr_of(&mut self,
1949 mutability: ast::Mutability,
1952 self.print_mutability(mutability);
1953 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1956 crate fn print_expr(&mut self, expr: &ast::Expr) {
1957 self.print_expr_outer_attr_style(expr, true)
1960 fn print_expr_outer_attr_style(&mut self,
1963 self.maybe_print_comment(expr.span.lo());
1965 let attrs = &expr.attrs;
1967 self.print_outer_attributes_inline(attrs);
1969 self.print_outer_attributes(attrs);
1972 self.ibox(INDENT_UNIT);
1973 self.ann.pre(self, AnnNode::Expr(expr));
1975 ast::ExprKind::Box(ref expr) => {
1976 self.word_space("box");
1977 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1979 ast::ExprKind::Array(ref exprs) => {
1980 self.print_expr_vec(&exprs[..], attrs);
1982 ast::ExprKind::Repeat(ref element, ref count) => {
1983 self.print_expr_repeat(element, count, attrs);
1985 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
1986 self.print_expr_struct(path, &fields[..], wth, attrs);
1988 ast::ExprKind::Tup(ref exprs) => {
1989 self.print_expr_tup(&exprs[..], attrs);
1991 ast::ExprKind::Call(ref func, ref args) => {
1992 self.print_expr_call(func, &args[..]);
1994 ast::ExprKind::MethodCall(ref segment, ref args) => {
1995 self.print_expr_method_call(segment, &args[..]);
1997 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1998 self.print_expr_binary(op, lhs, rhs);
2000 ast::ExprKind::Unary(op, ref expr) => {
2001 self.print_expr_unary(op, expr);
2003 ast::ExprKind::AddrOf(m, ref expr) => {
2004 self.print_expr_addr_of(m, expr);
2006 ast::ExprKind::Lit(ref lit) => {
2007 self.print_literal(lit);
2009 ast::ExprKind::Cast(ref expr, ref ty) => {
2010 let prec = AssocOp::As.precedence() as i8;
2011 self.print_expr_maybe_paren(expr, prec);
2013 self.word_space("as");
2014 self.print_type(ty);
2016 ast::ExprKind::Type(ref expr, ref ty) => {
2017 let prec = AssocOp::Colon.precedence() as i8;
2018 self.print_expr_maybe_paren(expr, prec);
2019 self.word_space(":");
2020 self.print_type(ty);
2022 ast::ExprKind::Let(ref pats, ref scrutinee) => {
2023 self.print_let(pats, scrutinee);
2025 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2026 self.print_if(test, blk, elseopt.as_ref().map(|e| &**e));
2028 ast::ExprKind::While(ref test, ref blk, opt_label) => {
2029 if let Some(label) = opt_label {
2030 self.print_ident(label.ident);
2031 self.word_space(":");
2034 self.print_expr_as_cond(test);
2036 self.print_block_with_attrs(blk, attrs);
2038 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2039 if let Some(label) = opt_label {
2040 self.print_ident(label.ident);
2041 self.word_space(":");
2044 self.print_pat(pat);
2046 self.word_space("in");
2047 self.print_expr_as_cond(iter);
2049 self.print_block_with_attrs(blk, attrs);
2051 ast::ExprKind::Loop(ref blk, opt_label) => {
2052 if let Some(label) = opt_label {
2053 self.print_ident(label.ident);
2054 self.word_space(":");
2058 self.print_block_with_attrs(blk, attrs);
2060 ast::ExprKind::Match(ref expr, ref arms) => {
2061 self.cbox(INDENT_UNIT);
2062 self.ibox(INDENT_UNIT);
2063 self.word_nbsp("match");
2064 self.print_expr_as_cond(expr);
2067 self.print_inner_attributes_no_trailing_hardbreak(attrs);
2069 self.print_arm(arm);
2071 self.bclose(expr.span);
2073 ast::ExprKind::Closure(
2074 capture_clause, asyncness, movability, ref decl, ref body, _) => {
2075 self.print_movability(movability);
2076 self.print_asyncness(asyncness);
2077 self.print_capture_clause(capture_clause);
2079 self.print_fn_block_args(decl);
2081 self.print_expr(body);
2082 self.end(); // need to close a box
2084 // a box will be closed by print_expr, but we didn't want an overall
2085 // wrapper so we closed the corresponding opening. so create an
2086 // empty box to satisfy the close.
2089 ast::ExprKind::Block(ref blk, opt_label) => {
2090 if let Some(label) = opt_label {
2091 self.print_ident(label.ident);
2092 self.word_space(":");
2094 // containing cbox, will be closed by print-block at }
2095 self.cbox(INDENT_UNIT);
2096 // head-box, will be closed by print-block after {
2098 self.print_block_with_attrs(blk, attrs);
2100 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2101 self.word_nbsp("async");
2102 self.print_capture_clause(capture_clause);
2104 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2105 self.cbox(INDENT_UNIT);
2107 self.print_block_with_attrs(blk, attrs);
2109 ast::ExprKind::Await(origin, ref expr) => {
2111 ast::AwaitOrigin::MacroLike => {
2112 self.s.word("await!");
2113 self.print_expr_maybe_paren(expr, parser::PREC_FORCE_PAREN);
2115 ast::AwaitOrigin::FieldLike => {
2116 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2117 self.s.word(".await");
2121 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2122 let prec = AssocOp::Assign.precedence() as i8;
2123 self.print_expr_maybe_paren(lhs, prec + 1);
2125 self.word_space("=");
2126 self.print_expr_maybe_paren(rhs, prec);
2128 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2129 let prec = AssocOp::Assign.precedence() as i8;
2130 self.print_expr_maybe_paren(lhs, prec + 1);
2132 self.s.word(op.node.to_string());
2133 self.word_space("=");
2134 self.print_expr_maybe_paren(rhs, prec);
2136 ast::ExprKind::Field(ref expr, ident) => {
2137 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2139 self.print_ident(ident);
2141 ast::ExprKind::Index(ref expr, ref index) => {
2142 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2144 self.print_expr(index);
2147 ast::ExprKind::Range(ref start, ref end, limits) => {
2148 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2149 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2150 // Here we use a fake precedence value so that any child with lower precedence than
2151 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2152 let fake_prec = AssocOp::LOr.precedence() as i8;
2153 if let Some(ref e) = *start {
2154 self.print_expr_maybe_paren(e, fake_prec);
2156 if limits == ast::RangeLimits::HalfOpen {
2161 if let Some(ref e) = *end {
2162 self.print_expr_maybe_paren(e, fake_prec);
2165 ast::ExprKind::Path(None, ref path) => {
2166 self.print_path(path, true, 0)
2168 ast::ExprKind::Path(Some(ref qself), ref path) => {
2169 self.print_qpath(path, qself, true)
2171 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2172 self.s.word("break");
2174 if let Some(label) = opt_label {
2175 self.print_ident(label.ident);
2178 if let Some(ref expr) = *opt_expr {
2179 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2183 ast::ExprKind::Continue(opt_label) => {
2184 self.s.word("continue");
2186 if let Some(label) = opt_label {
2187 self.print_ident(label.ident);
2191 ast::ExprKind::Ret(ref result) => {
2192 self.s.word("return");
2193 if let Some(ref expr) = *result {
2195 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2198 ast::ExprKind::InlineAsm(ref a) => {
2199 self.s.word("asm!");
2201 self.print_string(&a.asm.as_str(), a.asm_str_style);
2202 self.word_space(":");
2204 self.commasep(Inconsistent, &a.outputs, |s, out| {
2205 let constraint = out.constraint.as_str();
2206 let mut ch = constraint.chars();
2208 Some('=') if out.is_rw => {
2209 s.print_string(&format!("+{}", ch.as_str()),
2210 ast::StrStyle::Cooked)
2212 _ => s.print_string(&constraint, ast::StrStyle::Cooked)
2215 s.print_expr(&out.expr);
2219 self.word_space(":");
2221 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2222 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2228 self.word_space(":");
2230 self.commasep(Inconsistent, &a.clobbers,
2232 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2235 let mut options = vec![];
2237 options.push("volatile");
2240 options.push("alignstack");
2242 if a.dialect == ast::AsmDialect::Intel {
2243 options.push("intel");
2246 if !options.is_empty() {
2248 self.word_space(":");
2249 self.commasep(Inconsistent, &options,
2251 s.print_string(co, ast::StrStyle::Cooked);
2257 ast::ExprKind::Mac(ref m) => self.print_mac(m),
2258 ast::ExprKind::Paren(ref e) => {
2260 self.print_inner_attributes_inline(attrs);
2264 ast::ExprKind::Yield(ref e) => {
2265 self.s.word("yield");
2269 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2274 ast::ExprKind::Try(ref e) => {
2275 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2278 ast::ExprKind::TryBlock(ref blk) => {
2281 self.print_block_with_attrs(blk, attrs)
2283 ast::ExprKind::Err => {
2285 self.s.word("/*ERROR*/");
2289 self.ann.post(self, AnnNode::Expr(expr));
2293 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2294 self.print_pat(&loc.pat);
2295 if let Some(ref ty) = loc.ty {
2296 self.word_space(":");
2297 self.print_type(ty);
2301 crate fn print_usize(&mut self, i: usize) {
2302 self.s.word(i.to_string())
2305 crate fn print_name(&mut self, name: ast::Name) {
2306 self.s.word(name.as_str().to_string());
2307 self.ann.post(self, AnnNode::Name(&name))
2310 fn print_qpath(&mut self,
2313 colons_before_params: bool)
2316 self.print_type(&qself.ty);
2317 if qself.position > 0 {
2319 self.word_space("as");
2320 let depth = path.segments.len() - qself.position;
2321 self.print_path(path, false, depth);
2325 let item_segment = path.segments.last().unwrap();
2326 self.print_ident(item_segment.ident);
2327 match item_segment.args {
2328 Some(ref args) => self.print_generic_args(args, colons_before_params),
2333 crate fn print_pat(&mut self, pat: &ast::Pat) {
2334 self.maybe_print_comment(pat.span.lo());
2335 self.ann.pre(self, AnnNode::Pat(pat));
2336 /* Pat isn't normalized, but the beauty of it
2337 is that it doesn't matter */
2339 PatKind::Wild => self.s.word("_"),
2340 PatKind::Ident(binding_mode, ident, ref sub) => {
2341 match binding_mode {
2342 ast::BindingMode::ByRef(mutbl) => {
2343 self.word_nbsp("ref");
2344 self.print_mutability(mutbl);
2346 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2347 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2348 self.word_nbsp("mut");
2351 self.print_ident(ident);
2352 if let Some(ref p) = *sub {
2357 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2358 self.print_path(path, true, 0);
2360 if let Some(ddpos) = ddpos {
2361 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
2363 self.word_space(",");
2366 if ddpos != elts.len() {
2368 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
2371 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2375 PatKind::Path(None, ref path) => {
2376 self.print_path(path, true, 0);
2378 PatKind::Path(Some(ref qself), ref path) => {
2379 self.print_qpath(path, qself, false);
2381 PatKind::Struct(ref path, ref fields, etc) => {
2382 self.print_path(path, true, 0);
2384 self.word_space("{");
2386 Consistent, &fields[..],
2388 s.cbox(INDENT_UNIT);
2389 if !f.node.is_shorthand {
2390 s.print_ident(f.node.ident);
2393 s.print_pat(&f.node.pat);
2396 |f| f.node.pat.span);
2398 if !fields.is_empty() { self.word_space(","); }
2404 PatKind::Tuple(ref elts, ddpos) => {
2406 if let Some(ddpos) = ddpos {
2407 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
2409 self.word_space(",");
2412 if ddpos != elts.len() {
2414 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
2417 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2418 if elts.len() == 1 {
2424 PatKind::Box(ref inner) => {
2425 self.s.word("box ");
2426 self.print_pat(inner);
2428 PatKind::Ref(ref inner, mutbl) => {
2430 if mutbl == ast::Mutability::Mutable {
2431 self.s.word("mut ");
2433 self.print_pat(inner);
2435 PatKind::Lit(ref e) => self.print_expr(&**e),
2436 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2437 self.print_expr(begin);
2440 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("..."),
2441 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..="),
2442 RangeEnd::Excluded => self.s.word(".."),
2444 self.print_expr(end);
2446 PatKind::Slice(ref before, ref slice, ref after) => {
2448 self.commasep(Inconsistent,
2450 |s, p| s.print_pat(p));
2451 if let Some(ref p) = *slice {
2452 if !before.is_empty() { self.word_space(","); }
2453 if let PatKind::Wild = p.node {
2459 if !after.is_empty() { self.word_space(","); }
2461 self.commasep(Inconsistent,
2463 |s, p| s.print_pat(p));
2466 PatKind::Paren(ref inner) => {
2468 self.print_pat(inner);
2471 PatKind::Mac(ref m) => self.print_mac(m),
2473 self.ann.post(self, AnnNode::Pat(pat))
2476 fn print_pats(&mut self, pats: &[P<ast::Pat>]) {
2477 let mut first = true;
2483 self.word_space("|");
2489 fn print_arm(&mut self, arm: &ast::Arm) {
2490 // I have no idea why this check is necessary, but here it
2492 if arm.attrs.is_empty() {
2495 self.cbox(INDENT_UNIT);
2497 self.maybe_print_comment(arm.pats[0].span.lo());
2498 self.print_outer_attributes(&arm.attrs);
2499 self.print_pats(&arm.pats);
2501 if let Some(ref e) = arm.guard {
2502 self.word_space("if");
2506 self.word_space("=>");
2508 match arm.body.node {
2509 ast::ExprKind::Block(ref blk, opt_label) => {
2510 if let Some(label) = opt_label {
2511 self.print_ident(label.ident);
2512 self.word_space(":");
2515 // the block will close the pattern's ibox
2516 self.print_block_unclosed_indent(blk);
2518 // If it is a user-provided unsafe block, print a comma after it
2519 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2524 self.end(); // close the ibox for the pattern
2525 self.print_expr(&arm.body);
2529 self.end(); // close enclosing cbox
2532 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2533 match explicit_self.node {
2534 SelfKind::Value(m) => {
2535 self.print_mutability(m);
2538 SelfKind::Region(ref lt, m) => {
2540 self.print_opt_lifetime(lt);
2541 self.print_mutability(m);
2544 SelfKind::Explicit(ref typ, m) => {
2545 self.print_mutability(m);
2546 self.s.word("self");
2547 self.word_space(":");
2548 self.print_type(typ)
2553 crate fn print_fn(&mut self,
2555 header: ast::FnHeader,
2556 name: Option<ast::Ident>,
2557 generics: &ast::Generics,
2558 vis: &ast::Visibility) {
2559 self.print_fn_header_info(header, vis);
2561 if let Some(name) = name {
2563 self.print_ident(name);
2565 self.print_generic_params(&generics.params);
2566 self.print_fn_args_and_ret(decl);
2567 self.print_where_clause(&generics.where_clause)
2570 crate fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl) {
2572 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false));
2575 self.print_fn_output(decl)
2578 crate fn print_fn_block_args(&mut self, decl: &ast::FnDecl) {
2580 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true));
2583 if let ast::FunctionRetTy::Default(..) = decl.output {
2587 self.space_if_not_bol();
2588 self.word_space("->");
2590 ast::FunctionRetTy::Ty(ref ty) => {
2591 self.print_type(ty);
2592 self.maybe_print_comment(ty.span.lo())
2594 ast::FunctionRetTy::Default(..) => unreachable!(),
2598 crate fn print_movability(&mut self, movability: ast::Movability) {
2600 ast::Movability::Static => self.word_space("static"),
2601 ast::Movability::Movable => {},
2605 crate fn print_asyncness(&mut self, asyncness: ast::IsAsync) {
2606 if asyncness.is_async() {
2607 self.word_nbsp("async");
2611 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2612 match capture_clause {
2613 ast::CaptureBy::Value => self.word_space("move"),
2614 ast::CaptureBy::Ref => {},
2618 crate fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2619 if !bounds.is_empty() {
2620 self.s.word(prefix);
2621 let mut first = true;
2622 for bound in bounds {
2623 if !(first && prefix.is_empty()) {
2629 self.word_space("+");
2633 GenericBound::Trait(tref, modifier) => {
2634 if modifier == &TraitBoundModifier::Maybe {
2637 self.print_poly_trait_ref(tref);
2639 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2645 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2646 self.print_name(lifetime.ident.name)
2649 crate fn print_lifetime_bounds(
2650 &mut self, lifetime: ast::Lifetime, bounds: &ast::GenericBounds) {
2651 self.print_lifetime(lifetime);
2652 if !bounds.is_empty() {
2654 for (i, bound) in bounds.iter().enumerate() {
2659 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2666 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2667 if generic_params.is_empty() {
2673 self.commasep(Inconsistent, &generic_params, |s, param| {
2675 ast::GenericParamKind::Lifetime => {
2676 s.print_outer_attributes_inline(¶m.attrs);
2677 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2678 s.print_lifetime_bounds(lt, ¶m.bounds)
2680 ast::GenericParamKind::Type { ref default } => {
2681 s.print_outer_attributes_inline(¶m.attrs);
2682 s.print_ident(param.ident);
2683 s.print_type_bounds(":", ¶m.bounds);
2685 Some(ref default) => {
2688 s.print_type(default)
2693 ast::GenericParamKind::Const { ref ty } => {
2694 s.print_outer_attributes_inline(¶m.attrs);
2695 s.word_space("const");
2696 s.print_ident(param.ident);
2700 s.print_type_bounds(":", ¶m.bounds)
2708 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2709 if where_clause.predicates.is_empty() {
2714 self.word_space("where");
2716 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2718 self.word_space(",");
2722 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2723 ref bound_generic_params,
2728 self.print_formal_generic_params(bound_generic_params);
2729 self.print_type(bounded_ty);
2730 self.print_type_bounds(":", bounds);
2732 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2735 self.print_lifetime_bounds(*lifetime, bounds);
2737 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2740 self.print_type(lhs_ty);
2742 self.word_space("=");
2743 self.print_type(rhs_ty);
2749 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2751 ast::UseTreeKind::Simple(rename, ..) => {
2752 self.print_path(&tree.prefix, false, 0);
2753 if let Some(rename) = rename {
2755 self.word_space("as");
2756 self.print_ident(rename);
2759 ast::UseTreeKind::Glob => {
2760 if !tree.prefix.segments.is_empty() {
2761 self.print_path(&tree.prefix, false, 0);
2766 ast::UseTreeKind::Nested(ref items) => {
2767 if tree.prefix.segments.is_empty() {
2770 self.print_path(&tree.prefix, false, 0);
2773 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2774 this.print_use_tree(tree)
2781 crate fn print_mutability(&mut self, mutbl: ast::Mutability) {
2783 ast::Mutability::Mutable => self.word_nbsp("mut"),
2784 ast::Mutability::Immutable => {},
2788 crate fn print_mt(&mut self, mt: &ast::MutTy) {
2789 self.print_mutability(mt.mutbl);
2790 self.print_type(&mt.ty)
2793 crate fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) {
2794 self.ibox(INDENT_UNIT);
2795 match input.ty.node {
2796 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2798 if let Some(eself) = input.to_self() {
2799 self.print_explicit_self(&eself);
2801 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
2802 ident.name == kw::Invalid
2807 self.print_pat(&input.pat);
2811 self.print_type(&input.ty);
2818 crate fn print_fn_output(&mut self, decl: &ast::FnDecl) {
2819 if let ast::FunctionRetTy::Default(..) = decl.output {
2823 self.space_if_not_bol();
2824 self.ibox(INDENT_UNIT);
2825 self.word_space("->");
2827 ast::FunctionRetTy::Default(..) => unreachable!(),
2828 ast::FunctionRetTy::Ty(ref ty) =>
2829 self.print_type(ty),
2834 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo()),
2839 crate fn print_ty_fn(&mut self,
2841 unsafety: ast::Unsafety,
2843 name: Option<ast::Ident>,
2844 generic_params: &[ast::GenericParam])
2846 self.ibox(INDENT_UNIT);
2847 if !generic_params.is_empty() {
2849 self.print_generic_params(generic_params);
2851 let generics = ast::Generics {
2853 where_clause: ast::WhereClause {
2854 predicates: Vec::new(),
2855 span: syntax_pos::DUMMY_SP,
2857 span: syntax_pos::DUMMY_SP,
2860 ast::FnHeader { unsafety, abi, ..ast::FnHeader::default() },
2863 &source_map::dummy_spanned(ast::VisibilityKind::Inherited));
2867 crate fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
2868 next_pos: Option<BytePos>)
2870 if let Some(cmnts) = self.comments() {
2871 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2872 self.print_comment(&cmnt);
2877 crate fn print_remaining_comments(&mut self) {
2878 // If there aren't any remaining comments, then we need to manually
2879 // make sure there is a line break at the end.
2880 if self.next_comment().is_none() {
2883 while let Some(ref cmnt) = self.next_comment() {
2884 self.print_comment(cmnt);
2888 crate fn print_fn_header_info(&mut self,
2889 header: ast::FnHeader,
2890 vis: &ast::Visibility) {
2891 self.s.word(visibility_qualified(vis, ""));
2893 match header.constness.node {
2894 ast::Constness::NotConst => {}
2895 ast::Constness::Const => self.word_nbsp("const")
2898 self.print_asyncness(header.asyncness.node);
2899 self.print_unsafety(header.unsafety);
2901 if header.abi != Abi::Rust {
2902 self.word_nbsp("extern");
2903 self.word_nbsp(header.abi.to_string());
2909 crate fn print_unsafety(&mut self, s: ast::Unsafety) {
2911 ast::Unsafety::Normal => {},
2912 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2916 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2918 ast::IsAuto::Yes => self.word_nbsp("auto"),
2919 ast::IsAuto::No => {}
2929 use crate::source_map;
2930 use crate::with_default_globals;
2934 fn test_fun_to_string() {
2935 with_default_globals(|| {
2936 let abba_ident = ast::Ident::from_str("abba");
2938 let decl = ast::FnDecl {
2940 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
2943 let generics = ast::Generics::default();
2948 unsafety: ast::Unsafety::Normal,
2949 constness: source_map::dummy_spanned(ast::Constness::NotConst),
2950 asyncness: source_map::dummy_spanned(ast::IsAsync::NotAsync),
2962 fn test_variant_to_string() {
2963 with_default_globals(|| {
2964 let ident = ast::Ident::from_str("principal_skinner");
2966 let var = source_map::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
2969 id: ast::DUMMY_NODE_ID,
2970 // making this up as I go.... ?
2971 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
2975 let varstr = variant_to_string(&var);
2976 assert_eq!(varstr, "principal_skinner");