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 if let Some(mi) = attr.meta() {
621 self.print_meta_item(&mi);
623 match attr.tokens.trees().next() {
624 Some(TokenTree::Delimited(_, delim, tts)) => {
625 self.print_mac_common(
626 Some(&attr.path), false, None, delim, tts, true, attr.span
630 self.print_path(&attr.path, false, 0);
633 self.print_tts(attr.tokens.clone(), true);
643 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) {
645 ast::NestedMetaItem::MetaItem(ref mi) => {
646 self.print_meta_item(mi)
648 ast::NestedMetaItem::Literal(ref lit) => {
649 self.print_literal(lit)
654 fn print_meta_item(&mut self, item: &ast::MetaItem) {
655 self.ibox(INDENT_UNIT);
657 ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
658 ast::MetaItemKind::NameValue(ref value) => {
659 self.print_path(&item.path, false, 0);
661 self.word_space("=");
662 self.print_literal(value);
664 ast::MetaItemKind::List(ref items) => {
665 self.print_path(&item.path, false, 0);
667 self.commasep(Consistent,
669 |s, i| s.print_meta_list_item(i));
676 /// This doesn't deserve to be called "pretty" printing, but it should be
677 /// meaning-preserving. A quick hack that might help would be to look at the
678 /// spans embedded in the TTs to decide where to put spaces and newlines.
679 /// But it'd be better to parse these according to the grammar of the
680 /// appropriate macro, transcribe back into the grammar we just parsed from,
681 /// and then pretty-print the resulting AST nodes (so, e.g., we print
682 /// expression arguments as expressions). It can be done! I think.
683 fn print_tt(&mut self, tt: tokenstream::TokenTree, convert_dollar_crate: bool) {
685 TokenTree::Token(ref token) => {
686 self.word(token_to_string_ext(&token, convert_dollar_crate));
688 token::DocComment(..) => {
694 TokenTree::Delimited(dspan, delim, tts) => {
695 self.print_mac_common(
696 None, false, None, delim, tts, convert_dollar_crate, dspan.entire()
702 fn print_tts(&mut self, tts: tokenstream::TokenStream, convert_dollar_crate: bool) {
703 for (i, tt) in tts.into_trees().enumerate() {
707 self.print_tt(tt, convert_dollar_crate);
713 path: Option<&ast::Path>,
715 ident: Option<ast::Ident>,
718 convert_dollar_crate: bool,
721 if let Some(path) = path {
722 self.print_path(path, false, 0);
727 if let Some(ident) = ident {
729 self.print_ident(ident);
733 DelimToken::Paren => self.popen(),
734 DelimToken::Bracket => self.word("["),
735 DelimToken::NoDelim => self.word(" "),
736 DelimToken::Brace => {
742 self.print_tts(tts, convert_dollar_crate);
745 DelimToken::Paren => self.pclose(),
746 DelimToken::Bracket => self.word("]"),
747 DelimToken::NoDelim => self.word(" "),
748 DelimToken::Brace => self.bclose(span),
752 fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
753 self.maybe_print_comment(path.span.lo());
755 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
759 self.print_path_segment(segment, colons_before_params);
763 fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
764 if segment.ident.name != kw::PathRoot {
765 self.print_ident(segment.ident);
766 if let Some(ref args) = segment.args {
767 self.print_generic_args(args, colons_before_params);
772 fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
774 // outer-box is consistent
775 self.cbox(INDENT_UNIT);
776 // head-box is inconsistent
777 self.ibox(w.len() + 1);
778 // keyword that starts the head
784 fn bopen(&mut self) {
786 self.end(); // close the head-box
789 fn bclose_maybe_open(&mut self, span: syntax_pos::Span, close_box: bool) {
790 self.maybe_print_comment(span.hi());
791 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
794 self.end(); // close the outer-box
798 fn bclose(&mut self, span: syntax_pos::Span) {
799 self.bclose_maybe_open(span, true)
802 fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
803 if !self.is_beginning_of_line() {
804 self.break_offset(n, off)
806 if off != 0 && self.last_token().is_hardbreak_tok() {
807 // We do something pretty sketchy here: tuck the nonzero
808 // offset-adjustment we were going to deposit along with the
809 // break into the previous hardbreak.
810 self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
816 impl<'a> PrintState<'a> for State<'a> {
817 fn comments(&mut self) -> &mut Option<Comments<'a>> {
821 fn print_ident(&mut self, ident: ast::Ident) {
822 self.s.word(ast_ident_to_string(ident, ident.is_raw_guess()));
823 self.ann.post(self, AnnNode::Ident(&ident))
826 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
827 if colons_before_params {
832 ast::GenericArgs::AngleBracketed(ref data) => {
835 self.commasep(Inconsistent, &data.args, |s, generic_arg| {
836 s.print_generic_arg(generic_arg)
839 let mut comma = data.args.len() != 0;
841 for constraint in data.constraints.iter() {
845 self.print_ident(constraint.ident);
847 match constraint.kind {
848 ast::AssocTyConstraintKind::Equality { ref ty } => {
849 self.word_space("=");
852 ast::AssocTyConstraintKind::Bound { ref bounds } => {
853 self.print_type_bounds(":", &*bounds);
862 ast::GenericArgs::Parenthesized(ref data) => {
867 |s, ty| s.print_type(ty));
870 if let Some(ref ty) = data.output {
871 self.space_if_not_bol();
872 self.word_space("->");
881 // Synthesizes a comment that was not textually present in the original source
883 pub fn synth_comment(&mut self, text: String) {
893 crate fn commasep_cmnt<T, F, G>(&mut self,
897 mut get_span: G) where
898 F: FnMut(&mut State<'_>, &T),
899 G: FnMut(&T) -> syntax_pos::Span,
902 let len = elts.len();
905 self.maybe_print_comment(get_span(elt).hi());
910 self.maybe_print_trailing_comment(get_span(elt),
911 Some(get_span(&elts[i]).hi()));
912 self.space_if_not_bol();
918 crate fn commasep_exprs(&mut self, b: Breaks,
919 exprs: &[P<ast::Expr>]) {
920 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
923 crate fn print_mod(&mut self, _mod: &ast::Mod,
924 attrs: &[ast::Attribute]) {
925 self.print_inner_attributes(attrs);
926 for item in &_mod.items {
927 self.print_item(item);
931 crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
932 attrs: &[ast::Attribute]) {
933 self.print_inner_attributes(attrs);
934 for item in &nmod.items {
935 self.print_foreign_item(item);
939 crate fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
940 if let Some(lt) = *lifetime {
941 self.print_lifetime(lt);
946 crate fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
948 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
949 GenericArg::Type(ty) => self.print_type(ty),
950 GenericArg::Const(ct) => self.print_expr(&ct.value),
954 crate fn print_type(&mut self, ty: &ast::Ty) {
955 self.maybe_print_comment(ty.span.lo());
958 ast::TyKind::Slice(ref ty) => {
963 ast::TyKind::Ptr(ref mt) => {
966 ast::Mutability::Mutable => self.word_nbsp("mut"),
967 ast::Mutability::Immutable => self.word_nbsp("const"),
969 self.print_type(&mt.ty);
971 ast::TyKind::Rptr(ref lifetime, ref mt) => {
973 self.print_opt_lifetime(lifetime);
976 ast::TyKind::Never => {
979 ast::TyKind::Tup(ref elts) => {
981 self.commasep(Inconsistent, &elts[..],
982 |s, ty| s.print_type(ty));
988 ast::TyKind::Paren(ref typ) => {
990 self.print_type(typ);
993 ast::TyKind::BareFn(ref f) => {
994 self.print_ty_fn(f.abi,
1000 ast::TyKind::Path(None, ref path) => {
1001 self.print_path(path, false, 0);
1003 ast::TyKind::Path(Some(ref qself), ref path) => {
1004 self.print_qpath(path, qself, false)
1006 ast::TyKind::TraitObject(ref bounds, syntax) => {
1007 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
1008 self.print_type_bounds(prefix, &bounds[..]);
1010 ast::TyKind::ImplTrait(_, ref bounds) => {
1011 self.print_type_bounds("impl", &bounds[..]);
1013 ast::TyKind::Array(ref ty, ref length) => {
1015 self.print_type(ty);
1017 self.print_expr(&length.value);
1020 ast::TyKind::Typeof(ref e) => {
1021 self.s.word("typeof(");
1022 self.print_expr(&e.value);
1025 ast::TyKind::Infer => {
1028 ast::TyKind::Err => {
1030 self.s.word("/*ERROR*/");
1033 ast::TyKind::ImplicitSelf => {
1034 self.s.word("Self");
1036 ast::TyKind::Mac(ref m) => {
1039 ast::TyKind::CVarArgs => {
1046 crate fn print_foreign_item(&mut self,
1047 item: &ast::ForeignItem) {
1048 self.hardbreak_if_not_bol();
1049 self.maybe_print_comment(item.span.lo());
1050 self.print_outer_attributes(&item.attrs);
1052 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1054 self.print_fn(decl, ast::FnHeader::default(),
1056 generics, &item.vis);
1057 self.end(); // end head-ibox
1059 self.end(); // end the outer fn box
1061 ast::ForeignItemKind::Static(ref t, m) => {
1062 self.head(visibility_qualified(&item.vis, "static"));
1063 if m == ast::Mutability::Mutable {
1064 self.word_space("mut");
1066 self.print_ident(item.ident);
1067 self.word_space(":");
1070 self.end(); // end the head-ibox
1071 self.end(); // end the outer cbox
1073 ast::ForeignItemKind::Ty => {
1074 self.head(visibility_qualified(&item.vis, "type"));
1075 self.print_ident(item.ident);
1077 self.end(); // end the head-ibox
1078 self.end(); // end the outer cbox
1080 ast::ForeignItemKind::Macro(ref m) => {
1082 match m.node.delim {
1083 MacDelimiter::Brace => {},
1084 _ => self.s.word(";")
1090 fn print_associated_const(&mut self,
1093 default: Option<&ast::Expr>,
1094 vis: &ast::Visibility)
1096 self.s.word(visibility_qualified(vis, ""));
1097 self.word_space("const");
1098 self.print_ident(ident);
1099 self.word_space(":");
1100 self.print_type(ty);
1101 if let Some(expr) = default {
1103 self.word_space("=");
1104 self.print_expr(expr);
1109 fn print_associated_type(&mut self,
1111 bounds: Option<&ast::GenericBounds>,
1112 ty: Option<&ast::Ty>)
1114 self.word_space("type");
1115 self.print_ident(ident);
1116 if let Some(bounds) = bounds {
1117 self.print_type_bounds(":", bounds);
1119 if let Some(ty) = ty {
1121 self.word_space("=");
1122 self.print_type(ty);
1127 /// Pretty-print an item
1128 crate fn print_item(&mut self, item: &ast::Item) {
1129 self.hardbreak_if_not_bol();
1130 self.maybe_print_comment(item.span.lo());
1131 self.print_outer_attributes(&item.attrs);
1132 self.ann.pre(self, AnnNode::Item(item));
1134 ast::ItemKind::ExternCrate(orig_name) => {
1135 self.head(visibility_qualified(&item.vis, "extern crate"));
1136 if let Some(orig_name) = orig_name {
1137 self.print_name(orig_name);
1142 self.print_ident(item.ident);
1144 self.end(); // end inner head-block
1145 self.end(); // end outer head-block
1147 ast::ItemKind::Use(ref tree) => {
1148 self.head(visibility_qualified(&item.vis, "use"));
1149 self.print_use_tree(tree);
1151 self.end(); // end inner head-block
1152 self.end(); // end outer head-block
1154 ast::ItemKind::Static(ref ty, m, ref expr) => {
1155 self.head(visibility_qualified(&item.vis, "static"));
1156 if m == ast::Mutability::Mutable {
1157 self.word_space("mut");
1159 self.print_ident(item.ident);
1160 self.word_space(":");
1161 self.print_type(ty);
1163 self.end(); // end the head-ibox
1165 self.word_space("=");
1166 self.print_expr(expr);
1168 self.end(); // end the outer cbox
1170 ast::ItemKind::Const(ref ty, ref expr) => {
1171 self.head(visibility_qualified(&item.vis, "const"));
1172 self.print_ident(item.ident);
1173 self.word_space(":");
1174 self.print_type(ty);
1176 self.end(); // end the head-ibox
1178 self.word_space("=");
1179 self.print_expr(expr);
1181 self.end(); // end the outer cbox
1183 ast::ItemKind::Fn(ref decl, header, ref param_names, ref body) => {
1193 self.print_block_with_attrs(body, &item.attrs);
1195 ast::ItemKind::Mod(ref _mod) => {
1196 self.head(visibility_qualified(&item.vis, "mod"));
1197 self.print_ident(item.ident);
1199 if _mod.inline || self.is_expanded {
1202 self.print_mod(_mod, &item.attrs);
1203 self.bclose(item.span);
1206 self.end(); // end inner head-block
1207 self.end(); // end outer head-block
1211 ast::ItemKind::ForeignMod(ref nmod) => {
1212 self.head("extern");
1213 self.word_nbsp(nmod.abi.to_string());
1215 self.print_foreign_mod(nmod, &item.attrs);
1216 self.bclose(item.span);
1218 ast::ItemKind::GlobalAsm(ref ga) => {
1219 self.head(visibility_qualified(&item.vis, "global_asm!"));
1220 self.s.word(ga.asm.as_str().to_string());
1223 ast::ItemKind::Ty(ref ty, ref generics) => {
1224 self.head(visibility_qualified(&item.vis, "type"));
1225 self.print_ident(item.ident);
1226 self.print_generic_params(&generics.params);
1227 self.end(); // end the inner ibox
1229 self.print_where_clause(&generics.where_clause);
1231 self.word_space("=");
1232 self.print_type(ty);
1234 self.end(); // end the outer ibox
1236 ast::ItemKind::Existential(ref bounds, ref generics) => {
1237 self.head(visibility_qualified(&item.vis, "existential type"));
1238 self.print_ident(item.ident);
1239 self.print_generic_params(&generics.params);
1240 self.end(); // end the inner ibox
1242 self.print_where_clause(&generics.where_clause);
1244 self.print_type_bounds(":", bounds);
1246 self.end(); // end the outer ibox
1248 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1249 self.print_enum_def(
1257 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1258 self.head(visibility_qualified(&item.vis, "struct"));
1259 self.print_struct(struct_def, generics, item.ident, item.span, true);
1261 ast::ItemKind::Union(ref struct_def, ref generics) => {
1262 self.head(visibility_qualified(&item.vis, "union"));
1263 self.print_struct(struct_def, generics, item.ident, item.span, true);
1265 ast::ItemKind::Impl(unsafety,
1271 ref impl_items) => {
1273 self.print_visibility(&item.vis);
1274 self.print_defaultness(defaultness);
1275 self.print_unsafety(unsafety);
1276 self.word_nbsp("impl");
1278 if !generics.params.is_empty() {
1279 self.print_generic_params(&generics.params);
1283 if polarity == ast::ImplPolarity::Negative {
1287 if let Some(ref t) = *opt_trait {
1288 self.print_trait_ref(t);
1290 self.word_space("for");
1293 self.print_type(ty);
1294 self.print_where_clause(&generics.where_clause);
1298 self.print_inner_attributes(&item.attrs);
1299 for impl_item in impl_items {
1300 self.print_impl_item(impl_item);
1302 self.bclose(item.span);
1304 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1306 self.print_visibility(&item.vis);
1307 self.print_unsafety(unsafety);
1308 self.print_is_auto(is_auto);
1309 self.word_nbsp("trait");
1310 self.print_ident(item.ident);
1311 self.print_generic_params(&generics.params);
1312 let mut real_bounds = Vec::with_capacity(bounds.len());
1313 for b in bounds.iter() {
1314 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1316 self.word_space("for ?");
1317 self.print_trait_ref(&ptr.trait_ref);
1319 real_bounds.push(b.clone());
1322 self.print_type_bounds(":", &real_bounds[..]);
1323 self.print_where_clause(&generics.where_clause);
1326 for trait_item in trait_items {
1327 self.print_trait_item(trait_item);
1329 self.bclose(item.span);
1331 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1333 self.print_visibility(&item.vis);
1334 self.word_nbsp("trait");
1335 self.print_ident(item.ident);
1336 self.print_generic_params(&generics.params);
1337 let mut real_bounds = Vec::with_capacity(bounds.len());
1338 // FIXME(durka) this seems to be some quite outdated syntax
1339 for b in bounds.iter() {
1340 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1342 self.word_space("for ?");
1343 self.print_trait_ref(&ptr.trait_ref);
1345 real_bounds.push(b.clone());
1349 self.print_type_bounds("=", &real_bounds[..]);
1350 self.print_where_clause(&generics.where_clause);
1353 ast::ItemKind::Mac(ref mac) => {
1354 self.print_mac(mac);
1355 match mac.node.delim {
1356 MacDelimiter::Brace => {}
1357 _ => self.s.word(";"),
1360 ast::ItemKind::MacroDef(ref macro_def) => {
1361 self.print_mac_common(
1362 Some(&ast::Path::from_ident(ast::Ident::with_empty_ctxt(sym::macro_rules))),
1372 self.ann.post(self, AnnNode::Item(item))
1375 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1376 self.print_path(&t.path, false, 0)
1379 fn print_formal_generic_params(
1381 generic_params: &[ast::GenericParam]
1383 if !generic_params.is_empty() {
1385 self.print_generic_params(generic_params);
1390 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1391 self.print_formal_generic_params(&t.bound_generic_params);
1392 self.print_trait_ref(&t.trait_ref)
1395 crate fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1396 generics: &ast::Generics, ident: ast::Ident,
1397 span: syntax_pos::Span,
1398 visibility: &ast::Visibility) {
1399 self.head(visibility_qualified(visibility, "enum"));
1400 self.print_ident(ident);
1401 self.print_generic_params(&generics.params);
1402 self.print_where_clause(&generics.where_clause);
1404 self.print_variants(&enum_definition.variants, span)
1407 crate fn print_variants(&mut self,
1408 variants: &[ast::Variant],
1409 span: syntax_pos::Span) {
1412 self.space_if_not_bol();
1413 self.maybe_print_comment(v.span.lo());
1414 self.print_outer_attributes(&v.node.attrs);
1415 self.ibox(INDENT_UNIT);
1416 self.print_variant(v);
1419 self.maybe_print_trailing_comment(v.span, None);
1424 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1426 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1427 ast::VisibilityKind::Crate(sugar) => match sugar {
1428 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1429 ast::CrateSugar::JustCrate => self.word_nbsp("crate")
1431 ast::VisibilityKind::Restricted { ref path, .. } => {
1432 let path = to_string(|s| s.print_path(path, false, 0));
1433 if path == "self" || path == "super" {
1434 self.word_nbsp(format!("pub({})", path))
1436 self.word_nbsp(format!("pub(in {})", path))
1439 ast::VisibilityKind::Inherited => {}
1443 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1444 if let ast::Defaultness::Default = defaultness {
1445 self.word_nbsp("default");
1449 crate fn print_struct(&mut self,
1450 struct_def: &ast::VariantData,
1451 generics: &ast::Generics,
1453 span: syntax_pos::Span,
1454 print_finalizer: bool) {
1455 self.print_ident(ident);
1456 self.print_generic_params(&generics.params);
1458 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1459 if let ast::VariantData::Tuple(..) = struct_def {
1462 Inconsistent, struct_def.fields(),
1464 s.maybe_print_comment(field.span.lo());
1465 s.print_outer_attributes(&field.attrs);
1466 s.print_visibility(&field.vis);
1467 s.print_type(&field.ty)
1472 self.print_where_clause(&generics.where_clause);
1473 if print_finalizer {
1477 self.end(); // close the outer-box
1479 ast::VariantData::Struct(..) => {
1480 self.print_where_clause(&generics.where_clause);
1483 self.hardbreak_if_not_bol();
1485 for field in struct_def.fields() {
1486 self.hardbreak_if_not_bol();
1487 self.maybe_print_comment(field.span.lo());
1488 self.print_outer_attributes(&field.attrs);
1489 self.print_visibility(&field.vis);
1490 self.print_ident(field.ident.unwrap());
1491 self.word_nbsp(":");
1492 self.print_type(&field.ty);
1501 crate fn print_variant(&mut self, v: &ast::Variant) {
1503 let generics = ast::Generics::default();
1504 self.print_struct(&v.node.data, &generics, v.node.ident, v.span, false);
1505 match v.node.disr_expr {
1508 self.word_space("=");
1509 self.print_expr(&d.value)
1515 crate fn print_method_sig(&mut self,
1517 generics: &ast::Generics,
1519 vis: &ast::Visibility)
1521 self.print_fn(&m.decl,
1528 crate fn print_trait_item(&mut self, ti: &ast::TraitItem)
1530 self.ann.pre(self, AnnNode::SubItem(ti.id));
1531 self.hardbreak_if_not_bol();
1532 self.maybe_print_comment(ti.span.lo());
1533 self.print_outer_attributes(&ti.attrs);
1535 ast::TraitItemKind::Const(ref ty, ref default) => {
1536 self.print_associated_const(
1539 default.as_ref().map(|expr| &**expr),
1540 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1543 ast::TraitItemKind::Method(ref sig, ref body) => {
1547 self.print_method_sig(
1551 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1553 if let Some(ref body) = *body {
1555 self.print_block_with_attrs(body, &ti.attrs);
1560 ast::TraitItemKind::Type(ref bounds, ref default) => {
1561 self.print_associated_type(ti.ident, Some(bounds),
1562 default.as_ref().map(|ty| &**ty));
1564 ast::TraitItemKind::Macro(ref mac) => {
1565 self.print_mac(mac);
1566 match mac.node.delim {
1567 MacDelimiter::Brace => {}
1568 _ => self.s.word(";"),
1572 self.ann.post(self, AnnNode::SubItem(ti.id))
1575 crate fn print_impl_item(&mut self, ii: &ast::ImplItem) {
1576 self.ann.pre(self, AnnNode::SubItem(ii.id));
1577 self.hardbreak_if_not_bol();
1578 self.maybe_print_comment(ii.span.lo());
1579 self.print_outer_attributes(&ii.attrs);
1580 self.print_defaultness(ii.defaultness);
1582 ast::ImplItemKind::Const(ref ty, ref expr) => {
1583 self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis);
1585 ast::ImplItemKind::Method(ref sig, ref body) => {
1587 self.print_method_sig(ii.ident, &ii.generics, sig, &ii.vis);
1589 self.print_block_with_attrs(body, &ii.attrs);
1591 ast::ImplItemKind::Type(ref ty) => {
1592 self.print_associated_type(ii.ident, None, Some(ty));
1594 ast::ImplItemKind::Existential(ref bounds) => {
1595 self.word_space("existential");
1596 self.print_associated_type(ii.ident, Some(bounds), None);
1598 ast::ImplItemKind::Macro(ref mac) => {
1599 self.print_mac(mac);
1600 match mac.node.delim {
1601 MacDelimiter::Brace => {}
1602 _ => self.s.word(";"),
1606 self.ann.post(self, AnnNode::SubItem(ii.id))
1609 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1610 self.maybe_print_comment(st.span.lo());
1612 ast::StmtKind::Local(ref loc) => {
1613 self.print_outer_attributes(&loc.attrs);
1614 self.space_if_not_bol();
1615 self.ibox(INDENT_UNIT);
1616 self.word_nbsp("let");
1618 self.ibox(INDENT_UNIT);
1619 self.print_local_decl(loc);
1621 if let Some(ref init) = loc.init {
1623 self.word_space("=");
1624 self.print_expr(init);
1629 ast::StmtKind::Item(ref item) => self.print_item(item),
1630 ast::StmtKind::Expr(ref expr) => {
1631 self.space_if_not_bol();
1632 self.print_expr_outer_attr_style(expr, false);
1633 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1637 ast::StmtKind::Semi(ref expr) => {
1638 self.space_if_not_bol();
1639 self.print_expr_outer_attr_style(expr, false);
1642 ast::StmtKind::Mac(ref mac) => {
1643 let (ref mac, style, ref attrs) = **mac;
1644 self.space_if_not_bol();
1645 self.print_outer_attributes(attrs);
1646 self.print_mac(mac);
1647 if style == ast::MacStmtStyle::Semicolon {
1652 self.maybe_print_trailing_comment(st.span, None)
1655 crate fn print_block(&mut self, blk: &ast::Block) {
1656 self.print_block_with_attrs(blk, &[])
1659 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1660 self.print_block_maybe_unclosed(blk, &[], false)
1663 crate fn print_block_with_attrs(&mut self,
1665 attrs: &[ast::Attribute]) {
1666 self.print_block_maybe_unclosed(blk, attrs, true)
1669 crate fn print_block_maybe_unclosed(&mut self,
1671 attrs: &[ast::Attribute],
1674 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1675 BlockCheckMode::Default => ()
1677 self.maybe_print_comment(blk.span.lo());
1678 self.ann.pre(self, AnnNode::Block(blk));
1681 self.print_inner_attributes(attrs);
1683 for (i, st) in blk.stmts.iter().enumerate() {
1685 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1686 self.maybe_print_comment(st.span.lo());
1687 self.space_if_not_bol();
1688 self.print_expr_outer_attr_style(expr, false);
1689 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1691 _ => self.print_stmt(st),
1695 self.bclose_maybe_open(blk.span, close_box);
1696 self.ann.post(self, AnnNode::Block(blk))
1699 /// Print a `let pats = scrutinee` expression.
1700 crate fn print_let(&mut self, pats: &[P<ast::Pat>], scrutinee: &ast::Expr) {
1701 self.s.word("let ");
1703 self.print_pats(pats);
1706 self.word_space("=");
1707 self.print_expr_cond_paren(
1709 Self::cond_needs_par(scrutinee)
1710 || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order())
1714 fn print_else(&mut self, els: Option<&ast::Expr>) {
1718 // Another `else if` block.
1719 ast::ExprKind::If(ref i, ref then, ref e) => {
1720 self.cbox(INDENT_UNIT - 1);
1722 self.s.word(" else if ");
1723 self.print_expr_as_cond(i);
1725 self.print_block(then);
1726 self.print_else(e.as_ref().map(|e| &**e))
1728 // Final `else` block.
1729 ast::ExprKind::Block(ref b, _) => {
1730 self.cbox(INDENT_UNIT - 1);
1732 self.s.word(" else ");
1735 // Constraints would be great here!
1737 panic!("print_if saw if with weird alternative");
1745 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1746 elseopt: Option<&ast::Expr>) {
1749 self.print_expr_as_cond(test);
1752 self.print_block(blk);
1753 self.print_else(elseopt)
1756 crate fn print_mac(&mut self, m: &ast::Mac) {
1757 self.print_mac_common(
1758 Some(&m.node.path), true, None, m.node.delim.to_token(), m.node.stream(), true, m.span
1762 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1764 self.commasep_exprs(Inconsistent, args);
1768 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1769 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1772 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1773 /// `if cond { ... }`.
1774 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1775 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1778 /// Does `expr` need parenthesis when printed in a condition position?
1779 fn cond_needs_par(expr: &ast::Expr) -> bool {
1781 // These cases need parens due to the parse error observed in #26461: `if return {}`
1782 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1783 ast::ExprKind::Closure(..) |
1784 ast::ExprKind::Ret(..) |
1785 ast::ExprKind::Break(..) => true,
1787 _ => parser::contains_exterior_struct_lit(expr),
1791 /// Print `expr` or `(expr)` when `needs_par` holds.
1792 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1796 self.print_expr(expr);
1802 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1803 attrs: &[Attribute]) {
1804 self.ibox(INDENT_UNIT);
1806 self.print_inner_attributes_inline(attrs);
1807 self.commasep_exprs(Inconsistent, &exprs[..]);
1812 fn print_expr_repeat(&mut self,
1813 element: &ast::Expr,
1814 count: &ast::AnonConst,
1815 attrs: &[Attribute]) {
1816 self.ibox(INDENT_UNIT);
1818 self.print_inner_attributes_inline(attrs);
1819 self.print_expr(element);
1820 self.word_space(";");
1821 self.print_expr(&count.value);
1826 fn print_expr_struct(&mut self,
1828 fields: &[ast::Field],
1829 wth: &Option<P<ast::Expr>>,
1830 attrs: &[Attribute]) {
1831 self.print_path(path, true, 0);
1833 self.print_inner_attributes_inline(attrs);
1838 s.ibox(INDENT_UNIT);
1839 if !field.is_shorthand {
1840 s.print_ident(field.ident);
1843 s.print_expr(&field.expr);
1849 self.ibox(INDENT_UNIT);
1850 if !fields.is_empty() {
1855 self.print_expr(expr);
1858 _ => if !fields.is_empty() {
1865 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1866 attrs: &[Attribute]) {
1868 self.print_inner_attributes_inline(attrs);
1869 self.commasep_exprs(Inconsistent, &exprs[..]);
1870 if exprs.len() == 1 {
1876 fn print_expr_call(&mut self,
1878 args: &[P<ast::Expr>]) {
1881 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1882 _ => parser::PREC_POSTFIX,
1885 self.print_expr_maybe_paren(func, prec);
1886 self.print_call_post(args)
1889 fn print_expr_method_call(&mut self,
1890 segment: &ast::PathSegment,
1891 args: &[P<ast::Expr>]) {
1892 let base_args = &args[1..];
1893 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1895 self.print_ident(segment.ident);
1896 if let Some(ref args) = segment.args {
1897 self.print_generic_args(args, true);
1899 self.print_call_post(base_args)
1902 fn print_expr_binary(&mut self,
1906 let assoc_op = AssocOp::from_ast_binop(op.node);
1907 let prec = assoc_op.precedence() as i8;
1908 let fixity = assoc_op.fixity();
1910 let (left_prec, right_prec) = match fixity {
1911 Fixity::Left => (prec, prec + 1),
1912 Fixity::Right => (prec + 1, prec),
1913 Fixity::None => (prec + 1, prec + 1),
1916 let left_prec = match (&lhs.node, op.node) {
1917 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1918 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1919 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1920 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) |
1921 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1922 // We are given `(let _ = a) OP b`.
1924 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1925 // as the parser will interpret this as `(let _ = a) OP b`.
1927 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1928 // parens are required since the parser would interpret `let a = b < c` as
1929 // `let a = (b < c)`. To achieve this, we force parens.
1930 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1931 parser::PREC_FORCE_PAREN
1936 self.print_expr_maybe_paren(lhs, left_prec);
1938 self.word_space(op.node.to_string());
1939 self.print_expr_maybe_paren(rhs, right_prec)
1942 fn print_expr_unary(&mut self,
1945 self.s.word(ast::UnOp::to_string(op));
1946 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1949 fn print_expr_addr_of(&mut self,
1950 mutability: ast::Mutability,
1953 self.print_mutability(mutability);
1954 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1957 crate fn print_expr(&mut self, expr: &ast::Expr) {
1958 self.print_expr_outer_attr_style(expr, true)
1961 fn print_expr_outer_attr_style(&mut self,
1964 self.maybe_print_comment(expr.span.lo());
1966 let attrs = &expr.attrs;
1968 self.print_outer_attributes_inline(attrs);
1970 self.print_outer_attributes(attrs);
1973 self.ibox(INDENT_UNIT);
1974 self.ann.pre(self, AnnNode::Expr(expr));
1976 ast::ExprKind::Box(ref expr) => {
1977 self.word_space("box");
1978 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1980 ast::ExprKind::Array(ref exprs) => {
1981 self.print_expr_vec(&exprs[..], attrs);
1983 ast::ExprKind::Repeat(ref element, ref count) => {
1984 self.print_expr_repeat(element, count, attrs);
1986 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
1987 self.print_expr_struct(path, &fields[..], wth, attrs);
1989 ast::ExprKind::Tup(ref exprs) => {
1990 self.print_expr_tup(&exprs[..], attrs);
1992 ast::ExprKind::Call(ref func, ref args) => {
1993 self.print_expr_call(func, &args[..]);
1995 ast::ExprKind::MethodCall(ref segment, ref args) => {
1996 self.print_expr_method_call(segment, &args[..]);
1998 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1999 self.print_expr_binary(op, lhs, rhs);
2001 ast::ExprKind::Unary(op, ref expr) => {
2002 self.print_expr_unary(op, expr);
2004 ast::ExprKind::AddrOf(m, ref expr) => {
2005 self.print_expr_addr_of(m, expr);
2007 ast::ExprKind::Lit(ref lit) => {
2008 self.print_literal(lit);
2010 ast::ExprKind::Cast(ref expr, ref ty) => {
2011 let prec = AssocOp::As.precedence() as i8;
2012 self.print_expr_maybe_paren(expr, prec);
2014 self.word_space("as");
2015 self.print_type(ty);
2017 ast::ExprKind::Type(ref expr, ref ty) => {
2018 let prec = AssocOp::Colon.precedence() as i8;
2019 self.print_expr_maybe_paren(expr, prec);
2020 self.word_space(":");
2021 self.print_type(ty);
2023 ast::ExprKind::Let(ref pats, ref scrutinee) => {
2024 self.print_let(pats, scrutinee);
2026 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2027 self.print_if(test, blk, elseopt.as_ref().map(|e| &**e));
2029 ast::ExprKind::While(ref test, ref blk, opt_label) => {
2030 if let Some(label) = opt_label {
2031 self.print_ident(label.ident);
2032 self.word_space(":");
2035 self.print_expr_as_cond(test);
2037 self.print_block_with_attrs(blk, attrs);
2039 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2040 if let Some(label) = opt_label {
2041 self.print_ident(label.ident);
2042 self.word_space(":");
2045 self.print_pat(pat);
2047 self.word_space("in");
2048 self.print_expr_as_cond(iter);
2050 self.print_block_with_attrs(blk, attrs);
2052 ast::ExprKind::Loop(ref blk, opt_label) => {
2053 if let Some(label) = opt_label {
2054 self.print_ident(label.ident);
2055 self.word_space(":");
2059 self.print_block_with_attrs(blk, attrs);
2061 ast::ExprKind::Match(ref expr, ref arms) => {
2062 self.cbox(INDENT_UNIT);
2063 self.ibox(INDENT_UNIT);
2064 self.word_nbsp("match");
2065 self.print_expr_as_cond(expr);
2068 self.print_inner_attributes_no_trailing_hardbreak(attrs);
2070 self.print_arm(arm);
2072 self.bclose(expr.span);
2074 ast::ExprKind::Closure(
2075 capture_clause, asyncness, movability, ref decl, ref body, _) => {
2076 self.print_movability(movability);
2077 self.print_asyncness(asyncness);
2078 self.print_capture_clause(capture_clause);
2080 self.print_fn_block_args(decl);
2082 self.print_expr(body);
2083 self.end(); // need to close a box
2085 // a box will be closed by print_expr, but we didn't want an overall
2086 // wrapper so we closed the corresponding opening. so create an
2087 // empty box to satisfy the close.
2090 ast::ExprKind::Block(ref blk, opt_label) => {
2091 if let Some(label) = opt_label {
2092 self.print_ident(label.ident);
2093 self.word_space(":");
2095 // containing cbox, will be closed by print-block at }
2096 self.cbox(INDENT_UNIT);
2097 // head-box, will be closed by print-block after {
2099 self.print_block_with_attrs(blk, attrs);
2101 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2102 self.word_nbsp("async");
2103 self.print_capture_clause(capture_clause);
2105 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2106 self.cbox(INDENT_UNIT);
2108 self.print_block_with_attrs(blk, attrs);
2110 ast::ExprKind::Await(origin, ref expr) => {
2112 ast::AwaitOrigin::MacroLike => {
2113 self.s.word("await!");
2114 self.print_expr_maybe_paren(expr, parser::PREC_FORCE_PAREN);
2116 ast::AwaitOrigin::FieldLike => {
2117 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2118 self.s.word(".await");
2122 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2123 let prec = AssocOp::Assign.precedence() as i8;
2124 self.print_expr_maybe_paren(lhs, prec + 1);
2126 self.word_space("=");
2127 self.print_expr_maybe_paren(rhs, prec);
2129 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2130 let prec = AssocOp::Assign.precedence() as i8;
2131 self.print_expr_maybe_paren(lhs, prec + 1);
2133 self.s.word(op.node.to_string());
2134 self.word_space("=");
2135 self.print_expr_maybe_paren(rhs, prec);
2137 ast::ExprKind::Field(ref expr, ident) => {
2138 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2140 self.print_ident(ident);
2142 ast::ExprKind::Index(ref expr, ref index) => {
2143 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2145 self.print_expr(index);
2148 ast::ExprKind::Range(ref start, ref end, limits) => {
2149 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2150 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2151 // Here we use a fake precedence value so that any child with lower precedence than
2152 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2153 let fake_prec = AssocOp::LOr.precedence() as i8;
2154 if let Some(ref e) = *start {
2155 self.print_expr_maybe_paren(e, fake_prec);
2157 if limits == ast::RangeLimits::HalfOpen {
2162 if let Some(ref e) = *end {
2163 self.print_expr_maybe_paren(e, fake_prec);
2166 ast::ExprKind::Path(None, ref path) => {
2167 self.print_path(path, true, 0)
2169 ast::ExprKind::Path(Some(ref qself), ref path) => {
2170 self.print_qpath(path, qself, true)
2172 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2173 self.s.word("break");
2175 if let Some(label) = opt_label {
2176 self.print_ident(label.ident);
2179 if let Some(ref expr) = *opt_expr {
2180 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2184 ast::ExprKind::Continue(opt_label) => {
2185 self.s.word("continue");
2187 if let Some(label) = opt_label {
2188 self.print_ident(label.ident);
2192 ast::ExprKind::Ret(ref result) => {
2193 self.s.word("return");
2194 if let Some(ref expr) = *result {
2196 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2199 ast::ExprKind::InlineAsm(ref a) => {
2200 self.s.word("asm!");
2202 self.print_string(&a.asm.as_str(), a.asm_str_style);
2203 self.word_space(":");
2205 self.commasep(Inconsistent, &a.outputs, |s, out| {
2206 let constraint = out.constraint.as_str();
2207 let mut ch = constraint.chars();
2209 Some('=') if out.is_rw => {
2210 s.print_string(&format!("+{}", ch.as_str()),
2211 ast::StrStyle::Cooked)
2213 _ => s.print_string(&constraint, ast::StrStyle::Cooked)
2216 s.print_expr(&out.expr);
2220 self.word_space(":");
2222 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2223 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2229 self.word_space(":");
2231 self.commasep(Inconsistent, &a.clobbers,
2233 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2236 let mut options = vec![];
2238 options.push("volatile");
2241 options.push("alignstack");
2243 if a.dialect == ast::AsmDialect::Intel {
2244 options.push("intel");
2247 if !options.is_empty() {
2249 self.word_space(":");
2250 self.commasep(Inconsistent, &options,
2252 s.print_string(co, ast::StrStyle::Cooked);
2258 ast::ExprKind::Mac(ref m) => self.print_mac(m),
2259 ast::ExprKind::Paren(ref e) => {
2261 self.print_inner_attributes_inline(attrs);
2265 ast::ExprKind::Yield(ref e) => {
2266 self.s.word("yield");
2270 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2275 ast::ExprKind::Try(ref e) => {
2276 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2279 ast::ExprKind::TryBlock(ref blk) => {
2282 self.print_block_with_attrs(blk, attrs)
2284 ast::ExprKind::Err => {
2286 self.s.word("/*ERROR*/");
2290 self.ann.post(self, AnnNode::Expr(expr));
2294 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2295 self.print_pat(&loc.pat);
2296 if let Some(ref ty) = loc.ty {
2297 self.word_space(":");
2298 self.print_type(ty);
2302 crate fn print_usize(&mut self, i: usize) {
2303 self.s.word(i.to_string())
2306 crate fn print_name(&mut self, name: ast::Name) {
2307 self.s.word(name.as_str().to_string());
2308 self.ann.post(self, AnnNode::Name(&name))
2311 fn print_qpath(&mut self,
2314 colons_before_params: bool)
2317 self.print_type(&qself.ty);
2318 if qself.position > 0 {
2320 self.word_space("as");
2321 let depth = path.segments.len() - qself.position;
2322 self.print_path(path, false, depth);
2326 let item_segment = path.segments.last().unwrap();
2327 self.print_ident(item_segment.ident);
2328 match item_segment.args {
2329 Some(ref args) => self.print_generic_args(args, colons_before_params),
2334 crate fn print_pat(&mut self, pat: &ast::Pat) {
2335 self.maybe_print_comment(pat.span.lo());
2336 self.ann.pre(self, AnnNode::Pat(pat));
2337 /* Pat isn't normalized, but the beauty of it
2338 is that it doesn't matter */
2340 PatKind::Wild => self.s.word("_"),
2341 PatKind::Ident(binding_mode, ident, ref sub) => {
2342 match binding_mode {
2343 ast::BindingMode::ByRef(mutbl) => {
2344 self.word_nbsp("ref");
2345 self.print_mutability(mutbl);
2347 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2348 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2349 self.word_nbsp("mut");
2352 self.print_ident(ident);
2353 if let Some(ref p) = *sub {
2358 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2359 self.print_path(path, true, 0);
2361 if let Some(ddpos) = ddpos {
2362 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
2364 self.word_space(",");
2367 if ddpos != elts.len() {
2369 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
2372 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2376 PatKind::Path(None, ref path) => {
2377 self.print_path(path, true, 0);
2379 PatKind::Path(Some(ref qself), ref path) => {
2380 self.print_qpath(path, qself, false);
2382 PatKind::Struct(ref path, ref fields, etc) => {
2383 self.print_path(path, true, 0);
2385 self.word_space("{");
2387 Consistent, &fields[..],
2389 s.cbox(INDENT_UNIT);
2390 if !f.node.is_shorthand {
2391 s.print_ident(f.node.ident);
2394 s.print_pat(&f.node.pat);
2397 |f| f.node.pat.span);
2399 if !fields.is_empty() { self.word_space(","); }
2405 PatKind::Tuple(ref elts, ddpos) => {
2407 if let Some(ddpos) = ddpos {
2408 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
2410 self.word_space(",");
2413 if ddpos != elts.len() {
2415 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
2418 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2419 if elts.len() == 1 {
2425 PatKind::Box(ref inner) => {
2426 self.s.word("box ");
2427 self.print_pat(inner);
2429 PatKind::Ref(ref inner, mutbl) => {
2431 if mutbl == ast::Mutability::Mutable {
2432 self.s.word("mut ");
2434 self.print_pat(inner);
2436 PatKind::Lit(ref e) => self.print_expr(&**e),
2437 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2438 self.print_expr(begin);
2441 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("..."),
2442 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..="),
2443 RangeEnd::Excluded => self.s.word(".."),
2445 self.print_expr(end);
2447 PatKind::Slice(ref before, ref slice, ref after) => {
2449 self.commasep(Inconsistent,
2451 |s, p| s.print_pat(p));
2452 if let Some(ref p) = *slice {
2453 if !before.is_empty() { self.word_space(","); }
2454 if let PatKind::Wild = p.node {
2460 if !after.is_empty() { self.word_space(","); }
2462 self.commasep(Inconsistent,
2464 |s, p| s.print_pat(p));
2467 PatKind::Paren(ref inner) => {
2469 self.print_pat(inner);
2472 PatKind::Mac(ref m) => self.print_mac(m),
2474 self.ann.post(self, AnnNode::Pat(pat))
2477 fn print_pats(&mut self, pats: &[P<ast::Pat>]) {
2478 let mut first = true;
2484 self.word_space("|");
2490 fn print_arm(&mut self, arm: &ast::Arm) {
2491 // I have no idea why this check is necessary, but here it
2493 if arm.attrs.is_empty() {
2496 self.cbox(INDENT_UNIT);
2498 self.maybe_print_comment(arm.pats[0].span.lo());
2499 self.print_outer_attributes(&arm.attrs);
2500 self.print_pats(&arm.pats);
2502 if let Some(ref e) = arm.guard {
2503 self.word_space("if");
2507 self.word_space("=>");
2509 match arm.body.node {
2510 ast::ExprKind::Block(ref blk, opt_label) => {
2511 if let Some(label) = opt_label {
2512 self.print_ident(label.ident);
2513 self.word_space(":");
2516 // the block will close the pattern's ibox
2517 self.print_block_unclosed_indent(blk);
2519 // If it is a user-provided unsafe block, print a comma after it
2520 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2525 self.end(); // close the ibox for the pattern
2526 self.print_expr(&arm.body);
2530 self.end(); // close enclosing cbox
2533 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2534 match explicit_self.node {
2535 SelfKind::Value(m) => {
2536 self.print_mutability(m);
2539 SelfKind::Region(ref lt, m) => {
2541 self.print_opt_lifetime(lt);
2542 self.print_mutability(m);
2545 SelfKind::Explicit(ref typ, m) => {
2546 self.print_mutability(m);
2547 self.s.word("self");
2548 self.word_space(":");
2549 self.print_type(typ)
2554 crate fn print_fn(&mut self,
2556 header: ast::FnHeader,
2557 name: Option<ast::Ident>,
2558 generics: &ast::Generics,
2559 vis: &ast::Visibility) {
2560 self.print_fn_header_info(header, vis);
2562 if let Some(name) = name {
2564 self.print_ident(name);
2566 self.print_generic_params(&generics.params);
2567 self.print_fn_args_and_ret(decl);
2568 self.print_where_clause(&generics.where_clause)
2571 crate fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl) {
2573 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false));
2576 self.print_fn_output(decl)
2579 crate fn print_fn_block_args(&mut self, decl: &ast::FnDecl) {
2581 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true));
2584 if let ast::FunctionRetTy::Default(..) = decl.output {
2588 self.space_if_not_bol();
2589 self.word_space("->");
2591 ast::FunctionRetTy::Ty(ref ty) => {
2592 self.print_type(ty);
2593 self.maybe_print_comment(ty.span.lo())
2595 ast::FunctionRetTy::Default(..) => unreachable!(),
2599 crate fn print_movability(&mut self, movability: ast::Movability) {
2601 ast::Movability::Static => self.word_space("static"),
2602 ast::Movability::Movable => {},
2606 crate fn print_asyncness(&mut self, asyncness: ast::IsAsync) {
2607 if asyncness.is_async() {
2608 self.word_nbsp("async");
2612 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2613 match capture_clause {
2614 ast::CaptureBy::Value => self.word_space("move"),
2615 ast::CaptureBy::Ref => {},
2619 crate fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2620 if !bounds.is_empty() {
2621 self.s.word(prefix);
2622 let mut first = true;
2623 for bound in bounds {
2624 if !(first && prefix.is_empty()) {
2630 self.word_space("+");
2634 GenericBound::Trait(tref, modifier) => {
2635 if modifier == &TraitBoundModifier::Maybe {
2638 self.print_poly_trait_ref(tref);
2640 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2646 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2647 self.print_name(lifetime.ident.name)
2650 crate fn print_lifetime_bounds(
2651 &mut self, lifetime: ast::Lifetime, bounds: &ast::GenericBounds) {
2652 self.print_lifetime(lifetime);
2653 if !bounds.is_empty() {
2655 for (i, bound) in bounds.iter().enumerate() {
2660 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2667 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2668 if generic_params.is_empty() {
2674 self.commasep(Inconsistent, &generic_params, |s, param| {
2676 ast::GenericParamKind::Lifetime => {
2677 s.print_outer_attributes_inline(¶m.attrs);
2678 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2679 s.print_lifetime_bounds(lt, ¶m.bounds)
2681 ast::GenericParamKind::Type { ref default } => {
2682 s.print_outer_attributes_inline(¶m.attrs);
2683 s.print_ident(param.ident);
2684 s.print_type_bounds(":", ¶m.bounds);
2686 Some(ref default) => {
2689 s.print_type(default)
2694 ast::GenericParamKind::Const { ref ty } => {
2695 s.print_outer_attributes_inline(¶m.attrs);
2696 s.word_space("const");
2697 s.print_ident(param.ident);
2701 s.print_type_bounds(":", ¶m.bounds)
2709 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2710 if where_clause.predicates.is_empty() {
2715 self.word_space("where");
2717 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2719 self.word_space(",");
2723 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2724 ref bound_generic_params,
2729 self.print_formal_generic_params(bound_generic_params);
2730 self.print_type(bounded_ty);
2731 self.print_type_bounds(":", bounds);
2733 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2736 self.print_lifetime_bounds(*lifetime, bounds);
2738 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2741 self.print_type(lhs_ty);
2743 self.word_space("=");
2744 self.print_type(rhs_ty);
2750 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2752 ast::UseTreeKind::Simple(rename, ..) => {
2753 self.print_path(&tree.prefix, false, 0);
2754 if let Some(rename) = rename {
2756 self.word_space("as");
2757 self.print_ident(rename);
2760 ast::UseTreeKind::Glob => {
2761 if !tree.prefix.segments.is_empty() {
2762 self.print_path(&tree.prefix, false, 0);
2767 ast::UseTreeKind::Nested(ref items) => {
2768 if tree.prefix.segments.is_empty() {
2771 self.print_path(&tree.prefix, false, 0);
2774 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2775 this.print_use_tree(tree)
2782 crate fn print_mutability(&mut self, mutbl: ast::Mutability) {
2784 ast::Mutability::Mutable => self.word_nbsp("mut"),
2785 ast::Mutability::Immutable => {},
2789 crate fn print_mt(&mut self, mt: &ast::MutTy) {
2790 self.print_mutability(mt.mutbl);
2791 self.print_type(&mt.ty)
2794 crate fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) {
2795 self.ibox(INDENT_UNIT);
2796 match input.ty.node {
2797 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2799 if let Some(eself) = input.to_self() {
2800 self.print_explicit_self(&eself);
2802 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
2803 ident.name == kw::Invalid
2808 self.print_pat(&input.pat);
2812 self.print_type(&input.ty);
2819 crate fn print_fn_output(&mut self, decl: &ast::FnDecl) {
2820 if let ast::FunctionRetTy::Default(..) = decl.output {
2824 self.space_if_not_bol();
2825 self.ibox(INDENT_UNIT);
2826 self.word_space("->");
2828 ast::FunctionRetTy::Default(..) => unreachable!(),
2829 ast::FunctionRetTy::Ty(ref ty) =>
2830 self.print_type(ty),
2835 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo()),
2840 crate fn print_ty_fn(&mut self,
2842 unsafety: ast::Unsafety,
2844 name: Option<ast::Ident>,
2845 generic_params: &[ast::GenericParam])
2847 self.ibox(INDENT_UNIT);
2848 if !generic_params.is_empty() {
2850 self.print_generic_params(generic_params);
2852 let generics = ast::Generics {
2854 where_clause: ast::WhereClause {
2855 predicates: Vec::new(),
2856 span: syntax_pos::DUMMY_SP,
2858 span: syntax_pos::DUMMY_SP,
2861 ast::FnHeader { unsafety, abi, ..ast::FnHeader::default() },
2864 &source_map::dummy_spanned(ast::VisibilityKind::Inherited));
2868 crate fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
2869 next_pos: Option<BytePos>)
2871 if let Some(cmnts) = self.comments() {
2872 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2873 self.print_comment(&cmnt);
2878 crate fn print_remaining_comments(&mut self) {
2879 // If there aren't any remaining comments, then we need to manually
2880 // make sure there is a line break at the end.
2881 if self.next_comment().is_none() {
2884 while let Some(ref cmnt) = self.next_comment() {
2885 self.print_comment(cmnt);
2889 crate fn print_fn_header_info(&mut self,
2890 header: ast::FnHeader,
2891 vis: &ast::Visibility) {
2892 self.s.word(visibility_qualified(vis, ""));
2894 match header.constness.node {
2895 ast::Constness::NotConst => {}
2896 ast::Constness::Const => self.word_nbsp("const")
2899 self.print_asyncness(header.asyncness.node);
2900 self.print_unsafety(header.unsafety);
2902 if header.abi != Abi::Rust {
2903 self.word_nbsp("extern");
2904 self.word_nbsp(header.abi.to_string());
2910 crate fn print_unsafety(&mut self, s: ast::Unsafety) {
2912 ast::Unsafety::Normal => {},
2913 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2917 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2919 ast::IsAuto::Yes => self.word_nbsp("auto"),
2920 ast::IsAuto::No => {}
2930 use crate::source_map;
2931 use crate::with_default_globals;
2935 fn test_fun_to_string() {
2936 with_default_globals(|| {
2937 let abba_ident = ast::Ident::from_str("abba");
2939 let decl = ast::FnDecl {
2941 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
2944 let generics = ast::Generics::default();
2949 unsafety: ast::Unsafety::Normal,
2950 constness: source_map::dummy_spanned(ast::Constness::NotConst),
2951 asyncness: source_map::dummy_spanned(ast::IsAsync::NotAsync),
2963 fn test_variant_to_string() {
2964 with_default_globals(|| {
2965 let ident = ast::Ident::from_str("principal_skinner");
2967 let var = source_map::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
2970 id: ast::DUMMY_NODE_ID,
2971 // making this up as I go.... ?
2972 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
2976 let varstr = variant_to_string(&var);
2977 assert_eq!(varstr, "principal_skinner");