]> git.proxmox.com Git - rustc.git/blob - src/libsyntax/print/pprust.rs
Imported Upstream version 1.1.0+dfsg1
[rustc.git] / src / libsyntax / print / pprust.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 pub use self::AnnNode::*;
12
13 use abi;
14 use ast;
15 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
16 use ast_util;
17 use attr;
18 use owned_slice::OwnedSlice;
19 use attr::{AttrMetaMethods, AttributeMethods};
20 use codemap::{self, CodeMap, BytePos};
21 use diagnostic;
22 use parse::token::{self, BinOpToken, Token, InternedString};
23 use parse::lexer::comments;
24 use parse;
25 use print::pp::{self, break_offset, word, space, zerobreak, hardbreak};
26 use print::pp::{Breaks, eof};
27 use print::pp::Breaks::{Consistent, Inconsistent};
28 use ptr::P;
29 use std_inject;
30
31 use std::ascii;
32 use std::io::{self, Write, Read};
33 use std::iter;
34
35 pub enum AnnNode<'a> {
36 NodeIdent(&'a ast::Ident),
37 NodeName(&'a ast::Name),
38 NodeBlock(&'a ast::Block),
39 NodeItem(&'a ast::Item),
40 NodeSubItem(ast::NodeId),
41 NodeExpr(&'a ast::Expr),
42 NodePat(&'a ast::Pat),
43 }
44
45 pub trait PpAnn {
46 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
47 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
48 }
49
50 #[derive(Copy, Clone)]
51 pub struct NoAnn;
52
53 impl PpAnn for NoAnn {}
54
55 #[derive(Copy, Clone)]
56 pub struct CurrentCommentAndLiteral {
57 cur_cmnt: usize,
58 cur_lit: usize,
59 }
60
61 pub struct State<'a> {
62 pub s: pp::Printer<'a>,
63 cm: Option<&'a CodeMap>,
64 comments: Option<Vec<comments::Comment> >,
65 literals: Option<Vec<comments::Literal> >,
66 cur_cmnt_and_lit: CurrentCommentAndLiteral,
67 boxes: Vec<pp::Breaks>,
68 ann: &'a (PpAnn+'a),
69 }
70
71 pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
72 static NO_ANN: NoAnn = NoAnn;
73 rust_printer_annotated(writer, &NO_ANN)
74 }
75
76 pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
77 ann: &'a PpAnn) -> State<'a> {
78 State {
79 s: pp::mk_printer(writer, default_columns),
80 cm: None,
81 comments: None,
82 literals: None,
83 cur_cmnt_and_lit: CurrentCommentAndLiteral {
84 cur_cmnt: 0,
85 cur_lit: 0
86 },
87 boxes: Vec::new(),
88 ann: ann,
89 }
90 }
91
92 #[allow(non_upper_case_globals)]
93 pub const indent_unit: usize = 4;
94
95 #[allow(non_upper_case_globals)]
96 pub const default_columns: usize = 78;
97
98 /// Requires you to pass an input filename and reader so that
99 /// it can scan the input text for comments and literals to
100 /// copy forward.
101 pub fn print_crate<'a>(cm: &'a CodeMap,
102 span_diagnostic: &diagnostic::SpanHandler,
103 krate: &ast::Crate,
104 filename: String,
105 input: &mut Read,
106 out: Box<Write+'a>,
107 ann: &'a PpAnn,
108 is_expanded: bool) -> io::Result<()> {
109 let mut s = State::new_from_input(cm,
110 span_diagnostic,
111 filename,
112 input,
113 out,
114 ann,
115 is_expanded);
116 if is_expanded && std_inject::use_std(krate) {
117 // We need to print `#![no_std]` (and its feature gate) so that
118 // compiling pretty-printed source won't inject libstd again.
119 // However we don't want these attributes in the AST because
120 // of the feature gate, so we fake them up here.
121
122 let no_std_meta = attr::mk_word_item(InternedString::new("no_std"));
123
124 // #![feature(no_std)]
125 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(),
126 attr::mk_list_item(InternedString::new("feature"),
127 vec![no_std_meta.clone()]));
128 try!(s.print_attribute(&fake_attr));
129
130 // #![no_std]
131 let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), no_std_meta);
132 try!(s.print_attribute(&fake_attr));
133 }
134
135 try!(s.print_mod(&krate.module, &krate.attrs));
136 try!(s.print_remaining_comments());
137 eof(&mut s.s)
138 }
139
140 impl<'a> State<'a> {
141 pub fn new_from_input(cm: &'a CodeMap,
142 span_diagnostic: &diagnostic::SpanHandler,
143 filename: String,
144 input: &mut Read,
145 out: Box<Write+'a>,
146 ann: &'a PpAnn,
147 is_expanded: bool) -> State<'a> {
148 let (cmnts, lits) = comments::gather_comments_and_literals(
149 span_diagnostic,
150 filename,
151 input);
152
153 State::new(
154 cm,
155 out,
156 ann,
157 Some(cmnts),
158 // If the code is post expansion, don't use the table of
159 // literals, since it doesn't correspond with the literals
160 // in the AST anymore.
161 if is_expanded { None } else { Some(lits) })
162 }
163
164 pub fn new(cm: &'a CodeMap,
165 out: Box<Write+'a>,
166 ann: &'a PpAnn,
167 comments: Option<Vec<comments::Comment>>,
168 literals: Option<Vec<comments::Literal>>) -> State<'a> {
169 State {
170 s: pp::mk_printer(out, default_columns),
171 cm: Some(cm),
172 comments: comments,
173 literals: literals,
174 cur_cmnt_and_lit: CurrentCommentAndLiteral {
175 cur_cmnt: 0,
176 cur_lit: 0
177 },
178 boxes: Vec::new(),
179 ann: ann,
180 }
181 }
182 }
183
184 pub fn to_string<F>(f: F) -> String where
185 F: FnOnce(&mut State) -> io::Result<()>,
186 {
187 let mut wr = Vec::new();
188 {
189 let mut printer = rust_printer(Box::new(&mut wr));
190 f(&mut printer).unwrap();
191 eof(&mut printer.s).unwrap();
192 }
193 String::from_utf8(wr).unwrap()
194 }
195
196 pub fn binop_to_string(op: BinOpToken) -> &'static str {
197 match op {
198 token::Plus => "+",
199 token::Minus => "-",
200 token::Star => "*",
201 token::Slash => "/",
202 token::Percent => "%",
203 token::Caret => "^",
204 token::And => "&",
205 token::Or => "|",
206 token::Shl => "<<",
207 token::Shr => ">>",
208 }
209 }
210
211 pub fn token_to_string(tok: &Token) -> String {
212 match *tok {
213 token::Eq => "=".to_string(),
214 token::Lt => "<".to_string(),
215 token::Le => "<=".to_string(),
216 token::EqEq => "==".to_string(),
217 token::Ne => "!=".to_string(),
218 token::Ge => ">=".to_string(),
219 token::Gt => ">".to_string(),
220 token::Not => "!".to_string(),
221 token::Tilde => "~".to_string(),
222 token::OrOr => "||".to_string(),
223 token::AndAnd => "&&".to_string(),
224 token::BinOp(op) => binop_to_string(op).to_string(),
225 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
226
227 /* Structural symbols */
228 token::At => "@".to_string(),
229 token::Dot => ".".to_string(),
230 token::DotDot => "..".to_string(),
231 token::DotDotDot => "...".to_string(),
232 token::Comma => ",".to_string(),
233 token::Semi => ";".to_string(),
234 token::Colon => ":".to_string(),
235 token::ModSep => "::".to_string(),
236 token::RArrow => "->".to_string(),
237 token::LArrow => "<-".to_string(),
238 token::FatArrow => "=>".to_string(),
239 token::OpenDelim(token::Paren) => "(".to_string(),
240 token::CloseDelim(token::Paren) => ")".to_string(),
241 token::OpenDelim(token::Bracket) => "[".to_string(),
242 token::CloseDelim(token::Bracket) => "]".to_string(),
243 token::OpenDelim(token::Brace) => "{".to_string(),
244 token::CloseDelim(token::Brace) => "}".to_string(),
245 token::Pound => "#".to_string(),
246 token::Dollar => "$".to_string(),
247 token::Question => "?".to_string(),
248
249 /* Literals */
250 token::Literal(lit, suf) => {
251 let mut out = match lit {
252 token::Byte(b) => format!("b'{}'", b.as_str()),
253 token::Char(c) => format!("'{}'", c.as_str()),
254 token::Float(c) => c.as_str().to_string(),
255 token::Integer(c) => c.as_str().to_string(),
256 token::Str_(s) => format!("\"{}\"", s.as_str()),
257 token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
258 delim=repeat("#", n),
259 string=s.as_str()),
260 token::Binary(v) => format!("b\"{}\"", v.as_str()),
261 token::BinaryRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
262 delim=repeat("#", n),
263 string=s.as_str()),
264 };
265
266 if let Some(s) = suf {
267 out.push_str(s.as_str())
268 }
269
270 out
271 }
272
273 /* Name components */
274 token::Ident(s, _) => token::get_ident(s).to_string(),
275 token::Lifetime(s) => format!("{}", token::get_ident(s)),
276 token::Underscore => "_".to_string(),
277
278 /* Other */
279 token::DocComment(s) => s.as_str().to_string(),
280 token::SubstNt(s, _) => format!("${}", s),
281 token::MatchNt(s, t, _, _) => format!("${}:{}", s, t),
282 token::Eof => "<eof>".to_string(),
283 token::Whitespace => " ".to_string(),
284 token::Comment => "/* */".to_string(),
285 token::Shebang(s) => format!("/* shebang: {}*/", s.as_str()),
286
287 token::SpecialVarNt(var) => format!("${}", var.as_str()),
288
289 token::Interpolated(ref nt) => match *nt {
290 token::NtExpr(ref e) => expr_to_string(&**e),
291 token::NtMeta(ref e) => meta_item_to_string(&**e),
292 token::NtTy(ref e) => ty_to_string(&**e),
293 token::NtPath(ref e) => path_to_string(&**e),
294 token::NtItem(ref e) => item_to_string(&**e),
295 token::NtBlock(ref e) => block_to_string(&**e),
296 token::NtStmt(ref e) => stmt_to_string(&**e),
297 token::NtPat(ref e) => pat_to_string(&**e),
298 token::NtIdent(ref e, _) => ident_to_string(&**e),
299 token::NtTT(ref e) => tt_to_string(&**e),
300 token::NtArm(ref e) => arm_to_string(&*e),
301 token::NtImplItem(ref e) => impl_item_to_string(&**e),
302 token::NtTraitItem(ref e) => trait_item_to_string(&**e),
303 token::NtGenerics(ref e) => generics_to_string(&*e),
304 token::NtWhereClause(ref e) => where_clause_to_string(&*e),
305 }
306 }
307 }
308
309 pub fn ty_to_string(ty: &ast::Ty) -> String {
310 to_string(|s| s.print_type(ty))
311 }
312
313 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
314 to_string(|s| s.print_bounds("", bounds))
315 }
316
317 pub fn pat_to_string(pat: &ast::Pat) -> String {
318 to_string(|s| s.print_pat(pat))
319 }
320
321 pub fn arm_to_string(arm: &ast::Arm) -> String {
322 to_string(|s| s.print_arm(arm))
323 }
324
325 pub fn expr_to_string(e: &ast::Expr) -> String {
326 to_string(|s| s.print_expr(e))
327 }
328
329 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
330 to_string(|s| s.print_lifetime(e))
331 }
332
333 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
334 to_string(|s| s.print_tt(tt))
335 }
336
337 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
338 to_string(|s| s.print_tts(tts))
339 }
340
341 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
342 to_string(|s| s.print_stmt(stmt))
343 }
344
345 pub fn attr_to_string(attr: &ast::Attribute) -> String {
346 to_string(|s| s.print_attribute(attr))
347 }
348
349 pub fn item_to_string(i: &ast::Item) -> String {
350 to_string(|s| s.print_item(i))
351 }
352
353 pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
354 to_string(|s| s.print_impl_item(i))
355 }
356
357 pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
358 to_string(|s| s.print_trait_item(i))
359 }
360
361 pub fn generics_to_string(generics: &ast::Generics) -> String {
362 to_string(|s| s.print_generics(generics))
363 }
364
365 pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
366 to_string(|s| s.print_where_clause(i))
367 }
368
369 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
370 to_string(|s| s.print_fn_block_args(p))
371 }
372
373 pub fn path_to_string(p: &ast::Path) -> String {
374 to_string(|s| s.print_path(p, false, 0))
375 }
376
377 pub fn ident_to_string(id: &ast::Ident) -> String {
378 to_string(|s| s.print_ident(*id))
379 }
380
381 pub fn fun_to_string(decl: &ast::FnDecl, unsafety: ast::Unsafety, name: ast::Ident,
382 opt_explicit_self: Option<&ast::ExplicitSelf_>,
383 generics: &ast::Generics) -> String {
384 to_string(|s| {
385 try!(s.head(""));
386 try!(s.print_fn(decl, unsafety, abi::Rust, Some(name),
387 generics, opt_explicit_self, ast::Inherited));
388 try!(s.end()); // Close the head box
389 s.end() // Close the outer box
390 })
391 }
392
393 pub fn block_to_string(blk: &ast::Block) -> String {
394 to_string(|s| {
395 // containing cbox, will be closed by print-block at }
396 try!(s.cbox(indent_unit));
397 // head-ibox, will be closed by print-block after {
398 try!(s.ibox(0));
399 s.print_block(blk)
400 })
401 }
402
403 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
404 to_string(|s| s.print_meta_item(mi))
405 }
406
407 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
408 to_string(|s| s.print_attribute(attr))
409 }
410
411 pub fn lit_to_string(l: &ast::Lit) -> String {
412 to_string(|s| s.print_literal(l))
413 }
414
415 pub fn explicit_self_to_string(explicit_self: &ast::ExplicitSelf_) -> String {
416 to_string(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
417 }
418
419 pub fn variant_to_string(var: &ast::Variant) -> String {
420 to_string(|s| s.print_variant(var))
421 }
422
423 pub fn arg_to_string(arg: &ast::Arg) -> String {
424 to_string(|s| s.print_arg(arg))
425 }
426
427 pub fn mac_to_string(arg: &ast::Mac) -> String {
428 to_string(|s| s.print_mac(arg, ::parse::token::Paren))
429 }
430
431 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
432 match vis {
433 ast::Public => format!("pub {}", s),
434 ast::Inherited => s.to_string()
435 }
436 }
437
438 fn needs_parentheses(expr: &ast::Expr) -> bool {
439 match expr.node {
440 ast::ExprAssign(..) | ast::ExprBinary(..) |
441 ast::ExprClosure(..) |
442 ast::ExprAssignOp(..) | ast::ExprCast(..) => true,
443 _ => false,
444 }
445 }
446
447 impl<'a> State<'a> {
448 pub fn ibox(&mut self, u: usize) -> io::Result<()> {
449 self.boxes.push(pp::Breaks::Inconsistent);
450 pp::ibox(&mut self.s, u)
451 }
452
453 pub fn end(&mut self) -> io::Result<()> {
454 self.boxes.pop().unwrap();
455 pp::end(&mut self.s)
456 }
457
458 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
459 self.boxes.push(pp::Breaks::Consistent);
460 pp::cbox(&mut self.s, u)
461 }
462
463 // "raw box"
464 pub fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
465 self.boxes.push(b);
466 pp::rbox(&mut self.s, u, b)
467 }
468
469 pub fn nbsp(&mut self) -> io::Result<()> { word(&mut self.s, " ") }
470
471 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
472 try!(word(&mut self.s, w));
473 self.nbsp()
474 }
475
476 pub fn word_space(&mut self, w: &str) -> io::Result<()> {
477 try!(word(&mut self.s, w));
478 space(&mut self.s)
479 }
480
481 pub fn popen(&mut self) -> io::Result<()> { word(&mut self.s, "(") }
482
483 pub fn pclose(&mut self) -> io::Result<()> { word(&mut self.s, ")") }
484
485 pub fn head(&mut self, w: &str) -> io::Result<()> {
486 // outer-box is consistent
487 try!(self.cbox(indent_unit));
488 // head-box is inconsistent
489 try!(self.ibox(w.len() + 1));
490 // keyword that starts the head
491 if !w.is_empty() {
492 try!(self.word_nbsp(w));
493 }
494 Ok(())
495 }
496
497 pub fn bopen(&mut self) -> io::Result<()> {
498 try!(word(&mut self.s, "{"));
499 self.end() // close the head-box
500 }
501
502 pub fn bclose_(&mut self, span: codemap::Span,
503 indented: usize) -> io::Result<()> {
504 self.bclose_maybe_open(span, indented, true)
505 }
506 pub fn bclose_maybe_open (&mut self, span: codemap::Span,
507 indented: usize, close_box: bool) -> io::Result<()> {
508 try!(self.maybe_print_comment(span.hi));
509 try!(self.break_offset_if_not_bol(1, -(indented as isize)));
510 try!(word(&mut self.s, "}"));
511 if close_box {
512 try!(self.end()); // close the outer-box
513 }
514 Ok(())
515 }
516 pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
517 self.bclose_(span, indent_unit)
518 }
519
520 pub fn is_begin(&mut self) -> bool {
521 match self.s.last_token() {
522 pp::Token::Begin(_) => true,
523 _ => false,
524 }
525 }
526
527 pub fn is_end(&mut self) -> bool {
528 match self.s.last_token() {
529 pp::Token::End => true,
530 _ => false,
531 }
532 }
533
534 // is this the beginning of a line?
535 pub fn is_bol(&mut self) -> bool {
536 self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok()
537 }
538
539 pub fn in_cbox(&self) -> bool {
540 match self.boxes.last() {
541 Some(&last_box) => last_box == pp::Breaks::Consistent,
542 None => false
543 }
544 }
545
546 pub fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
547 if !self.is_bol() {
548 try!(hardbreak(&mut self.s))
549 }
550 Ok(())
551 }
552 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
553 if !self.is_bol() { try!(space(&mut self.s)); }
554 Ok(())
555 }
556 pub fn break_offset_if_not_bol(&mut self, n: usize,
557 off: isize) -> io::Result<()> {
558 if !self.is_bol() {
559 break_offset(&mut self.s, n, off)
560 } else {
561 if off != 0 && self.s.last_token().is_hardbreak_tok() {
562 // We do something pretty sketchy here: tuck the nonzero
563 // offset-adjustment we were going to deposit along with the
564 // break into the previous hardbreak.
565 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
566 }
567 Ok(())
568 }
569 }
570
571 // Synthesizes a comment that was not textually present in the original source
572 // file.
573 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
574 try!(word(&mut self.s, "/*"));
575 try!(space(&mut self.s));
576 try!(word(&mut self.s, &text[..]));
577 try!(space(&mut self.s));
578 word(&mut self.s, "*/")
579 }
580
581 pub fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()> where
582 F: FnMut(&mut State, &T) -> io::Result<()>,
583 {
584 try!(self.rbox(0, b));
585 let mut first = true;
586 for elt in elts {
587 if first { first = false; } else { try!(self.word_space(",")); }
588 try!(op(self, elt));
589 }
590 self.end()
591 }
592
593
594 pub fn commasep_cmnt<T, F, G>(&mut self,
595 b: Breaks,
596 elts: &[T],
597 mut op: F,
598 mut get_span: G) -> io::Result<()> where
599 F: FnMut(&mut State, &T) -> io::Result<()>,
600 G: FnMut(&T) -> codemap::Span,
601 {
602 try!(self.rbox(0, b));
603 let len = elts.len();
604 let mut i = 0;
605 for elt in elts {
606 try!(self.maybe_print_comment(get_span(elt).hi));
607 try!(op(self, elt));
608 i += 1;
609 if i < len {
610 try!(word(&mut self.s, ","));
611 try!(self.maybe_print_trailing_comment(get_span(elt),
612 Some(get_span(&elts[i]).hi)));
613 try!(self.space_if_not_bol());
614 }
615 }
616 self.end()
617 }
618
619 pub fn commasep_exprs(&mut self, b: Breaks,
620 exprs: &[P<ast::Expr>]) -> io::Result<()> {
621 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
622 }
623
624 pub fn print_mod(&mut self, _mod: &ast::Mod,
625 attrs: &[ast::Attribute]) -> io::Result<()> {
626 try!(self.print_inner_attributes(attrs));
627 for item in &_mod.items {
628 try!(self.print_item(&**item));
629 }
630 Ok(())
631 }
632
633 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
634 attrs: &[ast::Attribute]) -> io::Result<()> {
635 try!(self.print_inner_attributes(attrs));
636 for item in &nmod.items {
637 try!(self.print_foreign_item(&**item));
638 }
639 Ok(())
640 }
641
642 pub fn print_opt_lifetime(&mut self,
643 lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
644 if let Some(l) = *lifetime {
645 try!(self.print_lifetime(&l));
646 try!(self.nbsp());
647 }
648 Ok(())
649 }
650
651 pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
652 try!(self.maybe_print_comment(ty.span.lo));
653 try!(self.ibox(0));
654 match ty.node {
655 ast::TyVec(ref ty) => {
656 try!(word(&mut self.s, "["));
657 try!(self.print_type(&**ty));
658 try!(word(&mut self.s, "]"));
659 }
660 ast::TyPtr(ref mt) => {
661 try!(word(&mut self.s, "*"));
662 match mt.mutbl {
663 ast::MutMutable => try!(self.word_nbsp("mut")),
664 ast::MutImmutable => try!(self.word_nbsp("const")),
665 }
666 try!(self.print_type(&*mt.ty));
667 }
668 ast::TyRptr(ref lifetime, ref mt) => {
669 try!(word(&mut self.s, "&"));
670 try!(self.print_opt_lifetime(lifetime));
671 try!(self.print_mt(mt));
672 }
673 ast::TyTup(ref elts) => {
674 try!(self.popen());
675 try!(self.commasep(Inconsistent, &elts[..],
676 |s, ty| s.print_type(&**ty)));
677 if elts.len() == 1 {
678 try!(word(&mut self.s, ","));
679 }
680 try!(self.pclose());
681 }
682 ast::TyParen(ref typ) => {
683 try!(self.popen());
684 try!(self.print_type(&**typ));
685 try!(self.pclose());
686 }
687 ast::TyBareFn(ref f) => {
688 let generics = ast::Generics {
689 lifetimes: f.lifetimes.clone(),
690 ty_params: OwnedSlice::empty(),
691 where_clause: ast::WhereClause {
692 id: ast::DUMMY_NODE_ID,
693 predicates: Vec::new(),
694 },
695 };
696 try!(self.print_ty_fn(f.abi,
697 f.unsafety,
698 &*f.decl,
699 None,
700 &generics,
701 None));
702 }
703 ast::TyPath(None, ref path) => {
704 try!(self.print_path(path, false, 0));
705 }
706 ast::TyPath(Some(ref qself), ref path) => {
707 try!(self.print_qpath(path, qself, false))
708 }
709 ast::TyObjectSum(ref ty, ref bounds) => {
710 try!(self.print_type(&**ty));
711 try!(self.print_bounds("+", &bounds[..]));
712 }
713 ast::TyPolyTraitRef(ref bounds) => {
714 try!(self.print_bounds("", &bounds[..]));
715 }
716 ast::TyFixedLengthVec(ref ty, ref v) => {
717 try!(word(&mut self.s, "["));
718 try!(self.print_type(&**ty));
719 try!(word(&mut self.s, "; "));
720 try!(self.print_expr(&**v));
721 try!(word(&mut self.s, "]"));
722 }
723 ast::TyTypeof(ref e) => {
724 try!(word(&mut self.s, "typeof("));
725 try!(self.print_expr(&**e));
726 try!(word(&mut self.s, ")"));
727 }
728 ast::TyInfer => {
729 try!(word(&mut self.s, "_"));
730 }
731 }
732 self.end()
733 }
734
735 pub fn print_foreign_item(&mut self,
736 item: &ast::ForeignItem) -> io::Result<()> {
737 try!(self.hardbreak_if_not_bol());
738 try!(self.maybe_print_comment(item.span.lo));
739 try!(self.print_outer_attributes(&item.attrs));
740 match item.node {
741 ast::ForeignItemFn(ref decl, ref generics) => {
742 try!(self.head(""));
743 try!(self.print_fn(&**decl, ast::Unsafety::Normal,
744 abi::Rust, Some(item.ident),
745 generics, None, item.vis));
746 try!(self.end()); // end head-ibox
747 try!(word(&mut self.s, ";"));
748 self.end() // end the outer fn box
749 }
750 ast::ForeignItemStatic(ref t, m) => {
751 try!(self.head(&visibility_qualified(item.vis,
752 "static")));
753 if m {
754 try!(self.word_space("mut"));
755 }
756 try!(self.print_ident(item.ident));
757 try!(self.word_space(":"));
758 try!(self.print_type(&**t));
759 try!(word(&mut self.s, ";"));
760 try!(self.end()); // end the head-ibox
761 self.end() // end the outer cbox
762 }
763 }
764 }
765
766 fn print_associated_const(&mut self,
767 ident: ast::Ident,
768 ty: &ast::Ty,
769 default: Option<&ast::Expr>,
770 vis: ast::Visibility)
771 -> io::Result<()>
772 {
773 try!(word(&mut self.s, &visibility_qualified(vis, "")));
774 try!(self.word_space("const"));
775 try!(self.print_ident(ident));
776 try!(self.word_space(":"));
777 try!(self.print_type(ty));
778 if let Some(expr) = default {
779 try!(space(&mut self.s));
780 try!(self.word_space("="));
781 try!(self.print_expr(expr));
782 }
783 word(&mut self.s, ";")
784 }
785
786 fn print_associated_type(&mut self,
787 ident: ast::Ident,
788 bounds: Option<&ast::TyParamBounds>,
789 ty: Option<&ast::Ty>)
790 -> io::Result<()> {
791 try!(self.word_space("type"));
792 try!(self.print_ident(ident));
793 if let Some(bounds) = bounds {
794 try!(self.print_bounds(":", bounds));
795 }
796 if let Some(ty) = ty {
797 try!(space(&mut self.s));
798 try!(self.word_space("="));
799 try!(self.print_type(ty));
800 }
801 word(&mut self.s, ";")
802 }
803
804 /// Pretty-print an item
805 pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
806 try!(self.hardbreak_if_not_bol());
807 try!(self.maybe_print_comment(item.span.lo));
808 try!(self.print_outer_attributes(&item.attrs));
809 try!(self.ann.pre(self, NodeItem(item)));
810 match item.node {
811 ast::ItemExternCrate(ref optional_path) => {
812 try!(self.head(&visibility_qualified(item.vis,
813 "extern crate")));
814 if let Some(p) = *optional_path {
815 let val = token::get_name(p);
816 if val.contains("-") {
817 try!(self.print_string(&val, ast::CookedStr));
818 } else {
819 try!(self.print_name(p));
820 }
821 try!(space(&mut self.s));
822 try!(word(&mut self.s, "as"));
823 try!(space(&mut self.s));
824 }
825 try!(self.print_ident(item.ident));
826 try!(word(&mut self.s, ";"));
827 try!(self.end()); // end inner head-block
828 try!(self.end()); // end outer head-block
829 }
830 ast::ItemUse(ref vp) => {
831 try!(self.head(&visibility_qualified(item.vis,
832 "use")));
833 try!(self.print_view_path(&**vp));
834 try!(word(&mut self.s, ";"));
835 try!(self.end()); // end inner head-block
836 try!(self.end()); // end outer head-block
837 }
838 ast::ItemStatic(ref ty, m, ref expr) => {
839 try!(self.head(&visibility_qualified(item.vis,
840 "static")));
841 if m == ast::MutMutable {
842 try!(self.word_space("mut"));
843 }
844 try!(self.print_ident(item.ident));
845 try!(self.word_space(":"));
846 try!(self.print_type(&**ty));
847 try!(space(&mut self.s));
848 try!(self.end()); // end the head-ibox
849
850 try!(self.word_space("="));
851 try!(self.print_expr(&**expr));
852 try!(word(&mut self.s, ";"));
853 try!(self.end()); // end the outer cbox
854 }
855 ast::ItemConst(ref ty, ref expr) => {
856 try!(self.head(&visibility_qualified(item.vis,
857 "const")));
858 try!(self.print_ident(item.ident));
859 try!(self.word_space(":"));
860 try!(self.print_type(&**ty));
861 try!(space(&mut self.s));
862 try!(self.end()); // end the head-ibox
863
864 try!(self.word_space("="));
865 try!(self.print_expr(&**expr));
866 try!(word(&mut self.s, ";"));
867 try!(self.end()); // end the outer cbox
868 }
869 ast::ItemFn(ref decl, unsafety, abi, ref typarams, ref body) => {
870 try!(self.head(""));
871 try!(self.print_fn(
872 decl,
873 unsafety,
874 abi,
875 Some(item.ident),
876 typarams,
877 None,
878 item.vis
879 ));
880 try!(word(&mut self.s, " "));
881 try!(self.print_block_with_attrs(&**body, &item.attrs));
882 }
883 ast::ItemMod(ref _mod) => {
884 try!(self.head(&visibility_qualified(item.vis,
885 "mod")));
886 try!(self.print_ident(item.ident));
887 try!(self.nbsp());
888 try!(self.bopen());
889 try!(self.print_mod(_mod, &item.attrs));
890 try!(self.bclose(item.span));
891 }
892 ast::ItemForeignMod(ref nmod) => {
893 try!(self.head("extern"));
894 try!(self.word_nbsp(&nmod.abi.to_string()));
895 try!(self.bopen());
896 try!(self.print_foreign_mod(nmod, &item.attrs));
897 try!(self.bclose(item.span));
898 }
899 ast::ItemTy(ref ty, ref params) => {
900 try!(self.ibox(indent_unit));
901 try!(self.ibox(0));
902 try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
903 try!(self.print_ident(item.ident));
904 try!(self.print_generics(params));
905 try!(self.end()); // end the inner ibox
906
907 try!(self.print_where_clause(&params.where_clause));
908 try!(space(&mut self.s));
909 try!(self.word_space("="));
910 try!(self.print_type(&**ty));
911 try!(word(&mut self.s, ";"));
912 try!(self.end()); // end the outer ibox
913 }
914 ast::ItemEnum(ref enum_definition, ref params) => {
915 try!(self.print_enum_def(
916 enum_definition,
917 params,
918 item.ident,
919 item.span,
920 item.vis
921 ));
922 }
923 ast::ItemStruct(ref struct_def, ref generics) => {
924 try!(self.head(&visibility_qualified(item.vis,"struct")));
925 try!(self.print_struct(&**struct_def, generics, item.ident, item.span));
926 }
927
928 ast::ItemDefaultImpl(unsafety, ref trait_ref) => {
929 try!(self.head(""));
930 try!(self.print_visibility(item.vis));
931 try!(self.print_unsafety(unsafety));
932 try!(self.word_nbsp("impl"));
933 try!(self.print_trait_ref(trait_ref));
934 try!(space(&mut self.s));
935 try!(self.word_space("for"));
936 try!(self.word_space(".."));
937 try!(self.bopen());
938 try!(self.bclose(item.span));
939 }
940 ast::ItemImpl(unsafety,
941 polarity,
942 ref generics,
943 ref opt_trait,
944 ref ty,
945 ref impl_items) => {
946 try!(self.head(""));
947 try!(self.print_visibility(item.vis));
948 try!(self.print_unsafety(unsafety));
949 try!(self.word_nbsp("impl"));
950
951 if generics.is_parameterized() {
952 try!(self.print_generics(generics));
953 try!(space(&mut self.s));
954 }
955
956 match polarity {
957 ast::ImplPolarity::Negative => {
958 try!(word(&mut self.s, "!"));
959 },
960 _ => {}
961 }
962
963 match opt_trait {
964 &Some(ref t) => {
965 try!(self.print_trait_ref(t));
966 try!(space(&mut self.s));
967 try!(self.word_space("for"));
968 }
969 &None => {}
970 }
971
972 try!(self.print_type(&**ty));
973 try!(self.print_where_clause(&generics.where_clause));
974
975 try!(space(&mut self.s));
976 try!(self.bopen());
977 try!(self.print_inner_attributes(&item.attrs));
978 for impl_item in impl_items {
979 try!(self.print_impl_item(impl_item));
980 }
981 try!(self.bclose(item.span));
982 }
983 ast::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
984 try!(self.head(""));
985 try!(self.print_visibility(item.vis));
986 try!(self.print_unsafety(unsafety));
987 try!(self.word_nbsp("trait"));
988 try!(self.print_ident(item.ident));
989 try!(self.print_generics(generics));
990 let mut real_bounds = Vec::with_capacity(bounds.len());
991 for b in bounds.iter() {
992 if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
993 try!(space(&mut self.s));
994 try!(self.word_space("for ?"));
995 try!(self.print_trait_ref(&ptr.trait_ref));
996 } else {
997 real_bounds.push(b.clone());
998 }
999 }
1000 try!(self.print_bounds(":", &real_bounds[..]));
1001 try!(self.print_where_clause(&generics.where_clause));
1002 try!(word(&mut self.s, " "));
1003 try!(self.bopen());
1004 for trait_item in trait_items {
1005 try!(self.print_trait_item(trait_item));
1006 }
1007 try!(self.bclose(item.span));
1008 }
1009 // I think it's reasonable to hide the context here:
1010 ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
1011 ..}) => {
1012 try!(self.print_visibility(item.vis));
1013 try!(self.print_path(pth, false, 0));
1014 try!(word(&mut self.s, "! "));
1015 try!(self.print_ident(item.ident));
1016 try!(self.cbox(indent_unit));
1017 try!(self.popen());
1018 try!(self.print_tts(&tts[..]));
1019 try!(self.pclose());
1020 try!(word(&mut self.s, ";"));
1021 try!(self.end());
1022 }
1023 }
1024 self.ann.post(self, NodeItem(item))
1025 }
1026
1027 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1028 self.print_path(&t.path, false, 0)
1029 }
1030
1031 fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1032 if !lifetimes.is_empty() {
1033 try!(word(&mut self.s, "for<"));
1034 let mut comma = false;
1035 for lifetime_def in lifetimes {
1036 if comma {
1037 try!(self.word_space(","))
1038 }
1039 try!(self.print_lifetime_def(lifetime_def));
1040 comma = true;
1041 }
1042 try!(word(&mut self.s, ">"));
1043 }
1044 Ok(())
1045 }
1046
1047 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1048 try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
1049 self.print_trait_ref(&t.trait_ref)
1050 }
1051
1052 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1053 generics: &ast::Generics, ident: ast::Ident,
1054 span: codemap::Span,
1055 visibility: ast::Visibility) -> io::Result<()> {
1056 try!(self.head(&visibility_qualified(visibility, "enum")));
1057 try!(self.print_ident(ident));
1058 try!(self.print_generics(generics));
1059 try!(self.print_where_clause(&generics.where_clause));
1060 try!(space(&mut self.s));
1061 self.print_variants(&enum_definition.variants, span)
1062 }
1063
1064 pub fn print_variants(&mut self,
1065 variants: &[P<ast::Variant>],
1066 span: codemap::Span) -> io::Result<()> {
1067 try!(self.bopen());
1068 for v in variants {
1069 try!(self.space_if_not_bol());
1070 try!(self.maybe_print_comment(v.span.lo));
1071 try!(self.print_outer_attributes(&v.node.attrs));
1072 try!(self.ibox(indent_unit));
1073 try!(self.print_variant(&**v));
1074 try!(word(&mut self.s, ","));
1075 try!(self.end());
1076 try!(self.maybe_print_trailing_comment(v.span, None));
1077 }
1078 self.bclose(span)
1079 }
1080
1081 pub fn print_visibility(&mut self, vis: ast::Visibility) -> io::Result<()> {
1082 match vis {
1083 ast::Public => self.word_nbsp("pub"),
1084 ast::Inherited => Ok(())
1085 }
1086 }
1087
1088 pub fn print_struct(&mut self,
1089 struct_def: &ast::StructDef,
1090 generics: &ast::Generics,
1091 ident: ast::Ident,
1092 span: codemap::Span) -> io::Result<()> {
1093 try!(self.print_ident(ident));
1094 try!(self.print_generics(generics));
1095 if ast_util::struct_def_is_tuple_like(struct_def) {
1096 if !struct_def.fields.is_empty() {
1097 try!(self.popen());
1098 try!(self.commasep(
1099 Inconsistent, &struct_def.fields,
1100 |s, field| {
1101 match field.node.kind {
1102 ast::NamedField(..) => panic!("unexpected named field"),
1103 ast::UnnamedField(vis) => {
1104 try!(s.print_visibility(vis));
1105 try!(s.maybe_print_comment(field.span.lo));
1106 s.print_type(&*field.node.ty)
1107 }
1108 }
1109 }
1110 ));
1111 try!(self.pclose());
1112 }
1113 try!(self.print_where_clause(&generics.where_clause));
1114 try!(word(&mut self.s, ";"));
1115 try!(self.end());
1116 self.end() // close the outer-box
1117 } else {
1118 try!(self.print_where_clause(&generics.where_clause));
1119 try!(self.nbsp());
1120 try!(self.bopen());
1121 try!(self.hardbreak_if_not_bol());
1122
1123 for field in &struct_def.fields {
1124 match field.node.kind {
1125 ast::UnnamedField(..) => panic!("unexpected unnamed field"),
1126 ast::NamedField(ident, visibility) => {
1127 try!(self.hardbreak_if_not_bol());
1128 try!(self.maybe_print_comment(field.span.lo));
1129 try!(self.print_outer_attributes(&field.node.attrs));
1130 try!(self.print_visibility(visibility));
1131 try!(self.print_ident(ident));
1132 try!(self.word_nbsp(":"));
1133 try!(self.print_type(&*field.node.ty));
1134 try!(word(&mut self.s, ","));
1135 }
1136 }
1137 }
1138
1139 self.bclose(span)
1140 }
1141 }
1142
1143 /// This doesn't deserve to be called "pretty" printing, but it should be
1144 /// meaning-preserving. A quick hack that might help would be to look at the
1145 /// spans embedded in the TTs to decide where to put spaces and newlines.
1146 /// But it'd be better to parse these according to the grammar of the
1147 /// appropriate macro, transcribe back into the grammar we just parsed from,
1148 /// and then pretty-print the resulting AST nodes (so, e.g., we print
1149 /// expression arguments as expressions). It can be done! I think.
1150 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> io::Result<()> {
1151 match *tt {
1152 ast::TtToken(_, ref tk) => {
1153 try!(word(&mut self.s, &token_to_string(tk)));
1154 match *tk {
1155 parse::token::DocComment(..) => {
1156 hardbreak(&mut self.s)
1157 }
1158 _ => Ok(())
1159 }
1160 }
1161 ast::TtDelimited(_, ref delimed) => {
1162 try!(word(&mut self.s, &token_to_string(&delimed.open_token())));
1163 try!(space(&mut self.s));
1164 try!(self.print_tts(&delimed.tts));
1165 try!(space(&mut self.s));
1166 word(&mut self.s, &token_to_string(&delimed.close_token()))
1167 },
1168 ast::TtSequence(_, ref seq) => {
1169 try!(word(&mut self.s, "$("));
1170 for tt_elt in &seq.tts {
1171 try!(self.print_tt(tt_elt));
1172 }
1173 try!(word(&mut self.s, ")"));
1174 match seq.separator {
1175 Some(ref tk) => {
1176 try!(word(&mut self.s, &token_to_string(tk)));
1177 }
1178 None => {},
1179 }
1180 match seq.op {
1181 ast::ZeroOrMore => word(&mut self.s, "*"),
1182 ast::OneOrMore => word(&mut self.s, "+"),
1183 }
1184 }
1185 }
1186 }
1187
1188 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> io::Result<()> {
1189 try!(self.ibox(0));
1190 let mut suppress_space = false;
1191 for (i, tt) in tts.iter().enumerate() {
1192 if i != 0 && !suppress_space {
1193 try!(space(&mut self.s));
1194 }
1195 try!(self.print_tt(tt));
1196 // There should be no space between the module name and the following `::` in paths,
1197 // otherwise imported macros get re-parsed from crate metadata incorrectly (#20701)
1198 suppress_space = match tt {
1199 &ast::TtToken(_, token::Ident(_, token::ModName)) |
1200 &ast::TtToken(_, token::MatchNt(_, _, _, token::ModName)) |
1201 &ast::TtToken(_, token::SubstNt(_, token::ModName)) => true,
1202 _ => false
1203 }
1204 }
1205 self.end()
1206 }
1207
1208 pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1209 try!(self.print_visibility(v.node.vis));
1210 match v.node.kind {
1211 ast::TupleVariantKind(ref args) => {
1212 try!(self.print_ident(v.node.name));
1213 if !args.is_empty() {
1214 try!(self.popen());
1215 try!(self.commasep(Consistent,
1216 &args[..],
1217 |s, arg| s.print_type(&*arg.ty)));
1218 try!(self.pclose());
1219 }
1220 }
1221 ast::StructVariantKind(ref struct_def) => {
1222 try!(self.head(""));
1223 let generics = ast_util::empty_generics();
1224 try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
1225 }
1226 }
1227 match v.node.disr_expr {
1228 Some(ref d) => {
1229 try!(space(&mut self.s));
1230 try!(self.word_space("="));
1231 self.print_expr(&**d)
1232 }
1233 _ => Ok(())
1234 }
1235 }
1236
1237 pub fn print_method_sig(&mut self,
1238 ident: ast::Ident,
1239 m: &ast::MethodSig,
1240 vis: ast::Visibility)
1241 -> io::Result<()> {
1242 self.print_fn(&m.decl,
1243 m.unsafety,
1244 m.abi,
1245 Some(ident),
1246 &m.generics,
1247 Some(&m.explicit_self.node),
1248 vis)
1249 }
1250
1251 pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1252 -> io::Result<()> {
1253 try!(self.ann.pre(self, NodeSubItem(ti.id)));
1254 try!(self.hardbreak_if_not_bol());
1255 try!(self.maybe_print_comment(ti.span.lo));
1256 try!(self.print_outer_attributes(&ti.attrs));
1257 match ti.node {
1258 ast::ConstTraitItem(ref ty, ref default) => {
1259 try!(self.print_associated_const(ti.ident, &ty,
1260 default.as_ref().map(|expr| &**expr),
1261 ast::Inherited));
1262 }
1263 ast::MethodTraitItem(ref sig, ref body) => {
1264 if body.is_some() {
1265 try!(self.head(""));
1266 }
1267 try!(self.print_method_sig(ti.ident, sig, ast::Inherited));
1268 if let Some(ref body) = *body {
1269 try!(self.nbsp());
1270 try!(self.print_block_with_attrs(body, &ti.attrs));
1271 } else {
1272 try!(word(&mut self.s, ";"));
1273 }
1274 }
1275 ast::TypeTraitItem(ref bounds, ref default) => {
1276 try!(self.print_associated_type(ti.ident, Some(bounds),
1277 default.as_ref().map(|ty| &**ty)));
1278 }
1279 }
1280 self.ann.post(self, NodeSubItem(ti.id))
1281 }
1282
1283 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1284 try!(self.ann.pre(self, NodeSubItem(ii.id)));
1285 try!(self.hardbreak_if_not_bol());
1286 try!(self.maybe_print_comment(ii.span.lo));
1287 try!(self.print_outer_attributes(&ii.attrs));
1288 match ii.node {
1289 ast::ConstImplItem(ref ty, ref expr) => {
1290 try!(self.print_associated_const(ii.ident, &ty, Some(&expr), ii.vis));
1291 }
1292 ast::MethodImplItem(ref sig, ref body) => {
1293 try!(self.head(""));
1294 try!(self.print_method_sig(ii.ident, sig, ii.vis));
1295 try!(self.nbsp());
1296 try!(self.print_block_with_attrs(body, &ii.attrs));
1297 }
1298 ast::TypeImplItem(ref ty) => {
1299 try!(self.print_associated_type(ii.ident, None, Some(ty)));
1300 }
1301 ast::MacImplItem(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
1302 ..}) => {
1303 // code copied from ItemMac:
1304 try!(self.print_path(pth, false, 0));
1305 try!(word(&mut self.s, "! "));
1306 try!(self.cbox(indent_unit));
1307 try!(self.popen());
1308 try!(self.print_tts(&tts[..]));
1309 try!(self.pclose());
1310 try!(word(&mut self.s, ";"));
1311 try!(self.end())
1312 }
1313 }
1314 self.ann.post(self, NodeSubItem(ii.id))
1315 }
1316
1317 pub fn print_outer_attributes(&mut self,
1318 attrs: &[ast::Attribute]) -> io::Result<()> {
1319 let mut count = 0;
1320 for attr in attrs {
1321 match attr.node.style {
1322 ast::AttrOuter => {
1323 try!(self.print_attribute(attr));
1324 count += 1;
1325 }
1326 _ => {/* fallthrough */ }
1327 }
1328 }
1329 if count > 0 {
1330 try!(self.hardbreak_if_not_bol());
1331 }
1332 Ok(())
1333 }
1334
1335 pub fn print_inner_attributes(&mut self,
1336 attrs: &[ast::Attribute]) -> io::Result<()> {
1337 let mut count = 0;
1338 for attr in attrs {
1339 match attr.node.style {
1340 ast::AttrInner => {
1341 try!(self.print_attribute(attr));
1342 count += 1;
1343 }
1344 _ => {/* fallthrough */ }
1345 }
1346 }
1347 if count > 0 {
1348 try!(self.hardbreak_if_not_bol());
1349 }
1350 Ok(())
1351 }
1352
1353 pub fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
1354 try!(self.hardbreak_if_not_bol());
1355 try!(self.maybe_print_comment(attr.span.lo));
1356 if attr.node.is_sugared_doc {
1357 word(&mut self.s, &attr.value_str().unwrap())
1358 } else {
1359 match attr.node.style {
1360 ast::AttrInner => try!(word(&mut self.s, "#![")),
1361 ast::AttrOuter => try!(word(&mut self.s, "#[")),
1362 }
1363 try!(self.print_meta_item(&*attr.meta()));
1364 word(&mut self.s, "]")
1365 }
1366 }
1367
1368
1369 pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1370 try!(self.maybe_print_comment(st.span.lo));
1371 match st.node {
1372 ast::StmtDecl(ref decl, _) => {
1373 try!(self.print_decl(&**decl));
1374 }
1375 ast::StmtExpr(ref expr, _) => {
1376 try!(self.space_if_not_bol());
1377 try!(self.print_expr(&**expr));
1378 }
1379 ast::StmtSemi(ref expr, _) => {
1380 try!(self.space_if_not_bol());
1381 try!(self.print_expr(&**expr));
1382 try!(word(&mut self.s, ";"));
1383 }
1384 ast::StmtMac(ref mac, style) => {
1385 try!(self.space_if_not_bol());
1386 let delim = match style {
1387 ast::MacStmtWithBraces => token::Brace,
1388 _ => token::Paren
1389 };
1390 try!(self.print_mac(&**mac, delim));
1391 match style {
1392 ast::MacStmtWithBraces => {}
1393 _ => try!(word(&mut self.s, ";")),
1394 }
1395 }
1396 }
1397 if parse::classify::stmt_ends_with_semi(&st.node) {
1398 try!(word(&mut self.s, ";"));
1399 }
1400 self.maybe_print_trailing_comment(st.span, None)
1401 }
1402
1403 pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1404 self.print_block_with_attrs(blk, &[])
1405 }
1406
1407 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1408 self.print_block_unclosed_indent(blk, indent_unit)
1409 }
1410
1411 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1412 indented: usize) -> io::Result<()> {
1413 self.print_block_maybe_unclosed(blk, indented, &[], false)
1414 }
1415
1416 pub fn print_block_with_attrs(&mut self,
1417 blk: &ast::Block,
1418 attrs: &[ast::Attribute]) -> io::Result<()> {
1419 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1420 }
1421
1422 pub fn print_block_maybe_unclosed(&mut self,
1423 blk: &ast::Block,
1424 indented: usize,
1425 attrs: &[ast::Attribute],
1426 close_box: bool) -> io::Result<()> {
1427 match blk.rules {
1428 ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1429 ast::DefaultBlock => ()
1430 }
1431 try!(self.maybe_print_comment(blk.span.lo));
1432 try!(self.ann.pre(self, NodeBlock(blk)));
1433 try!(self.bopen());
1434
1435 try!(self.print_inner_attributes(attrs));
1436
1437 for st in &blk.stmts {
1438 try!(self.print_stmt(&**st));
1439 }
1440 match blk.expr {
1441 Some(ref expr) => {
1442 try!(self.space_if_not_bol());
1443 try!(self.print_expr(&**expr));
1444 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1445 }
1446 _ => ()
1447 }
1448 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1449 self.ann.post(self, NodeBlock(blk))
1450 }
1451
1452 fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1453 match els {
1454 Some(_else) => {
1455 match _else.node {
1456 // "another else-if"
1457 ast::ExprIf(ref i, ref then, ref e) => {
1458 try!(self.cbox(indent_unit - 1));
1459 try!(self.ibox(0));
1460 try!(word(&mut self.s, " else if "));
1461 try!(self.print_expr(&**i));
1462 try!(space(&mut self.s));
1463 try!(self.print_block(&**then));
1464 self.print_else(e.as_ref().map(|e| &**e))
1465 }
1466 // "another else-if-let"
1467 ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => {
1468 try!(self.cbox(indent_unit - 1));
1469 try!(self.ibox(0));
1470 try!(word(&mut self.s, " else if let "));
1471 try!(self.print_pat(&**pat));
1472 try!(space(&mut self.s));
1473 try!(self.word_space("="));
1474 try!(self.print_expr(&**expr));
1475 try!(space(&mut self.s));
1476 try!(self.print_block(&**then));
1477 self.print_else(e.as_ref().map(|e| &**e))
1478 }
1479 // "final else"
1480 ast::ExprBlock(ref b) => {
1481 try!(self.cbox(indent_unit - 1));
1482 try!(self.ibox(0));
1483 try!(word(&mut self.s, " else "));
1484 self.print_block(&**b)
1485 }
1486 // BLEAH, constraints would be great here
1487 _ => {
1488 panic!("print_if saw if with weird alternative");
1489 }
1490 }
1491 }
1492 _ => Ok(())
1493 }
1494 }
1495
1496 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1497 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1498 try!(self.head("if"));
1499 try!(self.print_expr(test));
1500 try!(space(&mut self.s));
1501 try!(self.print_block(blk));
1502 self.print_else(elseopt)
1503 }
1504
1505 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1506 elseopt: Option<&ast::Expr>) -> io::Result<()> {
1507 try!(self.head("if let"));
1508 try!(self.print_pat(pat));
1509 try!(space(&mut self.s));
1510 try!(self.word_space("="));
1511 try!(self.print_expr(expr));
1512 try!(space(&mut self.s));
1513 try!(self.print_block(blk));
1514 self.print_else(elseopt)
1515 }
1516
1517 pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1518 -> io::Result<()> {
1519 match m.node {
1520 // I think it's reasonable to hide the ctxt here:
1521 ast::MacInvocTT(ref pth, ref tts, _) => {
1522 try!(self.print_path(pth, false, 0));
1523 try!(word(&mut self.s, "!"));
1524 match delim {
1525 token::Paren => try!(self.popen()),
1526 token::Bracket => try!(word(&mut self.s, "[")),
1527 token::Brace => try!(self.bopen()),
1528 }
1529 try!(self.print_tts(tts));
1530 match delim {
1531 token::Paren => self.pclose(),
1532 token::Bracket => word(&mut self.s, "]"),
1533 token::Brace => self.bclose(m.span),
1534 }
1535 }
1536 }
1537 }
1538
1539
1540 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1541 try!(self.popen());
1542 try!(self.commasep_exprs(Inconsistent, args));
1543 self.pclose()
1544 }
1545
1546 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1547 let needs_par = needs_parentheses(expr);
1548 if needs_par {
1549 try!(self.popen());
1550 }
1551 try!(self.print_expr(expr));
1552 if needs_par {
1553 try!(self.pclose());
1554 }
1555 Ok(())
1556 }
1557
1558 fn print_expr_box(&mut self,
1559 place: &Option<P<ast::Expr>>,
1560 expr: &ast::Expr) -> io::Result<()> {
1561 try!(word(&mut self.s, "box"));
1562 try!(word(&mut self.s, "("));
1563 try!(place.as_ref().map_or(Ok(()), |e|self.print_expr(&**e)));
1564 try!(self.word_space(")"));
1565 self.print_expr(expr)
1566 }
1567
1568 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) -> io::Result<()> {
1569 try!(self.ibox(indent_unit));
1570 try!(word(&mut self.s, "["));
1571 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1572 try!(word(&mut self.s, "]"));
1573 self.end()
1574 }
1575
1576 fn print_expr_repeat(&mut self,
1577 element: &ast::Expr,
1578 count: &ast::Expr) -> io::Result<()> {
1579 try!(self.ibox(indent_unit));
1580 try!(word(&mut self.s, "["));
1581 try!(self.print_expr(element));
1582 try!(self.word_space(";"));
1583 try!(self.print_expr(count));
1584 try!(word(&mut self.s, "]"));
1585 self.end()
1586 }
1587
1588 fn print_expr_struct(&mut self,
1589 path: &ast::Path,
1590 fields: &[ast::Field],
1591 wth: &Option<P<ast::Expr>>) -> io::Result<()> {
1592 try!(self.print_path(path, true, 0));
1593 if !(fields.is_empty() && wth.is_none()) {
1594 try!(word(&mut self.s, "{"));
1595 try!(self.commasep_cmnt(
1596 Consistent,
1597 &fields[..],
1598 |s, field| {
1599 try!(s.ibox(indent_unit));
1600 try!(s.print_ident(field.ident.node));
1601 try!(s.word_space(":"));
1602 try!(s.print_expr(&*field.expr));
1603 s.end()
1604 },
1605 |f| f.span));
1606 match *wth {
1607 Some(ref expr) => {
1608 try!(self.ibox(indent_unit));
1609 if !fields.is_empty() {
1610 try!(word(&mut self.s, ","));
1611 try!(space(&mut self.s));
1612 }
1613 try!(word(&mut self.s, ".."));
1614 try!(self.print_expr(&**expr));
1615 try!(self.end());
1616 }
1617 _ => try!(word(&mut self.s, ",")),
1618 }
1619 try!(word(&mut self.s, "}"));
1620 }
1621 Ok(())
1622 }
1623
1624 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) -> io::Result<()> {
1625 try!(self.popen());
1626 try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1627 if exprs.len() == 1 {
1628 try!(word(&mut self.s, ","));
1629 }
1630 self.pclose()
1631 }
1632
1633 fn print_expr_call(&mut self,
1634 func: &ast::Expr,
1635 args: &[P<ast::Expr>]) -> io::Result<()> {
1636 try!(self.print_expr_maybe_paren(func));
1637 self.print_call_post(args)
1638 }
1639
1640 fn print_expr_method_call(&mut self,
1641 ident: ast::SpannedIdent,
1642 tys: &[P<ast::Ty>],
1643 args: &[P<ast::Expr>]) -> io::Result<()> {
1644 let base_args = &args[1..];
1645 try!(self.print_expr(&*args[0]));
1646 try!(word(&mut self.s, "."));
1647 try!(self.print_ident(ident.node));
1648 if !tys.is_empty() {
1649 try!(word(&mut self.s, "::<"));
1650 try!(self.commasep(Inconsistent, tys,
1651 |s, ty| s.print_type(&**ty)));
1652 try!(word(&mut self.s, ">"));
1653 }
1654 self.print_call_post(base_args)
1655 }
1656
1657 fn print_expr_binary(&mut self,
1658 op: ast::BinOp,
1659 lhs: &ast::Expr,
1660 rhs: &ast::Expr) -> io::Result<()> {
1661 try!(self.print_expr(lhs));
1662 try!(space(&mut self.s));
1663 try!(self.word_space(ast_util::binop_to_string(op.node)));
1664 self.print_expr(rhs)
1665 }
1666
1667 fn print_expr_unary(&mut self,
1668 op: ast::UnOp,
1669 expr: &ast::Expr) -> io::Result<()> {
1670 try!(word(&mut self.s, ast_util::unop_to_string(op)));
1671 self.print_expr_maybe_paren(expr)
1672 }
1673
1674 fn print_expr_addr_of(&mut self,
1675 mutability: ast::Mutability,
1676 expr: &ast::Expr) -> io::Result<()> {
1677 try!(word(&mut self.s, "&"));
1678 try!(self.print_mutability(mutability));
1679 self.print_expr_maybe_paren(expr)
1680 }
1681
1682 pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1683 try!(self.maybe_print_comment(expr.span.lo));
1684 try!(self.ibox(indent_unit));
1685 try!(self.ann.pre(self, NodeExpr(expr)));
1686 match expr.node {
1687 ast::ExprBox(ref place, ref expr) => {
1688 try!(self.print_expr_box(place, &**expr));
1689 }
1690 ast::ExprVec(ref exprs) => {
1691 try!(self.print_expr_vec(&exprs[..]));
1692 }
1693 ast::ExprRepeat(ref element, ref count) => {
1694 try!(self.print_expr_repeat(&**element, &**count));
1695 }
1696 ast::ExprStruct(ref path, ref fields, ref wth) => {
1697 try!(self.print_expr_struct(path, &fields[..], wth));
1698 }
1699 ast::ExprTup(ref exprs) => {
1700 try!(self.print_expr_tup(&exprs[..]));
1701 }
1702 ast::ExprCall(ref func, ref args) => {
1703 try!(self.print_expr_call(&**func, &args[..]));
1704 }
1705 ast::ExprMethodCall(ident, ref tys, ref args) => {
1706 try!(self.print_expr_method_call(ident, &tys[..], &args[..]));
1707 }
1708 ast::ExprBinary(op, ref lhs, ref rhs) => {
1709 try!(self.print_expr_binary(op, &**lhs, &**rhs));
1710 }
1711 ast::ExprUnary(op, ref expr) => {
1712 try!(self.print_expr_unary(op, &**expr));
1713 }
1714 ast::ExprAddrOf(m, ref expr) => {
1715 try!(self.print_expr_addr_of(m, &**expr));
1716 }
1717 ast::ExprLit(ref lit) => {
1718 try!(self.print_literal(&**lit));
1719 }
1720 ast::ExprCast(ref expr, ref ty) => {
1721 try!(self.print_expr(&**expr));
1722 try!(space(&mut self.s));
1723 try!(self.word_space("as"));
1724 try!(self.print_type(&**ty));
1725 }
1726 ast::ExprIf(ref test, ref blk, ref elseopt) => {
1727 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1728 }
1729 ast::ExprIfLet(ref pat, ref expr, ref blk, ref elseopt) => {
1730 try!(self.print_if_let(&**pat, &**expr, &** blk, elseopt.as_ref().map(|e| &**e)));
1731 }
1732 ast::ExprWhile(ref test, ref blk, opt_ident) => {
1733 if let Some(ident) = opt_ident {
1734 try!(self.print_ident(ident));
1735 try!(self.word_space(":"));
1736 }
1737 try!(self.head("while"));
1738 try!(self.print_expr(&**test));
1739 try!(space(&mut self.s));
1740 try!(self.print_block(&**blk));
1741 }
1742 ast::ExprWhileLet(ref pat, ref expr, ref blk, opt_ident) => {
1743 if let Some(ident) = opt_ident {
1744 try!(self.print_ident(ident));
1745 try!(self.word_space(":"));
1746 }
1747 try!(self.head("while let"));
1748 try!(self.print_pat(&**pat));
1749 try!(space(&mut self.s));
1750 try!(self.word_space("="));
1751 try!(self.print_expr(&**expr));
1752 try!(space(&mut self.s));
1753 try!(self.print_block(&**blk));
1754 }
1755 ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
1756 if let Some(ident) = opt_ident {
1757 try!(self.print_ident(ident));
1758 try!(self.word_space(":"));
1759 }
1760 try!(self.head("for"));
1761 try!(self.print_pat(&**pat));
1762 try!(space(&mut self.s));
1763 try!(self.word_space("in"));
1764 try!(self.print_expr(&**iter));
1765 try!(space(&mut self.s));
1766 try!(self.print_block(&**blk));
1767 }
1768 ast::ExprLoop(ref blk, opt_ident) => {
1769 if let Some(ident) = opt_ident {
1770 try!(self.print_ident(ident));
1771 try!(self.word_space(":"));
1772 }
1773 try!(self.head("loop"));
1774 try!(space(&mut self.s));
1775 try!(self.print_block(&**blk));
1776 }
1777 ast::ExprMatch(ref expr, ref arms, _) => {
1778 try!(self.cbox(indent_unit));
1779 try!(self.ibox(4));
1780 try!(self.word_nbsp("match"));
1781 try!(self.print_expr(&**expr));
1782 try!(space(&mut self.s));
1783 try!(self.bopen());
1784 for arm in arms {
1785 try!(self.print_arm(arm));
1786 }
1787 try!(self.bclose_(expr.span, indent_unit));
1788 }
1789 ast::ExprClosure(capture_clause, ref decl, ref body) => {
1790 try!(self.print_capture_clause(capture_clause));
1791
1792 try!(self.print_fn_block_args(&**decl));
1793 try!(space(&mut self.s));
1794
1795 let default_return = match decl.output {
1796 ast::DefaultReturn(..) => true,
1797 _ => false
1798 };
1799
1800 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
1801 try!(self.print_block_unclosed(&**body));
1802 } else {
1803 // we extract the block, so as not to create another set of boxes
1804 match body.expr.as_ref().unwrap().node {
1805 ast::ExprBlock(ref blk) => {
1806 try!(self.print_block_unclosed(&**blk));
1807 }
1808 _ => {
1809 // this is a bare expression
1810 try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1811 try!(self.end()); // need to close a box
1812 }
1813 }
1814 }
1815 // a box will be closed by print_expr, but we didn't want an overall
1816 // wrapper so we closed the corresponding opening. so create an
1817 // empty box to satisfy the close.
1818 try!(self.ibox(0));
1819 }
1820 ast::ExprBlock(ref blk) => {
1821 // containing cbox, will be closed by print-block at }
1822 try!(self.cbox(indent_unit));
1823 // head-box, will be closed by print-block after {
1824 try!(self.ibox(0));
1825 try!(self.print_block(&**blk));
1826 }
1827 ast::ExprAssign(ref lhs, ref rhs) => {
1828 try!(self.print_expr(&**lhs));
1829 try!(space(&mut self.s));
1830 try!(self.word_space("="));
1831 try!(self.print_expr(&**rhs));
1832 }
1833 ast::ExprAssignOp(op, ref lhs, ref rhs) => {
1834 try!(self.print_expr(&**lhs));
1835 try!(space(&mut self.s));
1836 try!(word(&mut self.s, ast_util::binop_to_string(op.node)));
1837 try!(self.word_space("="));
1838 try!(self.print_expr(&**rhs));
1839 }
1840 ast::ExprField(ref expr, id) => {
1841 try!(self.print_expr(&**expr));
1842 try!(word(&mut self.s, "."));
1843 try!(self.print_ident(id.node));
1844 }
1845 ast::ExprTupField(ref expr, id) => {
1846 try!(self.print_expr(&**expr));
1847 try!(word(&mut self.s, "."));
1848 try!(self.print_usize(id.node));
1849 }
1850 ast::ExprIndex(ref expr, ref index) => {
1851 try!(self.print_expr(&**expr));
1852 try!(word(&mut self.s, "["));
1853 try!(self.print_expr(&**index));
1854 try!(word(&mut self.s, "]"));
1855 }
1856 ast::ExprRange(ref start, ref end) => {
1857 if let &Some(ref e) = start {
1858 try!(self.print_expr(&**e));
1859 }
1860 try!(word(&mut self.s, ".."));
1861 if let &Some(ref e) = end {
1862 try!(self.print_expr(&**e));
1863 }
1864 }
1865 ast::ExprPath(None, ref path) => {
1866 try!(self.print_path(path, true, 0))
1867 }
1868 ast::ExprPath(Some(ref qself), ref path) => {
1869 try!(self.print_qpath(path, qself, true))
1870 }
1871 ast::ExprBreak(opt_ident) => {
1872 try!(word(&mut self.s, "break"));
1873 try!(space(&mut self.s));
1874 if let Some(ident) = opt_ident {
1875 try!(self.print_ident(ident));
1876 try!(space(&mut self.s));
1877 }
1878 }
1879 ast::ExprAgain(opt_ident) => {
1880 try!(word(&mut self.s, "continue"));
1881 try!(space(&mut self.s));
1882 if let Some(ident) = opt_ident {
1883 try!(self.print_ident(ident));
1884 try!(space(&mut self.s))
1885 }
1886 }
1887 ast::ExprRet(ref result) => {
1888 try!(word(&mut self.s, "return"));
1889 match *result {
1890 Some(ref expr) => {
1891 try!(word(&mut self.s, " "));
1892 try!(self.print_expr(&**expr));
1893 }
1894 _ => ()
1895 }
1896 }
1897 ast::ExprInlineAsm(ref a) => {
1898 try!(word(&mut self.s, "asm!"));
1899 try!(self.popen());
1900 try!(self.print_string(&a.asm, a.asm_str_style));
1901 try!(self.word_space(":"));
1902
1903 try!(self.commasep(Inconsistent, &a.outputs,
1904 |s, &(ref co, ref o, is_rw)| {
1905 match co.slice_shift_char() {
1906 Some(('=', operand)) if is_rw => {
1907 try!(s.print_string(&format!("+{}", operand),
1908 ast::CookedStr))
1909 }
1910 _ => try!(s.print_string(&co, ast::CookedStr))
1911 }
1912 try!(s.popen());
1913 try!(s.print_expr(&**o));
1914 try!(s.pclose());
1915 Ok(())
1916 }));
1917 try!(space(&mut self.s));
1918 try!(self.word_space(":"));
1919
1920 try!(self.commasep(Inconsistent, &a.inputs,
1921 |s, &(ref co, ref o)| {
1922 try!(s.print_string(&co, ast::CookedStr));
1923 try!(s.popen());
1924 try!(s.print_expr(&**o));
1925 try!(s.pclose());
1926 Ok(())
1927 }));
1928 try!(space(&mut self.s));
1929 try!(self.word_space(":"));
1930
1931 try!(self.commasep(Inconsistent, &a.clobbers,
1932 |s, co| {
1933 try!(s.print_string(&co, ast::CookedStr));
1934 Ok(())
1935 }));
1936
1937 let mut options = vec!();
1938 if a.volatile {
1939 options.push("volatile");
1940 }
1941 if a.alignstack {
1942 options.push("alignstack");
1943 }
1944 if a.dialect == ast::AsmDialect::AsmIntel {
1945 options.push("intel");
1946 }
1947
1948 if !options.is_empty() {
1949 try!(space(&mut self.s));
1950 try!(self.word_space(":"));
1951 try!(self.commasep(Inconsistent, &*options,
1952 |s, &co| {
1953 try!(s.print_string(co, ast::CookedStr));
1954 Ok(())
1955 }));
1956 }
1957
1958 try!(self.pclose());
1959 }
1960 ast::ExprMac(ref m) => try!(self.print_mac(m, token::Paren)),
1961 ast::ExprParen(ref e) => {
1962 try!(self.popen());
1963 try!(self.print_expr(&**e));
1964 try!(self.pclose());
1965 }
1966 }
1967 try!(self.ann.post(self, NodeExpr(expr)));
1968 self.end()
1969 }
1970
1971 pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
1972 try!(self.print_pat(&*loc.pat));
1973 if let Some(ref ty) = loc.ty {
1974 try!(self.word_space(":"));
1975 try!(self.print_type(&**ty));
1976 }
1977 Ok(())
1978 }
1979
1980 pub fn print_decl(&mut self, decl: &ast::Decl) -> io::Result<()> {
1981 try!(self.maybe_print_comment(decl.span.lo));
1982 match decl.node {
1983 ast::DeclLocal(ref loc) => {
1984 try!(self.space_if_not_bol());
1985 try!(self.ibox(indent_unit));
1986 try!(self.word_nbsp("let"));
1987
1988 try!(self.ibox(indent_unit));
1989 try!(self.print_local_decl(&**loc));
1990 try!(self.end());
1991 if let Some(ref init) = loc.init {
1992 try!(self.nbsp());
1993 try!(self.word_space("="));
1994 try!(self.print_expr(&**init));
1995 }
1996 self.end()
1997 }
1998 ast::DeclItem(ref item) => self.print_item(&**item)
1999 }
2000 }
2001
2002 pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2003 try!(word(&mut self.s, &token::get_ident(ident)));
2004 self.ann.post(self, NodeIdent(&ident))
2005 }
2006
2007 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2008 word(&mut self.s, &i.to_string())
2009 }
2010
2011 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2012 try!(word(&mut self.s, &token::get_name(name)));
2013 self.ann.post(self, NodeName(&name))
2014 }
2015
2016 pub fn print_for_decl(&mut self, loc: &ast::Local,
2017 coll: &ast::Expr) -> io::Result<()> {
2018 try!(self.print_local_decl(loc));
2019 try!(space(&mut self.s));
2020 try!(self.word_space("in"));
2021 self.print_expr(coll)
2022 }
2023
2024 fn print_path(&mut self,
2025 path: &ast::Path,
2026 colons_before_params: bool,
2027 depth: usize)
2028 -> io::Result<()>
2029 {
2030 try!(self.maybe_print_comment(path.span.lo));
2031
2032 let mut first = !path.global;
2033 for segment in &path.segments[..path.segments.len()-depth] {
2034 if first {
2035 first = false
2036 } else {
2037 try!(word(&mut self.s, "::"))
2038 }
2039
2040 try!(self.print_ident(segment.identifier));
2041
2042 try!(self.print_path_parameters(&segment.parameters, colons_before_params));
2043 }
2044
2045 Ok(())
2046 }
2047
2048 fn print_qpath(&mut self,
2049 path: &ast::Path,
2050 qself: &ast::QSelf,
2051 colons_before_params: bool)
2052 -> io::Result<()>
2053 {
2054 try!(word(&mut self.s, "<"));
2055 try!(self.print_type(&qself.ty));
2056 if qself.position > 0 {
2057 try!(space(&mut self.s));
2058 try!(self.word_space("as"));
2059 let depth = path.segments.len() - qself.position;
2060 try!(self.print_path(&path, false, depth));
2061 }
2062 try!(word(&mut self.s, ">"));
2063 try!(word(&mut self.s, "::"));
2064 let item_segment = path.segments.last().unwrap();
2065 try!(self.print_ident(item_segment.identifier));
2066 self.print_path_parameters(&item_segment.parameters, colons_before_params)
2067 }
2068
2069 fn print_path_parameters(&mut self,
2070 parameters: &ast::PathParameters,
2071 colons_before_params: bool)
2072 -> io::Result<()>
2073 {
2074 if parameters.is_empty() {
2075 return Ok(());
2076 }
2077
2078 if colons_before_params {
2079 try!(word(&mut self.s, "::"))
2080 }
2081
2082 match *parameters {
2083 ast::AngleBracketedParameters(ref data) => {
2084 try!(word(&mut self.s, "<"));
2085
2086 let mut comma = false;
2087 for lifetime in &data.lifetimes {
2088 if comma {
2089 try!(self.word_space(","))
2090 }
2091 try!(self.print_lifetime(lifetime));
2092 comma = true;
2093 }
2094
2095 if !data.types.is_empty() {
2096 if comma {
2097 try!(self.word_space(","))
2098 }
2099 try!(self.commasep(
2100 Inconsistent,
2101 &data.types,
2102 |s, ty| s.print_type(&**ty)));
2103 comma = true;
2104 }
2105
2106 for binding in &*data.bindings {
2107 if comma {
2108 try!(self.word_space(","))
2109 }
2110 try!(self.print_ident(binding.ident));
2111 try!(space(&mut self.s));
2112 try!(self.word_space("="));
2113 try!(self.print_type(&*binding.ty));
2114 comma = true;
2115 }
2116
2117 try!(word(&mut self.s, ">"))
2118 }
2119
2120 ast::ParenthesizedParameters(ref data) => {
2121 try!(word(&mut self.s, "("));
2122 try!(self.commasep(
2123 Inconsistent,
2124 &data.inputs,
2125 |s, ty| s.print_type(&**ty)));
2126 try!(word(&mut self.s, ")"));
2127
2128 match data.output {
2129 None => { }
2130 Some(ref ty) => {
2131 try!(self.space_if_not_bol());
2132 try!(self.word_space("->"));
2133 try!(self.print_type(&**ty));
2134 }
2135 }
2136 }
2137 }
2138
2139 Ok(())
2140 }
2141
2142 pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2143 try!(self.maybe_print_comment(pat.span.lo));
2144 try!(self.ann.pre(self, NodePat(pat)));
2145 /* Pat isn't normalized, but the beauty of it
2146 is that it doesn't matter */
2147 match pat.node {
2148 ast::PatWild(ast::PatWildSingle) => try!(word(&mut self.s, "_")),
2149 ast::PatWild(ast::PatWildMulti) => try!(word(&mut self.s, "..")),
2150 ast::PatIdent(binding_mode, ref path1, ref sub) => {
2151 match binding_mode {
2152 ast::BindByRef(mutbl) => {
2153 try!(self.word_nbsp("ref"));
2154 try!(self.print_mutability(mutbl));
2155 }
2156 ast::BindByValue(ast::MutImmutable) => {}
2157 ast::BindByValue(ast::MutMutable) => {
2158 try!(self.word_nbsp("mut"));
2159 }
2160 }
2161 try!(self.print_ident(path1.node));
2162 match *sub {
2163 Some(ref p) => {
2164 try!(word(&mut self.s, "@"));
2165 try!(self.print_pat(&**p));
2166 }
2167 None => ()
2168 }
2169 }
2170 ast::PatEnum(ref path, ref args_) => {
2171 try!(self.print_path(path, true, 0));
2172 match *args_ {
2173 None => try!(word(&mut self.s, "(..)")),
2174 Some(ref args) => {
2175 if !args.is_empty() {
2176 try!(self.popen());
2177 try!(self.commasep(Inconsistent, &args[..],
2178 |s, p| s.print_pat(&**p)));
2179 try!(self.pclose());
2180 }
2181 }
2182 }
2183 }
2184 ast::PatQPath(ref qself, ref path) => {
2185 try!(self.print_qpath(path, qself, false));
2186 }
2187 ast::PatStruct(ref path, ref fields, etc) => {
2188 try!(self.print_path(path, true, 0));
2189 try!(self.nbsp());
2190 try!(self.word_space("{"));
2191 try!(self.commasep_cmnt(
2192 Consistent, &fields[..],
2193 |s, f| {
2194 try!(s.cbox(indent_unit));
2195 if !f.node.is_shorthand {
2196 try!(s.print_ident(f.node.ident));
2197 try!(s.word_nbsp(":"));
2198 }
2199 try!(s.print_pat(&*f.node.pat));
2200 s.end()
2201 },
2202 |f| f.node.pat.span));
2203 if etc {
2204 if !fields.is_empty() { try!(self.word_space(",")); }
2205 try!(word(&mut self.s, ".."));
2206 }
2207 try!(space(&mut self.s));
2208 try!(word(&mut self.s, "}"));
2209 }
2210 ast::PatTup(ref elts) => {
2211 try!(self.popen());
2212 try!(self.commasep(Inconsistent,
2213 &elts[..],
2214 |s, p| s.print_pat(&**p)));
2215 if elts.len() == 1 {
2216 try!(word(&mut self.s, ","));
2217 }
2218 try!(self.pclose());
2219 }
2220 ast::PatBox(ref inner) => {
2221 try!(word(&mut self.s, "box "));
2222 try!(self.print_pat(&**inner));
2223 }
2224 ast::PatRegion(ref inner, mutbl) => {
2225 try!(word(&mut self.s, "&"));
2226 if mutbl == ast::MutMutable {
2227 try!(word(&mut self.s, "mut "));
2228 }
2229 try!(self.print_pat(&**inner));
2230 }
2231 ast::PatLit(ref e) => try!(self.print_expr(&**e)),
2232 ast::PatRange(ref begin, ref end) => {
2233 try!(self.print_expr(&**begin));
2234 try!(space(&mut self.s));
2235 try!(word(&mut self.s, "..."));
2236 try!(self.print_expr(&**end));
2237 }
2238 ast::PatVec(ref before, ref slice, ref after) => {
2239 try!(word(&mut self.s, "["));
2240 try!(self.commasep(Inconsistent,
2241 &before[..],
2242 |s, p| s.print_pat(&**p)));
2243 if let Some(ref p) = *slice {
2244 if !before.is_empty() { try!(self.word_space(",")); }
2245 try!(self.print_pat(&**p));
2246 match **p {
2247 ast::Pat { node: ast::PatWild(ast::PatWildMulti), .. } => {
2248 // this case is handled by print_pat
2249 }
2250 _ => try!(word(&mut self.s, "..")),
2251 }
2252 if !after.is_empty() { try!(self.word_space(",")); }
2253 }
2254 try!(self.commasep(Inconsistent,
2255 &after[..],
2256 |s, p| s.print_pat(&**p)));
2257 try!(word(&mut self.s, "]"));
2258 }
2259 ast::PatMac(ref m) => try!(self.print_mac(m, token::Paren)),
2260 }
2261 self.ann.post(self, NodePat(pat))
2262 }
2263
2264 fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2265 // I have no idea why this check is necessary, but here it
2266 // is :(
2267 if arm.attrs.is_empty() {
2268 try!(space(&mut self.s));
2269 }
2270 try!(self.cbox(indent_unit));
2271 try!(self.ibox(0));
2272 try!(self.print_outer_attributes(&arm.attrs));
2273 let mut first = true;
2274 for p in &arm.pats {
2275 if first {
2276 first = false;
2277 } else {
2278 try!(space(&mut self.s));
2279 try!(self.word_space("|"));
2280 }
2281 try!(self.print_pat(&**p));
2282 }
2283 try!(space(&mut self.s));
2284 if let Some(ref e) = arm.guard {
2285 try!(self.word_space("if"));
2286 try!(self.print_expr(&**e));
2287 try!(space(&mut self.s));
2288 }
2289 try!(self.word_space("=>"));
2290
2291 match arm.body.node {
2292 ast::ExprBlock(ref blk) => {
2293 // the block will close the pattern's ibox
2294 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
2295
2296 // If it is a user-provided unsafe block, print a comma after it
2297 if let ast::UnsafeBlock(ast::UserProvided) = blk.rules {
2298 try!(word(&mut self.s, ","));
2299 }
2300 }
2301 _ => {
2302 try!(self.end()); // close the ibox for the pattern
2303 try!(self.print_expr(&*arm.body));
2304 try!(word(&mut self.s, ","));
2305 }
2306 }
2307 self.end() // close enclosing cbox
2308 }
2309
2310 // Returns whether it printed anything
2311 fn print_explicit_self(&mut self,
2312 explicit_self: &ast::ExplicitSelf_,
2313 mutbl: ast::Mutability) -> io::Result<bool> {
2314 try!(self.print_mutability(mutbl));
2315 match *explicit_self {
2316 ast::SelfStatic => { return Ok(false); }
2317 ast::SelfValue(_) => {
2318 try!(word(&mut self.s, "self"));
2319 }
2320 ast::SelfRegion(ref lt, m, _) => {
2321 try!(word(&mut self.s, "&"));
2322 try!(self.print_opt_lifetime(lt));
2323 try!(self.print_mutability(m));
2324 try!(word(&mut self.s, "self"));
2325 }
2326 ast::SelfExplicit(ref typ, _) => {
2327 try!(word(&mut self.s, "self"));
2328 try!(self.word_space(":"));
2329 try!(self.print_type(&**typ));
2330 }
2331 }
2332 return Ok(true);
2333 }
2334
2335 pub fn print_fn(&mut self,
2336 decl: &ast::FnDecl,
2337 unsafety: ast::Unsafety,
2338 abi: abi::Abi,
2339 name: Option<ast::Ident>,
2340 generics: &ast::Generics,
2341 opt_explicit_self: Option<&ast::ExplicitSelf_>,
2342 vis: ast::Visibility) -> io::Result<()> {
2343 try!(self.print_fn_header_info(unsafety, abi, vis));
2344
2345 if let Some(name) = name {
2346 try!(self.nbsp());
2347 try!(self.print_ident(name));
2348 }
2349 try!(self.print_generics(generics));
2350 try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
2351 self.print_where_clause(&generics.where_clause)
2352 }
2353
2354 pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
2355 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2356 -> io::Result<()> {
2357 // It is unfortunate to duplicate the commasep logic, but we want the
2358 // self type and the args all in the same box.
2359 try!(self.rbox(0, Inconsistent));
2360 let mut first = true;
2361 if let Some(explicit_self) = opt_explicit_self {
2362 let m = match explicit_self {
2363 &ast::SelfStatic => ast::MutImmutable,
2364 _ => match decl.inputs[0].pat.node {
2365 ast::PatIdent(ast::BindByValue(m), _, _) => m,
2366 _ => ast::MutImmutable
2367 }
2368 };
2369 first = !try!(self.print_explicit_self(explicit_self, m));
2370 }
2371
2372 // HACK(eddyb) ignore the separately printed self argument.
2373 let args = if first {
2374 &decl.inputs[..]
2375 } else {
2376 &decl.inputs[1..]
2377 };
2378
2379 for arg in args {
2380 if first { first = false; } else { try!(self.word_space(",")); }
2381 try!(self.print_arg(arg));
2382 }
2383
2384 self.end()
2385 }
2386
2387 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
2388 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2389 -> io::Result<()> {
2390 try!(self.popen());
2391 try!(self.print_fn_args(decl, opt_explicit_self));
2392 if decl.variadic {
2393 try!(word(&mut self.s, ", ..."));
2394 }
2395 try!(self.pclose());
2396
2397 self.print_fn_output(decl)
2398 }
2399
2400 pub fn print_fn_block_args(
2401 &mut self,
2402 decl: &ast::FnDecl)
2403 -> io::Result<()> {
2404 try!(word(&mut self.s, "|"));
2405 try!(self.print_fn_args(decl, None));
2406 try!(word(&mut self.s, "|"));
2407
2408 if let ast::DefaultReturn(..) = decl.output {
2409 return Ok(());
2410 }
2411
2412 try!(self.space_if_not_bol());
2413 try!(self.word_space("->"));
2414 match decl.output {
2415 ast::Return(ref ty) => {
2416 try!(self.print_type(&**ty));
2417 self.maybe_print_comment(ty.span.lo)
2418 }
2419 ast::DefaultReturn(..) => unreachable!(),
2420 ast::NoReturn(span) => {
2421 try!(self.word_nbsp("!"));
2422 self.maybe_print_comment(span.lo)
2423 }
2424 }
2425 }
2426
2427 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
2428 -> io::Result<()> {
2429 match capture_clause {
2430 ast::CaptureByValue => self.word_space("move"),
2431 ast::CaptureByRef => Ok(()),
2432 }
2433 }
2434
2435 pub fn print_bounds(&mut self,
2436 prefix: &str,
2437 bounds: &[ast::TyParamBound])
2438 -> io::Result<()> {
2439 if !bounds.is_empty() {
2440 try!(word(&mut self.s, prefix));
2441 let mut first = true;
2442 for bound in bounds {
2443 try!(self.nbsp());
2444 if first {
2445 first = false;
2446 } else {
2447 try!(self.word_space("+"));
2448 }
2449
2450 try!(match *bound {
2451 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2452 self.print_poly_trait_ref(tref)
2453 }
2454 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2455 try!(word(&mut self.s, "?"));
2456 self.print_poly_trait_ref(tref)
2457 }
2458 RegionTyParamBound(ref lt) => {
2459 self.print_lifetime(lt)
2460 }
2461 })
2462 }
2463 Ok(())
2464 } else {
2465 Ok(())
2466 }
2467 }
2468
2469 pub fn print_lifetime(&mut self,
2470 lifetime: &ast::Lifetime)
2471 -> io::Result<()>
2472 {
2473 self.print_name(lifetime.name)
2474 }
2475
2476 pub fn print_lifetime_def(&mut self,
2477 lifetime: &ast::LifetimeDef)
2478 -> io::Result<()>
2479 {
2480 try!(self.print_lifetime(&lifetime.lifetime));
2481 let mut sep = ":";
2482 for v in &lifetime.bounds {
2483 try!(word(&mut self.s, sep));
2484 try!(self.print_lifetime(v));
2485 sep = "+";
2486 }
2487 Ok(())
2488 }
2489
2490 pub fn print_generics(&mut self,
2491 generics: &ast::Generics)
2492 -> io::Result<()>
2493 {
2494 let total = generics.lifetimes.len() + generics.ty_params.len();
2495 if total == 0 {
2496 return Ok(());
2497 }
2498
2499 try!(word(&mut self.s, "<"));
2500
2501 let mut ints = Vec::new();
2502 for i in 0..total {
2503 ints.push(i);
2504 }
2505
2506 try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2507 if idx < generics.lifetimes.len() {
2508 let lifetime = &generics.lifetimes[idx];
2509 s.print_lifetime_def(lifetime)
2510 } else {
2511 let idx = idx - generics.lifetimes.len();
2512 let param = &generics.ty_params[idx];
2513 s.print_ty_param(param)
2514 }
2515 }));
2516
2517 try!(word(&mut self.s, ">"));
2518 Ok(())
2519 }
2520
2521 pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2522 try!(self.print_ident(param.ident));
2523 try!(self.print_bounds(":", &param.bounds));
2524 match param.default {
2525 Some(ref default) => {
2526 try!(space(&mut self.s));
2527 try!(self.word_space("="));
2528 self.print_type(&**default)
2529 }
2530 _ => Ok(())
2531 }
2532 }
2533
2534 pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2535 -> io::Result<()> {
2536 if where_clause.predicates.is_empty() {
2537 return Ok(())
2538 }
2539
2540 try!(space(&mut self.s));
2541 try!(self.word_space("where"));
2542
2543 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2544 if i != 0 {
2545 try!(self.word_space(","));
2546 }
2547
2548 match predicate {
2549 &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2550 ref bounded_ty,
2551 ref bounds,
2552 ..}) => {
2553 try!(self.print_formal_lifetime_list(bound_lifetimes));
2554 try!(self.print_type(&**bounded_ty));
2555 try!(self.print_bounds(":", bounds));
2556 }
2557 &ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2558 ref bounds,
2559 ..}) => {
2560 try!(self.print_lifetime(lifetime));
2561 try!(word(&mut self.s, ":"));
2562
2563 for (i, bound) in bounds.iter().enumerate() {
2564 try!(self.print_lifetime(bound));
2565
2566 if i != 0 {
2567 try!(word(&mut self.s, ":"));
2568 }
2569 }
2570 }
2571 &ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
2572 try!(self.print_path(path, false, 0));
2573 try!(space(&mut self.s));
2574 try!(self.word_space("="));
2575 try!(self.print_type(&**ty));
2576 }
2577 }
2578 }
2579
2580 Ok(())
2581 }
2582
2583 pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
2584 try!(self.ibox(indent_unit));
2585 match item.node {
2586 ast::MetaWord(ref name) => {
2587 try!(word(&mut self.s, &name));
2588 }
2589 ast::MetaNameValue(ref name, ref value) => {
2590 try!(self.word_space(&name[..]));
2591 try!(self.word_space("="));
2592 try!(self.print_literal(value));
2593 }
2594 ast::MetaList(ref name, ref items) => {
2595 try!(word(&mut self.s, &name));
2596 try!(self.popen());
2597 try!(self.commasep(Consistent,
2598 &items[..],
2599 |s, i| s.print_meta_item(&**i)));
2600 try!(self.pclose());
2601 }
2602 }
2603 self.end()
2604 }
2605
2606 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2607 match vp.node {
2608 ast::ViewPathSimple(ident, ref path) => {
2609 try!(self.print_path(path, false, 0));
2610
2611 // FIXME(#6993) can't compare identifiers directly here
2612 if path.segments.last().unwrap().identifier.name !=
2613 ident.name {
2614 try!(space(&mut self.s));
2615 try!(self.word_space("as"));
2616 try!(self.print_ident(ident));
2617 }
2618
2619 Ok(())
2620 }
2621
2622 ast::ViewPathGlob(ref path) => {
2623 try!(self.print_path(path, false, 0));
2624 word(&mut self.s, "::*")
2625 }
2626
2627 ast::ViewPathList(ref path, ref idents) => {
2628 if path.segments.is_empty() {
2629 try!(word(&mut self.s, "{"));
2630 } else {
2631 try!(self.print_path(path, false, 0));
2632 try!(word(&mut self.s, "::{"));
2633 }
2634 try!(self.commasep(Inconsistent, &idents[..], |s, w| {
2635 match w.node {
2636 ast::PathListIdent { name, .. } => {
2637 s.print_ident(name)
2638 },
2639 ast::PathListMod { .. } => {
2640 word(&mut s.s, "self")
2641 }
2642 }
2643 }));
2644 word(&mut self.s, "}")
2645 }
2646 }
2647 }
2648
2649 pub fn print_mutability(&mut self,
2650 mutbl: ast::Mutability) -> io::Result<()> {
2651 match mutbl {
2652 ast::MutMutable => self.word_nbsp("mut"),
2653 ast::MutImmutable => Ok(()),
2654 }
2655 }
2656
2657 pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2658 try!(self.print_mutability(mt.mutbl));
2659 self.print_type(&*mt.ty)
2660 }
2661
2662 pub fn print_arg(&mut self, input: &ast::Arg) -> io::Result<()> {
2663 try!(self.ibox(indent_unit));
2664 match input.ty.node {
2665 ast::TyInfer => try!(self.print_pat(&*input.pat)),
2666 _ => {
2667 match input.pat.node {
2668 ast::PatIdent(_, ref path1, _) if
2669 path1.node.name ==
2670 parse::token::special_idents::invalid.name => {
2671 // Do nothing.
2672 }
2673 _ => {
2674 try!(self.print_pat(&*input.pat));
2675 try!(word(&mut self.s, ":"));
2676 try!(space(&mut self.s));
2677 }
2678 }
2679 try!(self.print_type(&*input.ty));
2680 }
2681 }
2682 self.end()
2683 }
2684
2685 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2686 if let ast::DefaultReturn(..) = decl.output {
2687 return Ok(());
2688 }
2689
2690 try!(self.space_if_not_bol());
2691 try!(self.ibox(indent_unit));
2692 try!(self.word_space("->"));
2693 match decl.output {
2694 ast::NoReturn(_) =>
2695 try!(self.word_nbsp("!")),
2696 ast::DefaultReturn(..) => unreachable!(),
2697 ast::Return(ref ty) =>
2698 try!(self.print_type(&**ty))
2699 }
2700 try!(self.end());
2701
2702 match decl.output {
2703 ast::Return(ref output) => self.maybe_print_comment(output.span.lo),
2704 _ => Ok(())
2705 }
2706 }
2707
2708 pub fn print_ty_fn(&mut self,
2709 abi: abi::Abi,
2710 unsafety: ast::Unsafety,
2711 decl: &ast::FnDecl,
2712 name: Option<ast::Ident>,
2713 generics: &ast::Generics,
2714 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2715 -> io::Result<()> {
2716 try!(self.ibox(indent_unit));
2717 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2718 try!(word(&mut self.s, "for"));
2719 try!(self.print_generics(generics));
2720 }
2721 let generics = ast::Generics {
2722 lifetimes: Vec::new(),
2723 ty_params: OwnedSlice::empty(),
2724 where_clause: ast::WhereClause {
2725 id: ast::DUMMY_NODE_ID,
2726 predicates: Vec::new(),
2727 },
2728 };
2729 try!(self.print_fn(decl, unsafety, abi, name,
2730 &generics, opt_explicit_self,
2731 ast::Inherited));
2732 self.end()
2733 }
2734
2735 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2736 next_pos: Option<BytePos>)
2737 -> io::Result<()> {
2738 let cm = match self.cm {
2739 Some(cm) => cm,
2740 _ => return Ok(())
2741 };
2742 match self.next_comment() {
2743 Some(ref cmnt) => {
2744 if (*cmnt).style != comments::Trailing { return Ok(()) }
2745 let span_line = cm.lookup_char_pos(span.hi);
2746 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2747 let mut next = (*cmnt).pos + BytePos(1);
2748 match next_pos { None => (), Some(p) => next = p }
2749 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2750 span_line.line == comment_line.line {
2751 try!(self.print_comment(cmnt));
2752 self.cur_cmnt_and_lit.cur_cmnt += 1;
2753 }
2754 }
2755 _ => ()
2756 }
2757 Ok(())
2758 }
2759
2760 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2761 // If there aren't any remaining comments, then we need to manually
2762 // make sure there is a line break at the end.
2763 if self.next_comment().is_none() {
2764 try!(hardbreak(&mut self.s));
2765 }
2766 loop {
2767 match self.next_comment() {
2768 Some(ref cmnt) => {
2769 try!(self.print_comment(cmnt));
2770 self.cur_cmnt_and_lit.cur_cmnt += 1;
2771 }
2772 _ => break
2773 }
2774 }
2775 Ok(())
2776 }
2777
2778 pub fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
2779 try!(self.maybe_print_comment(lit.span.lo));
2780 match self.next_lit(lit.span.lo) {
2781 Some(ref ltrl) => {
2782 return word(&mut self.s, &(*ltrl).lit);
2783 }
2784 _ => ()
2785 }
2786 match lit.node {
2787 ast::LitStr(ref st, style) => self.print_string(&st, style),
2788 ast::LitByte(byte) => {
2789 let mut res = String::from("b'");
2790 res.extend(ascii::escape_default(byte).map(|c| c as char));
2791 res.push('\'');
2792 word(&mut self.s, &res[..])
2793 }
2794 ast::LitChar(ch) => {
2795 let mut res = String::from("'");
2796 res.extend(ch.escape_default());
2797 res.push('\'');
2798 word(&mut self.s, &res[..])
2799 }
2800 ast::LitInt(i, t) => {
2801 match t {
2802 ast::SignedIntLit(st, ast::Plus) => {
2803 word(&mut self.s,
2804 &ast_util::int_ty_to_string(st, Some(i as i64)))
2805 }
2806 ast::SignedIntLit(st, ast::Minus) => {
2807 let istr = ast_util::int_ty_to_string(st, Some(-(i as i64)));
2808 word(&mut self.s,
2809 &format!("-{}", istr))
2810 }
2811 ast::UnsignedIntLit(ut) => {
2812 word(&mut self.s, &ast_util::uint_ty_to_string(ut, Some(i)))
2813 }
2814 ast::UnsuffixedIntLit(ast::Plus) => {
2815 word(&mut self.s, &format!("{}", i))
2816 }
2817 ast::UnsuffixedIntLit(ast::Minus) => {
2818 word(&mut self.s, &format!("-{}", i))
2819 }
2820 }
2821 }
2822 ast::LitFloat(ref f, t) => {
2823 word(&mut self.s,
2824 &format!(
2825 "{}{}",
2826 &f,
2827 &ast_util::float_ty_to_string(t)))
2828 }
2829 ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, &f[..]),
2830 ast::LitBool(val) => {
2831 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2832 }
2833 ast::LitBinary(ref v) => {
2834 let mut escaped: String = String::new();
2835 for &ch in &**v {
2836 escaped.extend(ascii::escape_default(ch)
2837 .map(|c| c as char));
2838 }
2839 word(&mut self.s, &format!("b\"{}\"", escaped))
2840 }
2841 }
2842 }
2843
2844 pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2845 match self.literals {
2846 Some(ref lits) => {
2847 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2848 let ltrl = (*lits)[self.cur_cmnt_and_lit.cur_lit].clone();
2849 if ltrl.pos > pos { return None; }
2850 self.cur_cmnt_and_lit.cur_lit += 1;
2851 if ltrl.pos == pos { return Some(ltrl); }
2852 }
2853 None
2854 }
2855 _ => None
2856 }
2857 }
2858
2859 pub fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
2860 loop {
2861 match self.next_comment() {
2862 Some(ref cmnt) => {
2863 if (*cmnt).pos < pos {
2864 try!(self.print_comment(cmnt));
2865 self.cur_cmnt_and_lit.cur_cmnt += 1;
2866 } else { break; }
2867 }
2868 _ => break
2869 }
2870 }
2871 Ok(())
2872 }
2873
2874 pub fn print_comment(&mut self,
2875 cmnt: &comments::Comment) -> io::Result<()> {
2876 match cmnt.style {
2877 comments::Mixed => {
2878 assert_eq!(cmnt.lines.len(), 1);
2879 try!(zerobreak(&mut self.s));
2880 try!(word(&mut self.s, &cmnt.lines[0]));
2881 zerobreak(&mut self.s)
2882 }
2883 comments::Isolated => {
2884 try!(self.hardbreak_if_not_bol());
2885 for line in &cmnt.lines {
2886 // Don't print empty lines because they will end up as trailing
2887 // whitespace
2888 if !line.is_empty() {
2889 try!(word(&mut self.s, &line[..]));
2890 }
2891 try!(hardbreak(&mut self.s));
2892 }
2893 Ok(())
2894 }
2895 comments::Trailing => {
2896 try!(word(&mut self.s, " "));
2897 if cmnt.lines.len() == 1 {
2898 try!(word(&mut self.s, &cmnt.lines[0]));
2899 hardbreak(&mut self.s)
2900 } else {
2901 try!(self.ibox(0));
2902 for line in &cmnt.lines {
2903 if !line.is_empty() {
2904 try!(word(&mut self.s, &line[..]));
2905 }
2906 try!(hardbreak(&mut self.s));
2907 }
2908 self.end()
2909 }
2910 }
2911 comments::BlankLine => {
2912 // We need to do at least one, possibly two hardbreaks.
2913 let is_semi = match self.s.last_token() {
2914 pp::Token::String(s, _) => ";" == s,
2915 _ => false
2916 };
2917 if is_semi || self.is_begin() || self.is_end() {
2918 try!(hardbreak(&mut self.s));
2919 }
2920 hardbreak(&mut self.s)
2921 }
2922 }
2923 }
2924
2925 pub fn print_string(&mut self, st: &str,
2926 style: ast::StrStyle) -> io::Result<()> {
2927 let st = match style {
2928 ast::CookedStr => {
2929 (format!("\"{}\"", st.escape_default()))
2930 }
2931 ast::RawStr(n) => {
2932 (format!("r{delim}\"{string}\"{delim}",
2933 delim=repeat("#", n),
2934 string=st))
2935 }
2936 };
2937 word(&mut self.s, &st[..])
2938 }
2939
2940 pub fn next_comment(&mut self) -> Option<comments::Comment> {
2941 match self.comments {
2942 Some(ref cmnts) => {
2943 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2944 Some(cmnts[self.cur_cmnt_and_lit.cur_cmnt].clone())
2945 } else {
2946 None
2947 }
2948 }
2949 _ => None
2950 }
2951 }
2952
2953 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2954 opt_abi: Option<abi::Abi>)
2955 -> io::Result<()> {
2956 match opt_abi {
2957 Some(abi::Rust) => Ok(()),
2958 Some(abi) => {
2959 try!(self.word_nbsp("extern"));
2960 self.word_nbsp(&abi.to_string())
2961 }
2962 None => Ok(())
2963 }
2964 }
2965
2966 pub fn print_extern_opt_abi(&mut self,
2967 opt_abi: Option<abi::Abi>) -> io::Result<()> {
2968 match opt_abi {
2969 Some(abi) => {
2970 try!(self.word_nbsp("extern"));
2971 self.word_nbsp(&abi.to_string())
2972 }
2973 None => Ok(())
2974 }
2975 }
2976
2977 pub fn print_fn_header_info(&mut self,
2978 unsafety: ast::Unsafety,
2979 abi: abi::Abi,
2980 vis: ast::Visibility) -> io::Result<()> {
2981 try!(word(&mut self.s, &visibility_qualified(vis, "")));
2982 try!(self.print_unsafety(unsafety));
2983
2984 if abi != abi::Rust {
2985 try!(self.word_nbsp("extern"));
2986 try!(self.word_nbsp(&abi.to_string()));
2987 }
2988
2989 word(&mut self.s, "fn")
2990 }
2991
2992 pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
2993 match s {
2994 ast::Unsafety::Normal => Ok(()),
2995 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2996 }
2997 }
2998 }
2999
3000 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3001
3002 #[cfg(test)]
3003 mod tests {
3004 use super::*;
3005
3006 use ast;
3007 use ast_util;
3008 use codemap;
3009 use parse::token;
3010
3011 #[test]
3012 fn test_fun_to_string() {
3013 let abba_ident = token::str_to_ident("abba");
3014
3015 let decl = ast::FnDecl {
3016 inputs: Vec::new(),
3017 output: ast::DefaultReturn(codemap::DUMMY_SP),
3018 variadic: false
3019 };
3020 let generics = ast_util::empty_generics();
3021 assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal, abba_ident,
3022 None, &generics),
3023 "fn abba()");
3024 }
3025
3026 #[test]
3027 fn test_variant_to_string() {
3028 let ident = token::str_to_ident("principal_skinner");
3029
3030 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
3031 name: ident,
3032 attrs: Vec::new(),
3033 // making this up as I go.... ?
3034 kind: ast::TupleVariantKind(Vec::new()),
3035 id: 0,
3036 disr_expr: None,
3037 vis: ast::Public,
3038 });
3039
3040 let varstr = variant_to_string(&var);
3041 assert_eq!(varstr, "pub principal_skinner");
3042 }
3043
3044 #[test]
3045 fn test_signed_int_to_string() {
3046 let pos_int = ast::LitInt(42, ast::SignedIntLit(ast::TyI32, ast::Plus));
3047 let neg_int = ast::LitInt((!42 + 1) as u64, ast::SignedIntLit(ast::TyI32, ast::Minus));
3048 assert_eq!(format!("-{}", lit_to_string(&codemap::dummy_spanned(pos_int))),
3049 lit_to_string(&codemap::dummy_spanned(neg_int)));
3050 }
3051 }