1 use rustc_target::spec::abi::{self, Abi};
2 use ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax};
3 use ast::{SelfKind, GenericBound, TraitBoundModifier};
4 use ast::{Attribute, MacDelimiter, GenericArg};
5 use util::parser::{self, AssocOp, Fixity};
7 use source_map::{self, SourceMap, Spanned};
8 use syntax_pos::{self, BytePos};
9 use parse::token::{self, BinOpToken, Token};
10 use parse::lexer::comments;
11 use parse::{self, ParseSess};
12 use print::pp::{self, Breaks};
13 use print::pp::Breaks::{Consistent, Inconsistent};
17 use syntax_pos::{DUMMY_SP, FileName};
18 use tokenstream::{self, TokenStream, TokenTree};
22 use std::io::{self, Write, Read};
23 use std::iter::Peekable;
26 pub enum AnnNode<'a> {
27 Ident(&'a ast::Ident),
29 Block(&'a ast::Block),
37 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
38 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
41 #[derive(Copy, Clone)]
44 impl PpAnn for NoAnn {}
46 pub struct State<'a> {
47 pub s: pp::Printer<'a>,
48 cm: Option<&'a SourceMap>,
49 comments: Option<Vec<comments::Comment> >,
50 literals: Peekable<vec::IntoIter<comments::Literal>>,
52 boxes: Vec<pp::Breaks>,
53 ann: &'a (dyn PpAnn+'a),
57 fn rust_printer<'a>(writer: Box<dyn Write+'a>, ann: &'a dyn PpAnn) -> State<'a> {
59 s: pp::mk_printer(writer, DEFAULT_COLUMNS),
62 literals: vec![].into_iter().peekable(),
70 pub const INDENT_UNIT: usize = 4;
72 pub const DEFAULT_COLUMNS: usize = 78;
74 /// Requires you to pass an input filename and reader so that
75 /// it can scan the input text for comments and literals to
77 pub fn print_crate<'a>(cm: &'a SourceMap,
82 out: Box<dyn Write+'a>,
84 is_expanded: bool) -> io::Result<()> {
85 let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
87 if is_expanded && std_inject::injected_crate_name().is_some() {
88 // We need to print `#![no_std]` (and its feature gate) so that
89 // compiling pretty-printed source won't inject libstd again.
90 // However we don't want these attributes in the AST because
91 // of the feature gate, so we fake them up here.
93 // #![feature(prelude_import)]
94 let pi_nested = attr::mk_nested_word_item(ast::Ident::from_str("prelude_import"));
95 let list = attr::mk_list_item(DUMMY_SP, ast::Ident::from_str("feature"), vec![pi_nested]);
96 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), list);
97 s.print_attribute(&fake_attr)?;
100 let no_std_meta = attr::mk_word_item(ast::Ident::from_str("no_std"));
101 let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), no_std_meta);
102 s.print_attribute(&fake_attr)?;
105 s.print_mod(&krate.module, &krate.attrs)?;
106 s.print_remaining_comments()?;
111 pub fn new_from_input(cm: &'a SourceMap,
114 input: &mut dyn Read,
115 out: Box<dyn Write+'a>,
117 is_expanded: bool) -> State<'a> {
118 let (cmnts, lits) = comments::gather_comments_and_literals(sess, filename, input);
125 // If the code is post expansion, don't use the table of
126 // literals, since it doesn't correspond with the literals
127 // in the AST anymore.
128 if is_expanded { None } else { Some(lits) },
133 pub fn new(cm: &'a SourceMap,
134 out: Box<dyn Write+'a>,
136 comments: Option<Vec<comments::Comment>>,
137 literals: Option<Vec<comments::Literal>>,
138 is_expanded: bool) -> State<'a> {
140 s: pp::mk_printer(out, DEFAULT_COLUMNS),
143 literals: literals.unwrap_or_default().into_iter().peekable(),
147 is_expanded: is_expanded
152 pub fn to_string<F>(f: F) -> String where
153 F: FnOnce(&mut State) -> io::Result<()>,
155 let mut wr = Vec::new();
158 let mut printer = rust_printer(Box::new(&mut wr), &ann);
159 f(&mut printer).unwrap();
160 printer.s.eof().unwrap();
162 String::from_utf8(wr).unwrap()
165 fn binop_to_string(op: BinOpToken) -> &'static str {
171 token::Percent => "%",
180 pub fn token_to_string(tok: &Token) -> String {
182 token::Eq => "=".to_string(),
183 token::Lt => "<".to_string(),
184 token::Le => "<=".to_string(),
185 token::EqEq => "==".to_string(),
186 token::Ne => "!=".to_string(),
187 token::Ge => ">=".to_string(),
188 token::Gt => ">".to_string(),
189 token::Not => "!".to_string(),
190 token::Tilde => "~".to_string(),
191 token::OrOr => "||".to_string(),
192 token::AndAnd => "&&".to_string(),
193 token::BinOp(op) => binop_to_string(op).to_string(),
194 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
196 /* Structural symbols */
197 token::At => "@".to_string(),
198 token::Dot => ".".to_string(),
199 token::DotDot => "..".to_string(),
200 token::DotDotDot => "...".to_string(),
201 token::DotDotEq => "..=".to_string(),
202 token::Comma => ",".to_string(),
203 token::Semi => ";".to_string(),
204 token::Colon => ":".to_string(),
205 token::ModSep => "::".to_string(),
206 token::RArrow => "->".to_string(),
207 token::LArrow => "<-".to_string(),
208 token::FatArrow => "=>".to_string(),
209 token::OpenDelim(token::Paren) => "(".to_string(),
210 token::CloseDelim(token::Paren) => ")".to_string(),
211 token::OpenDelim(token::Bracket) => "[".to_string(),
212 token::CloseDelim(token::Bracket) => "]".to_string(),
213 token::OpenDelim(token::Brace) => "{".to_string(),
214 token::CloseDelim(token::Brace) => "}".to_string(),
215 token::OpenDelim(token::NoDelim) |
216 token::CloseDelim(token::NoDelim) => " ".to_string(),
217 token::Pound => "#".to_string(),
218 token::Dollar => "$".to_string(),
219 token::Question => "?".to_string(),
220 token::SingleQuote => "'".to_string(),
223 token::Literal(lit, suf) => {
224 let mut out = match lit {
225 token::Byte(b) => format!("b'{}'", b),
226 token::Char(c) => format!("'{}'", c),
227 token::Err(c) => format!("'{}'", c),
229 token::Integer(c) => c.to_string(),
230 token::Str_(s) => format!("\"{}\"", s),
231 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
232 delim="#".repeat(n as usize),
234 token::ByteStr(v) => format!("b\"{}\"", v),
235 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
236 delim="#".repeat(n as usize),
240 if let Some(s) = suf {
241 out.push_str(&s.as_str())
247 /* Name components */
248 token::Ident(s, false) => s.to_string(),
249 token::Ident(s, true) => format!("r#{}", s),
250 token::Lifetime(s) => s.to_string(),
253 token::DocComment(s) => s.to_string(),
254 token::Eof => "<eof>".to_string(),
255 token::Whitespace => " ".to_string(),
256 token::Comment => "/* */".to_string(),
257 token::Shebang(s) => format!("/* shebang: {}*/", s),
259 token::Interpolated(ref nt) => match nt.0 {
260 token::NtExpr(ref e) => expr_to_string(e),
261 token::NtMeta(ref e) => meta_item_to_string(e),
262 token::NtTy(ref e) => ty_to_string(e),
263 token::NtPath(ref e) => path_to_string(e),
264 token::NtItem(ref e) => item_to_string(e),
265 token::NtBlock(ref e) => block_to_string(e),
266 token::NtStmt(ref e) => stmt_to_string(e),
267 token::NtPat(ref e) => pat_to_string(e),
268 token::NtIdent(e, false) => ident_to_string(e),
269 token::NtIdent(e, true) => format!("r#{}", ident_to_string(e)),
270 token::NtLifetime(e) => ident_to_string(e),
271 token::NtLiteral(ref e) => expr_to_string(e),
272 token::NtTT(ref tree) => tt_to_string(tree.clone()),
273 token::NtArm(ref e) => arm_to_string(e),
274 token::NtImplItem(ref e) => impl_item_to_string(e),
275 token::NtTraitItem(ref e) => trait_item_to_string(e),
276 token::NtGenerics(ref e) => generic_params_to_string(&e.params),
277 token::NtWhereClause(ref e) => where_clause_to_string(e),
278 token::NtArg(ref e) => arg_to_string(e),
279 token::NtVis(ref e) => vis_to_string(e),
280 token::NtForeignItem(ref e) => foreign_item_to_string(e),
285 pub fn ty_to_string(ty: &ast::Ty) -> String {
286 to_string(|s| s.print_type(ty))
289 pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
290 to_string(|s| s.print_type_bounds("", bounds))
293 pub fn pat_to_string(pat: &ast::Pat) -> String {
294 to_string(|s| s.print_pat(pat))
297 pub fn arm_to_string(arm: &ast::Arm) -> String {
298 to_string(|s| s.print_arm(arm))
301 pub fn expr_to_string(e: &ast::Expr) -> String {
302 to_string(|s| s.print_expr(e))
305 pub fn lifetime_to_string(lt: &ast::Lifetime) -> String {
306 to_string(|s| s.print_lifetime(*lt))
309 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
310 to_string(|s| s.print_tt(tt))
313 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
314 to_string(|s| s.print_tts(tts.iter().cloned().collect()))
317 pub fn tokens_to_string(tokens: TokenStream) -> String {
318 to_string(|s| s.print_tts(tokens))
321 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
322 to_string(|s| s.print_stmt(stmt))
325 pub fn attr_to_string(attr: &ast::Attribute) -> String {
326 to_string(|s| s.print_attribute(attr))
329 pub fn item_to_string(i: &ast::Item) -> String {
330 to_string(|s| s.print_item(i))
333 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
334 to_string(|s| s.print_impl_item(i))
337 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
338 to_string(|s| s.print_trait_item(i))
341 pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String {
342 to_string(|s| s.print_generic_params(generic_params))
345 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
346 to_string(|s| s.print_where_clause(i))
349 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
350 to_string(|s| s.print_fn_block_args(p))
353 pub fn path_to_string(p: &ast::Path) -> String {
354 to_string(|s| s.print_path(p, false, 0))
357 pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
358 to_string(|s| s.print_path_segment(p, false))
361 pub fn ident_to_string(id: ast::Ident) -> String {
362 to_string(|s| s.print_ident(id))
365 pub fn vis_to_string(v: &ast::Visibility) -> String {
366 to_string(|s| s.print_visibility(v))
369 pub fn fun_to_string(decl: &ast::FnDecl,
370 header: ast::FnHeader,
372 generics: &ast::Generics)
376 s.print_fn(decl, header, Some(name),
377 generics, &source_map::dummy_spanned(ast::VisibilityKind::Inherited))?;
378 s.end()?; // Close the head box
379 s.end() // Close the outer box
383 pub fn block_to_string(blk: &ast::Block) -> String {
385 // containing cbox, will be closed by print-block at }
386 s.cbox(INDENT_UNIT)?;
387 // head-ibox, will be closed by print-block after {
393 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
394 to_string(|s| s.print_meta_list_item(li))
397 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
398 to_string(|s| s.print_meta_item(mi))
401 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
402 to_string(|s| s.print_attribute(attr))
405 pub fn lit_to_string(l: &ast::Lit) -> String {
406 to_string(|s| s.print_literal(l))
409 pub fn variant_to_string(var: &ast::Variant) -> String {
410 to_string(|s| s.print_variant(var))
413 pub fn arg_to_string(arg: &ast::Arg) -> String {
414 to_string(|s| s.print_arg(arg, false))
417 pub fn mac_to_string(arg: &ast::Mac) -> String {
418 to_string(|s| s.print_mac(arg))
421 pub fn foreign_item_to_string(arg: &ast::ForeignItem) -> String {
422 to_string(|s| s.print_foreign_item(arg))
425 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
426 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
429 pub trait PrintState<'a> {
430 fn writer(&mut self) -> &mut pp::Printer<'a>;
431 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
432 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
433 fn cur_cmnt(&mut self) -> &mut usize;
434 fn cur_lit(&mut self) -> Option<&comments::Literal>;
435 fn bump_lit(&mut self) -> Option<comments::Literal>;
437 fn word_space<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
438 self.writer().word(w)?;
439 self.writer().space()
442 fn popen(&mut self) -> io::Result<()> { self.writer().word("(") }
444 fn pclose(&mut self) -> io::Result<()> { self.writer().word(")") }
446 fn is_begin(&mut self) -> bool {
447 match self.writer().last_token() {
448 pp::Token::Begin(_) => true,
453 fn is_end(&mut self) -> bool {
454 match self.writer().last_token() {
455 pp::Token::End => true,
460 // is this the beginning of a line?
461 fn is_bol(&mut self) -> bool {
462 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
465 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
467 self.writer().hardbreak()?
473 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
474 self.boxes().push(b);
475 self.writer().rbox(u, b)
478 fn ibox(&mut self, u: usize) -> io::Result<()> {
479 self.boxes().push(pp::Breaks::Inconsistent);
480 self.writer().ibox(u)
483 fn end(&mut self) -> io::Result<()> {
484 self.boxes().pop().unwrap();
488 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
489 where F: FnMut(&mut Self, &T) -> io::Result<()>,
492 let mut first = true;
494 if first { first = false; } else { self.word_space(",")?; }
500 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
501 while let Some(ltrl) = self.cur_lit().cloned() {
502 if ltrl.pos > pos { break; }
504 // we don't need the value here since we're forced to clone cur_lit
505 // due to lack of NLL.
515 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
516 while let Some(ref cmnt) = self.next_comment() {
518 self.print_comment(cmnt)?;
526 fn print_comment(&mut self,
527 cmnt: &comments::Comment) -> io::Result<()> {
528 let r = match cmnt.style {
530 assert_eq!(cmnt.lines.len(), 1);
531 self.writer().zerobreak()?;
532 self.writer().word(cmnt.lines[0].clone())?;
533 self.writer().zerobreak()
535 comments::Isolated => {
536 self.hardbreak_if_not_bol()?;
537 for line in &cmnt.lines {
538 // Don't print empty lines because they will end up as trailing
540 if !line.is_empty() {
541 self.writer().word(line.clone())?;
543 self.writer().hardbreak()?;
547 comments::Trailing => {
549 self.writer().word(" ")?;
551 if cmnt.lines.len() == 1 {
552 self.writer().word(cmnt.lines[0].clone())?;
553 self.writer().hardbreak()
556 for line in &cmnt.lines {
557 if !line.is_empty() {
558 self.writer().word(line.clone())?;
560 self.writer().hardbreak()?;
565 comments::BlankLine => {
566 // We need to do at least one, possibly two hardbreaks.
567 let is_semi = match self.writer().last_token() {
568 pp::Token::String(s, _) => ";" == s,
571 if is_semi || self.is_begin() || self.is_end() {
572 self.writer().hardbreak()?;
574 self.writer().hardbreak()
579 *self.cur_cmnt() = *self.cur_cmnt() + 1;
586 fn next_comment(&mut self) -> Option<comments::Comment> {
587 let cur_cmnt = *self.cur_cmnt();
588 match *self.comments() {
590 if cur_cmnt < cmnts.len() {
591 Some(cmnts[cur_cmnt].clone())
600 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
601 self.maybe_print_comment(lit.span.lo())?;
602 if let Some(ltrl) = self.next_lit(lit.span.lo()) {
603 return self.writer().word(ltrl.lit.clone());
606 ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style),
607 ast::LitKind::Byte(byte) => {
608 let mut res = String::from("b'");
609 res.extend(ascii::escape_default(byte).map(|c| c as char));
611 self.writer().word(res)
613 ast::LitKind::Char(ch) => {
614 let mut res = String::from("'");
615 res.extend(ch.escape_default());
617 self.writer().word(res)
619 ast::LitKind::Int(i, t) => {
621 ast::LitIntType::Signed(st) => {
622 self.writer().word(st.val_to_string(i as i128))
624 ast::LitIntType::Unsigned(ut) => {
625 self.writer().word(ut.val_to_string(i))
627 ast::LitIntType::Unsuffixed => {
628 self.writer().word(i.to_string())
632 ast::LitKind::Float(ref f, t) => {
633 self.writer().word(format!("{}{}", &f, t.ty_to_string()))
635 ast::LitKind::FloatUnsuffixed(ref f) => self.writer().word(f.as_str().get()),
636 ast::LitKind::Bool(val) => {
637 if val { self.writer().word("true") } else { self.writer().word("false") }
639 ast::LitKind::ByteStr(ref v) => {
640 let mut escaped: String = String::new();
641 for &ch in v.iter() {
642 escaped.extend(ascii::escape_default(ch)
643 .map(|c| c as char));
645 self.writer().word(format!("b\"{}\"", escaped))
650 fn print_string(&mut self, st: &str,
651 style: ast::StrStyle) -> io::Result<()> {
652 let st = match style {
653 ast::StrStyle::Cooked => {
654 (format!("\"{}\"", st.escape_debug()))
656 ast::StrStyle::Raw(n) => {
657 (format!("r{delim}\"{string}\"{delim}",
658 delim="#".repeat(n as usize),
662 self.writer().word(st)
665 fn print_inner_attributes(&mut self,
666 attrs: &[ast::Attribute]) -> io::Result<()> {
667 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
670 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
671 attrs: &[ast::Attribute])
673 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
676 fn print_outer_attributes(&mut self,
677 attrs: &[ast::Attribute]) -> io::Result<()> {
678 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
681 fn print_inner_attributes_inline(&mut self,
682 attrs: &[ast::Attribute]) -> io::Result<()> {
683 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
686 fn print_outer_attributes_inline(&mut self,
687 attrs: &[ast::Attribute]) -> io::Result<()> {
688 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
691 fn print_either_attributes(&mut self,
692 attrs: &[ast::Attribute],
693 kind: ast::AttrStyle,
695 trailing_hardbreak: bool) -> io::Result<()> {
698 if attr.style == kind {
699 self.print_attribute_inline(attr, is_inline)?;
706 if count > 0 && trailing_hardbreak && !is_inline {
707 self.hardbreak_if_not_bol()?;
712 fn print_attribute_path(&mut self, path: &ast::Path) -> io::Result<()> {
713 for (i, segment) in path.segments.iter().enumerate() {
715 self.writer().word("::")?
717 if segment.ident.name != keywords::PathRoot.name() {
718 if segment.ident.name == keywords::DollarCrate.name() {
719 self.print_dollar_crate(segment.ident)?;
721 self.writer().word(segment.ident.as_str().get())?;
728 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
729 self.print_attribute_inline(attr, false)
732 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
733 is_inline: bool) -> io::Result<()> {
735 self.hardbreak_if_not_bol()?;
737 self.maybe_print_comment(attr.span.lo())?;
738 if attr.is_sugared_doc {
739 self.writer().word(attr.value_str().unwrap().as_str().get())?;
740 self.writer().hardbreak()
743 ast::AttrStyle::Inner => self.writer().word("#![")?,
744 ast::AttrStyle::Outer => self.writer().word("#[")?,
746 if let Some(mi) = attr.meta() {
747 self.print_meta_item(&mi)?
749 self.print_attribute_path(&attr.path)?;
750 self.writer().space()?;
751 self.print_tts(attr.tokens.clone())?;
753 self.writer().word("]")
757 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> {
759 ast::NestedMetaItemKind::MetaItem(ref mi) => {
760 self.print_meta_item(mi)
762 ast::NestedMetaItemKind::Literal(ref lit) => {
763 self.print_literal(lit)
768 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
769 self.ibox(INDENT_UNIT)?;
771 ast::MetaItemKind::Word => self.print_attribute_path(&item.ident)?,
772 ast::MetaItemKind::NameValue(ref value) => {
773 self.print_attribute_path(&item.ident)?;
774 self.writer().space()?;
775 self.word_space("=")?;
776 self.print_literal(value)?;
778 ast::MetaItemKind::List(ref items) => {
779 self.print_attribute_path(&item.ident)?;
781 self.commasep(Consistent,
783 |s, i| s.print_meta_list_item(i))?;
790 /// This doesn't deserve to be called "pretty" printing, but it should be
791 /// meaning-preserving. A quick hack that might help would be to look at the
792 /// spans embedded in the TTs to decide where to put spaces and newlines.
793 /// But it'd be better to parse these according to the grammar of the
794 /// appropriate macro, transcribe back into the grammar we just parsed from,
795 /// and then pretty-print the resulting AST nodes (so, e.g., we print
796 /// expression arguments as expressions). It can be done! I think.
797 fn print_tt(&mut self, tt: tokenstream::TokenTree) -> io::Result<()> {
799 TokenTree::Token(_, ref tk) => {
800 self.writer().word(token_to_string(tk))?;
802 parse::token::DocComment(..) => {
803 self.writer().hardbreak()
808 TokenTree::Delimited(_, delim, tts) => {
809 self.writer().word(token_to_string(&token::OpenDelim(delim)))?;
810 self.writer().space()?;
811 self.print_tts(tts.stream())?;
812 self.writer().space()?;
813 self.writer().word(token_to_string(&token::CloseDelim(delim)))
818 fn print_tts(&mut self, tts: tokenstream::TokenStream) -> io::Result<()> {
820 for (i, tt) in tts.into_trees().enumerate() {
822 self.writer().space()?;
829 fn space_if_not_bol(&mut self) -> io::Result<()> {
830 if !self.is_bol() { self.writer().space()?; }
834 fn nbsp(&mut self) -> io::Result<()> { self.writer().word(" ") }
836 // AST pretty-printer is used as a fallback for turning AST structures into token streams for
837 // proc macros. Additionally, proc macros may stringify their input and expect it survive the
838 // stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
839 // So we need to somehow pretty-print `$crate` in paths in a way preserving at least some of
840 // its hygiene data, most importantly name of the crate it refers to.
841 // As a result we print `$crate` as `crate` if it refers to the local crate
842 // and as `::other_crate_name` if it refers to some other crate.
843 fn print_dollar_crate(&mut self, ident: ast::Ident) -> io::Result<()> {
844 let name = ident.span.ctxt().dollar_crate_name();
845 if !ast::Ident::with_empty_ctxt(name).is_path_segment_keyword() {
846 self.writer().word("::")?;
848 self.writer().word(name.as_str().get())
852 impl<'a> PrintState<'a> for State<'a> {
853 fn writer(&mut self) -> &mut pp::Printer<'a> {
857 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
861 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
865 fn cur_cmnt(&mut self) -> &mut usize {
869 fn cur_lit(&mut self) -> Option<&comments::Literal> {
873 fn bump_lit(&mut self) -> Option<comments::Literal> {
879 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
880 self.boxes.push(pp::Breaks::Consistent);
884 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
889 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
891 // outer-box is consistent
892 self.cbox(INDENT_UNIT)?;
893 // head-box is inconsistent
894 self.ibox(w.len() + 1)?;
895 // keyword that starts the head
902 pub fn bopen(&mut self) -> io::Result<()> {
904 self.end() // close the head-box
907 pub fn bclose_(&mut self, span: syntax_pos::Span,
908 indented: usize) -> io::Result<()> {
909 self.bclose_maybe_open(span, indented, true)
911 pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
912 indented: usize, close_box: bool) -> io::Result<()> {
913 self.maybe_print_comment(span.hi())?;
914 self.break_offset_if_not_bol(1, -(indented as isize))?;
917 self.end()?; // close the outer-box
921 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
922 self.bclose_(span, INDENT_UNIT)
925 pub fn in_cbox(&self) -> bool {
926 match self.boxes.last() {
927 Some(&last_box) => last_box == pp::Breaks::Consistent,
932 pub fn break_offset_if_not_bol(&mut self, n: usize,
933 off: isize) -> io::Result<()> {
935 self.s.break_offset(n, off)
937 if off != 0 && self.s.last_token().is_hardbreak_tok() {
938 // We do something pretty sketchy here: tuck the nonzero
939 // offset-adjustment we were going to deposit along with the
940 // break into the previous hardbreak.
941 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
947 // Synthesizes a comment that was not textually present in the original source
949 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
959 pub fn commasep_cmnt<T, F, G>(&mut self,
963 mut get_span: G) -> io::Result<()> where
964 F: FnMut(&mut State, &T) -> io::Result<()>,
965 G: FnMut(&T) -> syntax_pos::Span,
968 let len = elts.len();
971 self.maybe_print_comment(get_span(elt).hi())?;
976 self.maybe_print_trailing_comment(get_span(elt),
977 Some(get_span(&elts[i]).hi()))?;
978 self.space_if_not_bol()?;
984 pub fn commasep_exprs(&mut self, b: Breaks,
985 exprs: &[P<ast::Expr>]) -> io::Result<()> {
986 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
989 pub fn print_mod(&mut self, _mod: &ast::Mod,
990 attrs: &[ast::Attribute]) -> io::Result<()> {
991 self.print_inner_attributes(attrs)?;
992 for item in &_mod.items {
993 self.print_item(item)?;
998 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
999 attrs: &[ast::Attribute]) -> io::Result<()> {
1000 self.print_inner_attributes(attrs)?;
1001 for item in &nmod.items {
1002 self.print_foreign_item(item)?;
1007 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
1008 if let Some(lt) = *lifetime {
1009 self.print_lifetime(lt)?;
1015 pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) -> io::Result<()> {
1017 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
1018 GenericArg::Type(ty) => self.print_type(ty),
1022 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
1023 self.maybe_print_comment(ty.span.lo())?;
1026 ast::TyKind::Slice(ref ty) => {
1028 self.print_type(ty)?;
1031 ast::TyKind::Ptr(ref mt) => {
1034 ast::Mutability::Mutable => self.word_nbsp("mut")?,
1035 ast::Mutability::Immutable => self.word_nbsp("const")?,
1037 self.print_type(&mt.ty)?;
1039 ast::TyKind::Rptr(ref lifetime, ref mt) => {
1041 self.print_opt_lifetime(lifetime)?;
1044 ast::TyKind::Never => {
1047 ast::TyKind::Tup(ref elts) => {
1049 self.commasep(Inconsistent, &elts[..],
1050 |s, ty| s.print_type(ty))?;
1051 if elts.len() == 1 {
1056 ast::TyKind::Paren(ref typ) => {
1058 self.print_type(typ)?;
1061 ast::TyKind::BareFn(ref f) => {
1062 self.print_ty_fn(f.abi,
1066 &f.generic_params)?;
1068 ast::TyKind::Path(None, ref path) => {
1069 self.print_path(path, false, 0)?;
1071 ast::TyKind::Path(Some(ref qself), ref path) => {
1072 self.print_qpath(path, qself, false)?
1074 ast::TyKind::TraitObject(ref bounds, syntax) => {
1075 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
1076 self.print_type_bounds(prefix, &bounds[..])?;
1078 ast::TyKind::ImplTrait(_, ref bounds) => {
1079 self.print_type_bounds("impl", &bounds[..])?;
1081 ast::TyKind::Array(ref ty, ref length) => {
1083 self.print_type(ty)?;
1085 self.print_expr(&length.value)?;
1088 ast::TyKind::Typeof(ref e) => {
1089 self.s.word("typeof(")?;
1090 self.print_expr(&e.value)?;
1093 ast::TyKind::Infer => {
1096 ast::TyKind::Err => {
1098 self.s.word("/*ERROR*/")?;
1101 ast::TyKind::ImplicitSelf => {
1102 self.s.word("Self")?;
1104 ast::TyKind::Mac(ref m) => {
1111 pub fn print_foreign_item(&mut self,
1112 item: &ast::ForeignItem) -> io::Result<()> {
1113 self.hardbreak_if_not_bol()?;
1114 self.maybe_print_comment(item.span.lo())?;
1115 self.print_outer_attributes(&item.attrs)?;
1117 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1119 self.print_fn(decl, ast::FnHeader::default(),
1121 generics, &item.vis)?;
1122 self.end()?; // end head-ibox
1124 self.end() // end the outer fn box
1126 ast::ForeignItemKind::Static(ref t, m) => {
1127 self.head(visibility_qualified(&item.vis, "static"))?;
1129 self.word_space("mut")?;
1131 self.print_ident(item.ident)?;
1132 self.word_space(":")?;
1133 self.print_type(t)?;
1135 self.end()?; // end the head-ibox
1136 self.end() // end the outer cbox
1138 ast::ForeignItemKind::Ty => {
1139 self.head(visibility_qualified(&item.vis, "type"))?;
1140 self.print_ident(item.ident)?;
1142 self.end()?; // end the head-ibox
1143 self.end() // end the outer cbox
1145 ast::ForeignItemKind::Macro(ref m) => {
1147 match m.node.delim {
1148 MacDelimiter::Brace => Ok(()),
1149 _ => self.s.word(";")
1155 fn print_associated_const(&mut self,
1158 default: Option<&ast::Expr>,
1159 vis: &ast::Visibility)
1162 self.s.word(visibility_qualified(vis, ""))?;
1163 self.word_space("const")?;
1164 self.print_ident(ident)?;
1165 self.word_space(":")?;
1166 self.print_type(ty)?;
1167 if let Some(expr) = default {
1169 self.word_space("=")?;
1170 self.print_expr(expr)?;
1175 fn print_associated_type(&mut self,
1177 bounds: Option<&ast::GenericBounds>,
1178 ty: Option<&ast::Ty>)
1180 self.word_space("type")?;
1181 self.print_ident(ident)?;
1182 if let Some(bounds) = bounds {
1183 self.print_type_bounds(":", bounds)?;
1185 if let Some(ty) = ty {
1187 self.word_space("=")?;
1188 self.print_type(ty)?;
1193 /// Pretty-print an item
1194 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1195 self.hardbreak_if_not_bol()?;
1196 self.maybe_print_comment(item.span.lo())?;
1197 self.print_outer_attributes(&item.attrs)?;
1198 self.ann.pre(self, AnnNode::Item(item))?;
1200 ast::ItemKind::ExternCrate(orig_name) => {
1201 self.head(visibility_qualified(&item.vis, "extern crate"))?;
1202 if let Some(orig_name) = orig_name {
1203 self.print_name(orig_name)?;
1208 self.print_ident(item.ident)?;
1210 self.end()?; // end inner head-block
1211 self.end()?; // end outer head-block
1213 ast::ItemKind::Use(ref tree) => {
1214 self.head(visibility_qualified(&item.vis, "use"))?;
1215 self.print_use_tree(tree)?;
1217 self.end()?; // end inner head-block
1218 self.end()?; // end outer head-block
1220 ast::ItemKind::Static(ref ty, m, ref expr) => {
1221 self.head(visibility_qualified(&item.vis, "static"))?;
1222 if m == ast::Mutability::Mutable {
1223 self.word_space("mut")?;
1225 self.print_ident(item.ident)?;
1226 self.word_space(":")?;
1227 self.print_type(ty)?;
1229 self.end()?; // end the head-ibox
1231 self.word_space("=")?;
1232 self.print_expr(expr)?;
1234 self.end()?; // end the outer cbox
1236 ast::ItemKind::Const(ref ty, ref expr) => {
1237 self.head(visibility_qualified(&item.vis, "const"))?;
1238 self.print_ident(item.ident)?;
1239 self.word_space(":")?;
1240 self.print_type(ty)?;
1242 self.end()?; // end the head-ibox
1244 self.word_space("=")?;
1245 self.print_expr(expr)?;
1247 self.end()?; // end the outer cbox
1249 ast::ItemKind::Fn(ref decl, header, ref typarams, ref body) => {
1259 self.print_block_with_attrs(body, &item.attrs)?;
1261 ast::ItemKind::Mod(ref _mod) => {
1262 self.head(visibility_qualified(&item.vis, "mod"))?;
1263 self.print_ident(item.ident)?;
1265 if _mod.inline || self.is_expanded {
1268 self.print_mod(_mod, &item.attrs)?;
1269 self.bclose(item.span)?;
1272 self.end()?; // end inner head-block
1273 self.end()?; // end outer head-block
1277 ast::ItemKind::ForeignMod(ref nmod) => {
1278 self.head("extern")?;
1279 self.word_nbsp(nmod.abi.to_string())?;
1281 self.print_foreign_mod(nmod, &item.attrs)?;
1282 self.bclose(item.span)?;
1284 ast::ItemKind::GlobalAsm(ref ga) => {
1285 self.head(visibility_qualified(&item.vis, "global_asm!"))?;
1286 self.s.word(ga.asm.as_str().get())?;
1289 ast::ItemKind::Ty(ref ty, ref generics) => {
1290 self.head(visibility_qualified(&item.vis, "type"))?;
1291 self.print_ident(item.ident)?;
1292 self.print_generic_params(&generics.params)?;
1293 self.end()?; // end the inner ibox
1295 self.print_where_clause(&generics.where_clause)?;
1297 self.word_space("=")?;
1298 self.print_type(ty)?;
1300 self.end()?; // end the outer ibox
1302 ast::ItemKind::Existential(ref bounds, ref generics) => {
1303 self.head(visibility_qualified(&item.vis, "existential type"))?;
1304 self.print_ident(item.ident)?;
1305 self.print_generic_params(&generics.params)?;
1306 self.end()?; // end the inner ibox
1308 self.print_where_clause(&generics.where_clause)?;
1310 self.print_type_bounds(":", bounds)?;
1312 self.end()?; // end the outer ibox
1314 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1315 self.print_enum_def(
1323 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1324 self.head(visibility_qualified(&item.vis, "struct"))?;
1325 self.print_struct(struct_def, generics, item.ident, item.span, true)?;
1327 ast::ItemKind::Union(ref struct_def, ref generics) => {
1328 self.head(visibility_qualified(&item.vis, "union"))?;
1329 self.print_struct(struct_def, generics, item.ident, item.span, true)?;
1331 ast::ItemKind::Impl(unsafety,
1337 ref impl_items) => {
1339 self.print_visibility(&item.vis)?;
1340 self.print_defaultness(defaultness)?;
1341 self.print_unsafety(unsafety)?;
1342 self.word_nbsp("impl")?;
1344 if !generics.params.is_empty() {
1345 self.print_generic_params(&generics.params)?;
1349 if polarity == ast::ImplPolarity::Negative {
1353 if let Some(ref t) = *opt_trait {
1354 self.print_trait_ref(t)?;
1356 self.word_space("for")?;
1359 self.print_type(ty)?;
1360 self.print_where_clause(&generics.where_clause)?;
1364 self.print_inner_attributes(&item.attrs)?;
1365 for impl_item in impl_items {
1366 self.print_impl_item(impl_item)?;
1368 self.bclose(item.span)?;
1370 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1372 self.print_visibility(&item.vis)?;
1373 self.print_unsafety(unsafety)?;
1374 self.print_is_auto(is_auto)?;
1375 self.word_nbsp("trait")?;
1376 self.print_ident(item.ident)?;
1377 self.print_generic_params(&generics.params)?;
1378 let mut real_bounds = Vec::with_capacity(bounds.len());
1379 for b in bounds.iter() {
1380 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1382 self.word_space("for ?")?;
1383 self.print_trait_ref(&ptr.trait_ref)?;
1385 real_bounds.push(b.clone());
1388 self.print_type_bounds(":", &real_bounds[..])?;
1389 self.print_where_clause(&generics.where_clause)?;
1392 for trait_item in trait_items {
1393 self.print_trait_item(trait_item)?;
1395 self.bclose(item.span)?;
1397 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1399 self.print_visibility(&item.vis)?;
1400 self.word_nbsp("trait")?;
1401 self.print_ident(item.ident)?;
1402 self.print_generic_params(&generics.params)?;
1403 let mut real_bounds = Vec::with_capacity(bounds.len());
1404 // FIXME(durka) this seems to be some quite outdated syntax
1405 for b in bounds.iter() {
1406 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1408 self.word_space("for ?")?;
1409 self.print_trait_ref(&ptr.trait_ref)?;
1411 real_bounds.push(b.clone());
1415 self.print_type_bounds("=", &real_bounds[..])?;
1416 self.print_where_clause(&generics.where_clause)?;
1419 ast::ItemKind::Mac(ref mac) => {
1420 if item.ident.name == keywords::Invalid.name() {
1421 self.print_mac(mac)?;
1422 match mac.node.delim {
1423 MacDelimiter::Brace => {}
1424 _ => self.s.word(";")?,
1427 self.print_path(&mac.node.path, false, 0)?;
1429 self.print_ident(item.ident)?;
1430 self.cbox(INDENT_UNIT)?;
1432 self.print_tts(mac.node.stream())?;
1438 ast::ItemKind::MacroDef(ref tts) => {
1439 self.s.word("macro_rules! ")?;
1440 self.print_ident(item.ident)?;
1441 self.cbox(INDENT_UNIT)?;
1443 self.print_tts(tts.stream())?;
1449 self.ann.post(self, AnnNode::Item(item))
1452 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1453 self.print_path(&t.path, false, 0)
1456 fn print_formal_generic_params(
1458 generic_params: &[ast::GenericParam]
1459 ) -> io::Result<()> {
1460 if !generic_params.is_empty() {
1461 self.s.word("for")?;
1462 self.print_generic_params(generic_params)?;
1468 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1469 self.print_formal_generic_params(&t.bound_generic_params)?;
1470 self.print_trait_ref(&t.trait_ref)
1473 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1474 generics: &ast::Generics, ident: ast::Ident,
1475 span: syntax_pos::Span,
1476 visibility: &ast::Visibility) -> io::Result<()> {
1477 self.head(visibility_qualified(visibility, "enum"))?;
1478 self.print_ident(ident)?;
1479 self.print_generic_params(&generics.params)?;
1480 self.print_where_clause(&generics.where_clause)?;
1482 self.print_variants(&enum_definition.variants, span)
1485 pub fn print_variants(&mut self,
1486 variants: &[ast::Variant],
1487 span: syntax_pos::Span) -> io::Result<()> {
1490 self.space_if_not_bol()?;
1491 self.maybe_print_comment(v.span.lo())?;
1492 self.print_outer_attributes(&v.node.attrs)?;
1493 self.ibox(INDENT_UNIT)?;
1494 self.print_variant(v)?;
1497 self.maybe_print_trailing_comment(v.span, None)?;
1502 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1504 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1505 ast::VisibilityKind::Crate(sugar) => match sugar {
1506 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1507 ast::CrateSugar::JustCrate => self.word_nbsp("crate")
1509 ast::VisibilityKind::Restricted { ref path, .. } => {
1510 let path = to_string(|s| s.print_path(path, false, 0));
1511 if path == "self" || path == "super" {
1512 self.word_nbsp(format!("pub({})", path))
1514 self.word_nbsp(format!("pub(in {})", path))
1517 ast::VisibilityKind::Inherited => Ok(())
1521 pub fn print_defaultness(&mut self, defaultness: ast::Defaultness) -> io::Result<()> {
1522 if let ast::Defaultness::Default = defaultness {
1523 self.word_nbsp("default")?;
1528 pub fn print_struct(&mut self,
1529 struct_def: &ast::VariantData,
1530 generics: &ast::Generics,
1532 span: syntax_pos::Span,
1533 print_finalizer: bool) -> io::Result<()> {
1534 self.print_ident(ident)?;
1535 self.print_generic_params(&generics.params)?;
1536 if !struct_def.is_struct() {
1537 if struct_def.is_tuple() {
1540 Inconsistent, struct_def.fields(),
1542 s.maybe_print_comment(field.span.lo())?;
1543 s.print_outer_attributes(&field.attrs)?;
1544 s.print_visibility(&field.vis)?;
1545 s.print_type(&field.ty)
1550 self.print_where_clause(&generics.where_clause)?;
1551 if print_finalizer {
1555 self.end() // close the outer-box
1557 self.print_where_clause(&generics.where_clause)?;
1560 self.hardbreak_if_not_bol()?;
1562 for field in struct_def.fields() {
1563 self.hardbreak_if_not_bol()?;
1564 self.maybe_print_comment(field.span.lo())?;
1565 self.print_outer_attributes(&field.attrs)?;
1566 self.print_visibility(&field.vis)?;
1567 self.print_ident(field.ident.unwrap())?;
1568 self.word_nbsp(":")?;
1569 self.print_type(&field.ty)?;
1577 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1579 let generics = ast::Generics::default();
1580 self.print_struct(&v.node.data, &generics, v.node.ident, v.span, false)?;
1581 match v.node.disr_expr {
1584 self.word_space("=")?;
1585 self.print_expr(&d.value)
1591 pub fn print_method_sig(&mut self,
1593 generics: &ast::Generics,
1595 vis: &ast::Visibility)
1597 self.print_fn(&m.decl,
1604 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1606 self.ann.pre(self, AnnNode::SubItem(ti.id))?;
1607 self.hardbreak_if_not_bol()?;
1608 self.maybe_print_comment(ti.span.lo())?;
1609 self.print_outer_attributes(&ti.attrs)?;
1611 ast::TraitItemKind::Const(ref ty, ref default) => {
1612 self.print_associated_const(
1615 default.as_ref().map(|expr| &**expr),
1616 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1619 ast::TraitItemKind::Method(ref sig, ref body) => {
1623 self.print_method_sig(
1627 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1629 if let Some(ref body) = *body {
1631 self.print_block_with_attrs(body, &ti.attrs)?;
1636 ast::TraitItemKind::Type(ref bounds, ref default) => {
1637 self.print_associated_type(ti.ident, Some(bounds),
1638 default.as_ref().map(|ty| &**ty))?;
1640 ast::TraitItemKind::Macro(ref mac) => {
1641 self.print_mac(mac)?;
1642 match mac.node.delim {
1643 MacDelimiter::Brace => {}
1644 _ => self.s.word(";")?,
1648 self.ann.post(self, AnnNode::SubItem(ti.id))
1651 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1652 self.ann.pre(self, AnnNode::SubItem(ii.id))?;
1653 self.hardbreak_if_not_bol()?;
1654 self.maybe_print_comment(ii.span.lo())?;
1655 self.print_outer_attributes(&ii.attrs)?;
1656 self.print_defaultness(ii.defaultness)?;
1658 ast::ImplItemKind::Const(ref ty, ref expr) => {
1659 self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis)?;
1661 ast::ImplItemKind::Method(ref sig, ref body) => {
1663 self.print_method_sig(ii.ident, &ii.generics, sig, &ii.vis)?;
1665 self.print_block_with_attrs(body, &ii.attrs)?;
1667 ast::ImplItemKind::Type(ref ty) => {
1668 self.print_associated_type(ii.ident, None, Some(ty))?;
1670 ast::ImplItemKind::Existential(ref bounds) => {
1671 self.word_space("existential")?;
1672 self.print_associated_type(ii.ident, Some(bounds), None)?;
1674 ast::ImplItemKind::Macro(ref mac) => {
1675 self.print_mac(mac)?;
1676 match mac.node.delim {
1677 MacDelimiter::Brace => {}
1678 _ => self.s.word(";")?,
1682 self.ann.post(self, AnnNode::SubItem(ii.id))
1685 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1686 self.maybe_print_comment(st.span.lo())?;
1688 ast::StmtKind::Local(ref loc) => {
1689 self.print_outer_attributes(&loc.attrs)?;
1690 self.space_if_not_bol()?;
1691 self.ibox(INDENT_UNIT)?;
1692 self.word_nbsp("let")?;
1694 self.ibox(INDENT_UNIT)?;
1695 self.print_local_decl(loc)?;
1697 if let Some(ref init) = loc.init {
1699 self.word_space("=")?;
1700 self.print_expr(init)?;
1705 ast::StmtKind::Item(ref item) => self.print_item(item)?,
1706 ast::StmtKind::Expr(ref expr) => {
1707 self.space_if_not_bol()?;
1708 self.print_expr_outer_attr_style(expr, false)?;
1709 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1713 ast::StmtKind::Semi(ref expr) => {
1714 self.space_if_not_bol()?;
1715 self.print_expr_outer_attr_style(expr, false)?;
1718 ast::StmtKind::Mac(ref mac) => {
1719 let (ref mac, style, ref attrs) = **mac;
1720 self.space_if_not_bol()?;
1721 self.print_outer_attributes(attrs)?;
1722 self.print_mac(mac)?;
1723 if style == ast::MacStmtStyle::Semicolon {
1728 self.maybe_print_trailing_comment(st.span, None)
1731 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1732 self.print_block_with_attrs(blk, &[])
1735 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1736 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1739 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1740 attrs: &[ast::Attribute])
1742 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1745 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1746 indented: usize) -> io::Result<()> {
1747 self.print_block_maybe_unclosed(blk, indented, &[], false)
1750 pub fn print_block_with_attrs(&mut self,
1752 attrs: &[ast::Attribute]) -> io::Result<()> {
1753 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1756 pub fn print_block_maybe_unclosed(&mut self,
1759 attrs: &[ast::Attribute],
1760 close_box: bool) -> io::Result<()> {
1762 BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
1763 BlockCheckMode::Default => ()
1765 self.maybe_print_comment(blk.span.lo())?;
1766 self.ann.pre(self, AnnNode::Block(blk))?;
1769 self.print_inner_attributes(attrs)?;
1771 for (i, st) in blk.stmts.iter().enumerate() {
1773 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1774 self.maybe_print_comment(st.span.lo())?;
1775 self.space_if_not_bol()?;
1776 self.print_expr_outer_attr_style(expr, false)?;
1777 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1779 _ => self.print_stmt(st)?,
1783 self.bclose_maybe_open(blk.span, indented, close_box)?;
1784 self.ann.post(self, AnnNode::Block(blk))
1787 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1791 // "another else-if"
1792 ast::ExprKind::If(ref i, ref then, ref e) => {
1793 self.cbox(INDENT_UNIT - 1)?;
1795 self.s.word(" else if ")?;
1796 self.print_expr_as_cond(i)?;
1798 self.print_block(then)?;
1799 self.print_else(e.as_ref().map(|e| &**e))
1801 // "another else-if-let"
1802 ast::ExprKind::IfLet(ref pats, ref expr, ref then, ref e) => {
1803 self.cbox(INDENT_UNIT - 1)?;
1805 self.s.word(" else if let ")?;
1806 self.print_pats(pats)?;
1808 self.word_space("=")?;
1809 self.print_expr_as_cond(expr)?;
1811 self.print_block(then)?;
1812 self.print_else(e.as_ref().map(|e| &**e))
1815 ast::ExprKind::Block(ref b, _) => {
1816 self.cbox(INDENT_UNIT - 1)?;
1818 self.s.word(" else ")?;
1821 // BLEAH, constraints would be great here
1823 panic!("print_if saw if with weird alternative");
1831 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1832 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1834 self.print_expr_as_cond(test)?;
1836 self.print_block(blk)?;
1837 self.print_else(elseopt)
1840 pub fn print_if_let(&mut self, pats: &[P<ast::Pat>], expr: &ast::Expr, blk: &ast::Block,
1841 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1842 self.head("if let")?;
1843 self.print_pats(pats)?;
1845 self.word_space("=")?;
1846 self.print_expr_as_cond(expr)?;
1848 self.print_block(blk)?;
1849 self.print_else(elseopt)
1852 pub fn print_mac(&mut self, m: &ast::Mac) -> io::Result<()> {
1853 self.print_path(&m.node.path, false, 0)?;
1855 match m.node.delim {
1856 MacDelimiter::Parenthesis => self.popen()?,
1857 MacDelimiter::Bracket => self.s.word("[")?,
1858 MacDelimiter::Brace => {
1863 self.print_tts(m.node.stream())?;
1864 match m.node.delim {
1865 MacDelimiter::Parenthesis => self.pclose(),
1866 MacDelimiter::Bracket => self.s.word("]"),
1867 MacDelimiter::Brace => self.bclose(m.span),
1872 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1874 self.commasep_exprs(Inconsistent, args)?;
1878 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) -> io::Result<()> {
1879 let needs_par = expr.precedence().order() < prec;
1883 self.print_expr(expr)?;
1890 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1891 /// `if cond { ... }`.
1892 pub fn print_expr_as_cond(&mut self, expr: &ast::Expr) -> io::Result<()> {
1893 let needs_par = match expr.node {
1894 // These cases need parens due to the parse error observed in #26461: `if return {}`
1895 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1896 ast::ExprKind::Closure(..) |
1897 ast::ExprKind::Ret(..) |
1898 ast::ExprKind::Break(..) => true,
1900 _ => parser::contains_exterior_struct_lit(expr),
1906 self.print_expr(expr)?;
1913 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1914 attrs: &[Attribute]) -> io::Result<()> {
1915 self.ibox(INDENT_UNIT)?;
1917 self.print_inner_attributes_inline(attrs)?;
1918 self.commasep_exprs(Inconsistent, &exprs[..])?;
1923 fn print_expr_repeat(&mut self,
1924 element: &ast::Expr,
1925 count: &ast::AnonConst,
1926 attrs: &[Attribute]) -> io::Result<()> {
1927 self.ibox(INDENT_UNIT)?;
1929 self.print_inner_attributes_inline(attrs)?;
1930 self.print_expr(element)?;
1931 self.word_space(";")?;
1932 self.print_expr(&count.value)?;
1937 fn print_expr_struct(&mut self,
1939 fields: &[ast::Field],
1940 wth: &Option<P<ast::Expr>>,
1941 attrs: &[Attribute]) -> io::Result<()> {
1942 self.print_path(path, true, 0)?;
1944 self.print_inner_attributes_inline(attrs)?;
1949 s.ibox(INDENT_UNIT)?;
1950 if !field.is_shorthand {
1951 s.print_ident(field.ident)?;
1954 s.print_expr(&field.expr)?;
1960 self.ibox(INDENT_UNIT)?;
1961 if !fields.is_empty() {
1966 self.print_expr(expr)?;
1969 _ => if !fields.is_empty() {
1977 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1978 attrs: &[Attribute]) -> io::Result<()> {
1980 self.print_inner_attributes_inline(attrs)?;
1981 self.commasep_exprs(Inconsistent, &exprs[..])?;
1982 if exprs.len() == 1 {
1988 fn print_expr_call(&mut self,
1990 args: &[P<ast::Expr>]) -> io::Result<()> {
1993 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1994 _ => parser::PREC_POSTFIX,
1997 self.print_expr_maybe_paren(func, prec)?;
1998 self.print_call_post(args)
2001 fn print_expr_method_call(&mut self,
2002 segment: &ast::PathSegment,
2003 args: &[P<ast::Expr>]) -> io::Result<()> {
2004 let base_args = &args[1..];
2005 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
2007 self.print_ident(segment.ident)?;
2008 if let Some(ref args) = segment.args {
2009 self.print_generic_args(args, true)?;
2011 self.print_call_post(base_args)
2014 fn print_expr_binary(&mut self,
2017 rhs: &ast::Expr) -> io::Result<()> {
2018 let assoc_op = AssocOp::from_ast_binop(op.node);
2019 let prec = assoc_op.precedence() as i8;
2020 let fixity = assoc_op.fixity();
2022 let (left_prec, right_prec) = match fixity {
2023 Fixity::Left => (prec, prec + 1),
2024 Fixity::Right => (prec + 1, prec),
2025 Fixity::None => (prec + 1, prec + 1),
2028 let left_prec = match (&lhs.node, op.node) {
2029 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
2030 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
2031 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
2032 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) |
2033 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
2037 self.print_expr_maybe_paren(lhs, left_prec)?;
2039 self.word_space(op.node.to_string())?;
2040 self.print_expr_maybe_paren(rhs, right_prec)
2043 fn print_expr_unary(&mut self,
2045 expr: &ast::Expr) -> io::Result<()> {
2046 self.s.word(ast::UnOp::to_string(op))?;
2047 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
2050 fn print_expr_addr_of(&mut self,
2051 mutability: ast::Mutability,
2052 expr: &ast::Expr) -> io::Result<()> {
2054 self.print_mutability(mutability)?;
2055 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
2058 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
2059 self.print_expr_outer_attr_style(expr, true)
2062 fn print_expr_outer_attr_style(&mut self,
2064 is_inline: bool) -> io::Result<()> {
2065 self.maybe_print_comment(expr.span.lo())?;
2067 let attrs = &expr.attrs;
2069 self.print_outer_attributes_inline(attrs)?;
2071 self.print_outer_attributes(attrs)?;
2074 self.ibox(INDENT_UNIT)?;
2075 self.ann.pre(self, AnnNode::Expr(expr))?;
2077 ast::ExprKind::Box(ref expr) => {
2078 self.word_space("box")?;
2079 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
2081 ast::ExprKind::ObsoleteInPlace(ref place, ref expr) => {
2082 let prec = AssocOp::ObsoleteInPlace.precedence() as i8;
2083 self.print_expr_maybe_paren(place, prec + 1)?;
2085 self.word_space("<-")?;
2086 self.print_expr_maybe_paren(expr, prec)?;
2088 ast::ExprKind::Array(ref exprs) => {
2089 self.print_expr_vec(&exprs[..], attrs)?;
2091 ast::ExprKind::Repeat(ref element, ref count) => {
2092 self.print_expr_repeat(element, count, attrs)?;
2094 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2095 self.print_expr_struct(path, &fields[..], wth, attrs)?;
2097 ast::ExprKind::Tup(ref exprs) => {
2098 self.print_expr_tup(&exprs[..], attrs)?;
2100 ast::ExprKind::Call(ref func, ref args) => {
2101 self.print_expr_call(func, &args[..])?;
2103 ast::ExprKind::MethodCall(ref segment, ref args) => {
2104 self.print_expr_method_call(segment, &args[..])?;
2106 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2107 self.print_expr_binary(op, lhs, rhs)?;
2109 ast::ExprKind::Unary(op, ref expr) => {
2110 self.print_expr_unary(op, expr)?;
2112 ast::ExprKind::AddrOf(m, ref expr) => {
2113 self.print_expr_addr_of(m, expr)?;
2115 ast::ExprKind::Lit(ref lit) => {
2116 self.print_literal(lit)?;
2118 ast::ExprKind::Cast(ref expr, ref ty) => {
2119 let prec = AssocOp::As.precedence() as i8;
2120 self.print_expr_maybe_paren(expr, prec)?;
2122 self.word_space("as")?;
2123 self.print_type(ty)?;
2125 ast::ExprKind::Type(ref expr, ref ty) => {
2126 let prec = AssocOp::Colon.precedence() as i8;
2127 self.print_expr_maybe_paren(expr, prec)?;
2128 self.word_space(":")?;
2129 self.print_type(ty)?;
2131 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2132 self.print_if(test, blk, elseopt.as_ref().map(|e| &**e))?;
2134 ast::ExprKind::IfLet(ref pats, ref expr, ref blk, ref elseopt) => {
2135 self.print_if_let(pats, expr, blk, elseopt.as_ref().map(|e| &**e))?;
2137 ast::ExprKind::While(ref test, ref blk, opt_label) => {
2138 if let Some(label) = opt_label {
2139 self.print_ident(label.ident)?;
2140 self.word_space(":")?;
2142 self.head("while")?;
2143 self.print_expr_as_cond(test)?;
2145 self.print_block_with_attrs(blk, attrs)?;
2147 ast::ExprKind::WhileLet(ref pats, ref expr, ref blk, opt_label) => {
2148 if let Some(label) = opt_label {
2149 self.print_ident(label.ident)?;
2150 self.word_space(":")?;
2152 self.head("while let")?;
2153 self.print_pats(pats)?;
2155 self.word_space("=")?;
2156 self.print_expr_as_cond(expr)?;
2158 self.print_block_with_attrs(blk, attrs)?;
2160 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2161 if let Some(label) = opt_label {
2162 self.print_ident(label.ident)?;
2163 self.word_space(":")?;
2166 self.print_pat(pat)?;
2168 self.word_space("in")?;
2169 self.print_expr_as_cond(iter)?;
2171 self.print_block_with_attrs(blk, attrs)?;
2173 ast::ExprKind::Loop(ref blk, opt_label) => {
2174 if let Some(label) = opt_label {
2175 self.print_ident(label.ident)?;
2176 self.word_space(":")?;
2180 self.print_block_with_attrs(blk, attrs)?;
2182 ast::ExprKind::Match(ref expr, ref arms) => {
2183 self.cbox(INDENT_UNIT)?;
2185 self.word_nbsp("match")?;
2186 self.print_expr_as_cond(expr)?;
2189 self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
2191 self.print_arm(arm)?;
2193 self.bclose_(expr.span, INDENT_UNIT)?;
2195 ast::ExprKind::Closure(
2196 capture_clause, asyncness, movability, ref decl, ref body, _) => {
2197 self.print_movability(movability)?;
2198 self.print_asyncness(asyncness)?;
2199 self.print_capture_clause(capture_clause)?;
2201 self.print_fn_block_args(decl)?;
2203 self.print_expr(body)?;
2204 self.end()?; // need to close a box
2206 // a box will be closed by print_expr, but we didn't want an overall
2207 // wrapper so we closed the corresponding opening. so create an
2208 // empty box to satisfy the close.
2211 ast::ExprKind::Block(ref blk, opt_label) => {
2212 if let Some(label) = opt_label {
2213 self.print_ident(label.ident)?;
2214 self.word_space(":")?;
2216 // containing cbox, will be closed by print-block at }
2217 self.cbox(INDENT_UNIT)?;
2218 // head-box, will be closed by print-block after {
2220 self.print_block_with_attrs(blk, attrs)?;
2222 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2223 self.word_nbsp("async")?;
2224 self.print_capture_clause(capture_clause)?;
2226 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2227 self.cbox(INDENT_UNIT)?;
2229 self.print_block_with_attrs(blk, attrs)?;
2231 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2232 let prec = AssocOp::Assign.precedence() as i8;
2233 self.print_expr_maybe_paren(lhs, prec + 1)?;
2235 self.word_space("=")?;
2236 self.print_expr_maybe_paren(rhs, prec)?;
2238 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2239 let prec = AssocOp::Assign.precedence() as i8;
2240 self.print_expr_maybe_paren(lhs, prec + 1)?;
2242 self.s.word(op.node.to_string())?;
2243 self.word_space("=")?;
2244 self.print_expr_maybe_paren(rhs, prec)?;
2246 ast::ExprKind::Field(ref expr, ident) => {
2247 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
2249 self.print_ident(ident)?;
2251 ast::ExprKind::Index(ref expr, ref index) => {
2252 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
2254 self.print_expr(index)?;
2257 ast::ExprKind::Range(ref start, ref end, limits) => {
2258 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2259 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2260 // Here we use a fake precedence value so that any child with lower precedence than
2261 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2262 let fake_prec = AssocOp::LOr.precedence() as i8;
2263 if let Some(ref e) = *start {
2264 self.print_expr_maybe_paren(e, fake_prec)?;
2266 if limits == ast::RangeLimits::HalfOpen {
2269 self.s.word("..=")?;
2271 if let Some(ref e) = *end {
2272 self.print_expr_maybe_paren(e, fake_prec)?;
2275 ast::ExprKind::Path(None, ref path) => {
2276 self.print_path(path, true, 0)?
2278 ast::ExprKind::Path(Some(ref qself), ref path) => {
2279 self.print_qpath(path, qself, true)?
2281 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2282 self.s.word("break")?;
2284 if let Some(label) = opt_label {
2285 self.print_ident(label.ident)?;
2288 if let Some(ref expr) = *opt_expr {
2289 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2293 ast::ExprKind::Continue(opt_label) => {
2294 self.s.word("continue")?;
2296 if let Some(label) = opt_label {
2297 self.print_ident(label.ident)?;
2301 ast::ExprKind::Ret(ref result) => {
2302 self.s.word("return")?;
2303 if let Some(ref expr) = *result {
2305 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2308 ast::ExprKind::InlineAsm(ref a) => {
2309 self.s.word("asm!")?;
2311 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
2312 self.word_space(":")?;
2314 self.commasep(Inconsistent, &a.outputs, |s, out| {
2315 let constraint = out.constraint.as_str();
2316 let mut ch = constraint.chars();
2318 Some('=') if out.is_rw => {
2319 s.print_string(&format!("+{}", ch.as_str()),
2320 ast::StrStyle::Cooked)?
2322 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?
2325 s.print_expr(&out.expr)?;
2330 self.word_space(":")?;
2332 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2333 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2340 self.word_space(":")?;
2342 self.commasep(Inconsistent, &a.clobbers,
2344 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2348 let mut options = vec![];
2350 options.push("volatile");
2353 options.push("alignstack");
2355 if a.dialect == ast::AsmDialect::Intel {
2356 options.push("intel");
2359 if !options.is_empty() {
2361 self.word_space(":")?;
2362 self.commasep(Inconsistent, &options,
2364 s.print_string(co, ast::StrStyle::Cooked)?;
2371 ast::ExprKind::Mac(ref m) => self.print_mac(m)?,
2372 ast::ExprKind::Paren(ref e) => {
2374 self.print_inner_attributes_inline(attrs)?;
2375 self.print_expr(e)?;
2378 ast::ExprKind::Yield(ref e) => {
2379 self.s.word("yield")?;
2383 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2388 ast::ExprKind::Try(ref e) => {
2389 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX)?;
2392 ast::ExprKind::TryBlock(ref blk) => {
2395 self.print_block_with_attrs(blk, attrs)?
2397 ast::ExprKind::Err => {
2399 self.s.word("/*ERROR*/")?;
2403 self.ann.post(self, AnnNode::Expr(expr))?;
2407 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2408 self.print_pat(&loc.pat)?;
2409 if let Some(ref ty) = loc.ty {
2410 self.word_space(":")?;
2411 self.print_type(ty)?;
2416 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2417 if ident.is_raw_guess() {
2418 self.s.word(format!("r#{}", ident))?;
2420 self.s.word(ident.as_str().get())?;
2422 self.ann.post(self, AnnNode::Ident(&ident))
2425 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2426 self.s.word(i.to_string())
2429 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2430 self.s.word(name.as_str().get())?;
2431 self.ann.post(self, AnnNode::Name(&name))
2434 pub fn print_for_decl(&mut self, loc: &ast::Local,
2435 coll: &ast::Expr) -> io::Result<()> {
2436 self.print_local_decl(loc)?;
2438 self.word_space("in")?;
2439 self.print_expr(coll)
2442 fn print_path(&mut self,
2444 colons_before_params: bool,
2448 self.maybe_print_comment(path.span.lo())?;
2450 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
2454 self.print_path_segment(segment, colons_before_params)?;
2460 fn print_path_segment(&mut self,
2461 segment: &ast::PathSegment,
2462 colons_before_params: bool)
2465 if segment.ident.name != keywords::PathRoot.name() {
2466 if segment.ident.name == keywords::DollarCrate.name() {
2467 self.print_dollar_crate(segment.ident)?;
2469 self.print_ident(segment.ident)?;
2471 if let Some(ref args) = segment.args {
2472 self.print_generic_args(args, colons_before_params)?;
2478 fn print_qpath(&mut self,
2481 colons_before_params: bool)
2485 self.print_type(&qself.ty)?;
2486 if qself.position > 0 {
2488 self.word_space("as")?;
2489 let depth = path.segments.len() - qself.position;
2490 self.print_path(path, false, depth)?;
2494 let item_segment = path.segments.last().unwrap();
2495 self.print_ident(item_segment.ident)?;
2496 match item_segment.args {
2497 Some(ref args) => self.print_generic_args(args, colons_before_params),
2502 fn print_generic_args(&mut self,
2503 args: &ast::GenericArgs,
2504 colons_before_params: bool)
2507 if colons_before_params {
2512 ast::GenericArgs::AngleBracketed(ref data) => {
2515 self.commasep(Inconsistent, &data.args, |s, generic_arg| {
2516 s.print_generic_arg(generic_arg)
2519 let mut comma = data.args.len() != 0;
2521 for binding in data.bindings.iter() {
2523 self.word_space(",")?
2525 self.print_ident(binding.ident)?;
2527 self.word_space("=")?;
2528 self.print_type(&binding.ty)?;
2535 ast::GenericArgs::Parenthesized(ref data) => {
2540 |s, ty| s.print_type(ty))?;
2543 if let Some(ref ty) = data.output {
2544 self.space_if_not_bol()?;
2545 self.word_space("->")?;
2546 self.print_type(ty)?;
2554 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2555 self.maybe_print_comment(pat.span.lo())?;
2556 self.ann.pre(self, AnnNode::Pat(pat))?;
2557 /* Pat isn't normalized, but the beauty of it
2558 is that it doesn't matter */
2560 PatKind::Wild => self.s.word("_")?,
2561 PatKind::Ident(binding_mode, ident, ref sub) => {
2562 match binding_mode {
2563 ast::BindingMode::ByRef(mutbl) => {
2564 self.word_nbsp("ref")?;
2565 self.print_mutability(mutbl)?;
2567 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2568 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2569 self.word_nbsp("mut")?;
2572 self.print_ident(ident)?;
2573 if let Some(ref p) = *sub {
2578 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2579 self.print_path(path, true, 0)?;
2581 if let Some(ddpos) = ddpos {
2582 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
2584 self.word_space(",")?;
2587 if ddpos != elts.len() {
2589 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
2592 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
2596 PatKind::Path(None, ref path) => {
2597 self.print_path(path, true, 0)?;
2599 PatKind::Path(Some(ref qself), ref path) => {
2600 self.print_qpath(path, qself, false)?;
2602 PatKind::Struct(ref path, ref fields, etc) => {
2603 self.print_path(path, true, 0)?;
2605 self.word_space("{")?;
2607 Consistent, &fields[..],
2609 s.cbox(INDENT_UNIT)?;
2610 if !f.node.is_shorthand {
2611 s.print_ident(f.node.ident)?;
2614 s.print_pat(&f.node.pat)?;
2617 |f| f.node.pat.span)?;
2619 if !fields.is_empty() { self.word_space(",")?; }
2625 PatKind::Tuple(ref elts, ddpos) => {
2627 if let Some(ddpos) = ddpos {
2628 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
2630 self.word_space(",")?;
2633 if ddpos != elts.len() {
2635 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
2638 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
2639 if elts.len() == 1 {
2645 PatKind::Box(ref inner) => {
2646 self.s.word("box ")?;
2647 self.print_pat(inner)?;
2649 PatKind::Ref(ref inner, mutbl) => {
2651 if mutbl == ast::Mutability::Mutable {
2652 self.s.word("mut ")?;
2654 self.print_pat(inner)?;
2656 PatKind::Lit(ref e) => self.print_expr(&**e)?,
2657 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2658 self.print_expr(begin)?;
2661 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("...")?,
2662 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..=")?,
2663 RangeEnd::Excluded => self.s.word("..")?,
2665 self.print_expr(end)?;
2667 PatKind::Slice(ref before, ref slice, ref after) => {
2669 self.commasep(Inconsistent,
2671 |s, p| s.print_pat(p))?;
2672 if let Some(ref p) = *slice {
2673 if !before.is_empty() { self.word_space(",")?; }
2674 if let PatKind::Wild = p.node {
2680 if !after.is_empty() { self.word_space(",")?; }
2682 self.commasep(Inconsistent,
2684 |s, p| s.print_pat(p))?;
2687 PatKind::Paren(ref inner) => {
2689 self.print_pat(inner)?;
2692 PatKind::Mac(ref m) => self.print_mac(m)?,
2694 self.ann.post(self, AnnNode::Pat(pat))
2697 fn print_pats(&mut self, pats: &[P<ast::Pat>]) -> io::Result<()> {
2698 let mut first = true;
2704 self.word_space("|")?;
2711 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2712 // I have no idea why this check is necessary, but here it
2714 if arm.attrs.is_empty() {
2717 self.cbox(INDENT_UNIT)?;
2719 self.maybe_print_comment(arm.pats[0].span.lo())?;
2720 self.print_outer_attributes(&arm.attrs)?;
2721 self.print_pats(&arm.pats)?;
2723 if let Some(ref g) = arm.guard {
2725 ast::Guard::If(ref e) => {
2726 self.word_space("if")?;
2727 self.print_expr(e)?;
2732 self.word_space("=>")?;
2734 match arm.body.node {
2735 ast::ExprKind::Block(ref blk, opt_label) => {
2736 if let Some(label) = opt_label {
2737 self.print_ident(label.ident)?;
2738 self.word_space(":")?;
2741 // the block will close the pattern's ibox
2742 self.print_block_unclosed_indent(blk, INDENT_UNIT)?;
2744 // If it is a user-provided unsafe block, print a comma after it
2745 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2750 self.end()?; // close the ibox for the pattern
2751 self.print_expr(&arm.body)?;
2755 self.end() // close enclosing cbox
2758 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2759 match explicit_self.node {
2760 SelfKind::Value(m) => {
2761 self.print_mutability(m)?;
2764 SelfKind::Region(ref lt, m) => {
2766 self.print_opt_lifetime(lt)?;
2767 self.print_mutability(m)?;
2770 SelfKind::Explicit(ref typ, m) => {
2771 self.print_mutability(m)?;
2772 self.s.word("self")?;
2773 self.word_space(":")?;
2774 self.print_type(typ)
2779 pub fn print_fn(&mut self,
2781 header: ast::FnHeader,
2782 name: Option<ast::Ident>,
2783 generics: &ast::Generics,
2784 vis: &ast::Visibility) -> io::Result<()> {
2785 self.print_fn_header_info(header, vis)?;
2787 if let Some(name) = name {
2789 self.print_ident(name)?;
2791 self.print_generic_params(&generics.params)?;
2792 self.print_fn_args_and_ret(decl)?;
2793 self.print_where_clause(&generics.where_clause)
2796 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2799 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
2801 self.s.word(", ...")?;
2805 self.print_fn_output(decl)
2808 pub fn print_fn_block_args(
2813 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
2816 if let ast::FunctionRetTy::Default(..) = decl.output {
2820 self.space_if_not_bol()?;
2821 self.word_space("->")?;
2823 ast::FunctionRetTy::Ty(ref ty) => {
2824 self.print_type(ty)?;
2825 self.maybe_print_comment(ty.span.lo())
2827 ast::FunctionRetTy::Default(..) => unreachable!(),
2831 pub fn print_movability(&mut self, movability: ast::Movability)
2834 ast::Movability::Static => self.word_space("static"),
2835 ast::Movability::Movable => Ok(()),
2839 pub fn print_asyncness(&mut self, asyncness: ast::IsAsync)
2841 if asyncness.is_async() {
2842 self.word_nbsp("async")?;
2847 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2849 match capture_clause {
2850 ast::CaptureBy::Value => self.word_space("move"),
2851 ast::CaptureBy::Ref => Ok(()),
2855 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound])
2857 if !bounds.is_empty() {
2858 self.s.word(prefix)?;
2859 let mut first = true;
2860 for bound in bounds {
2861 if !(first && prefix.is_empty()) {
2867 self.word_space("+")?;
2871 GenericBound::Trait(tref, modifier) => {
2872 if modifier == &TraitBoundModifier::Maybe {
2875 self.print_poly_trait_ref(tref)?;
2877 GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
2884 pub fn print_lifetime(&mut self, lifetime: ast::Lifetime) -> io::Result<()> {
2885 self.print_name(lifetime.ident.name)
2888 pub fn print_lifetime_bounds(&mut self, lifetime: ast::Lifetime, bounds: &ast::GenericBounds)
2891 self.print_lifetime(lifetime)?;
2892 if !bounds.is_empty() {
2894 for (i, bound) in bounds.iter().enumerate() {
2896 self.s.word(" + ")?;
2899 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
2907 pub fn print_generic_params(
2909 generic_params: &[ast::GenericParam]
2910 ) -> io::Result<()> {
2911 if generic_params.is_empty() {
2917 self.commasep(Inconsistent, &generic_params, |s, param| {
2919 ast::GenericParamKind::Lifetime => {
2920 s.print_outer_attributes_inline(¶m.attrs)?;
2921 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2922 s.print_lifetime_bounds(lt, ¶m.bounds)
2924 ast::GenericParamKind::Type { ref default } => {
2925 s.print_outer_attributes_inline(¶m.attrs)?;
2926 s.print_ident(param.ident)?;
2927 s.print_type_bounds(":", ¶m.bounds)?;
2929 Some(ref default) => {
2932 s.print_type(default)
2944 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2946 if where_clause.predicates.is_empty() {
2951 self.word_space("where")?;
2953 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2955 self.word_space(",")?;
2959 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2960 ref bound_generic_params,
2965 self.print_formal_generic_params(bound_generic_params)?;
2966 self.print_type(bounded_ty)?;
2967 self.print_type_bounds(":", bounds)?;
2969 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2972 self.print_lifetime_bounds(*lifetime, bounds)?;
2974 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2977 self.print_type(lhs_ty)?;
2979 self.word_space("=")?;
2980 self.print_type(rhs_ty)?;
2988 pub fn print_use_tree(&mut self, tree: &ast::UseTree) -> io::Result<()> {
2990 ast::UseTreeKind::Simple(rename, ..) => {
2991 self.print_path(&tree.prefix, false, 0)?;
2992 if let Some(rename) = rename {
2994 self.word_space("as")?;
2995 self.print_ident(rename)?;
2998 ast::UseTreeKind::Glob => {
2999 if !tree.prefix.segments.is_empty() {
3000 self.print_path(&tree.prefix, false, 0)?;
3005 ast::UseTreeKind::Nested(ref items) => {
3006 if tree.prefix.segments.is_empty() {
3009 self.print_path(&tree.prefix, false, 0)?;
3010 self.s.word("::{")?;
3012 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
3013 this.print_use_tree(tree)
3022 pub fn print_mutability(&mut self,
3023 mutbl: ast::Mutability) -> io::Result<()> {
3025 ast::Mutability::Mutable => self.word_nbsp("mut"),
3026 ast::Mutability::Immutable => Ok(()),
3030 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
3031 self.print_mutability(mt.mutbl)?;
3032 self.print_type(&mt.ty)
3035 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
3036 self.ibox(INDENT_UNIT)?;
3037 match input.ty.node {
3038 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat)?,
3040 if let Some(eself) = input.to_self() {
3041 self.print_explicit_self(&eself)?;
3043 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
3044 ident.name == keywords::Invalid.name()
3049 self.print_pat(&input.pat)?;
3053 self.print_type(&input.ty)?;
3060 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
3061 if let ast::FunctionRetTy::Default(..) = decl.output {
3065 self.space_if_not_bol()?;
3066 self.ibox(INDENT_UNIT)?;
3067 self.word_space("->")?;
3069 ast::FunctionRetTy::Default(..) => unreachable!(),
3070 ast::FunctionRetTy::Ty(ref ty) =>
3071 self.print_type(ty)?
3076 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo()),
3081 pub fn print_ty_fn(&mut self,
3083 unsafety: ast::Unsafety,
3085 name: Option<ast::Ident>,
3086 generic_params: &[ast::GenericParam])
3088 self.ibox(INDENT_UNIT)?;
3089 if !generic_params.is_empty() {
3090 self.s.word("for")?;
3091 self.print_generic_params(generic_params)?;
3093 let generics = ast::Generics {
3095 where_clause: ast::WhereClause {
3096 id: ast::DUMMY_NODE_ID,
3097 predicates: Vec::new(),
3098 span: syntax_pos::DUMMY_SP,
3100 span: syntax_pos::DUMMY_SP,
3103 ast::FnHeader { unsafety, abi, ..ast::FnHeader::default() },
3106 &source_map::dummy_spanned(ast::VisibilityKind::Inherited))?;
3110 pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
3111 next_pos: Option<BytePos>)
3113 let cm = match self.cm {
3117 if let Some(ref cmnt) = self.next_comment() {
3118 if cmnt.style != comments::Trailing { return Ok(()) }
3119 let span_line = cm.lookup_char_pos(span.hi());
3120 let comment_line = cm.lookup_char_pos(cmnt.pos);
3121 let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1));
3122 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
3123 self.print_comment(cmnt)?;
3129 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3130 // If there aren't any remaining comments, then we need to manually
3131 // make sure there is a line break at the end.
3132 if self.next_comment().is_none() {
3133 self.s.hardbreak()?;
3135 while let Some(ref cmnt) = self.next_comment() {
3136 self.print_comment(cmnt)?;
3141 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3142 opt_abi: Option<Abi>)
3145 Some(Abi::Rust) => Ok(()),
3147 self.word_nbsp("extern")?;
3148 self.word_nbsp(abi.to_string())
3154 pub fn print_extern_opt_abi(&mut self,
3155 opt_abi: Option<Abi>) -> io::Result<()> {
3158 self.word_nbsp("extern")?;
3159 self.word_nbsp(abi.to_string())
3165 pub fn print_fn_header_info(&mut self,
3166 header: ast::FnHeader,
3167 vis: &ast::Visibility) -> io::Result<()> {
3168 self.s.word(visibility_qualified(vis, ""))?;
3170 match header.constness.node {
3171 ast::Constness::NotConst => {}
3172 ast::Constness::Const => self.word_nbsp("const")?
3175 self.print_asyncness(header.asyncness)?;
3176 self.print_unsafety(header.unsafety)?;
3178 if header.abi != Abi::Rust {
3179 self.word_nbsp("extern")?;
3180 self.word_nbsp(header.abi.to_string())?;
3186 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3188 ast::Unsafety::Normal => Ok(()),
3189 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3193 pub fn print_is_auto(&mut self, s: ast::IsAuto) -> io::Result<()> {
3195 ast::IsAuto::Yes => self.word_nbsp("auto"),
3196 ast::IsAuto::No => Ok(()),
3211 fn test_fun_to_string() {
3213 let abba_ident = ast::Ident::from_str("abba");
3215 let decl = ast::FnDecl {
3217 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
3220 let generics = ast::Generics::default();
3225 unsafety: ast::Unsafety::Normal,
3226 constness: source_map::dummy_spanned(ast::Constness::NotConst),
3227 asyncness: ast::IsAsync::NotAsync,
3239 fn test_variant_to_string() {
3241 let ident = ast::Ident::from_str("principal_skinner");
3243 let var = source_map::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
3246 // making this up as I go.... ?
3247 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3251 let varstr = variant_to_string(&var);
3252 assert_eq!(varstr, "principal_skinner");