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, Nonterminal, Token};
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::keywords;
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};
23 use std::io::{self, Write, Read};
24 use std::iter::Peekable;
27 pub enum AnnNode<'a> {
28 Ident(&'a ast::Ident),
30 Block(&'a ast::Block),
38 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) -> io::Result<()> { Ok(()) }
39 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) -> io::Result<()> { Ok(()) }
42 #[derive(Copy, Clone)]
45 impl PpAnn for NoAnn {}
47 pub struct State<'a> {
48 pub s: pp::Printer<'a>,
49 cm: Option<&'a SourceMap>,
50 comments: Option<Vec<comments::Comment> >,
51 literals: Peekable<vec::IntoIter<comments::Literal>>,
53 boxes: Vec<pp::Breaks>,
54 ann: &'a (dyn PpAnn+'a),
58 fn rust_printer<'a>(writer: Box<dyn Write+'a>, ann: &'a dyn PpAnn) -> State<'a> {
60 s: pp::mk_printer(writer, DEFAULT_COLUMNS),
63 literals: vec![].into_iter().peekable(),
71 pub const INDENT_UNIT: usize = 4;
73 pub const DEFAULT_COLUMNS: usize = 78;
75 /// Requires you to pass an input filename and reader so that
76 /// it can scan the input text for comments and literals to
78 pub fn print_crate<'a>(cm: &'a SourceMap,
83 out: Box<dyn Write+'a>,
85 is_expanded: bool) -> io::Result<()> {
86 let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
88 if is_expanded && std_inject::injected_crate_name().is_some() {
89 // We need to print `#![no_std]` (and its feature gate) so that
90 // compiling pretty-printed source won't inject libstd again.
91 // However we don't want these attributes in the AST because
92 // of the feature gate, so we fake them up here.
94 // #![feature(prelude_import)]
95 let pi_nested = attr::mk_nested_word_item(ast::Ident::from_str("prelude_import"));
96 let list = attr::mk_list_item(DUMMY_SP, ast::Ident::from_str("feature"), vec![pi_nested]);
97 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), list);
98 s.print_attribute(&fake_attr)?;
101 let no_std_meta = attr::mk_word_item(ast::Ident::from_str("no_std"));
102 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), no_std_meta);
103 s.print_attribute(&fake_attr)?;
106 s.print_mod(&krate.module, &krate.attrs)?;
107 s.print_remaining_comments()?;
112 pub fn new_from_input(cm: &'a SourceMap,
115 input: &mut dyn Read,
116 out: Box<dyn Write+'a>,
118 is_expanded: bool) -> State<'a> {
119 let (cmnts, lits) = comments::gather_comments_and_literals(sess, filename, input);
126 // If the code is post expansion, don't use the table of
127 // literals, since it doesn't correspond with the literals
128 // in the AST anymore.
129 if is_expanded { None } else { Some(lits) },
134 pub fn new(cm: &'a SourceMap,
135 out: Box<dyn Write+'a>,
137 comments: Option<Vec<comments::Comment>>,
138 literals: Option<Vec<comments::Literal>>,
139 is_expanded: bool) -> State<'a> {
141 s: pp::mk_printer(out, DEFAULT_COLUMNS),
144 literals: literals.unwrap_or_default().into_iter().peekable(),
148 is_expanded: is_expanded
153 pub fn to_string<F>(f: F) -> String where
154 F: FnOnce(&mut State<'_>) -> io::Result<()>,
156 let mut wr = Vec::new();
159 let mut printer = rust_printer(Box::new(&mut wr), &ann);
160 f(&mut printer).unwrap();
161 printer.s.eof().unwrap();
163 String::from_utf8(wr).unwrap()
166 fn binop_to_string(op: BinOpToken) -> &'static str {
172 token::Percent => "%",
181 pub fn token_to_string(tok: &Token) -> String {
183 token::Eq => "=".to_string(),
184 token::Lt => "<".to_string(),
185 token::Le => "<=".to_string(),
186 token::EqEq => "==".to_string(),
187 token::Ne => "!=".to_string(),
188 token::Ge => ">=".to_string(),
189 token::Gt => ">".to_string(),
190 token::Not => "!".to_string(),
191 token::Tilde => "~".to_string(),
192 token::OrOr => "||".to_string(),
193 token::AndAnd => "&&".to_string(),
194 token::BinOp(op) => binop_to_string(op).to_string(),
195 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
197 /* Structural symbols */
198 token::At => "@".to_string(),
199 token::Dot => ".".to_string(),
200 token::DotDot => "..".to_string(),
201 token::DotDotDot => "...".to_string(),
202 token::DotDotEq => "..=".to_string(),
203 token::Comma => ",".to_string(),
204 token::Semi => ";".to_string(),
205 token::Colon => ":".to_string(),
206 token::ModSep => "::".to_string(),
207 token::RArrow => "->".to_string(),
208 token::LArrow => "<-".to_string(),
209 token::FatArrow => "=>".to_string(),
210 token::OpenDelim(token::Paren) => "(".to_string(),
211 token::CloseDelim(token::Paren) => ")".to_string(),
212 token::OpenDelim(token::Bracket) => "[".to_string(),
213 token::CloseDelim(token::Bracket) => "]".to_string(),
214 token::OpenDelim(token::Brace) => "{".to_string(),
215 token::CloseDelim(token::Brace) => "}".to_string(),
216 token::OpenDelim(token::NoDelim) |
217 token::CloseDelim(token::NoDelim) => " ".to_string(),
218 token::Pound => "#".to_string(),
219 token::Dollar => "$".to_string(),
220 token::Question => "?".to_string(),
221 token::SingleQuote => "'".to_string(),
224 token::Literal(lit, suf) => {
225 let mut out = match lit {
226 token::Byte(b) => format!("b'{}'", b),
227 token::Char(c) => format!("'{}'", c),
228 token::Err(c) => format!("'{}'", c),
230 token::Integer(c) => c.to_string(),
231 token::Str_(s) => format!("\"{}\"", s),
232 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
233 delim="#".repeat(n as usize),
235 token::ByteStr(v) => format!("b\"{}\"", v),
236 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
237 delim="#".repeat(n as usize),
241 if let Some(s) = suf {
242 out.push_str(&s.as_str())
248 /* Name components */
249 token::Ident(s, false) => s.to_string(),
250 token::Ident(s, true) => format!("r#{}", s),
251 token::Lifetime(s) => s.to_string(),
254 token::DocComment(s) => s.to_string(),
255 token::Eof => "<eof>".to_string(),
256 token::Whitespace => " ".to_string(),
257 token::Comment => "/* */".to_string(),
258 token::Shebang(s) => format!("/* shebang: {}*/", s),
260 token::Interpolated(ref nt) => nonterminal_to_string(nt),
264 pub fn nonterminal_to_string(nt: &Nonterminal) -> String {
266 token::NtExpr(ref e) => expr_to_string(e),
267 token::NtMeta(ref e) => meta_item_to_string(e),
268 token::NtTy(ref e) => ty_to_string(e),
269 token::NtPath(ref e) => path_to_string(e),
270 token::NtItem(ref e) => item_to_string(e),
271 token::NtBlock(ref e) => block_to_string(e),
272 token::NtStmt(ref e) => stmt_to_string(e),
273 token::NtPat(ref e) => pat_to_string(e),
274 token::NtIdent(e, false) => ident_to_string(e),
275 token::NtIdent(e, true) => format!("r#{}", ident_to_string(e)),
276 token::NtLifetime(e) => ident_to_string(e),
277 token::NtLiteral(ref e) => expr_to_string(e),
278 token::NtTT(ref tree) => tt_to_string(tree.clone()),
279 token::NtArm(ref e) => arm_to_string(e),
280 token::NtImplItem(ref e) => impl_item_to_string(e),
281 token::NtTraitItem(ref e) => trait_item_to_string(e),
282 token::NtGenerics(ref e) => generic_params_to_string(&e.params),
283 token::NtWhereClause(ref e) => where_clause_to_string(e),
284 token::NtArg(ref e) => arg_to_string(e),
285 token::NtVis(ref e) => vis_to_string(e),
286 token::NtForeignItem(ref e) => foreign_item_to_string(e),
290 pub fn ty_to_string(ty: &ast::Ty) -> String {
291 to_string(|s| s.print_type(ty))
294 pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
295 to_string(|s| s.print_type_bounds("", bounds))
298 pub fn pat_to_string(pat: &ast::Pat) -> String {
299 to_string(|s| s.print_pat(pat))
302 pub fn arm_to_string(arm: &ast::Arm) -> String {
303 to_string(|s| s.print_arm(arm))
306 pub fn expr_to_string(e: &ast::Expr) -> String {
307 to_string(|s| s.print_expr(e))
310 pub fn lifetime_to_string(lt: &ast::Lifetime) -> String {
311 to_string(|s| s.print_lifetime(*lt))
314 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
315 to_string(|s| s.print_tt(tt))
318 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
319 to_string(|s| s.print_tts(tts.iter().cloned().collect()))
322 pub fn tokens_to_string(tokens: TokenStream) -> String {
323 to_string(|s| s.print_tts(tokens))
326 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
327 to_string(|s| s.print_stmt(stmt))
330 pub fn attr_to_string(attr: &ast::Attribute) -> String {
331 to_string(|s| s.print_attribute(attr))
334 pub fn item_to_string(i: &ast::Item) -> String {
335 to_string(|s| s.print_item(i))
338 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
339 to_string(|s| s.print_impl_item(i))
342 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
343 to_string(|s| s.print_trait_item(i))
346 pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String {
347 to_string(|s| s.print_generic_params(generic_params))
350 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
351 to_string(|s| s.print_where_clause(i))
354 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
355 to_string(|s| s.print_fn_block_args(p))
358 pub fn path_to_string(p: &ast::Path) -> String {
359 to_string(|s| s.print_path(p, false, 0))
362 pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
363 to_string(|s| s.print_path_segment(p, false))
366 pub fn ident_to_string(id: ast::Ident) -> String {
367 to_string(|s| s.print_ident(id))
370 pub fn vis_to_string(v: &ast::Visibility) -> String {
371 to_string(|s| s.print_visibility(v))
374 pub fn fun_to_string(decl: &ast::FnDecl,
375 header: ast::FnHeader,
377 generics: &ast::Generics)
381 s.print_fn(decl, header, Some(name),
382 generics, &source_map::dummy_spanned(ast::VisibilityKind::Inherited))?;
383 s.end()?; // Close the head box
384 s.end() // Close the outer box
388 pub fn block_to_string(blk: &ast::Block) -> String {
390 // containing cbox, will be closed by print-block at }
391 s.cbox(INDENT_UNIT)?;
392 // head-ibox, will be closed by print-block after {
398 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
399 to_string(|s| s.print_meta_list_item(li))
402 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
403 to_string(|s| s.print_meta_item(mi))
406 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
407 to_string(|s| s.print_attribute(attr))
410 pub fn lit_to_string(l: &ast::Lit) -> String {
411 to_string(|s| s.print_literal(l))
414 pub fn variant_to_string(var: &ast::Variant) -> String {
415 to_string(|s| s.print_variant(var))
418 pub fn arg_to_string(arg: &ast::Arg) -> String {
419 to_string(|s| s.print_arg(arg, false))
422 pub fn mac_to_string(arg: &ast::Mac) -> String {
423 to_string(|s| s.print_mac(arg))
426 pub fn foreign_item_to_string(arg: &ast::ForeignItem) -> String {
427 to_string(|s| s.print_foreign_item(arg))
430 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
431 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
434 pub trait PrintState<'a> {
435 fn writer(&mut self) -> &mut pp::Printer<'a>;
436 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
437 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
438 fn cur_cmnt(&mut self) -> &mut usize;
439 fn cur_lit(&mut self) -> Option<&comments::Literal>;
440 fn bump_lit(&mut self) -> Option<comments::Literal>;
442 fn word_space<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
443 self.writer().word(w)?;
444 self.writer().space()
447 fn popen(&mut self) -> io::Result<()> { self.writer().word("(") }
449 fn pclose(&mut self) -> io::Result<()> { self.writer().word(")") }
451 fn is_begin(&mut self) -> bool {
452 match self.writer().last_token() {
453 pp::Token::Begin(_) => true,
458 fn is_end(&mut self) -> bool {
459 match self.writer().last_token() {
460 pp::Token::End => true,
465 // is this the beginning of a line?
466 fn is_bol(&mut self) -> bool {
467 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
470 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
472 self.writer().hardbreak()?
478 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
479 self.boxes().push(b);
480 self.writer().rbox(u, b)
483 fn ibox(&mut self, u: usize) -> io::Result<()> {
484 self.boxes().push(pp::Breaks::Inconsistent);
485 self.writer().ibox(u)
488 fn end(&mut self) -> io::Result<()> {
489 self.boxes().pop().unwrap();
493 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
494 where F: FnMut(&mut Self, &T) -> io::Result<()>,
497 let mut first = true;
499 if first { first = false; } else { self.word_space(",")?; }
505 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
506 while let Some(ltrl) = self.cur_lit().cloned() {
507 if ltrl.pos > pos { break; }
509 // we don't need the value here since we're forced to clone cur_lit
510 // due to lack of NLL.
520 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
521 while let Some(ref cmnt) = self.next_comment() {
523 self.print_comment(cmnt)?;
531 fn print_comment(&mut self,
532 cmnt: &comments::Comment) -> io::Result<()> {
533 let r = match cmnt.style {
535 assert_eq!(cmnt.lines.len(), 1);
536 self.writer().zerobreak()?;
537 self.writer().word(cmnt.lines[0].clone())?;
538 self.writer().zerobreak()
540 comments::Isolated => {
541 self.hardbreak_if_not_bol()?;
542 for line in &cmnt.lines {
543 // Don't print empty lines because they will end up as trailing
545 if !line.is_empty() {
546 self.writer().word(line.clone())?;
548 self.writer().hardbreak()?;
552 comments::Trailing => {
554 self.writer().word(" ")?;
556 if cmnt.lines.len() == 1 {
557 self.writer().word(cmnt.lines[0].clone())?;
558 self.writer().hardbreak()
561 for line in &cmnt.lines {
562 if !line.is_empty() {
563 self.writer().word(line.clone())?;
565 self.writer().hardbreak()?;
570 comments::BlankLine => {
571 // We need to do at least one, possibly two hardbreaks.
572 let is_semi = match self.writer().last_token() {
573 pp::Token::String(s, _) => ";" == s,
576 if is_semi || self.is_begin() || self.is_end() {
577 self.writer().hardbreak()?;
579 self.writer().hardbreak()
584 *self.cur_cmnt() = *self.cur_cmnt() + 1;
591 fn next_comment(&mut self) -> Option<comments::Comment> {
592 let cur_cmnt = *self.cur_cmnt();
593 match *self.comments() {
595 if cur_cmnt < cmnts.len() {
596 Some(cmnts[cur_cmnt].clone())
605 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
606 self.maybe_print_comment(lit.span.lo())?;
607 if let Some(ltrl) = self.next_lit(lit.span.lo()) {
608 return self.writer().word(ltrl.lit.clone());
611 ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style),
612 ast::LitKind::Err(st) => {
613 let st = st.as_str().escape_debug().to_string();
614 let mut res = String::with_capacity(st.len() + 2);
618 self.writer().word(res)
620 ast::LitKind::Byte(byte) => {
621 let mut res = String::from("b'");
622 res.extend(ascii::escape_default(byte).map(|c| c as char));
624 self.writer().word(res)
626 ast::LitKind::Char(ch) => {
627 let mut res = String::from("'");
628 res.extend(ch.escape_default());
630 self.writer().word(res)
632 ast::LitKind::Int(i, t) => {
634 ast::LitIntType::Signed(st) => {
635 self.writer().word(st.val_to_string(i as i128))
637 ast::LitIntType::Unsigned(ut) => {
638 self.writer().word(ut.val_to_string(i))
640 ast::LitIntType::Unsuffixed => {
641 self.writer().word(i.to_string())
645 ast::LitKind::Float(ref f, t) => {
646 self.writer().word(format!("{}{}", &f, t.ty_to_string()))
648 ast::LitKind::FloatUnsuffixed(ref f) => self.writer().word(f.as_str().get()),
649 ast::LitKind::Bool(val) => {
650 if val { self.writer().word("true") } else { self.writer().word("false") }
652 ast::LitKind::ByteStr(ref v) => {
653 let mut escaped: String = String::new();
654 for &ch in v.iter() {
655 escaped.extend(ascii::escape_default(ch)
656 .map(|c| c as char));
658 self.writer().word(format!("b\"{}\"", escaped))
663 fn print_string(&mut self, st: &str,
664 style: ast::StrStyle) -> io::Result<()> {
665 let st = match style {
666 ast::StrStyle::Cooked => {
667 (format!("\"{}\"", st.escape_debug()))
669 ast::StrStyle::Raw(n) => {
670 (format!("r{delim}\"{string}\"{delim}",
671 delim="#".repeat(n as usize),
675 self.writer().word(st)
678 fn print_inner_attributes(&mut self,
679 attrs: &[ast::Attribute]) -> io::Result<()> {
680 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
683 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
684 attrs: &[ast::Attribute])
686 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
689 fn print_outer_attributes(&mut self,
690 attrs: &[ast::Attribute]) -> io::Result<()> {
691 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
694 fn print_inner_attributes_inline(&mut self,
695 attrs: &[ast::Attribute]) -> io::Result<()> {
696 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
699 fn print_outer_attributes_inline(&mut self,
700 attrs: &[ast::Attribute]) -> io::Result<()> {
701 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
704 fn print_either_attributes(&mut self,
705 attrs: &[ast::Attribute],
706 kind: ast::AttrStyle,
708 trailing_hardbreak: bool) -> io::Result<()> {
711 if attr.style == kind {
712 self.print_attribute_inline(attr, is_inline)?;
719 if count > 0 && trailing_hardbreak && !is_inline {
720 self.hardbreak_if_not_bol()?;
725 fn print_attribute_path(&mut self, path: &ast::Path) -> io::Result<()> {
726 for (i, segment) in path.segments.iter().enumerate() {
728 self.writer().word("::")?
730 if segment.ident.name != keywords::PathRoot.name() {
731 if segment.ident.name == keywords::DollarCrate.name() {
732 self.print_dollar_crate(segment.ident)?;
734 self.writer().word(segment.ident.as_str().get())?;
741 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
742 self.print_attribute_inline(attr, false)
745 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
746 is_inline: bool) -> io::Result<()> {
748 self.hardbreak_if_not_bol()?;
750 self.maybe_print_comment(attr.span.lo())?;
751 if attr.is_sugared_doc {
752 self.writer().word(attr.value_str().unwrap().as_str().get())?;
753 self.writer().hardbreak()
756 ast::AttrStyle::Inner => self.writer().word("#![")?,
757 ast::AttrStyle::Outer => self.writer().word("#[")?,
759 if let Some(mi) = attr.meta() {
760 self.print_meta_item(&mi)?
762 self.print_attribute_path(&attr.path)?;
763 self.writer().space()?;
764 self.print_tts(attr.tokens.clone())?;
766 self.writer().word("]")
770 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> {
772 ast::NestedMetaItem::MetaItem(ref mi) => {
773 self.print_meta_item(mi)
775 ast::NestedMetaItem::Literal(ref lit) => {
776 self.print_literal(lit)
781 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
782 self.ibox(INDENT_UNIT)?;
784 ast::MetaItemKind::Word => self.print_attribute_path(&item.path)?,
785 ast::MetaItemKind::NameValue(ref value) => {
786 self.print_attribute_path(&item.path)?;
787 self.writer().space()?;
788 self.word_space("=")?;
789 self.print_literal(value)?;
791 ast::MetaItemKind::List(ref items) => {
792 self.print_attribute_path(&item.path)?;
794 self.commasep(Consistent,
796 |s, i| s.print_meta_list_item(i))?;
803 /// This doesn't deserve to be called "pretty" printing, but it should be
804 /// meaning-preserving. A quick hack that might help would be to look at the
805 /// spans embedded in the TTs to decide where to put spaces and newlines.
806 /// But it'd be better to parse these according to the grammar of the
807 /// appropriate macro, transcribe back into the grammar we just parsed from,
808 /// and then pretty-print the resulting AST nodes (so, e.g., we print
809 /// expression arguments as expressions). It can be done! I think.
810 fn print_tt(&mut self, tt: tokenstream::TokenTree) -> io::Result<()> {
812 TokenTree::Token(_, ref tk) => {
813 self.writer().word(token_to_string(tk))?;
815 parse::token::DocComment(..) => {
816 self.writer().hardbreak()
821 TokenTree::Delimited(_, delim, tts) => {
822 self.writer().word(token_to_string(&token::OpenDelim(delim)))?;
823 self.writer().space()?;
824 self.print_tts(tts)?;
825 self.writer().space()?;
826 self.writer().word(token_to_string(&token::CloseDelim(delim)))
831 fn print_tts(&mut self, tts: tokenstream::TokenStream) -> io::Result<()> {
833 for (i, tt) in tts.into_trees().enumerate() {
835 self.writer().space()?;
842 fn space_if_not_bol(&mut self) -> io::Result<()> {
843 if !self.is_bol() { self.writer().space()?; }
847 fn nbsp(&mut self) -> io::Result<()> { self.writer().word(" ") }
849 // AST pretty-printer is used as a fallback for turning AST structures into token streams for
850 // proc macros. Additionally, proc macros may stringify their input and expect it survive the
851 // stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
852 // So we need to somehow pretty-print `$crate` in paths in a way preserving at least some of
853 // its hygiene data, most importantly name of the crate it refers to.
854 // As a result we print `$crate` as `crate` if it refers to the local crate
855 // and as `::other_crate_name` if it refers to some other crate.
856 fn print_dollar_crate(&mut self, ident: ast::Ident) -> io::Result<()> {
857 let name = ident.span.ctxt().dollar_crate_name();
858 if !ast::Ident::with_empty_ctxt(name).is_path_segment_keyword() {
859 self.writer().word("::")?;
861 self.writer().word(name.as_str().get())
865 impl<'a> PrintState<'a> for State<'a> {
866 fn writer(&mut self) -> &mut pp::Printer<'a> {
870 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
874 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
878 fn cur_cmnt(&mut self) -> &mut usize {
882 fn cur_lit(&mut self) -> Option<&comments::Literal> {
886 fn bump_lit(&mut self) -> Option<comments::Literal> {
892 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
893 self.boxes.push(pp::Breaks::Consistent);
897 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
902 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
904 // outer-box is consistent
905 self.cbox(INDENT_UNIT)?;
906 // head-box is inconsistent
907 self.ibox(w.len() + 1)?;
908 // keyword that starts the head
915 pub fn bopen(&mut self) -> io::Result<()> {
917 self.end() // close the head-box
920 pub fn bclose_(&mut self, span: syntax_pos::Span,
921 indented: usize) -> io::Result<()> {
922 self.bclose_maybe_open(span, indented, true)
924 pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
925 indented: usize, close_box: bool) -> io::Result<()> {
926 self.maybe_print_comment(span.hi())?;
927 self.break_offset_if_not_bol(1, -(indented as isize))?;
930 self.end()?; // close the outer-box
934 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
935 self.bclose_(span, INDENT_UNIT)
938 pub fn in_cbox(&self) -> bool {
939 match self.boxes.last() {
940 Some(&last_box) => last_box == pp::Breaks::Consistent,
945 pub fn break_offset_if_not_bol(&mut self, n: usize,
946 off: isize) -> io::Result<()> {
948 self.s.break_offset(n, off)
950 if off != 0 && self.s.last_token().is_hardbreak_tok() {
951 // We do something pretty sketchy here: tuck the nonzero
952 // offset-adjustment we were going to deposit along with the
953 // break into the previous hardbreak.
954 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
960 // Synthesizes a comment that was not textually present in the original source
962 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
972 pub fn commasep_cmnt<T, F, G>(&mut self,
976 mut get_span: G) -> io::Result<()> where
977 F: FnMut(&mut State<'_>, &T) -> io::Result<()>,
978 G: FnMut(&T) -> syntax_pos::Span,
981 let len = elts.len();
984 self.maybe_print_comment(get_span(elt).hi())?;
989 self.maybe_print_trailing_comment(get_span(elt),
990 Some(get_span(&elts[i]).hi()))?;
991 self.space_if_not_bol()?;
997 pub fn commasep_exprs(&mut self, b: Breaks,
998 exprs: &[P<ast::Expr>]) -> io::Result<()> {
999 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
1002 pub fn print_mod(&mut self, _mod: &ast::Mod,
1003 attrs: &[ast::Attribute]) -> io::Result<()> {
1004 self.print_inner_attributes(attrs)?;
1005 for item in &_mod.items {
1006 self.print_item(item)?;
1011 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
1012 attrs: &[ast::Attribute]) -> io::Result<()> {
1013 self.print_inner_attributes(attrs)?;
1014 for item in &nmod.items {
1015 self.print_foreign_item(item)?;
1020 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
1021 if let Some(lt) = *lifetime {
1022 self.print_lifetime(lt)?;
1028 pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) -> io::Result<()> {
1030 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
1031 GenericArg::Type(ty) => self.print_type(ty),
1032 GenericArg::Const(ct) => self.print_expr(&ct.value),
1036 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
1037 self.maybe_print_comment(ty.span.lo())?;
1040 ast::TyKind::Slice(ref ty) => {
1042 self.print_type(ty)?;
1045 ast::TyKind::Ptr(ref mt) => {
1048 ast::Mutability::Mutable => self.word_nbsp("mut")?,
1049 ast::Mutability::Immutable => self.word_nbsp("const")?,
1051 self.print_type(&mt.ty)?;
1053 ast::TyKind::Rptr(ref lifetime, ref mt) => {
1055 self.print_opt_lifetime(lifetime)?;
1058 ast::TyKind::Never => {
1061 ast::TyKind::Tup(ref elts) => {
1063 self.commasep(Inconsistent, &elts[..],
1064 |s, ty| s.print_type(ty))?;
1065 if elts.len() == 1 {
1070 ast::TyKind::Paren(ref typ) => {
1072 self.print_type(typ)?;
1075 ast::TyKind::BareFn(ref f) => {
1076 self.print_ty_fn(f.abi,
1080 &f.generic_params)?;
1082 ast::TyKind::Path(None, ref path) => {
1083 self.print_path(path, false, 0)?;
1085 ast::TyKind::Path(Some(ref qself), ref path) => {
1086 self.print_qpath(path, qself, false)?
1088 ast::TyKind::TraitObject(ref bounds, syntax) => {
1089 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
1090 self.print_type_bounds(prefix, &bounds[..])?;
1092 ast::TyKind::ImplTrait(_, ref bounds) => {
1093 self.print_type_bounds("impl", &bounds[..])?;
1095 ast::TyKind::Array(ref ty, ref length) => {
1097 self.print_type(ty)?;
1099 self.print_expr(&length.value)?;
1102 ast::TyKind::Typeof(ref e) => {
1103 self.s.word("typeof(")?;
1104 self.print_expr(&e.value)?;
1107 ast::TyKind::Infer => {
1110 ast::TyKind::Err => {
1112 self.s.word("/*ERROR*/")?;
1115 ast::TyKind::ImplicitSelf => {
1116 self.s.word("Self")?;
1118 ast::TyKind::Mac(ref m) => {
1121 ast::TyKind::CVarArgs => {
1122 self.s.word("...")?;
1128 pub fn print_foreign_item(&mut self,
1129 item: &ast::ForeignItem) -> io::Result<()> {
1130 self.hardbreak_if_not_bol()?;
1131 self.maybe_print_comment(item.span.lo())?;
1132 self.print_outer_attributes(&item.attrs)?;
1134 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1136 self.print_fn(decl, ast::FnHeader::default(),
1138 generics, &item.vis)?;
1139 self.end()?; // end head-ibox
1141 self.end() // end the outer fn box
1143 ast::ForeignItemKind::Static(ref t, m) => {
1144 self.head(visibility_qualified(&item.vis, "static"))?;
1146 self.word_space("mut")?;
1148 self.print_ident(item.ident)?;
1149 self.word_space(":")?;
1150 self.print_type(t)?;
1152 self.end()?; // end the head-ibox
1153 self.end() // end the outer cbox
1155 ast::ForeignItemKind::Ty => {
1156 self.head(visibility_qualified(&item.vis, "type"))?;
1157 self.print_ident(item.ident)?;
1159 self.end()?; // end the head-ibox
1160 self.end() // end the outer cbox
1162 ast::ForeignItemKind::Macro(ref m) => {
1164 match m.node.delim {
1165 MacDelimiter::Brace => Ok(()),
1166 _ => self.s.word(";")
1172 fn print_associated_const(&mut self,
1175 default: Option<&ast::Expr>,
1176 vis: &ast::Visibility)
1179 self.s.word(visibility_qualified(vis, ""))?;
1180 self.word_space("const")?;
1181 self.print_ident(ident)?;
1182 self.word_space(":")?;
1183 self.print_type(ty)?;
1184 if let Some(expr) = default {
1186 self.word_space("=")?;
1187 self.print_expr(expr)?;
1192 fn print_associated_type(&mut self,
1194 bounds: Option<&ast::GenericBounds>,
1195 ty: Option<&ast::Ty>)
1197 self.word_space("type")?;
1198 self.print_ident(ident)?;
1199 if let Some(bounds) = bounds {
1200 self.print_type_bounds(":", bounds)?;
1202 if let Some(ty) = ty {
1204 self.word_space("=")?;
1205 self.print_type(ty)?;
1210 /// Pretty-print an item
1211 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1212 self.hardbreak_if_not_bol()?;
1213 self.maybe_print_comment(item.span.lo())?;
1214 self.print_outer_attributes(&item.attrs)?;
1215 self.ann.pre(self, AnnNode::Item(item))?;
1217 ast::ItemKind::ExternCrate(orig_name) => {
1218 self.head(visibility_qualified(&item.vis, "extern crate"))?;
1219 if let Some(orig_name) = orig_name {
1220 self.print_name(orig_name)?;
1225 self.print_ident(item.ident)?;
1227 self.end()?; // end inner head-block
1228 self.end()?; // end outer head-block
1230 ast::ItemKind::Use(ref tree) => {
1231 self.head(visibility_qualified(&item.vis, "use"))?;
1232 self.print_use_tree(tree)?;
1234 self.end()?; // end inner head-block
1235 self.end()?; // end outer head-block
1237 ast::ItemKind::Static(ref ty, m, ref expr) => {
1238 self.head(visibility_qualified(&item.vis, "static"))?;
1239 if m == ast::Mutability::Mutable {
1240 self.word_space("mut")?;
1242 self.print_ident(item.ident)?;
1243 self.word_space(":")?;
1244 self.print_type(ty)?;
1246 self.end()?; // end the head-ibox
1248 self.word_space("=")?;
1249 self.print_expr(expr)?;
1251 self.end()?; // end the outer cbox
1253 ast::ItemKind::Const(ref ty, ref expr) => {
1254 self.head(visibility_qualified(&item.vis, "const"))?;
1255 self.print_ident(item.ident)?;
1256 self.word_space(":")?;
1257 self.print_type(ty)?;
1259 self.end()?; // end the head-ibox
1261 self.word_space("=")?;
1262 self.print_expr(expr)?;
1264 self.end()?; // end the outer cbox
1266 ast::ItemKind::Fn(ref decl, header, ref param_names, ref body) => {
1276 self.print_block_with_attrs(body, &item.attrs)?;
1278 ast::ItemKind::Mod(ref _mod) => {
1279 self.head(visibility_qualified(&item.vis, "mod"))?;
1280 self.print_ident(item.ident)?;
1282 if _mod.inline || self.is_expanded {
1285 self.print_mod(_mod, &item.attrs)?;
1286 self.bclose(item.span)?;
1289 self.end()?; // end inner head-block
1290 self.end()?; // end outer head-block
1294 ast::ItemKind::ForeignMod(ref nmod) => {
1295 self.head("extern")?;
1296 self.word_nbsp(nmod.abi.to_string())?;
1298 self.print_foreign_mod(nmod, &item.attrs)?;
1299 self.bclose(item.span)?;
1301 ast::ItemKind::GlobalAsm(ref ga) => {
1302 self.head(visibility_qualified(&item.vis, "global_asm!"))?;
1303 self.s.word(ga.asm.as_str().get())?;
1306 ast::ItemKind::Ty(ref ty, ref generics) => {
1307 self.head(visibility_qualified(&item.vis, "type"))?;
1308 self.print_ident(item.ident)?;
1309 self.print_generic_params(&generics.params)?;
1310 self.end()?; // end the inner ibox
1312 self.print_where_clause(&generics.where_clause)?;
1314 self.word_space("=")?;
1315 self.print_type(ty)?;
1317 self.end()?; // end the outer ibox
1319 ast::ItemKind::Existential(ref bounds, ref generics) => {
1320 self.head(visibility_qualified(&item.vis, "existential type"))?;
1321 self.print_ident(item.ident)?;
1322 self.print_generic_params(&generics.params)?;
1323 self.end()?; // end the inner ibox
1325 self.print_where_clause(&generics.where_clause)?;
1327 self.print_type_bounds(":", bounds)?;
1329 self.end()?; // end the outer ibox
1331 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1332 self.print_enum_def(
1340 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1341 self.head(visibility_qualified(&item.vis, "struct"))?;
1342 self.print_struct(struct_def, generics, item.ident, item.span, true)?;
1344 ast::ItemKind::Union(ref struct_def, ref generics) => {
1345 self.head(visibility_qualified(&item.vis, "union"))?;
1346 self.print_struct(struct_def, generics, item.ident, item.span, true)?;
1348 ast::ItemKind::Impl(unsafety,
1354 ref impl_items) => {
1356 self.print_visibility(&item.vis)?;
1357 self.print_defaultness(defaultness)?;
1358 self.print_unsafety(unsafety)?;
1359 self.word_nbsp("impl")?;
1361 if !generics.params.is_empty() {
1362 self.print_generic_params(&generics.params)?;
1366 if polarity == ast::ImplPolarity::Negative {
1370 if let Some(ref t) = *opt_trait {
1371 self.print_trait_ref(t)?;
1373 self.word_space("for")?;
1376 self.print_type(ty)?;
1377 self.print_where_clause(&generics.where_clause)?;
1381 self.print_inner_attributes(&item.attrs)?;
1382 for impl_item in impl_items {
1383 self.print_impl_item(impl_item)?;
1385 self.bclose(item.span)?;
1387 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1389 self.print_visibility(&item.vis)?;
1390 self.print_unsafety(unsafety)?;
1391 self.print_is_auto(is_auto)?;
1392 self.word_nbsp("trait")?;
1393 self.print_ident(item.ident)?;
1394 self.print_generic_params(&generics.params)?;
1395 let mut real_bounds = Vec::with_capacity(bounds.len());
1396 for b in bounds.iter() {
1397 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1399 self.word_space("for ?")?;
1400 self.print_trait_ref(&ptr.trait_ref)?;
1402 real_bounds.push(b.clone());
1405 self.print_type_bounds(":", &real_bounds[..])?;
1406 self.print_where_clause(&generics.where_clause)?;
1409 for trait_item in trait_items {
1410 self.print_trait_item(trait_item)?;
1412 self.bclose(item.span)?;
1414 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1416 self.print_visibility(&item.vis)?;
1417 self.word_nbsp("trait")?;
1418 self.print_ident(item.ident)?;
1419 self.print_generic_params(&generics.params)?;
1420 let mut real_bounds = Vec::with_capacity(bounds.len());
1421 // FIXME(durka) this seems to be some quite outdated syntax
1422 for b in bounds.iter() {
1423 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1425 self.word_space("for ?")?;
1426 self.print_trait_ref(&ptr.trait_ref)?;
1428 real_bounds.push(b.clone());
1432 self.print_type_bounds("=", &real_bounds[..])?;
1433 self.print_where_clause(&generics.where_clause)?;
1436 ast::ItemKind::Mac(ref mac) => {
1437 if item.ident.name == keywords::Invalid.name() {
1438 self.print_mac(mac)?;
1439 match mac.node.delim {
1440 MacDelimiter::Brace => {}
1441 _ => self.s.word(";")?,
1444 self.print_path(&mac.node.path, false, 0)?;
1446 self.print_ident(item.ident)?;
1447 self.cbox(INDENT_UNIT)?;
1449 self.print_tts(mac.node.stream())?;
1455 ast::ItemKind::MacroDef(ref tts) => {
1456 self.s.word("macro_rules! ")?;
1457 self.print_ident(item.ident)?;
1458 self.cbox(INDENT_UNIT)?;
1460 self.print_tts(tts.stream())?;
1466 self.ann.post(self, AnnNode::Item(item))
1469 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1470 self.print_path(&t.path, false, 0)
1473 fn print_formal_generic_params(
1475 generic_params: &[ast::GenericParam]
1476 ) -> io::Result<()> {
1477 if !generic_params.is_empty() {
1478 self.s.word("for")?;
1479 self.print_generic_params(generic_params)?;
1485 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1486 self.print_formal_generic_params(&t.bound_generic_params)?;
1487 self.print_trait_ref(&t.trait_ref)
1490 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1491 generics: &ast::Generics, ident: ast::Ident,
1492 span: syntax_pos::Span,
1493 visibility: &ast::Visibility) -> io::Result<()> {
1494 self.head(visibility_qualified(visibility, "enum"))?;
1495 self.print_ident(ident)?;
1496 self.print_generic_params(&generics.params)?;
1497 self.print_where_clause(&generics.where_clause)?;
1499 self.print_variants(&enum_definition.variants, span)
1502 pub fn print_variants(&mut self,
1503 variants: &[ast::Variant],
1504 span: syntax_pos::Span) -> io::Result<()> {
1507 self.space_if_not_bol()?;
1508 self.maybe_print_comment(v.span.lo())?;
1509 self.print_outer_attributes(&v.node.attrs)?;
1510 self.ibox(INDENT_UNIT)?;
1511 self.print_variant(v)?;
1514 self.maybe_print_trailing_comment(v.span, None)?;
1519 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1521 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1522 ast::VisibilityKind::Crate(sugar) => match sugar {
1523 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1524 ast::CrateSugar::JustCrate => self.word_nbsp("crate")
1526 ast::VisibilityKind::Restricted { ref path, .. } => {
1527 let path = to_string(|s| s.print_path(path, false, 0));
1528 if path == "self" || path == "super" {
1529 self.word_nbsp(format!("pub({})", path))
1531 self.word_nbsp(format!("pub(in {})", path))
1534 ast::VisibilityKind::Inherited => Ok(())
1538 pub fn print_defaultness(&mut self, defaultness: ast::Defaultness) -> io::Result<()> {
1539 if let ast::Defaultness::Default = defaultness {
1540 self.word_nbsp("default")?;
1545 pub fn print_struct(&mut self,
1546 struct_def: &ast::VariantData,
1547 generics: &ast::Generics,
1549 span: syntax_pos::Span,
1550 print_finalizer: bool) -> io::Result<()> {
1551 self.print_ident(ident)?;
1552 self.print_generic_params(&generics.params)?;
1554 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1555 if let ast::VariantData::Tuple(..) = struct_def {
1558 Inconsistent, struct_def.fields(),
1560 s.maybe_print_comment(field.span.lo())?;
1561 s.print_outer_attributes(&field.attrs)?;
1562 s.print_visibility(&field.vis)?;
1563 s.print_type(&field.ty)
1568 self.print_where_clause(&generics.where_clause)?;
1569 if print_finalizer {
1573 self.end() // close the outer-box
1575 ast::VariantData::Struct(..) => {
1576 self.print_where_clause(&generics.where_clause)?;
1579 self.hardbreak_if_not_bol()?;
1581 for field in struct_def.fields() {
1582 self.hardbreak_if_not_bol()?;
1583 self.maybe_print_comment(field.span.lo())?;
1584 self.print_outer_attributes(&field.attrs)?;
1585 self.print_visibility(&field.vis)?;
1586 self.print_ident(field.ident.unwrap())?;
1587 self.word_nbsp(":")?;
1588 self.print_type(&field.ty)?;
1597 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1599 let generics = ast::Generics::default();
1600 self.print_struct(&v.node.data, &generics, v.node.ident, v.span, false)?;
1601 match v.node.disr_expr {
1604 self.word_space("=")?;
1605 self.print_expr(&d.value)
1611 pub fn print_method_sig(&mut self,
1613 generics: &ast::Generics,
1615 vis: &ast::Visibility)
1617 self.print_fn(&m.decl,
1624 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1626 self.ann.pre(self, AnnNode::SubItem(ti.id))?;
1627 self.hardbreak_if_not_bol()?;
1628 self.maybe_print_comment(ti.span.lo())?;
1629 self.print_outer_attributes(&ti.attrs)?;
1631 ast::TraitItemKind::Const(ref ty, ref default) => {
1632 self.print_associated_const(
1635 default.as_ref().map(|expr| &**expr),
1636 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1639 ast::TraitItemKind::Method(ref sig, ref body) => {
1643 self.print_method_sig(
1647 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1649 if let Some(ref body) = *body {
1651 self.print_block_with_attrs(body, &ti.attrs)?;
1656 ast::TraitItemKind::Type(ref bounds, ref default) => {
1657 self.print_associated_type(ti.ident, Some(bounds),
1658 default.as_ref().map(|ty| &**ty))?;
1660 ast::TraitItemKind::Macro(ref mac) => {
1661 self.print_mac(mac)?;
1662 match mac.node.delim {
1663 MacDelimiter::Brace => {}
1664 _ => self.s.word(";")?,
1668 self.ann.post(self, AnnNode::SubItem(ti.id))
1671 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1672 self.ann.pre(self, AnnNode::SubItem(ii.id))?;
1673 self.hardbreak_if_not_bol()?;
1674 self.maybe_print_comment(ii.span.lo())?;
1675 self.print_outer_attributes(&ii.attrs)?;
1676 self.print_defaultness(ii.defaultness)?;
1678 ast::ImplItemKind::Const(ref ty, ref expr) => {
1679 self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis)?;
1681 ast::ImplItemKind::Method(ref sig, ref body) => {
1683 self.print_method_sig(ii.ident, &ii.generics, sig, &ii.vis)?;
1685 self.print_block_with_attrs(body, &ii.attrs)?;
1687 ast::ImplItemKind::Type(ref ty) => {
1688 self.print_associated_type(ii.ident, None, Some(ty))?;
1690 ast::ImplItemKind::Existential(ref bounds) => {
1691 self.word_space("existential")?;
1692 self.print_associated_type(ii.ident, Some(bounds), None)?;
1694 ast::ImplItemKind::Macro(ref mac) => {
1695 self.print_mac(mac)?;
1696 match mac.node.delim {
1697 MacDelimiter::Brace => {}
1698 _ => self.s.word(";")?,
1702 self.ann.post(self, AnnNode::SubItem(ii.id))
1705 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1706 self.maybe_print_comment(st.span.lo())?;
1708 ast::StmtKind::Local(ref loc) => {
1709 self.print_outer_attributes(&loc.attrs)?;
1710 self.space_if_not_bol()?;
1711 self.ibox(INDENT_UNIT)?;
1712 self.word_nbsp("let")?;
1714 self.ibox(INDENT_UNIT)?;
1715 self.print_local_decl(loc)?;
1717 if let Some(ref init) = loc.init {
1719 self.word_space("=")?;
1720 self.print_expr(init)?;
1725 ast::StmtKind::Item(ref item) => self.print_item(item)?,
1726 ast::StmtKind::Expr(ref expr) => {
1727 self.space_if_not_bol()?;
1728 self.print_expr_outer_attr_style(expr, false)?;
1729 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1733 ast::StmtKind::Semi(ref expr) => {
1734 self.space_if_not_bol()?;
1735 self.print_expr_outer_attr_style(expr, false)?;
1738 ast::StmtKind::Mac(ref mac) => {
1739 let (ref mac, style, ref attrs) = **mac;
1740 self.space_if_not_bol()?;
1741 self.print_outer_attributes(attrs)?;
1742 self.print_mac(mac)?;
1743 if style == ast::MacStmtStyle::Semicolon {
1748 self.maybe_print_trailing_comment(st.span, None)
1751 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1752 self.print_block_with_attrs(blk, &[])
1755 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1756 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1759 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1760 attrs: &[ast::Attribute])
1762 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1765 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1766 indented: usize) -> io::Result<()> {
1767 self.print_block_maybe_unclosed(blk, indented, &[], false)
1770 pub fn print_block_with_attrs(&mut self,
1772 attrs: &[ast::Attribute]) -> io::Result<()> {
1773 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1776 pub fn print_block_maybe_unclosed(&mut self,
1779 attrs: &[ast::Attribute],
1780 close_box: bool) -> io::Result<()> {
1782 BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
1783 BlockCheckMode::Default => ()
1785 self.maybe_print_comment(blk.span.lo())?;
1786 self.ann.pre(self, AnnNode::Block(blk))?;
1789 self.print_inner_attributes(attrs)?;
1791 for (i, st) in blk.stmts.iter().enumerate() {
1793 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1794 self.maybe_print_comment(st.span.lo())?;
1795 self.space_if_not_bol()?;
1796 self.print_expr_outer_attr_style(expr, false)?;
1797 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1799 _ => self.print_stmt(st)?,
1803 self.bclose_maybe_open(blk.span, indented, close_box)?;
1804 self.ann.post(self, AnnNode::Block(blk))
1807 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1811 // "another else-if"
1812 ast::ExprKind::If(ref i, ref then, ref e) => {
1813 self.cbox(INDENT_UNIT - 1)?;
1815 self.s.word(" else if ")?;
1816 self.print_expr_as_cond(i)?;
1818 self.print_block(then)?;
1819 self.print_else(e.as_ref().map(|e| &**e))
1821 // "another else-if-let"
1822 ast::ExprKind::IfLet(ref pats, ref expr, ref then, ref e) => {
1823 self.cbox(INDENT_UNIT - 1)?;
1825 self.s.word(" else if let ")?;
1826 self.print_pats(pats)?;
1828 self.word_space("=")?;
1829 self.print_expr_as_cond(expr)?;
1831 self.print_block(then)?;
1832 self.print_else(e.as_ref().map(|e| &**e))
1835 ast::ExprKind::Block(ref b, _) => {
1836 self.cbox(INDENT_UNIT - 1)?;
1838 self.s.word(" else ")?;
1841 // BLEAH, constraints would be great here
1843 panic!("print_if saw if with weird alternative");
1851 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1852 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1854 self.print_expr_as_cond(test)?;
1856 self.print_block(blk)?;
1857 self.print_else(elseopt)
1860 pub fn print_if_let(&mut self, pats: &[P<ast::Pat>], expr: &ast::Expr, blk: &ast::Block,
1861 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1862 self.head("if let")?;
1863 self.print_pats(pats)?;
1865 self.word_space("=")?;
1866 self.print_expr_as_cond(expr)?;
1868 self.print_block(blk)?;
1869 self.print_else(elseopt)
1872 pub fn print_mac(&mut self, m: &ast::Mac) -> io::Result<()> {
1873 self.print_path(&m.node.path, false, 0)?;
1875 match m.node.delim {
1876 MacDelimiter::Parenthesis => self.popen()?,
1877 MacDelimiter::Bracket => self.s.word("[")?,
1878 MacDelimiter::Brace => {
1883 self.print_tts(m.node.stream())?;
1884 match m.node.delim {
1885 MacDelimiter::Parenthesis => self.pclose(),
1886 MacDelimiter::Bracket => self.s.word("]"),
1887 MacDelimiter::Brace => self.bclose(m.span),
1892 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1894 self.commasep_exprs(Inconsistent, args)?;
1898 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) -> io::Result<()> {
1899 let needs_par = expr.precedence().order() < prec;
1903 self.print_expr(expr)?;
1910 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1911 /// `if cond { ... }`.
1912 pub fn print_expr_as_cond(&mut self, expr: &ast::Expr) -> io::Result<()> {
1913 let needs_par = match expr.node {
1914 // These cases need parens due to the parse error observed in #26461: `if return {}`
1915 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1916 ast::ExprKind::Closure(..) |
1917 ast::ExprKind::Ret(..) |
1918 ast::ExprKind::Break(..) => true,
1920 _ => parser::contains_exterior_struct_lit(expr),
1926 self.print_expr(expr)?;
1933 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1934 attrs: &[Attribute]) -> io::Result<()> {
1935 self.ibox(INDENT_UNIT)?;
1937 self.print_inner_attributes_inline(attrs)?;
1938 self.commasep_exprs(Inconsistent, &exprs[..])?;
1943 fn print_expr_repeat(&mut self,
1944 element: &ast::Expr,
1945 count: &ast::AnonConst,
1946 attrs: &[Attribute]) -> io::Result<()> {
1947 self.ibox(INDENT_UNIT)?;
1949 self.print_inner_attributes_inline(attrs)?;
1950 self.print_expr(element)?;
1951 self.word_space(";")?;
1952 self.print_expr(&count.value)?;
1957 fn print_expr_struct(&mut self,
1959 fields: &[ast::Field],
1960 wth: &Option<P<ast::Expr>>,
1961 attrs: &[Attribute]) -> io::Result<()> {
1962 self.print_path(path, true, 0)?;
1964 self.print_inner_attributes_inline(attrs)?;
1969 s.ibox(INDENT_UNIT)?;
1970 if !field.is_shorthand {
1971 s.print_ident(field.ident)?;
1974 s.print_expr(&field.expr)?;
1980 self.ibox(INDENT_UNIT)?;
1981 if !fields.is_empty() {
1986 self.print_expr(expr)?;
1989 _ => if !fields.is_empty() {
1997 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1998 attrs: &[Attribute]) -> io::Result<()> {
2000 self.print_inner_attributes_inline(attrs)?;
2001 self.commasep_exprs(Inconsistent, &exprs[..])?;
2002 if exprs.len() == 1 {
2008 fn print_expr_call(&mut self,
2010 args: &[P<ast::Expr>]) -> io::Result<()> {
2013 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
2014 _ => parser::PREC_POSTFIX,
2017 self.print_expr_maybe_paren(func, prec)?;
2018 self.print_call_post(args)
2021 fn print_expr_method_call(&mut self,
2022 segment: &ast::PathSegment,
2023 args: &[P<ast::Expr>]) -> io::Result<()> {
2024 let base_args = &args[1..];
2025 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
2027 self.print_ident(segment.ident)?;
2028 if let Some(ref args) = segment.args {
2029 self.print_generic_args(args, true)?;
2031 self.print_call_post(base_args)
2034 fn print_expr_binary(&mut self,
2037 rhs: &ast::Expr) -> io::Result<()> {
2038 let assoc_op = AssocOp::from_ast_binop(op.node);
2039 let prec = assoc_op.precedence() as i8;
2040 let fixity = assoc_op.fixity();
2042 let (left_prec, right_prec) = match fixity {
2043 Fixity::Left => (prec, prec + 1),
2044 Fixity::Right => (prec + 1, prec),
2045 Fixity::None => (prec + 1, prec + 1),
2048 let left_prec = match (&lhs.node, op.node) {
2049 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
2050 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
2051 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
2052 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) |
2053 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
2057 self.print_expr_maybe_paren(lhs, left_prec)?;
2059 self.word_space(op.node.to_string())?;
2060 self.print_expr_maybe_paren(rhs, right_prec)
2063 fn print_expr_unary(&mut self,
2065 expr: &ast::Expr) -> io::Result<()> {
2066 self.s.word(ast::UnOp::to_string(op))?;
2067 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
2070 fn print_expr_addr_of(&mut self,
2071 mutability: ast::Mutability,
2072 expr: &ast::Expr) -> io::Result<()> {
2074 self.print_mutability(mutability)?;
2075 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
2078 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
2079 self.print_expr_outer_attr_style(expr, true)
2082 fn print_expr_outer_attr_style(&mut self,
2084 is_inline: bool) -> io::Result<()> {
2085 self.maybe_print_comment(expr.span.lo())?;
2087 let attrs = &expr.attrs;
2089 self.print_outer_attributes_inline(attrs)?;
2091 self.print_outer_attributes(attrs)?;
2094 self.ibox(INDENT_UNIT)?;
2095 self.ann.pre(self, AnnNode::Expr(expr))?;
2097 ast::ExprKind::Box(ref expr) => {
2098 self.word_space("box")?;
2099 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
2101 ast::ExprKind::ObsoleteInPlace(ref place, ref expr) => {
2102 let prec = AssocOp::ObsoleteInPlace.precedence() as i8;
2103 self.print_expr_maybe_paren(place, prec + 1)?;
2105 self.word_space("<-")?;
2106 self.print_expr_maybe_paren(expr, prec)?;
2108 ast::ExprKind::Array(ref exprs) => {
2109 self.print_expr_vec(&exprs[..], attrs)?;
2111 ast::ExprKind::Repeat(ref element, ref count) => {
2112 self.print_expr_repeat(element, count, attrs)?;
2114 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2115 self.print_expr_struct(path, &fields[..], wth, attrs)?;
2117 ast::ExprKind::Tup(ref exprs) => {
2118 self.print_expr_tup(&exprs[..], attrs)?;
2120 ast::ExprKind::Call(ref func, ref args) => {
2121 self.print_expr_call(func, &args[..])?;
2123 ast::ExprKind::MethodCall(ref segment, ref args) => {
2124 self.print_expr_method_call(segment, &args[..])?;
2126 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2127 self.print_expr_binary(op, lhs, rhs)?;
2129 ast::ExprKind::Unary(op, ref expr) => {
2130 self.print_expr_unary(op, expr)?;
2132 ast::ExprKind::AddrOf(m, ref expr) => {
2133 self.print_expr_addr_of(m, expr)?;
2135 ast::ExprKind::Lit(ref lit) => {
2136 self.print_literal(lit)?;
2138 ast::ExprKind::Cast(ref expr, ref ty) => {
2139 let prec = AssocOp::As.precedence() as i8;
2140 self.print_expr_maybe_paren(expr, prec)?;
2142 self.word_space("as")?;
2143 self.print_type(ty)?;
2145 ast::ExprKind::Type(ref expr, ref ty) => {
2146 let prec = AssocOp::Colon.precedence() as i8;
2147 self.print_expr_maybe_paren(expr, prec)?;
2148 self.word_space(":")?;
2149 self.print_type(ty)?;
2151 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2152 self.print_if(test, blk, elseopt.as_ref().map(|e| &**e))?;
2154 ast::ExprKind::IfLet(ref pats, ref expr, ref blk, ref elseopt) => {
2155 self.print_if_let(pats, expr, blk, elseopt.as_ref().map(|e| &**e))?;
2157 ast::ExprKind::While(ref test, ref blk, opt_label) => {
2158 if let Some(label) = opt_label {
2159 self.print_ident(label.ident)?;
2160 self.word_space(":")?;
2162 self.head("while")?;
2163 self.print_expr_as_cond(test)?;
2165 self.print_block_with_attrs(blk, attrs)?;
2167 ast::ExprKind::WhileLet(ref pats, ref expr, ref blk, opt_label) => {
2168 if let Some(label) = opt_label {
2169 self.print_ident(label.ident)?;
2170 self.word_space(":")?;
2172 self.head("while let")?;
2173 self.print_pats(pats)?;
2175 self.word_space("=")?;
2176 self.print_expr_as_cond(expr)?;
2178 self.print_block_with_attrs(blk, attrs)?;
2180 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2181 if let Some(label) = opt_label {
2182 self.print_ident(label.ident)?;
2183 self.word_space(":")?;
2186 self.print_pat(pat)?;
2188 self.word_space("in")?;
2189 self.print_expr_as_cond(iter)?;
2191 self.print_block_with_attrs(blk, attrs)?;
2193 ast::ExprKind::Loop(ref blk, opt_label) => {
2194 if let Some(label) = opt_label {
2195 self.print_ident(label.ident)?;
2196 self.word_space(":")?;
2200 self.print_block_with_attrs(blk, attrs)?;
2202 ast::ExprKind::Match(ref expr, ref arms) => {
2203 self.cbox(INDENT_UNIT)?;
2205 self.word_nbsp("match")?;
2206 self.print_expr_as_cond(expr)?;
2209 self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
2211 self.print_arm(arm)?;
2213 self.bclose_(expr.span, INDENT_UNIT)?;
2215 ast::ExprKind::Closure(
2216 capture_clause, asyncness, movability, ref decl, ref body, _) => {
2217 self.print_movability(movability)?;
2218 self.print_asyncness(asyncness)?;
2219 self.print_capture_clause(capture_clause)?;
2221 self.print_fn_block_args(decl)?;
2223 self.print_expr(body)?;
2224 self.end()?; // need to close a box
2226 // a box will be closed by print_expr, but we didn't want an overall
2227 // wrapper so we closed the corresponding opening. so create an
2228 // empty box to satisfy the close.
2231 ast::ExprKind::Block(ref blk, opt_label) => {
2232 if let Some(label) = opt_label {
2233 self.print_ident(label.ident)?;
2234 self.word_space(":")?;
2236 // containing cbox, will be closed by print-block at }
2237 self.cbox(INDENT_UNIT)?;
2238 // head-box, will be closed by print-block after {
2240 self.print_block_with_attrs(blk, attrs)?;
2242 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2243 self.word_nbsp("async")?;
2244 self.print_capture_clause(capture_clause)?;
2246 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2247 self.cbox(INDENT_UNIT)?;
2249 self.print_block_with_attrs(blk, attrs)?;
2251 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2252 let prec = AssocOp::Assign.precedence() as i8;
2253 self.print_expr_maybe_paren(lhs, prec + 1)?;
2255 self.word_space("=")?;
2256 self.print_expr_maybe_paren(rhs, prec)?;
2258 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2259 let prec = AssocOp::Assign.precedence() as i8;
2260 self.print_expr_maybe_paren(lhs, prec + 1)?;
2262 self.s.word(op.node.to_string())?;
2263 self.word_space("=")?;
2264 self.print_expr_maybe_paren(rhs, prec)?;
2266 ast::ExprKind::Field(ref expr, ident) => {
2267 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
2269 self.print_ident(ident)?;
2271 ast::ExprKind::Index(ref expr, ref index) => {
2272 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
2274 self.print_expr(index)?;
2277 ast::ExprKind::Range(ref start, ref end, limits) => {
2278 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2279 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2280 // Here we use a fake precedence value so that any child with lower precedence than
2281 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2282 let fake_prec = AssocOp::LOr.precedence() as i8;
2283 if let Some(ref e) = *start {
2284 self.print_expr_maybe_paren(e, fake_prec)?;
2286 if limits == ast::RangeLimits::HalfOpen {
2289 self.s.word("..=")?;
2291 if let Some(ref e) = *end {
2292 self.print_expr_maybe_paren(e, fake_prec)?;
2295 ast::ExprKind::Path(None, ref path) => {
2296 self.print_path(path, true, 0)?
2298 ast::ExprKind::Path(Some(ref qself), ref path) => {
2299 self.print_qpath(path, qself, true)?
2301 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2302 self.s.word("break")?;
2304 if let Some(label) = opt_label {
2305 self.print_ident(label.ident)?;
2308 if let Some(ref expr) = *opt_expr {
2309 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2313 ast::ExprKind::Continue(opt_label) => {
2314 self.s.word("continue")?;
2316 if let Some(label) = opt_label {
2317 self.print_ident(label.ident)?;
2321 ast::ExprKind::Ret(ref result) => {
2322 self.s.word("return")?;
2323 if let Some(ref expr) = *result {
2325 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2328 ast::ExprKind::InlineAsm(ref a) => {
2329 self.s.word("asm!")?;
2331 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
2332 self.word_space(":")?;
2334 self.commasep(Inconsistent, &a.outputs, |s, out| {
2335 let constraint = out.constraint.as_str();
2336 let mut ch = constraint.chars();
2338 Some('=') if out.is_rw => {
2339 s.print_string(&format!("+{}", ch.as_str()),
2340 ast::StrStyle::Cooked)?
2342 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?
2345 s.print_expr(&out.expr)?;
2350 self.word_space(":")?;
2352 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2353 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2360 self.word_space(":")?;
2362 self.commasep(Inconsistent, &a.clobbers,
2364 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2368 let mut options = vec![];
2370 options.push("volatile");
2373 options.push("alignstack");
2375 if a.dialect == ast::AsmDialect::Intel {
2376 options.push("intel");
2379 if !options.is_empty() {
2381 self.word_space(":")?;
2382 self.commasep(Inconsistent, &options,
2384 s.print_string(co, ast::StrStyle::Cooked)?;
2391 ast::ExprKind::Mac(ref m) => self.print_mac(m)?,
2392 ast::ExprKind::Paren(ref e) => {
2394 self.print_inner_attributes_inline(attrs)?;
2395 self.print_expr(e)?;
2398 ast::ExprKind::Yield(ref e) => {
2399 self.s.word("yield")?;
2403 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2408 ast::ExprKind::Try(ref e) => {
2409 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX)?;
2412 ast::ExprKind::TryBlock(ref blk) => {
2415 self.print_block_with_attrs(blk, attrs)?
2417 ast::ExprKind::Err => {
2419 self.s.word("/*ERROR*/")?;
2423 self.ann.post(self, AnnNode::Expr(expr))?;
2427 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2428 self.print_pat(&loc.pat)?;
2429 if let Some(ref ty) = loc.ty {
2430 self.word_space(":")?;
2431 self.print_type(ty)?;
2436 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2437 if ident.is_raw_guess() {
2438 self.s.word(format!("r#{}", ident))?;
2440 self.s.word(ident.as_str().get())?;
2442 self.ann.post(self, AnnNode::Ident(&ident))
2445 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2446 self.s.word(i.to_string())
2449 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2450 self.s.word(name.as_str().get())?;
2451 self.ann.post(self, AnnNode::Name(&name))
2454 pub fn print_for_decl(&mut self, loc: &ast::Local,
2455 coll: &ast::Expr) -> io::Result<()> {
2456 self.print_local_decl(loc)?;
2458 self.word_space("in")?;
2459 self.print_expr(coll)
2462 fn print_path(&mut self,
2464 colons_before_params: bool,
2468 self.maybe_print_comment(path.span.lo())?;
2470 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
2474 self.print_path_segment(segment, colons_before_params)?;
2480 fn print_path_segment(&mut self,
2481 segment: &ast::PathSegment,
2482 colons_before_params: bool)
2485 if segment.ident.name != keywords::PathRoot.name() {
2486 if segment.ident.name == keywords::DollarCrate.name() {
2487 self.print_dollar_crate(segment.ident)?;
2489 self.print_ident(segment.ident)?;
2491 if let Some(ref args) = segment.args {
2492 self.print_generic_args(args, colons_before_params)?;
2498 fn print_qpath(&mut self,
2501 colons_before_params: bool)
2505 self.print_type(&qself.ty)?;
2506 if qself.position > 0 {
2508 self.word_space("as")?;
2509 let depth = path.segments.len() - qself.position;
2510 self.print_path(path, false, depth)?;
2514 let item_segment = path.segments.last().unwrap();
2515 self.print_ident(item_segment.ident)?;
2516 match item_segment.args {
2517 Some(ref args) => self.print_generic_args(args, colons_before_params),
2522 fn print_generic_args(&mut self,
2523 args: &ast::GenericArgs,
2524 colons_before_params: bool)
2527 if colons_before_params {
2532 ast::GenericArgs::AngleBracketed(ref data) => {
2535 self.commasep(Inconsistent, &data.args, |s, generic_arg| {
2536 s.print_generic_arg(generic_arg)
2539 let mut comma = data.args.len() != 0;
2541 for binding in data.bindings.iter() {
2543 self.word_space(",")?
2545 self.print_ident(binding.ident)?;
2547 self.word_space("=")?;
2548 self.print_type(&binding.ty)?;
2555 ast::GenericArgs::Parenthesized(ref data) => {
2560 |s, ty| s.print_type(ty))?;
2563 if let Some(ref ty) = data.output {
2564 self.space_if_not_bol()?;
2565 self.word_space("->")?;
2566 self.print_type(ty)?;
2574 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2575 self.maybe_print_comment(pat.span.lo())?;
2576 self.ann.pre(self, AnnNode::Pat(pat))?;
2577 /* Pat isn't normalized, but the beauty of it
2578 is that it doesn't matter */
2580 PatKind::Wild => self.s.word("_")?,
2581 PatKind::Ident(binding_mode, ident, ref sub) => {
2582 match binding_mode {
2583 ast::BindingMode::ByRef(mutbl) => {
2584 self.word_nbsp("ref")?;
2585 self.print_mutability(mutbl)?;
2587 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2588 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2589 self.word_nbsp("mut")?;
2592 self.print_ident(ident)?;
2593 if let Some(ref p) = *sub {
2598 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2599 self.print_path(path, true, 0)?;
2601 if let Some(ddpos) = ddpos {
2602 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
2604 self.word_space(",")?;
2607 if ddpos != elts.len() {
2609 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
2612 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
2616 PatKind::Path(None, ref path) => {
2617 self.print_path(path, true, 0)?;
2619 PatKind::Path(Some(ref qself), ref path) => {
2620 self.print_qpath(path, qself, false)?;
2622 PatKind::Struct(ref path, ref fields, etc) => {
2623 self.print_path(path, true, 0)?;
2625 self.word_space("{")?;
2627 Consistent, &fields[..],
2629 s.cbox(INDENT_UNIT)?;
2630 if !f.node.is_shorthand {
2631 s.print_ident(f.node.ident)?;
2634 s.print_pat(&f.node.pat)?;
2637 |f| f.node.pat.span)?;
2639 if !fields.is_empty() { self.word_space(",")?; }
2645 PatKind::Tuple(ref elts, ddpos) => {
2647 if let Some(ddpos) = ddpos {
2648 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
2650 self.word_space(",")?;
2653 if ddpos != elts.len() {
2655 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
2658 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
2659 if elts.len() == 1 {
2665 PatKind::Box(ref inner) => {
2666 self.s.word("box ")?;
2667 self.print_pat(inner)?;
2669 PatKind::Ref(ref inner, mutbl) => {
2671 if mutbl == ast::Mutability::Mutable {
2672 self.s.word("mut ")?;
2674 self.print_pat(inner)?;
2676 PatKind::Lit(ref e) => self.print_expr(&**e)?,
2677 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2678 self.print_expr(begin)?;
2681 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("...")?,
2682 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..=")?,
2683 RangeEnd::Excluded => self.s.word("..")?,
2685 self.print_expr(end)?;
2687 PatKind::Slice(ref before, ref slice, ref after) => {
2689 self.commasep(Inconsistent,
2691 |s, p| s.print_pat(p))?;
2692 if let Some(ref p) = *slice {
2693 if !before.is_empty() { self.word_space(",")?; }
2694 if let PatKind::Wild = p.node {
2700 if !after.is_empty() { self.word_space(",")?; }
2702 self.commasep(Inconsistent,
2704 |s, p| s.print_pat(p))?;
2707 PatKind::Paren(ref inner) => {
2709 self.print_pat(inner)?;
2712 PatKind::Mac(ref m) => self.print_mac(m)?,
2714 self.ann.post(self, AnnNode::Pat(pat))
2717 fn print_pats(&mut self, pats: &[P<ast::Pat>]) -> io::Result<()> {
2718 let mut first = true;
2724 self.word_space("|")?;
2731 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2732 // I have no idea why this check is necessary, but here it
2734 if arm.attrs.is_empty() {
2737 self.cbox(INDENT_UNIT)?;
2739 self.maybe_print_comment(arm.pats[0].span.lo())?;
2740 self.print_outer_attributes(&arm.attrs)?;
2741 self.print_pats(&arm.pats)?;
2743 if let Some(ref g) = arm.guard {
2745 ast::Guard::If(ref e) => {
2746 self.word_space("if")?;
2747 self.print_expr(e)?;
2752 self.word_space("=>")?;
2754 match arm.body.node {
2755 ast::ExprKind::Block(ref blk, opt_label) => {
2756 if let Some(label) = opt_label {
2757 self.print_ident(label.ident)?;
2758 self.word_space(":")?;
2761 // the block will close the pattern's ibox
2762 self.print_block_unclosed_indent(blk, INDENT_UNIT)?;
2764 // If it is a user-provided unsafe block, print a comma after it
2765 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2770 self.end()?; // close the ibox for the pattern
2771 self.print_expr(&arm.body)?;
2775 self.end() // close enclosing cbox
2778 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2779 match explicit_self.node {
2780 SelfKind::Value(m) => {
2781 self.print_mutability(m)?;
2784 SelfKind::Region(ref lt, m) => {
2786 self.print_opt_lifetime(lt)?;
2787 self.print_mutability(m)?;
2790 SelfKind::Explicit(ref typ, m) => {
2791 self.print_mutability(m)?;
2792 self.s.word("self")?;
2793 self.word_space(":")?;
2794 self.print_type(typ)
2799 pub fn print_fn(&mut self,
2801 header: ast::FnHeader,
2802 name: Option<ast::Ident>,
2803 generics: &ast::Generics,
2804 vis: &ast::Visibility) -> io::Result<()> {
2805 self.print_fn_header_info(header, vis)?;
2807 if let Some(name) = name {
2809 self.print_ident(name)?;
2811 self.print_generic_params(&generics.params)?;
2812 self.print_fn_args_and_ret(decl)?;
2813 self.print_where_clause(&generics.where_clause)
2816 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2819 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
2822 self.print_fn_output(decl)
2825 pub fn print_fn_block_args(
2830 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
2833 if let ast::FunctionRetTy::Default(..) = decl.output {
2837 self.space_if_not_bol()?;
2838 self.word_space("->")?;
2840 ast::FunctionRetTy::Ty(ref ty) => {
2841 self.print_type(ty)?;
2842 self.maybe_print_comment(ty.span.lo())
2844 ast::FunctionRetTy::Default(..) => unreachable!(),
2848 pub fn print_movability(&mut self, movability: ast::Movability)
2851 ast::Movability::Static => self.word_space("static"),
2852 ast::Movability::Movable => Ok(()),
2856 pub fn print_asyncness(&mut self, asyncness: ast::IsAsync)
2858 if asyncness.is_async() {
2859 self.word_nbsp("async")?;
2864 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2866 match capture_clause {
2867 ast::CaptureBy::Value => self.word_space("move"),
2868 ast::CaptureBy::Ref => Ok(()),
2872 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound])
2874 if !bounds.is_empty() {
2875 self.s.word(prefix)?;
2876 let mut first = true;
2877 for bound in bounds {
2878 if !(first && prefix.is_empty()) {
2884 self.word_space("+")?;
2888 GenericBound::Trait(tref, modifier) => {
2889 if modifier == &TraitBoundModifier::Maybe {
2892 self.print_poly_trait_ref(tref)?;
2894 GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
2901 pub fn print_lifetime(&mut self, lifetime: ast::Lifetime) -> io::Result<()> {
2902 self.print_name(lifetime.ident.name)
2905 pub fn print_lifetime_bounds(&mut self, lifetime: ast::Lifetime, bounds: &ast::GenericBounds)
2908 self.print_lifetime(lifetime)?;
2909 if !bounds.is_empty() {
2911 for (i, bound) in bounds.iter().enumerate() {
2913 self.s.word(" + ")?;
2916 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
2924 pub fn print_generic_params(
2926 generic_params: &[ast::GenericParam]
2927 ) -> io::Result<()> {
2928 if generic_params.is_empty() {
2934 self.commasep(Inconsistent, &generic_params, |s, param| {
2936 ast::GenericParamKind::Lifetime => {
2937 s.print_outer_attributes_inline(¶m.attrs)?;
2938 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2939 s.print_lifetime_bounds(lt, ¶m.bounds)
2941 ast::GenericParamKind::Type { ref default } => {
2942 s.print_outer_attributes_inline(¶m.attrs)?;
2943 s.print_ident(param.ident)?;
2944 s.print_type_bounds(":", ¶m.bounds)?;
2946 Some(ref default) => {
2949 s.print_type(default)
2954 ast::GenericParamKind::Const { ref ty } => {
2955 s.print_outer_attributes_inline(¶m.attrs)?;
2956 s.word_space("const")?;
2957 s.print_ident(param.ident)?;
2961 s.print_type_bounds(":", ¶m.bounds)
2970 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2972 if where_clause.predicates.is_empty() {
2977 self.word_space("where")?;
2979 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2981 self.word_space(",")?;
2985 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2986 ref bound_generic_params,
2991 self.print_formal_generic_params(bound_generic_params)?;
2992 self.print_type(bounded_ty)?;
2993 self.print_type_bounds(":", bounds)?;
2995 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2998 self.print_lifetime_bounds(*lifetime, bounds)?;
3000 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
3003 self.print_type(lhs_ty)?;
3005 self.word_space("=")?;
3006 self.print_type(rhs_ty)?;
3014 pub fn print_use_tree(&mut self, tree: &ast::UseTree) -> io::Result<()> {
3016 ast::UseTreeKind::Simple(rename, ..) => {
3017 self.print_path(&tree.prefix, false, 0)?;
3018 if let Some(rename) = rename {
3020 self.word_space("as")?;
3021 self.print_ident(rename)?;
3024 ast::UseTreeKind::Glob => {
3025 if !tree.prefix.segments.is_empty() {
3026 self.print_path(&tree.prefix, false, 0)?;
3031 ast::UseTreeKind::Nested(ref items) => {
3032 if tree.prefix.segments.is_empty() {
3035 self.print_path(&tree.prefix, false, 0)?;
3036 self.s.word("::{")?;
3038 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
3039 this.print_use_tree(tree)
3048 pub fn print_mutability(&mut self,
3049 mutbl: ast::Mutability) -> io::Result<()> {
3051 ast::Mutability::Mutable => self.word_nbsp("mut"),
3052 ast::Mutability::Immutable => Ok(()),
3056 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
3057 self.print_mutability(mt.mutbl)?;
3058 self.print_type(&mt.ty)
3061 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
3062 self.ibox(INDENT_UNIT)?;
3063 match input.ty.node {
3064 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat)?,
3066 if let Some(eself) = input.to_self() {
3067 self.print_explicit_self(&eself)?;
3069 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
3070 ident.name == keywords::Invalid.name()
3075 self.print_pat(&input.pat)?;
3079 self.print_type(&input.ty)?;
3086 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
3087 if let ast::FunctionRetTy::Default(..) = decl.output {
3091 self.space_if_not_bol()?;
3092 self.ibox(INDENT_UNIT)?;
3093 self.word_space("->")?;
3095 ast::FunctionRetTy::Default(..) => unreachable!(),
3096 ast::FunctionRetTy::Ty(ref ty) =>
3097 self.print_type(ty)?
3102 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo()),
3107 pub fn print_ty_fn(&mut self,
3109 unsafety: ast::Unsafety,
3111 name: Option<ast::Ident>,
3112 generic_params: &[ast::GenericParam])
3114 self.ibox(INDENT_UNIT)?;
3115 if !generic_params.is_empty() {
3116 self.s.word("for")?;
3117 self.print_generic_params(generic_params)?;
3119 let generics = ast::Generics {
3121 where_clause: ast::WhereClause {
3122 id: ast::DUMMY_NODE_ID,
3123 predicates: Vec::new(),
3124 span: syntax_pos::DUMMY_SP,
3126 span: syntax_pos::DUMMY_SP,
3129 ast::FnHeader { unsafety, abi, ..ast::FnHeader::default() },
3132 &source_map::dummy_spanned(ast::VisibilityKind::Inherited))?;
3136 pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
3137 next_pos: Option<BytePos>)
3139 let cm = match self.cm {
3143 if let Some(ref cmnt) = self.next_comment() {
3144 if cmnt.style != comments::Trailing { return Ok(()) }
3145 let span_line = cm.lookup_char_pos(span.hi());
3146 let comment_line = cm.lookup_char_pos(cmnt.pos);
3147 let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1));
3148 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
3149 self.print_comment(cmnt)?;
3155 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3156 // If there aren't any remaining comments, then we need to manually
3157 // make sure there is a line break at the end.
3158 if self.next_comment().is_none() {
3159 self.s.hardbreak()?;
3161 while let Some(ref cmnt) = self.next_comment() {
3162 self.print_comment(cmnt)?;
3167 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3168 opt_abi: Option<Abi>)
3171 Some(Abi::Rust) => Ok(()),
3173 self.word_nbsp("extern")?;
3174 self.word_nbsp(abi.to_string())
3180 pub fn print_extern_opt_abi(&mut self,
3181 opt_abi: Option<Abi>) -> io::Result<()> {
3184 self.word_nbsp("extern")?;
3185 self.word_nbsp(abi.to_string())
3191 pub fn print_fn_header_info(&mut self,
3192 header: ast::FnHeader,
3193 vis: &ast::Visibility) -> io::Result<()> {
3194 self.s.word(visibility_qualified(vis, ""))?;
3196 match header.constness.node {
3197 ast::Constness::NotConst => {}
3198 ast::Constness::Const => self.word_nbsp("const")?
3201 self.print_asyncness(header.asyncness.node)?;
3202 self.print_unsafety(header.unsafety)?;
3204 if header.abi != Abi::Rust {
3205 self.word_nbsp("extern")?;
3206 self.word_nbsp(header.abi.to_string())?;
3212 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3214 ast::Unsafety::Normal => Ok(()),
3215 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3219 pub fn print_is_auto(&mut self, s: ast::IsAuto) -> io::Result<()> {
3221 ast::IsAuto::Yes => self.word_nbsp("auto"),
3222 ast::IsAuto::No => Ok(()),
3232 use crate::source_map;
3233 use crate::with_globals;
3237 fn test_fun_to_string() {
3239 let abba_ident = ast::Ident::from_str("abba");
3241 let decl = ast::FnDecl {
3243 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
3246 let generics = ast::Generics::default();
3251 unsafety: ast::Unsafety::Normal,
3252 constness: source_map::dummy_spanned(ast::Constness::NotConst),
3253 asyncness: source_map::dummy_spanned(ast::IsAsync::NotAsync),
3265 fn test_variant_to_string() {
3267 let ident = ast::Ident::from_str("principal_skinner");
3269 let var = source_map::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
3272 id: ast::DUMMY_NODE_ID,
3273 // making this up as I go.... ?
3274 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3278 let varstr = variant_to_string(&var);
3279 assert_eq!(varstr, "principal_skinner");