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),
228 token::Integer(c) => c.to_string(),
229 token::Str_(s) => format!("\"{}\"", s),
230 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
231 delim="#".repeat(n as usize),
233 token::ByteStr(v) => format!("b\"{}\"", v),
234 token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
235 delim="#".repeat(n as usize),
239 if let Some(s) = suf {
240 out.push_str(&s.as_str())
246 /* Name components */
247 token::Ident(s, false) => s.to_string(),
248 token::Ident(s, true) => format!("r#{}", s),
249 token::Lifetime(s) => s.to_string(),
252 token::DocComment(s) => s.to_string(),
253 token::Eof => "<eof>".to_string(),
254 token::Whitespace => " ".to_string(),
255 token::Comment => "/* */".to_string(),
256 token::Shebang(s) => format!("/* shebang: {}*/", s),
258 token::Interpolated(ref nt) => match nt.0 {
259 token::NtExpr(ref e) => expr_to_string(e),
260 token::NtMeta(ref e) => meta_item_to_string(e),
261 token::NtTy(ref e) => ty_to_string(e),
262 token::NtPath(ref e) => path_to_string(e),
263 token::NtItem(ref e) => item_to_string(e),
264 token::NtBlock(ref e) => block_to_string(e),
265 token::NtStmt(ref e) => stmt_to_string(e),
266 token::NtPat(ref e) => pat_to_string(e),
267 token::NtIdent(e, false) => ident_to_string(e),
268 token::NtIdent(e, true) => format!("r#{}", ident_to_string(e)),
269 token::NtLifetime(e) => ident_to_string(e),
270 token::NtLiteral(ref e) => expr_to_string(e),
271 token::NtTT(ref tree) => tt_to_string(tree.clone()),
272 token::NtArm(ref e) => arm_to_string(e),
273 token::NtImplItem(ref e) => impl_item_to_string(e),
274 token::NtTraitItem(ref e) => trait_item_to_string(e),
275 token::NtGenerics(ref e) => generic_params_to_string(&e.params),
276 token::NtWhereClause(ref e) => where_clause_to_string(e),
277 token::NtArg(ref e) => arg_to_string(e),
278 token::NtVis(ref e) => vis_to_string(e),
279 token::NtForeignItem(ref e) => foreign_item_to_string(e),
284 pub fn ty_to_string(ty: &ast::Ty) -> String {
285 to_string(|s| s.print_type(ty))
288 pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
289 to_string(|s| s.print_type_bounds("", bounds))
292 pub fn pat_to_string(pat: &ast::Pat) -> String {
293 to_string(|s| s.print_pat(pat))
296 pub fn arm_to_string(arm: &ast::Arm) -> String {
297 to_string(|s| s.print_arm(arm))
300 pub fn expr_to_string(e: &ast::Expr) -> String {
301 to_string(|s| s.print_expr(e))
304 pub fn lifetime_to_string(lt: &ast::Lifetime) -> String {
305 to_string(|s| s.print_lifetime(*lt))
308 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
309 to_string(|s| s.print_tt(tt))
312 pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
313 to_string(|s| s.print_tts(tts.iter().cloned().collect()))
316 pub fn tokens_to_string(tokens: TokenStream) -> String {
317 to_string(|s| s.print_tts(tokens))
320 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
321 to_string(|s| s.print_stmt(stmt))
324 pub fn attr_to_string(attr: &ast::Attribute) -> String {
325 to_string(|s| s.print_attribute(attr))
328 pub fn item_to_string(i: &ast::Item) -> String {
329 to_string(|s| s.print_item(i))
332 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
333 to_string(|s| s.print_impl_item(i))
336 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
337 to_string(|s| s.print_trait_item(i))
340 pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String {
341 to_string(|s| s.print_generic_params(generic_params))
344 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
345 to_string(|s| s.print_where_clause(i))
348 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
349 to_string(|s| s.print_fn_block_args(p))
352 pub fn path_to_string(p: &ast::Path) -> String {
353 to_string(|s| s.print_path(p, false, 0))
356 pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
357 to_string(|s| s.print_path_segment(p, false))
360 pub fn ident_to_string(id: ast::Ident) -> String {
361 to_string(|s| s.print_ident(id))
364 pub fn vis_to_string(v: &ast::Visibility) -> String {
365 to_string(|s| s.print_visibility(v))
368 pub fn fun_to_string(decl: &ast::FnDecl,
369 header: ast::FnHeader,
371 generics: &ast::Generics)
375 s.print_fn(decl, header, Some(name),
376 generics, &source_map::dummy_spanned(ast::VisibilityKind::Inherited))?;
377 s.end()?; // Close the head box
378 s.end() // Close the outer box
382 pub fn block_to_string(blk: &ast::Block) -> String {
384 // containing cbox, will be closed by print-block at }
385 s.cbox(INDENT_UNIT)?;
386 // head-ibox, will be closed by print-block after {
392 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
393 to_string(|s| s.print_meta_list_item(li))
396 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
397 to_string(|s| s.print_meta_item(mi))
400 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
401 to_string(|s| s.print_attribute(attr))
404 pub fn lit_to_string(l: &ast::Lit) -> String {
405 to_string(|s| s.print_literal(l))
408 pub fn variant_to_string(var: &ast::Variant) -> String {
409 to_string(|s| s.print_variant(var))
412 pub fn arg_to_string(arg: &ast::Arg) -> String {
413 to_string(|s| s.print_arg(arg, false))
416 pub fn mac_to_string(arg: &ast::Mac) -> String {
417 to_string(|s| s.print_mac(arg))
420 pub fn foreign_item_to_string(arg: &ast::ForeignItem) -> String {
421 to_string(|s| s.print_foreign_item(arg))
424 pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
425 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
428 pub trait PrintState<'a> {
429 fn writer(&mut self) -> &mut pp::Printer<'a>;
430 fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
431 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
432 fn cur_cmnt(&mut self) -> &mut usize;
433 fn cur_lit(&mut self) -> Option<&comments::Literal>;
434 fn bump_lit(&mut self) -> Option<comments::Literal>;
436 fn word_space<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
437 self.writer().word(w)?;
438 self.writer().space()
441 fn popen(&mut self) -> io::Result<()> { self.writer().word("(") }
443 fn pclose(&mut self) -> io::Result<()> { self.writer().word(")") }
445 fn is_begin(&mut self) -> bool {
446 match self.writer().last_token() {
447 pp::Token::Begin(_) => true,
452 fn is_end(&mut self) -> bool {
453 match self.writer().last_token() {
454 pp::Token::End => true,
459 // is this the beginning of a line?
460 fn is_bol(&mut self) -> bool {
461 self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
464 fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
466 self.writer().hardbreak()?
472 fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
473 self.boxes().push(b);
474 self.writer().rbox(u, b)
477 fn ibox(&mut self, u: usize) -> io::Result<()> {
478 self.boxes().push(pp::Breaks::Inconsistent);
479 self.writer().ibox(u)
482 fn end(&mut self) -> io::Result<()> {
483 self.boxes().pop().unwrap();
487 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
488 where F: FnMut(&mut Self, &T) -> io::Result<()>,
491 let mut first = true;
493 if first { first = false; } else { self.word_space(",")?; }
499 fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
500 while let Some(ltrl) = self.cur_lit().cloned() {
501 if ltrl.pos > pos { break; }
503 // we don't need the value here since we're forced to clone cur_lit
504 // due to lack of NLL.
514 fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
515 while let Some(ref cmnt) = self.next_comment() {
517 self.print_comment(cmnt)?;
525 fn print_comment(&mut self,
526 cmnt: &comments::Comment) -> io::Result<()> {
527 let r = match cmnt.style {
529 assert_eq!(cmnt.lines.len(), 1);
530 self.writer().zerobreak()?;
531 self.writer().word(cmnt.lines[0].clone())?;
532 self.writer().zerobreak()
534 comments::Isolated => {
535 self.hardbreak_if_not_bol()?;
536 for line in &cmnt.lines {
537 // Don't print empty lines because they will end up as trailing
539 if !line.is_empty() {
540 self.writer().word(line.clone())?;
542 self.writer().hardbreak()?;
546 comments::Trailing => {
548 self.writer().word(" ")?;
550 if cmnt.lines.len() == 1 {
551 self.writer().word(cmnt.lines[0].clone())?;
552 self.writer().hardbreak()
555 for line in &cmnt.lines {
556 if !line.is_empty() {
557 self.writer().word(line.clone())?;
559 self.writer().hardbreak()?;
564 comments::BlankLine => {
565 // We need to do at least one, possibly two hardbreaks.
566 let is_semi = match self.writer().last_token() {
567 pp::Token::String(s, _) => ";" == s,
570 if is_semi || self.is_begin() || self.is_end() {
571 self.writer().hardbreak()?;
573 self.writer().hardbreak()
578 *self.cur_cmnt() = *self.cur_cmnt() + 1;
585 fn next_comment(&mut self) -> Option<comments::Comment> {
586 let cur_cmnt = *self.cur_cmnt();
587 match *self.comments() {
589 if cur_cmnt < cmnts.len() {
590 Some(cmnts[cur_cmnt].clone())
599 fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
600 self.maybe_print_comment(lit.span.lo())?;
601 if let Some(ltrl) = self.next_lit(lit.span.lo()) {
602 return self.writer().word(ltrl.lit.clone());
605 ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style),
606 ast::LitKind::Byte(byte) => {
607 let mut res = String::from("b'");
608 res.extend(ascii::escape_default(byte).map(|c| c as char));
610 self.writer().word(res)
612 ast::LitKind::Char(ch) => {
613 let mut res = String::from("'");
614 res.extend(ch.escape_default());
616 self.writer().word(res)
618 ast::LitKind::Int(i, t) => {
620 ast::LitIntType::Signed(st) => {
621 self.writer().word(st.val_to_string(i as i128))
623 ast::LitIntType::Unsigned(ut) => {
624 self.writer().word(ut.val_to_string(i))
626 ast::LitIntType::Unsuffixed => {
627 self.writer().word(i.to_string())
631 ast::LitKind::Float(ref f, t) => {
632 self.writer().word(format!("{}{}", &f, t.ty_to_string()))
634 ast::LitKind::FloatUnsuffixed(ref f) => self.writer().word(f.as_str().get()),
635 ast::LitKind::Bool(val) => {
636 if val { self.writer().word("true") } else { self.writer().word("false") }
638 ast::LitKind::ByteStr(ref v) => {
639 let mut escaped: String = String::new();
640 for &ch in v.iter() {
641 escaped.extend(ascii::escape_default(ch)
642 .map(|c| c as char));
644 self.writer().word(format!("b\"{}\"", escaped))
649 fn print_string(&mut self, st: &str,
650 style: ast::StrStyle) -> io::Result<()> {
651 let st = match style {
652 ast::StrStyle::Cooked => {
653 (format!("\"{}\"", st.escape_debug()))
655 ast::StrStyle::Raw(n) => {
656 (format!("r{delim}\"{string}\"{delim}",
657 delim="#".repeat(n as usize),
661 self.writer().word(st)
664 fn print_inner_attributes(&mut self,
665 attrs: &[ast::Attribute]) -> io::Result<()> {
666 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
669 fn print_inner_attributes_no_trailing_hardbreak(&mut self,
670 attrs: &[ast::Attribute])
672 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
675 fn print_outer_attributes(&mut self,
676 attrs: &[ast::Attribute]) -> io::Result<()> {
677 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
680 fn print_inner_attributes_inline(&mut self,
681 attrs: &[ast::Attribute]) -> io::Result<()> {
682 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
685 fn print_outer_attributes_inline(&mut self,
686 attrs: &[ast::Attribute]) -> io::Result<()> {
687 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
690 fn print_either_attributes(&mut self,
691 attrs: &[ast::Attribute],
692 kind: ast::AttrStyle,
694 trailing_hardbreak: bool) -> io::Result<()> {
697 if attr.style == kind {
698 self.print_attribute_inline(attr, is_inline)?;
705 if count > 0 && trailing_hardbreak && !is_inline {
706 self.hardbreak_if_not_bol()?;
711 fn print_attribute_path(&mut self, path: &ast::Path) -> io::Result<()> {
712 for (i, segment) in path.segments.iter().enumerate() {
714 self.writer().word("::")?
716 if segment.ident.name != keywords::PathRoot.name() {
717 if segment.ident.name == keywords::DollarCrate.name() {
718 self.print_dollar_crate(segment.ident)?;
720 self.writer().word(segment.ident.as_str().get())?;
727 fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
728 self.print_attribute_inline(attr, false)
731 fn print_attribute_inline(&mut self, attr: &ast::Attribute,
732 is_inline: bool) -> io::Result<()> {
734 self.hardbreak_if_not_bol()?;
736 self.maybe_print_comment(attr.span.lo())?;
737 if attr.is_sugared_doc {
738 self.writer().word(attr.value_str().unwrap().as_str().get())?;
739 self.writer().hardbreak()
742 ast::AttrStyle::Inner => self.writer().word("#![")?,
743 ast::AttrStyle::Outer => self.writer().word("#[")?,
745 if let Some(mi) = attr.meta() {
746 self.print_meta_item(&mi)?
748 self.print_attribute_path(&attr.path)?;
749 self.writer().space()?;
750 self.print_tts(attr.tokens.clone())?;
752 self.writer().word("]")
756 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> {
758 ast::NestedMetaItemKind::MetaItem(ref mi) => {
759 self.print_meta_item(mi)
761 ast::NestedMetaItemKind::Literal(ref lit) => {
762 self.print_literal(lit)
767 fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
768 self.ibox(INDENT_UNIT)?;
770 ast::MetaItemKind::Word => self.print_attribute_path(&item.ident)?,
771 ast::MetaItemKind::NameValue(ref value) => {
772 self.print_attribute_path(&item.ident)?;
773 self.writer().space()?;
774 self.word_space("=")?;
775 self.print_literal(value)?;
777 ast::MetaItemKind::List(ref items) => {
778 self.print_attribute_path(&item.ident)?;
780 self.commasep(Consistent,
782 |s, i| s.print_meta_list_item(i))?;
789 /// This doesn't deserve to be called "pretty" printing, but it should be
790 /// meaning-preserving. A quick hack that might help would be to look at the
791 /// spans embedded in the TTs to decide where to put spaces and newlines.
792 /// But it'd be better to parse these according to the grammar of the
793 /// appropriate macro, transcribe back into the grammar we just parsed from,
794 /// and then pretty-print the resulting AST nodes (so, e.g., we print
795 /// expression arguments as expressions). It can be done! I think.
796 fn print_tt(&mut self, tt: tokenstream::TokenTree) -> io::Result<()> {
798 TokenTree::Token(_, ref tk) => {
799 self.writer().word(token_to_string(tk))?;
801 parse::token::DocComment(..) => {
802 self.writer().hardbreak()
807 TokenTree::Delimited(_, delim, tts) => {
808 self.writer().word(token_to_string(&token::OpenDelim(delim)))?;
809 self.writer().space()?;
810 self.print_tts(tts.stream())?;
811 self.writer().space()?;
812 self.writer().word(token_to_string(&token::CloseDelim(delim)))
817 fn print_tts(&mut self, tts: tokenstream::TokenStream) -> io::Result<()> {
819 for (i, tt) in tts.into_trees().enumerate() {
821 self.writer().space()?;
828 fn space_if_not_bol(&mut self) -> io::Result<()> {
829 if !self.is_bol() { self.writer().space()?; }
833 fn nbsp(&mut self) -> io::Result<()> { self.writer().word(" ") }
835 // AST pretty-printer is used as a fallback for turning AST structures into token streams for
836 // proc macros. Additionally, proc macros may stringify their input and expect it survive the
837 // stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
838 // So we need to somehow pretty-print `$crate` in paths in a way preserving at least some of
839 // its hygiene data, most importantly name of the crate it refers to.
840 // As a result we print `$crate` as `crate` if it refers to the local crate
841 // and as `::other_crate_name` if it refers to some other crate.
842 fn print_dollar_crate(&mut self, ident: ast::Ident) -> io::Result<()> {
843 let name = ident.span.ctxt().dollar_crate_name();
844 if !ast::Ident::with_empty_ctxt(name).is_path_segment_keyword() {
845 self.writer().word("::")?;
847 self.writer().word(name.as_str().get())
851 impl<'a> PrintState<'a> for State<'a> {
852 fn writer(&mut self) -> &mut pp::Printer<'a> {
856 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
860 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
864 fn cur_cmnt(&mut self) -> &mut usize {
868 fn cur_lit(&mut self) -> Option<&comments::Literal> {
872 fn bump_lit(&mut self) -> Option<comments::Literal> {
878 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
879 self.boxes.push(pp::Breaks::Consistent);
883 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
888 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
890 // outer-box is consistent
891 self.cbox(INDENT_UNIT)?;
892 // head-box is inconsistent
893 self.ibox(w.len() + 1)?;
894 // keyword that starts the head
901 pub fn bopen(&mut self) -> io::Result<()> {
903 self.end() // close the head-box
906 pub fn bclose_(&mut self, span: syntax_pos::Span,
907 indented: usize) -> io::Result<()> {
908 self.bclose_maybe_open(span, indented, true)
910 pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
911 indented: usize, close_box: bool) -> io::Result<()> {
912 self.maybe_print_comment(span.hi())?;
913 self.break_offset_if_not_bol(1, -(indented as isize))?;
916 self.end()?; // close the outer-box
920 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
921 self.bclose_(span, INDENT_UNIT)
924 pub fn in_cbox(&self) -> bool {
925 match self.boxes.last() {
926 Some(&last_box) => last_box == pp::Breaks::Consistent,
931 pub fn break_offset_if_not_bol(&mut self, n: usize,
932 off: isize) -> io::Result<()> {
934 self.s.break_offset(n, off)
936 if off != 0 && self.s.last_token().is_hardbreak_tok() {
937 // We do something pretty sketchy here: tuck the nonzero
938 // offset-adjustment we were going to deposit along with the
939 // break into the previous hardbreak.
940 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
946 // Synthesizes a comment that was not textually present in the original source
948 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
958 pub fn commasep_cmnt<T, F, G>(&mut self,
962 mut get_span: G) -> io::Result<()> where
963 F: FnMut(&mut State, &T) -> io::Result<()>,
964 G: FnMut(&T) -> syntax_pos::Span,
967 let len = elts.len();
970 self.maybe_print_comment(get_span(elt).hi())?;
975 self.maybe_print_trailing_comment(get_span(elt),
976 Some(get_span(&elts[i]).hi()))?;
977 self.space_if_not_bol()?;
983 pub fn commasep_exprs(&mut self, b: Breaks,
984 exprs: &[P<ast::Expr>]) -> io::Result<()> {
985 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
988 pub fn print_mod(&mut self, _mod: &ast::Mod,
989 attrs: &[ast::Attribute]) -> io::Result<()> {
990 self.print_inner_attributes(attrs)?;
991 for item in &_mod.items {
992 self.print_item(item)?;
997 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
998 attrs: &[ast::Attribute]) -> io::Result<()> {
999 self.print_inner_attributes(attrs)?;
1000 for item in &nmod.items {
1001 self.print_foreign_item(item)?;
1006 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
1007 if let Some(lt) = *lifetime {
1008 self.print_lifetime(lt)?;
1014 pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) -> io::Result<()> {
1016 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
1017 GenericArg::Type(ty) => self.print_type(ty),
1021 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
1022 self.maybe_print_comment(ty.span.lo())?;
1025 ast::TyKind::Slice(ref ty) => {
1027 self.print_type(ty)?;
1030 ast::TyKind::Ptr(ref mt) => {
1033 ast::Mutability::Mutable => self.word_nbsp("mut")?,
1034 ast::Mutability::Immutable => self.word_nbsp("const")?,
1036 self.print_type(&mt.ty)?;
1038 ast::TyKind::Rptr(ref lifetime, ref mt) => {
1040 self.print_opt_lifetime(lifetime)?;
1043 ast::TyKind::Never => {
1046 ast::TyKind::Tup(ref elts) => {
1048 self.commasep(Inconsistent, &elts[..],
1049 |s, ty| s.print_type(ty))?;
1050 if elts.len() == 1 {
1055 ast::TyKind::Paren(ref typ) => {
1057 self.print_type(typ)?;
1060 ast::TyKind::BareFn(ref f) => {
1061 self.print_ty_fn(f.abi,
1065 &f.generic_params)?;
1067 ast::TyKind::Path(None, ref path) => {
1068 self.print_path(path, false, 0)?;
1070 ast::TyKind::Path(Some(ref qself), ref path) => {
1071 self.print_qpath(path, qself, false)?
1073 ast::TyKind::TraitObject(ref bounds, syntax) => {
1074 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
1075 self.print_type_bounds(prefix, &bounds[..])?;
1077 ast::TyKind::ImplTrait(_, ref bounds) => {
1078 self.print_type_bounds("impl", &bounds[..])?;
1080 ast::TyKind::Array(ref ty, ref length) => {
1082 self.print_type(ty)?;
1084 self.print_expr(&length.value)?;
1087 ast::TyKind::Typeof(ref e) => {
1088 self.s.word("typeof(")?;
1089 self.print_expr(&e.value)?;
1092 ast::TyKind::Infer => {
1095 ast::TyKind::Err => {
1097 self.s.word("/*ERROR*/")?;
1100 ast::TyKind::ImplicitSelf => {
1101 self.s.word("Self")?;
1103 ast::TyKind::Mac(ref m) => {
1110 pub fn print_foreign_item(&mut self,
1111 item: &ast::ForeignItem) -> io::Result<()> {
1112 self.hardbreak_if_not_bol()?;
1113 self.maybe_print_comment(item.span.lo())?;
1114 self.print_outer_attributes(&item.attrs)?;
1116 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1118 self.print_fn(decl, ast::FnHeader::default(),
1120 generics, &item.vis)?;
1121 self.end()?; // end head-ibox
1123 self.end() // end the outer fn box
1125 ast::ForeignItemKind::Static(ref t, m) => {
1126 self.head(visibility_qualified(&item.vis, "static"))?;
1128 self.word_space("mut")?;
1130 self.print_ident(item.ident)?;
1131 self.word_space(":")?;
1132 self.print_type(t)?;
1134 self.end()?; // end the head-ibox
1135 self.end() // end the outer cbox
1137 ast::ForeignItemKind::Ty => {
1138 self.head(visibility_qualified(&item.vis, "type"))?;
1139 self.print_ident(item.ident)?;
1141 self.end()?; // end the head-ibox
1142 self.end() // end the outer cbox
1144 ast::ForeignItemKind::Macro(ref m) => {
1146 match m.node.delim {
1147 MacDelimiter::Brace => Ok(()),
1148 _ => self.s.word(";")
1154 fn print_associated_const(&mut self,
1157 default: Option<&ast::Expr>,
1158 vis: &ast::Visibility)
1161 self.s.word(visibility_qualified(vis, ""))?;
1162 self.word_space("const")?;
1163 self.print_ident(ident)?;
1164 self.word_space(":")?;
1165 self.print_type(ty)?;
1166 if let Some(expr) = default {
1168 self.word_space("=")?;
1169 self.print_expr(expr)?;
1174 fn print_associated_type(&mut self,
1176 bounds: Option<&ast::GenericBounds>,
1177 ty: Option<&ast::Ty>)
1179 self.word_space("type")?;
1180 self.print_ident(ident)?;
1181 if let Some(bounds) = bounds {
1182 self.print_type_bounds(":", bounds)?;
1184 if let Some(ty) = ty {
1186 self.word_space("=")?;
1187 self.print_type(ty)?;
1192 /// Pretty-print an item
1193 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1194 self.hardbreak_if_not_bol()?;
1195 self.maybe_print_comment(item.span.lo())?;
1196 self.print_outer_attributes(&item.attrs)?;
1197 self.ann.pre(self, AnnNode::Item(item))?;
1199 ast::ItemKind::ExternCrate(orig_name) => {
1200 self.head(visibility_qualified(&item.vis, "extern crate"))?;
1201 if let Some(orig_name) = orig_name {
1202 self.print_name(orig_name)?;
1207 self.print_ident(item.ident)?;
1209 self.end()?; // end inner head-block
1210 self.end()?; // end outer head-block
1212 ast::ItemKind::Use(ref tree) => {
1213 self.head(visibility_qualified(&item.vis, "use"))?;
1214 self.print_use_tree(tree)?;
1216 self.end()?; // end inner head-block
1217 self.end()?; // end outer head-block
1219 ast::ItemKind::Static(ref ty, m, ref expr) => {
1220 self.head(visibility_qualified(&item.vis, "static"))?;
1221 if m == ast::Mutability::Mutable {
1222 self.word_space("mut")?;
1224 self.print_ident(item.ident)?;
1225 self.word_space(":")?;
1226 self.print_type(ty)?;
1228 self.end()?; // end the head-ibox
1230 self.word_space("=")?;
1231 self.print_expr(expr)?;
1233 self.end()?; // end the outer cbox
1235 ast::ItemKind::Const(ref ty, ref expr) => {
1236 self.head(visibility_qualified(&item.vis, "const"))?;
1237 self.print_ident(item.ident)?;
1238 self.word_space(":")?;
1239 self.print_type(ty)?;
1241 self.end()?; // end the head-ibox
1243 self.word_space("=")?;
1244 self.print_expr(expr)?;
1246 self.end()?; // end the outer cbox
1248 ast::ItemKind::Fn(ref decl, header, ref typarams, ref body) => {
1258 self.print_block_with_attrs(body, &item.attrs)?;
1260 ast::ItemKind::Mod(ref _mod) => {
1261 self.head(visibility_qualified(&item.vis, "mod"))?;
1262 self.print_ident(item.ident)?;
1264 if _mod.inline || self.is_expanded {
1267 self.print_mod(_mod, &item.attrs)?;
1268 self.bclose(item.span)?;
1271 self.end()?; // end inner head-block
1272 self.end()?; // end outer head-block
1276 ast::ItemKind::ForeignMod(ref nmod) => {
1277 self.head("extern")?;
1278 self.word_nbsp(nmod.abi.to_string())?;
1280 self.print_foreign_mod(nmod, &item.attrs)?;
1281 self.bclose(item.span)?;
1283 ast::ItemKind::GlobalAsm(ref ga) => {
1284 self.head(visibility_qualified(&item.vis, "global_asm!"))?;
1285 self.s.word(ga.asm.as_str().get())?;
1288 ast::ItemKind::Ty(ref ty, ref generics) => {
1289 self.head(visibility_qualified(&item.vis, "type"))?;
1290 self.print_ident(item.ident)?;
1291 self.print_generic_params(&generics.params)?;
1292 self.end()?; // end the inner ibox
1294 self.print_where_clause(&generics.where_clause)?;
1296 self.word_space("=")?;
1297 self.print_type(ty)?;
1299 self.end()?; // end the outer ibox
1301 ast::ItemKind::Existential(ref bounds, ref generics) => {
1302 self.head(visibility_qualified(&item.vis, "existential type"))?;
1303 self.print_ident(item.ident)?;
1304 self.print_generic_params(&generics.params)?;
1305 self.end()?; // end the inner ibox
1307 self.print_where_clause(&generics.where_clause)?;
1309 self.print_type_bounds(":", bounds)?;
1311 self.end()?; // end the outer ibox
1313 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1314 self.print_enum_def(
1322 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1323 self.head(visibility_qualified(&item.vis, "struct"))?;
1324 self.print_struct(struct_def, generics, item.ident, item.span, true)?;
1326 ast::ItemKind::Union(ref struct_def, ref generics) => {
1327 self.head(visibility_qualified(&item.vis, "union"))?;
1328 self.print_struct(struct_def, generics, item.ident, item.span, true)?;
1330 ast::ItemKind::Impl(unsafety,
1336 ref impl_items) => {
1338 self.print_visibility(&item.vis)?;
1339 self.print_defaultness(defaultness)?;
1340 self.print_unsafety(unsafety)?;
1341 self.word_nbsp("impl")?;
1343 if !generics.params.is_empty() {
1344 self.print_generic_params(&generics.params)?;
1348 if polarity == ast::ImplPolarity::Negative {
1352 if let Some(ref t) = *opt_trait {
1353 self.print_trait_ref(t)?;
1355 self.word_space("for")?;
1358 self.print_type(ty)?;
1359 self.print_where_clause(&generics.where_clause)?;
1363 self.print_inner_attributes(&item.attrs)?;
1364 for impl_item in impl_items {
1365 self.print_impl_item(impl_item)?;
1367 self.bclose(item.span)?;
1369 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1371 self.print_visibility(&item.vis)?;
1372 self.print_unsafety(unsafety)?;
1373 self.print_is_auto(is_auto)?;
1374 self.word_nbsp("trait")?;
1375 self.print_ident(item.ident)?;
1376 self.print_generic_params(&generics.params)?;
1377 let mut real_bounds = Vec::with_capacity(bounds.len());
1378 for b in bounds.iter() {
1379 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1381 self.word_space("for ?")?;
1382 self.print_trait_ref(&ptr.trait_ref)?;
1384 real_bounds.push(b.clone());
1387 self.print_type_bounds(":", &real_bounds[..])?;
1388 self.print_where_clause(&generics.where_clause)?;
1391 for trait_item in trait_items {
1392 self.print_trait_item(trait_item)?;
1394 self.bclose(item.span)?;
1396 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1398 self.print_visibility(&item.vis)?;
1399 self.word_nbsp("trait")?;
1400 self.print_ident(item.ident)?;
1401 self.print_generic_params(&generics.params)?;
1402 let mut real_bounds = Vec::with_capacity(bounds.len());
1403 // FIXME(durka) this seems to be some quite outdated syntax
1404 for b in bounds.iter() {
1405 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1407 self.word_space("for ?")?;
1408 self.print_trait_ref(&ptr.trait_ref)?;
1410 real_bounds.push(b.clone());
1414 self.print_type_bounds("=", &real_bounds[..])?;
1415 self.print_where_clause(&generics.where_clause)?;
1418 ast::ItemKind::Mac(ref mac) => {
1419 if item.ident.name == keywords::Invalid.name() {
1420 self.print_mac(mac)?;
1421 match mac.node.delim {
1422 MacDelimiter::Brace => {}
1423 _ => self.s.word(";")?,
1426 self.print_path(&mac.node.path, false, 0)?;
1428 self.print_ident(item.ident)?;
1429 self.cbox(INDENT_UNIT)?;
1431 self.print_tts(mac.node.stream())?;
1437 ast::ItemKind::MacroDef(ref tts) => {
1438 self.s.word("macro_rules! ")?;
1439 self.print_ident(item.ident)?;
1440 self.cbox(INDENT_UNIT)?;
1442 self.print_tts(tts.stream())?;
1448 self.ann.post(self, AnnNode::Item(item))
1451 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1452 self.print_path(&t.path, false, 0)
1455 fn print_formal_generic_params(
1457 generic_params: &[ast::GenericParam]
1458 ) -> io::Result<()> {
1459 if !generic_params.is_empty() {
1460 self.s.word("for")?;
1461 self.print_generic_params(generic_params)?;
1467 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1468 self.print_formal_generic_params(&t.bound_generic_params)?;
1469 self.print_trait_ref(&t.trait_ref)
1472 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1473 generics: &ast::Generics, ident: ast::Ident,
1474 span: syntax_pos::Span,
1475 visibility: &ast::Visibility) -> io::Result<()> {
1476 self.head(visibility_qualified(visibility, "enum"))?;
1477 self.print_ident(ident)?;
1478 self.print_generic_params(&generics.params)?;
1479 self.print_where_clause(&generics.where_clause)?;
1481 self.print_variants(&enum_definition.variants, span)
1484 pub fn print_variants(&mut self,
1485 variants: &[ast::Variant],
1486 span: syntax_pos::Span) -> io::Result<()> {
1489 self.space_if_not_bol()?;
1490 self.maybe_print_comment(v.span.lo())?;
1491 self.print_outer_attributes(&v.node.attrs)?;
1492 self.ibox(INDENT_UNIT)?;
1493 self.print_variant(v)?;
1496 self.maybe_print_trailing_comment(v.span, None)?;
1501 pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1503 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1504 ast::VisibilityKind::Crate(sugar) => match sugar {
1505 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1506 ast::CrateSugar::JustCrate => self.word_nbsp("crate")
1508 ast::VisibilityKind::Restricted { ref path, .. } => {
1509 let path = to_string(|s| s.print_path(path, false, 0));
1510 if path == "self" || path == "super" {
1511 self.word_nbsp(format!("pub({})", path))
1513 self.word_nbsp(format!("pub(in {})", path))
1516 ast::VisibilityKind::Inherited => Ok(())
1520 pub fn print_defaultness(&mut self, defaultness: ast::Defaultness) -> io::Result<()> {
1521 if let ast::Defaultness::Default = defaultness {
1522 self.word_nbsp("default")?;
1527 pub fn print_struct(&mut self,
1528 struct_def: &ast::VariantData,
1529 generics: &ast::Generics,
1531 span: syntax_pos::Span,
1532 print_finalizer: bool) -> io::Result<()> {
1533 self.print_ident(ident)?;
1534 self.print_generic_params(&generics.params)?;
1535 if !struct_def.is_struct() {
1536 if struct_def.is_tuple() {
1539 Inconsistent, struct_def.fields(),
1541 s.maybe_print_comment(field.span.lo())?;
1542 s.print_outer_attributes(&field.attrs)?;
1543 s.print_visibility(&field.vis)?;
1544 s.print_type(&field.ty)
1549 self.print_where_clause(&generics.where_clause)?;
1550 if print_finalizer {
1554 self.end() // close the outer-box
1556 self.print_where_clause(&generics.where_clause)?;
1559 self.hardbreak_if_not_bol()?;
1561 for field in struct_def.fields() {
1562 self.hardbreak_if_not_bol()?;
1563 self.maybe_print_comment(field.span.lo())?;
1564 self.print_outer_attributes(&field.attrs)?;
1565 self.print_visibility(&field.vis)?;
1566 self.print_ident(field.ident.unwrap())?;
1567 self.word_nbsp(":")?;
1568 self.print_type(&field.ty)?;
1576 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1578 let generics = ast::Generics::default();
1579 self.print_struct(&v.node.data, &generics, v.node.ident, v.span, false)?;
1580 match v.node.disr_expr {
1583 self.word_space("=")?;
1584 self.print_expr(&d.value)
1590 pub fn print_method_sig(&mut self,
1592 generics: &ast::Generics,
1594 vis: &ast::Visibility)
1596 self.print_fn(&m.decl,
1603 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1605 self.ann.pre(self, AnnNode::SubItem(ti.id))?;
1606 self.hardbreak_if_not_bol()?;
1607 self.maybe_print_comment(ti.span.lo())?;
1608 self.print_outer_attributes(&ti.attrs)?;
1610 ast::TraitItemKind::Const(ref ty, ref default) => {
1611 self.print_associated_const(
1614 default.as_ref().map(|expr| &**expr),
1615 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1618 ast::TraitItemKind::Method(ref sig, ref body) => {
1622 self.print_method_sig(
1626 &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1628 if let Some(ref body) = *body {
1630 self.print_block_with_attrs(body, &ti.attrs)?;
1635 ast::TraitItemKind::Type(ref bounds, ref default) => {
1636 self.print_associated_type(ti.ident, Some(bounds),
1637 default.as_ref().map(|ty| &**ty))?;
1639 ast::TraitItemKind::Macro(ref mac) => {
1640 self.print_mac(mac)?;
1641 match mac.node.delim {
1642 MacDelimiter::Brace => {}
1643 _ => self.s.word(";")?,
1647 self.ann.post(self, AnnNode::SubItem(ti.id))
1650 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1651 self.ann.pre(self, AnnNode::SubItem(ii.id))?;
1652 self.hardbreak_if_not_bol()?;
1653 self.maybe_print_comment(ii.span.lo())?;
1654 self.print_outer_attributes(&ii.attrs)?;
1655 self.print_defaultness(ii.defaultness)?;
1657 ast::ImplItemKind::Const(ref ty, ref expr) => {
1658 self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis)?;
1660 ast::ImplItemKind::Method(ref sig, ref body) => {
1662 self.print_method_sig(ii.ident, &ii.generics, sig, &ii.vis)?;
1664 self.print_block_with_attrs(body, &ii.attrs)?;
1666 ast::ImplItemKind::Type(ref ty) => {
1667 self.print_associated_type(ii.ident, None, Some(ty))?;
1669 ast::ImplItemKind::Existential(ref bounds) => {
1670 self.word_space("existential")?;
1671 self.print_associated_type(ii.ident, Some(bounds), None)?;
1673 ast::ImplItemKind::Macro(ref mac) => {
1674 self.print_mac(mac)?;
1675 match mac.node.delim {
1676 MacDelimiter::Brace => {}
1677 _ => self.s.word(";")?,
1681 self.ann.post(self, AnnNode::SubItem(ii.id))
1684 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1685 self.maybe_print_comment(st.span.lo())?;
1687 ast::StmtKind::Local(ref loc) => {
1688 self.print_outer_attributes(&loc.attrs)?;
1689 self.space_if_not_bol()?;
1690 self.ibox(INDENT_UNIT)?;
1691 self.word_nbsp("let")?;
1693 self.ibox(INDENT_UNIT)?;
1694 self.print_local_decl(loc)?;
1696 if let Some(ref init) = loc.init {
1698 self.word_space("=")?;
1699 self.print_expr(init)?;
1704 ast::StmtKind::Item(ref item) => self.print_item(item)?,
1705 ast::StmtKind::Expr(ref expr) => {
1706 self.space_if_not_bol()?;
1707 self.print_expr_outer_attr_style(expr, false)?;
1708 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1712 ast::StmtKind::Semi(ref expr) => {
1713 self.space_if_not_bol()?;
1714 self.print_expr_outer_attr_style(expr, false)?;
1717 ast::StmtKind::Mac(ref mac) => {
1718 let (ref mac, style, ref attrs) = **mac;
1719 self.space_if_not_bol()?;
1720 self.print_outer_attributes(attrs)?;
1721 self.print_mac(mac)?;
1722 if style == ast::MacStmtStyle::Semicolon {
1727 self.maybe_print_trailing_comment(st.span, None)
1730 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1731 self.print_block_with_attrs(blk, &[])
1734 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1735 self.print_block_unclosed_indent(blk, INDENT_UNIT)
1738 pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1739 attrs: &[ast::Attribute])
1741 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1744 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1745 indented: usize) -> io::Result<()> {
1746 self.print_block_maybe_unclosed(blk, indented, &[], false)
1749 pub fn print_block_with_attrs(&mut self,
1751 attrs: &[ast::Attribute]) -> io::Result<()> {
1752 self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1755 pub fn print_block_maybe_unclosed(&mut self,
1758 attrs: &[ast::Attribute],
1759 close_box: bool) -> io::Result<()> {
1761 BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
1762 BlockCheckMode::Default => ()
1764 self.maybe_print_comment(blk.span.lo())?;
1765 self.ann.pre(self, AnnNode::Block(blk))?;
1768 self.print_inner_attributes(attrs)?;
1770 for (i, st) in blk.stmts.iter().enumerate() {
1772 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1773 self.maybe_print_comment(st.span.lo())?;
1774 self.space_if_not_bol()?;
1775 self.print_expr_outer_attr_style(expr, false)?;
1776 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1778 _ => self.print_stmt(st)?,
1782 self.bclose_maybe_open(blk.span, indented, close_box)?;
1783 self.ann.post(self, AnnNode::Block(blk))
1786 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1790 // "another else-if"
1791 ast::ExprKind::If(ref i, ref then, ref e) => {
1792 self.cbox(INDENT_UNIT - 1)?;
1794 self.s.word(" else if ")?;
1795 self.print_expr_as_cond(i)?;
1797 self.print_block(then)?;
1798 self.print_else(e.as_ref().map(|e| &**e))
1800 // "another else-if-let"
1801 ast::ExprKind::IfLet(ref pats, ref expr, ref then, ref e) => {
1802 self.cbox(INDENT_UNIT - 1)?;
1804 self.s.word(" else if let ")?;
1805 self.print_pats(pats)?;
1807 self.word_space("=")?;
1808 self.print_expr_as_cond(expr)?;
1810 self.print_block(then)?;
1811 self.print_else(e.as_ref().map(|e| &**e))
1814 ast::ExprKind::Block(ref b, _) => {
1815 self.cbox(INDENT_UNIT - 1)?;
1817 self.s.word(" else ")?;
1820 // BLEAH, constraints would be great here
1822 panic!("print_if saw if with weird alternative");
1830 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1831 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1833 self.print_expr_as_cond(test)?;
1835 self.print_block(blk)?;
1836 self.print_else(elseopt)
1839 pub fn print_if_let(&mut self, pats: &[P<ast::Pat>], expr: &ast::Expr, blk: &ast::Block,
1840 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1841 self.head("if let")?;
1842 self.print_pats(pats)?;
1844 self.word_space("=")?;
1845 self.print_expr_as_cond(expr)?;
1847 self.print_block(blk)?;
1848 self.print_else(elseopt)
1851 pub fn print_mac(&mut self, m: &ast::Mac) -> io::Result<()> {
1852 self.print_path(&m.node.path, false, 0)?;
1854 match m.node.delim {
1855 MacDelimiter::Parenthesis => self.popen()?,
1856 MacDelimiter::Bracket => self.s.word("[")?,
1857 MacDelimiter::Brace => {
1862 self.print_tts(m.node.stream())?;
1863 match m.node.delim {
1864 MacDelimiter::Parenthesis => self.pclose(),
1865 MacDelimiter::Bracket => self.s.word("]"),
1866 MacDelimiter::Brace => self.bclose(m.span),
1871 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1873 self.commasep_exprs(Inconsistent, args)?;
1877 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) -> io::Result<()> {
1878 let needs_par = expr.precedence().order() < prec;
1882 self.print_expr(expr)?;
1889 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1890 /// `if cond { ... }`.
1891 pub fn print_expr_as_cond(&mut self, expr: &ast::Expr) -> io::Result<()> {
1892 let needs_par = match expr.node {
1893 // These cases need parens due to the parse error observed in #26461: `if return {}`
1894 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1895 ast::ExprKind::Closure(..) |
1896 ast::ExprKind::Ret(..) |
1897 ast::ExprKind::Break(..) => true,
1899 _ => parser::contains_exterior_struct_lit(expr),
1905 self.print_expr(expr)?;
1912 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1913 attrs: &[Attribute]) -> io::Result<()> {
1914 self.ibox(INDENT_UNIT)?;
1916 self.print_inner_attributes_inline(attrs)?;
1917 self.commasep_exprs(Inconsistent, &exprs[..])?;
1922 fn print_expr_repeat(&mut self,
1923 element: &ast::Expr,
1924 count: &ast::AnonConst,
1925 attrs: &[Attribute]) -> io::Result<()> {
1926 self.ibox(INDENT_UNIT)?;
1928 self.print_inner_attributes_inline(attrs)?;
1929 self.print_expr(element)?;
1930 self.word_space(";")?;
1931 self.print_expr(&count.value)?;
1936 fn print_expr_struct(&mut self,
1938 fields: &[ast::Field],
1939 wth: &Option<P<ast::Expr>>,
1940 attrs: &[Attribute]) -> io::Result<()> {
1941 self.print_path(path, true, 0)?;
1943 self.print_inner_attributes_inline(attrs)?;
1948 s.ibox(INDENT_UNIT)?;
1949 if !field.is_shorthand {
1950 s.print_ident(field.ident)?;
1953 s.print_expr(&field.expr)?;
1959 self.ibox(INDENT_UNIT)?;
1960 if !fields.is_empty() {
1965 self.print_expr(expr)?;
1968 _ => if !fields.is_empty() {
1976 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1977 attrs: &[Attribute]) -> io::Result<()> {
1979 self.print_inner_attributes_inline(attrs)?;
1980 self.commasep_exprs(Inconsistent, &exprs[..])?;
1981 if exprs.len() == 1 {
1987 fn print_expr_call(&mut self,
1989 args: &[P<ast::Expr>]) -> io::Result<()> {
1992 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1993 _ => parser::PREC_POSTFIX,
1996 self.print_expr_maybe_paren(func, prec)?;
1997 self.print_call_post(args)
2000 fn print_expr_method_call(&mut self,
2001 segment: &ast::PathSegment,
2002 args: &[P<ast::Expr>]) -> io::Result<()> {
2003 let base_args = &args[1..];
2004 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
2006 self.print_ident(segment.ident)?;
2007 if let Some(ref args) = segment.args {
2008 self.print_generic_args(args, true)?;
2010 self.print_call_post(base_args)
2013 fn print_expr_binary(&mut self,
2016 rhs: &ast::Expr) -> io::Result<()> {
2017 let assoc_op = AssocOp::from_ast_binop(op.node);
2018 let prec = assoc_op.precedence() as i8;
2019 let fixity = assoc_op.fixity();
2021 let (left_prec, right_prec) = match fixity {
2022 Fixity::Left => (prec, prec + 1),
2023 Fixity::Right => (prec + 1, prec),
2024 Fixity::None => (prec + 1, prec + 1),
2027 let left_prec = match (&lhs.node, op.node) {
2028 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
2029 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
2030 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
2031 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) |
2032 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
2036 self.print_expr_maybe_paren(lhs, left_prec)?;
2038 self.word_space(op.node.to_string())?;
2039 self.print_expr_maybe_paren(rhs, right_prec)
2042 fn print_expr_unary(&mut self,
2044 expr: &ast::Expr) -> io::Result<()> {
2045 self.s.word(ast::UnOp::to_string(op))?;
2046 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
2049 fn print_expr_addr_of(&mut self,
2050 mutability: ast::Mutability,
2051 expr: &ast::Expr) -> io::Result<()> {
2053 self.print_mutability(mutability)?;
2054 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
2057 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
2058 self.print_expr_outer_attr_style(expr, true)
2061 fn print_expr_outer_attr_style(&mut self,
2063 is_inline: bool) -> io::Result<()> {
2064 self.maybe_print_comment(expr.span.lo())?;
2066 let attrs = &expr.attrs;
2068 self.print_outer_attributes_inline(attrs)?;
2070 self.print_outer_attributes(attrs)?;
2073 self.ibox(INDENT_UNIT)?;
2074 self.ann.pre(self, AnnNode::Expr(expr))?;
2076 ast::ExprKind::Box(ref expr) => {
2077 self.word_space("box")?;
2078 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
2080 ast::ExprKind::ObsoleteInPlace(ref place, ref expr) => {
2081 let prec = AssocOp::ObsoleteInPlace.precedence() as i8;
2082 self.print_expr_maybe_paren(place, prec + 1)?;
2084 self.word_space("<-")?;
2085 self.print_expr_maybe_paren(expr, prec)?;
2087 ast::ExprKind::Array(ref exprs) => {
2088 self.print_expr_vec(&exprs[..], attrs)?;
2090 ast::ExprKind::Repeat(ref element, ref count) => {
2091 self.print_expr_repeat(element, count, attrs)?;
2093 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2094 self.print_expr_struct(path, &fields[..], wth, attrs)?;
2096 ast::ExprKind::Tup(ref exprs) => {
2097 self.print_expr_tup(&exprs[..], attrs)?;
2099 ast::ExprKind::Call(ref func, ref args) => {
2100 self.print_expr_call(func, &args[..])?;
2102 ast::ExprKind::MethodCall(ref segment, ref args) => {
2103 self.print_expr_method_call(segment, &args[..])?;
2105 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2106 self.print_expr_binary(op, lhs, rhs)?;
2108 ast::ExprKind::Unary(op, ref expr) => {
2109 self.print_expr_unary(op, expr)?;
2111 ast::ExprKind::AddrOf(m, ref expr) => {
2112 self.print_expr_addr_of(m, expr)?;
2114 ast::ExprKind::Lit(ref lit) => {
2115 self.print_literal(lit)?;
2117 ast::ExprKind::Cast(ref expr, ref ty) => {
2118 let prec = AssocOp::As.precedence() as i8;
2119 self.print_expr_maybe_paren(expr, prec)?;
2121 self.word_space("as")?;
2122 self.print_type(ty)?;
2124 ast::ExprKind::Type(ref expr, ref ty) => {
2125 let prec = AssocOp::Colon.precedence() as i8;
2126 self.print_expr_maybe_paren(expr, prec)?;
2127 self.word_space(":")?;
2128 self.print_type(ty)?;
2130 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2131 self.print_if(test, blk, elseopt.as_ref().map(|e| &**e))?;
2133 ast::ExprKind::IfLet(ref pats, ref expr, ref blk, ref elseopt) => {
2134 self.print_if_let(pats, expr, blk, elseopt.as_ref().map(|e| &**e))?;
2136 ast::ExprKind::While(ref test, ref blk, opt_label) => {
2137 if let Some(label) = opt_label {
2138 self.print_ident(label.ident)?;
2139 self.word_space(":")?;
2141 self.head("while")?;
2142 self.print_expr_as_cond(test)?;
2144 self.print_block_with_attrs(blk, attrs)?;
2146 ast::ExprKind::WhileLet(ref pats, ref expr, ref blk, opt_label) => {
2147 if let Some(label) = opt_label {
2148 self.print_ident(label.ident)?;
2149 self.word_space(":")?;
2151 self.head("while let")?;
2152 self.print_pats(pats)?;
2154 self.word_space("=")?;
2155 self.print_expr_as_cond(expr)?;
2157 self.print_block_with_attrs(blk, attrs)?;
2159 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2160 if let Some(label) = opt_label {
2161 self.print_ident(label.ident)?;
2162 self.word_space(":")?;
2165 self.print_pat(pat)?;
2167 self.word_space("in")?;
2168 self.print_expr_as_cond(iter)?;
2170 self.print_block_with_attrs(blk, attrs)?;
2172 ast::ExprKind::Loop(ref blk, opt_label) => {
2173 if let Some(label) = opt_label {
2174 self.print_ident(label.ident)?;
2175 self.word_space(":")?;
2179 self.print_block_with_attrs(blk, attrs)?;
2181 ast::ExprKind::Match(ref expr, ref arms) => {
2182 self.cbox(INDENT_UNIT)?;
2184 self.word_nbsp("match")?;
2185 self.print_expr_as_cond(expr)?;
2188 self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
2190 self.print_arm(arm)?;
2192 self.bclose_(expr.span, INDENT_UNIT)?;
2194 ast::ExprKind::Closure(
2195 capture_clause, asyncness, movability, ref decl, ref body, _) => {
2196 self.print_movability(movability)?;
2197 self.print_asyncness(asyncness)?;
2198 self.print_capture_clause(capture_clause)?;
2200 self.print_fn_block_args(decl)?;
2202 self.print_expr(body)?;
2203 self.end()?; // need to close a box
2205 // a box will be closed by print_expr, but we didn't want an overall
2206 // wrapper so we closed the corresponding opening. so create an
2207 // empty box to satisfy the close.
2210 ast::ExprKind::Block(ref blk, opt_label) => {
2211 if let Some(label) = opt_label {
2212 self.print_ident(label.ident)?;
2213 self.word_space(":")?;
2215 // containing cbox, will be closed by print-block at }
2216 self.cbox(INDENT_UNIT)?;
2217 // head-box, will be closed by print-block after {
2219 self.print_block_with_attrs(blk, attrs)?;
2221 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2222 self.word_nbsp("async")?;
2223 self.print_capture_clause(capture_clause)?;
2225 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2226 self.cbox(INDENT_UNIT)?;
2228 self.print_block_with_attrs(blk, attrs)?;
2230 ast::ExprKind::Assign(ref lhs, ref rhs) => {
2231 let prec = AssocOp::Assign.precedence() as i8;
2232 self.print_expr_maybe_paren(lhs, prec + 1)?;
2234 self.word_space("=")?;
2235 self.print_expr_maybe_paren(rhs, prec)?;
2237 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2238 let prec = AssocOp::Assign.precedence() as i8;
2239 self.print_expr_maybe_paren(lhs, prec + 1)?;
2241 self.s.word(op.node.to_string())?;
2242 self.word_space("=")?;
2243 self.print_expr_maybe_paren(rhs, prec)?;
2245 ast::ExprKind::Field(ref expr, ident) => {
2246 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
2248 self.print_ident(ident)?;
2250 ast::ExprKind::Index(ref expr, ref index) => {
2251 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
2253 self.print_expr(index)?;
2256 ast::ExprKind::Range(ref start, ref end, limits) => {
2257 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2258 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2259 // Here we use a fake precedence value so that any child with lower precedence than
2260 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2261 let fake_prec = AssocOp::LOr.precedence() as i8;
2262 if let Some(ref e) = *start {
2263 self.print_expr_maybe_paren(e, fake_prec)?;
2265 if limits == ast::RangeLimits::HalfOpen {
2268 self.s.word("..=")?;
2270 if let Some(ref e) = *end {
2271 self.print_expr_maybe_paren(e, fake_prec)?;
2274 ast::ExprKind::Path(None, ref path) => {
2275 self.print_path(path, true, 0)?
2277 ast::ExprKind::Path(Some(ref qself), ref path) => {
2278 self.print_qpath(path, qself, true)?
2280 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2281 self.s.word("break")?;
2283 if let Some(label) = opt_label {
2284 self.print_ident(label.ident)?;
2287 if let Some(ref expr) = *opt_expr {
2288 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2292 ast::ExprKind::Continue(opt_label) => {
2293 self.s.word("continue")?;
2295 if let Some(label) = opt_label {
2296 self.print_ident(label.ident)?;
2300 ast::ExprKind::Ret(ref result) => {
2301 self.s.word("return")?;
2302 if let Some(ref expr) = *result {
2304 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2307 ast::ExprKind::InlineAsm(ref a) => {
2308 self.s.word("asm!")?;
2310 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
2311 self.word_space(":")?;
2313 self.commasep(Inconsistent, &a.outputs, |s, out| {
2314 let constraint = out.constraint.as_str();
2315 let mut ch = constraint.chars();
2317 Some('=') if out.is_rw => {
2318 s.print_string(&format!("+{}", ch.as_str()),
2319 ast::StrStyle::Cooked)?
2321 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?
2324 s.print_expr(&out.expr)?;
2329 self.word_space(":")?;
2331 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2332 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2339 self.word_space(":")?;
2341 self.commasep(Inconsistent, &a.clobbers,
2343 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2347 let mut options = vec![];
2349 options.push("volatile");
2352 options.push("alignstack");
2354 if a.dialect == ast::AsmDialect::Intel {
2355 options.push("intel");
2358 if !options.is_empty() {
2360 self.word_space(":")?;
2361 self.commasep(Inconsistent, &options,
2363 s.print_string(co, ast::StrStyle::Cooked)?;
2370 ast::ExprKind::Mac(ref m) => self.print_mac(m)?,
2371 ast::ExprKind::Paren(ref e) => {
2373 self.print_inner_attributes_inline(attrs)?;
2374 self.print_expr(e)?;
2377 ast::ExprKind::Yield(ref e) => {
2378 self.s.word("yield")?;
2382 self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2387 ast::ExprKind::Try(ref e) => {
2388 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX)?;
2391 ast::ExprKind::TryBlock(ref blk) => {
2394 self.print_block_with_attrs(blk, attrs)?
2396 ast::ExprKind::Err => {
2398 self.s.word("/*ERROR*/")?;
2402 self.ann.post(self, AnnNode::Expr(expr))?;
2406 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2407 self.print_pat(&loc.pat)?;
2408 if let Some(ref ty) = loc.ty {
2409 self.word_space(":")?;
2410 self.print_type(ty)?;
2415 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2416 if ident.is_raw_guess() {
2417 self.s.word(format!("r#{}", ident))?;
2419 self.s.word(ident.as_str().get())?;
2421 self.ann.post(self, AnnNode::Ident(&ident))
2424 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2425 self.s.word(i.to_string())
2428 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2429 self.s.word(name.as_str().get())?;
2430 self.ann.post(self, AnnNode::Name(&name))
2433 pub fn print_for_decl(&mut self, loc: &ast::Local,
2434 coll: &ast::Expr) -> io::Result<()> {
2435 self.print_local_decl(loc)?;
2437 self.word_space("in")?;
2438 self.print_expr(coll)
2441 fn print_path(&mut self,
2443 colons_before_params: bool,
2447 self.maybe_print_comment(path.span.lo())?;
2449 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
2453 self.print_path_segment(segment, colons_before_params)?;
2459 fn print_path_segment(&mut self,
2460 segment: &ast::PathSegment,
2461 colons_before_params: bool)
2464 if segment.ident.name != keywords::PathRoot.name() {
2465 if segment.ident.name == keywords::DollarCrate.name() {
2466 self.print_dollar_crate(segment.ident)?;
2468 self.print_ident(segment.ident)?;
2470 if let Some(ref args) = segment.args {
2471 self.print_generic_args(args, colons_before_params)?;
2477 fn print_qpath(&mut self,
2480 colons_before_params: bool)
2484 self.print_type(&qself.ty)?;
2485 if qself.position > 0 {
2487 self.word_space("as")?;
2488 let depth = path.segments.len() - qself.position;
2489 self.print_path(path, false, depth)?;
2493 let item_segment = path.segments.last().unwrap();
2494 self.print_ident(item_segment.ident)?;
2495 match item_segment.args {
2496 Some(ref args) => self.print_generic_args(args, colons_before_params),
2501 fn print_generic_args(&mut self,
2502 args: &ast::GenericArgs,
2503 colons_before_params: bool)
2506 if colons_before_params {
2511 ast::GenericArgs::AngleBracketed(ref data) => {
2514 self.commasep(Inconsistent, &data.args, |s, generic_arg| {
2515 s.print_generic_arg(generic_arg)
2518 let mut comma = data.args.len() != 0;
2520 for binding in data.bindings.iter() {
2522 self.word_space(",")?
2524 self.print_ident(binding.ident)?;
2526 self.word_space("=")?;
2527 self.print_type(&binding.ty)?;
2534 ast::GenericArgs::Parenthesized(ref data) => {
2539 |s, ty| s.print_type(ty))?;
2542 if let Some(ref ty) = data.output {
2543 self.space_if_not_bol()?;
2544 self.word_space("->")?;
2545 self.print_type(ty)?;
2553 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2554 self.maybe_print_comment(pat.span.lo())?;
2555 self.ann.pre(self, AnnNode::Pat(pat))?;
2556 /* Pat isn't normalized, but the beauty of it
2557 is that it doesn't matter */
2559 PatKind::Wild => self.s.word("_")?,
2560 PatKind::Ident(binding_mode, ident, ref sub) => {
2561 match binding_mode {
2562 ast::BindingMode::ByRef(mutbl) => {
2563 self.word_nbsp("ref")?;
2564 self.print_mutability(mutbl)?;
2566 ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2567 ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2568 self.word_nbsp("mut")?;
2571 self.print_ident(ident)?;
2572 if let Some(ref p) = *sub {
2577 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2578 self.print_path(path, true, 0)?;
2580 if let Some(ddpos) = ddpos {
2581 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
2583 self.word_space(",")?;
2586 if ddpos != elts.len() {
2588 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
2591 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
2595 PatKind::Path(None, ref path) => {
2596 self.print_path(path, true, 0)?;
2598 PatKind::Path(Some(ref qself), ref path) => {
2599 self.print_qpath(path, qself, false)?;
2601 PatKind::Struct(ref path, ref fields, etc) => {
2602 self.print_path(path, true, 0)?;
2604 self.word_space("{")?;
2606 Consistent, &fields[..],
2608 s.cbox(INDENT_UNIT)?;
2609 if !f.node.is_shorthand {
2610 s.print_ident(f.node.ident)?;
2613 s.print_pat(&f.node.pat)?;
2616 |f| f.node.pat.span)?;
2618 if !fields.is_empty() { self.word_space(",")?; }
2624 PatKind::Tuple(ref elts, ddpos) => {
2626 if let Some(ddpos) = ddpos {
2627 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
2629 self.word_space(",")?;
2632 if ddpos != elts.len() {
2634 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
2637 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
2638 if elts.len() == 1 {
2644 PatKind::Box(ref inner) => {
2645 self.s.word("box ")?;
2646 self.print_pat(inner)?;
2648 PatKind::Ref(ref inner, mutbl) => {
2650 if mutbl == ast::Mutability::Mutable {
2651 self.s.word("mut ")?;
2653 self.print_pat(inner)?;
2655 PatKind::Lit(ref e) => self.print_expr(&**e)?,
2656 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2657 self.print_expr(begin)?;
2660 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("...")?,
2661 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..=")?,
2662 RangeEnd::Excluded => self.s.word("..")?,
2664 self.print_expr(end)?;
2666 PatKind::Slice(ref before, ref slice, ref after) => {
2668 self.commasep(Inconsistent,
2670 |s, p| s.print_pat(p))?;
2671 if let Some(ref p) = *slice {
2672 if !before.is_empty() { self.word_space(",")?; }
2673 if let PatKind::Wild = p.node {
2679 if !after.is_empty() { self.word_space(",")?; }
2681 self.commasep(Inconsistent,
2683 |s, p| s.print_pat(p))?;
2686 PatKind::Paren(ref inner) => {
2688 self.print_pat(inner)?;
2691 PatKind::Mac(ref m) => self.print_mac(m)?,
2693 self.ann.post(self, AnnNode::Pat(pat))
2696 fn print_pats(&mut self, pats: &[P<ast::Pat>]) -> io::Result<()> {
2697 let mut first = true;
2703 self.word_space("|")?;
2710 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2711 // I have no idea why this check is necessary, but here it
2713 if arm.attrs.is_empty() {
2716 self.cbox(INDENT_UNIT)?;
2718 self.maybe_print_comment(arm.pats[0].span.lo())?;
2719 self.print_outer_attributes(&arm.attrs)?;
2720 self.print_pats(&arm.pats)?;
2722 if let Some(ref g) = arm.guard {
2724 ast::Guard::If(ref e) => {
2725 self.word_space("if")?;
2726 self.print_expr(e)?;
2731 self.word_space("=>")?;
2733 match arm.body.node {
2734 ast::ExprKind::Block(ref blk, opt_label) => {
2735 if let Some(label) = opt_label {
2736 self.print_ident(label.ident)?;
2737 self.word_space(":")?;
2740 // the block will close the pattern's ibox
2741 self.print_block_unclosed_indent(blk, INDENT_UNIT)?;
2743 // If it is a user-provided unsafe block, print a comma after it
2744 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2749 self.end()?; // close the ibox for the pattern
2750 self.print_expr(&arm.body)?;
2754 self.end() // close enclosing cbox
2757 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2758 match explicit_self.node {
2759 SelfKind::Value(m) => {
2760 self.print_mutability(m)?;
2763 SelfKind::Region(ref lt, m) => {
2765 self.print_opt_lifetime(lt)?;
2766 self.print_mutability(m)?;
2769 SelfKind::Explicit(ref typ, m) => {
2770 self.print_mutability(m)?;
2771 self.s.word("self")?;
2772 self.word_space(":")?;
2773 self.print_type(typ)
2778 pub fn print_fn(&mut self,
2780 header: ast::FnHeader,
2781 name: Option<ast::Ident>,
2782 generics: &ast::Generics,
2783 vis: &ast::Visibility) -> io::Result<()> {
2784 self.print_fn_header_info(header, vis)?;
2786 if let Some(name) = name {
2788 self.print_ident(name)?;
2790 self.print_generic_params(&generics.params)?;
2791 self.print_fn_args_and_ret(decl)?;
2792 self.print_where_clause(&generics.where_clause)
2795 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2798 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
2800 self.s.word(", ...")?;
2804 self.print_fn_output(decl)
2807 pub fn print_fn_block_args(
2812 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
2815 if let ast::FunctionRetTy::Default(..) = decl.output {
2819 self.space_if_not_bol()?;
2820 self.word_space("->")?;
2822 ast::FunctionRetTy::Ty(ref ty) => {
2823 self.print_type(ty)?;
2824 self.maybe_print_comment(ty.span.lo())
2826 ast::FunctionRetTy::Default(..) => unreachable!(),
2830 pub fn print_movability(&mut self, movability: ast::Movability)
2833 ast::Movability::Static => self.word_space("static"),
2834 ast::Movability::Movable => Ok(()),
2838 pub fn print_asyncness(&mut self, asyncness: ast::IsAsync)
2840 if asyncness.is_async() {
2841 self.word_nbsp("async")?;
2846 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2848 match capture_clause {
2849 ast::CaptureBy::Value => self.word_space("move"),
2850 ast::CaptureBy::Ref => Ok(()),
2854 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound])
2856 if !bounds.is_empty() {
2857 self.s.word(prefix)?;
2858 let mut first = true;
2859 for bound in bounds {
2860 if !(first && prefix.is_empty()) {
2866 self.word_space("+")?;
2870 GenericBound::Trait(tref, modifier) => {
2871 if modifier == &TraitBoundModifier::Maybe {
2874 self.print_poly_trait_ref(tref)?;
2876 GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
2883 pub fn print_lifetime(&mut self, lifetime: ast::Lifetime) -> io::Result<()> {
2884 self.print_name(lifetime.ident.name)
2887 pub fn print_lifetime_bounds(&mut self, lifetime: ast::Lifetime, bounds: &ast::GenericBounds)
2890 self.print_lifetime(lifetime)?;
2891 if !bounds.is_empty() {
2893 for (i, bound) in bounds.iter().enumerate() {
2895 self.s.word(" + ")?;
2898 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
2906 pub fn print_generic_params(
2908 generic_params: &[ast::GenericParam]
2909 ) -> io::Result<()> {
2910 if generic_params.is_empty() {
2916 self.commasep(Inconsistent, &generic_params, |s, param| {
2918 ast::GenericParamKind::Lifetime => {
2919 s.print_outer_attributes_inline(¶m.attrs)?;
2920 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2921 s.print_lifetime_bounds(lt, ¶m.bounds)
2923 ast::GenericParamKind::Type { ref default } => {
2924 s.print_outer_attributes_inline(¶m.attrs)?;
2925 s.print_ident(param.ident)?;
2926 s.print_type_bounds(":", ¶m.bounds)?;
2928 Some(ref default) => {
2931 s.print_type(default)
2943 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2945 if where_clause.predicates.is_empty() {
2950 self.word_space("where")?;
2952 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2954 self.word_space(",")?;
2958 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2959 ref bound_generic_params,
2964 self.print_formal_generic_params(bound_generic_params)?;
2965 self.print_type(bounded_ty)?;
2966 self.print_type_bounds(":", bounds)?;
2968 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2971 self.print_lifetime_bounds(*lifetime, bounds)?;
2973 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2976 self.print_type(lhs_ty)?;
2978 self.word_space("=")?;
2979 self.print_type(rhs_ty)?;
2987 pub fn print_use_tree(&mut self, tree: &ast::UseTree) -> io::Result<()> {
2989 ast::UseTreeKind::Simple(rename, ..) => {
2990 self.print_path(&tree.prefix, false, 0)?;
2991 if let Some(rename) = rename {
2993 self.word_space("as")?;
2994 self.print_ident(rename)?;
2997 ast::UseTreeKind::Glob => {
2998 if !tree.prefix.segments.is_empty() {
2999 self.print_path(&tree.prefix, false, 0)?;
3004 ast::UseTreeKind::Nested(ref items) => {
3005 if tree.prefix.segments.is_empty() {
3008 self.print_path(&tree.prefix, false, 0)?;
3009 self.s.word("::{")?;
3011 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
3012 this.print_use_tree(tree)
3021 pub fn print_mutability(&mut self,
3022 mutbl: ast::Mutability) -> io::Result<()> {
3024 ast::Mutability::Mutable => self.word_nbsp("mut"),
3025 ast::Mutability::Immutable => Ok(()),
3029 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
3030 self.print_mutability(mt.mutbl)?;
3031 self.print_type(&mt.ty)
3034 pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
3035 self.ibox(INDENT_UNIT)?;
3036 match input.ty.node {
3037 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat)?,
3039 if let Some(eself) = input.to_self() {
3040 self.print_explicit_self(&eself)?;
3042 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
3043 ident.name == keywords::Invalid.name()
3048 self.print_pat(&input.pat)?;
3052 self.print_type(&input.ty)?;
3059 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
3060 if let ast::FunctionRetTy::Default(..) = decl.output {
3064 self.space_if_not_bol()?;
3065 self.ibox(INDENT_UNIT)?;
3066 self.word_space("->")?;
3068 ast::FunctionRetTy::Default(..) => unreachable!(),
3069 ast::FunctionRetTy::Ty(ref ty) =>
3070 self.print_type(ty)?
3075 ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo()),
3080 pub fn print_ty_fn(&mut self,
3082 unsafety: ast::Unsafety,
3084 name: Option<ast::Ident>,
3085 generic_params: &[ast::GenericParam])
3087 self.ibox(INDENT_UNIT)?;
3088 if !generic_params.is_empty() {
3089 self.s.word("for")?;
3090 self.print_generic_params(generic_params)?;
3092 let generics = ast::Generics {
3094 where_clause: ast::WhereClause {
3095 id: ast::DUMMY_NODE_ID,
3096 predicates: Vec::new(),
3097 span: syntax_pos::DUMMY_SP,
3099 span: syntax_pos::DUMMY_SP,
3102 ast::FnHeader { unsafety, abi, ..ast::FnHeader::default() },
3105 &source_map::dummy_spanned(ast::VisibilityKind::Inherited))?;
3109 pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
3110 next_pos: Option<BytePos>)
3112 let cm = match self.cm {
3116 if let Some(ref cmnt) = self.next_comment() {
3117 if cmnt.style != comments::Trailing { return Ok(()) }
3118 let span_line = cm.lookup_char_pos(span.hi());
3119 let comment_line = cm.lookup_char_pos(cmnt.pos);
3120 let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1));
3121 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
3122 self.print_comment(cmnt)?;
3128 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3129 // If there aren't any remaining comments, then we need to manually
3130 // make sure there is a line break at the end.
3131 if self.next_comment().is_none() {
3132 self.s.hardbreak()?;
3134 while let Some(ref cmnt) = self.next_comment() {
3135 self.print_comment(cmnt)?;
3140 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3141 opt_abi: Option<Abi>)
3144 Some(Abi::Rust) => Ok(()),
3146 self.word_nbsp("extern")?;
3147 self.word_nbsp(abi.to_string())
3153 pub fn print_extern_opt_abi(&mut self,
3154 opt_abi: Option<Abi>) -> io::Result<()> {
3157 self.word_nbsp("extern")?;
3158 self.word_nbsp(abi.to_string())
3164 pub fn print_fn_header_info(&mut self,
3165 header: ast::FnHeader,
3166 vis: &ast::Visibility) -> io::Result<()> {
3167 self.s.word(visibility_qualified(vis, ""))?;
3169 match header.constness.node {
3170 ast::Constness::NotConst => {}
3171 ast::Constness::Const => self.word_nbsp("const")?
3174 self.print_asyncness(header.asyncness)?;
3175 self.print_unsafety(header.unsafety)?;
3177 if header.abi != Abi::Rust {
3178 self.word_nbsp("extern")?;
3179 self.word_nbsp(header.abi.to_string())?;
3185 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3187 ast::Unsafety::Normal => Ok(()),
3188 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3192 pub fn print_is_auto(&mut self, s: ast::IsAuto) -> io::Result<()> {
3194 ast::IsAuto::Yes => self.word_nbsp("auto"),
3195 ast::IsAuto::No => Ok(()),
3210 fn test_fun_to_string() {
3212 let abba_ident = ast::Ident::from_str("abba");
3214 let decl = ast::FnDecl {
3216 output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
3219 let generics = ast::Generics::default();
3224 unsafety: ast::Unsafety::Normal,
3225 constness: source_map::dummy_spanned(ast::Constness::NotConst),
3226 asyncness: ast::IsAsync::NotAsync,
3238 fn test_variant_to_string() {
3240 let ident = ast::Ident::from_str("principal_skinner");
3242 let var = source_map::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
3245 // making this up as I go.... ?
3246 data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3250 let varstr = variant_to_string(&var);
3251 assert_eq!(varstr, "principal_skinner");