rust/src/libsyntax/print/pprust.rs

3034 lines
109 KiB
Rust
Raw Normal View History

2014-07-27 11:50:46 +00:00
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub use self::AnnNode::*;
use abi;
use ast;
use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
use ast_util;
use attr;
use owned_slice::OwnedSlice;
use attr::{AttrMetaMethods, AttributeMethods};
2015-01-04 03:42:21 +00:00
use codemap::{self, CodeMap, BytePos};
use diagnostic;
use parse::token::{self, BinOpToken, Token, InternedString};
2014-05-21 23:57:31 +00:00
use parse::lexer::comments;
use parse;
2015-01-04 03:42:21 +00:00
use print::pp::{self, break_offset, word, space, zerobreak, hardbreak};
use print::pp::{Breaks, eof};
use print::pp::Breaks::{Consistent, Inconsistent};
2014-09-13 16:06:01 +00:00
use ptr::P;
use std_inject;
2014-11-22 15:24:58 +00:00
use std::{ascii, mem};
use std::io::{self, Write, Read};
2014-12-11 03:46:38 +00:00
use std::iter;
2014-03-16 18:58:11 +00:00
pub enum AnnNode<'a> {
NodeIdent(&'a ast::Ident),
NodeName(&'a ast::Name),
2014-03-16 18:58:11 +00:00
NodeBlock(&'a ast::Block),
NodeItem(&'a ast::Item),
NodeExpr(&'a ast::Expr),
NodePat(&'a ast::Pat),
}
pub trait PpAnn {
fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
}
#[derive(Copy)]
pub struct NoAnn;
impl PpAnn for NoAnn {}
#[derive(Copy)]
pub struct CurrentCommentAndLiteral {
2015-01-17 23:33:05 +00:00
cur_cmnt: usize,
cur_lit: usize,
}
pub struct State<'a> {
pub s: pp::Printer<'a>,
2014-03-16 18:58:11 +00:00
cm: Option<&'a CodeMap>,
comments: Option<Vec<comments::Comment> >,
literals: Option<Vec<comments::Literal> >,
cur_cmnt_and_lit: CurrentCommentAndLiteral,
2014-03-27 17:31:00 +00:00
boxes: Vec<pp::Breaks>,
ann: &'a (PpAnn+'a),
encode_idents_with_hygiene: bool,
}
pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
2014-03-16 18:58:11 +00:00
static NO_ANN: NoAnn = NoAnn;
rust_printer_annotated(writer, &NO_ANN)
2012-05-10 14:24:56 +00:00
}
pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
ann: &'a PpAnn) -> State<'a> {
2014-02-06 22:38:33 +00:00
State {
s: pp::mk_printer(writer, default_columns),
cm: None,
comments: None,
literals: None,
cur_cmnt_and_lit: CurrentCommentAndLiteral {
cur_cmnt: 0,
cur_lit: 0
},
2014-03-27 17:31:00 +00:00
boxes: Vec::new(),
ann: ann,
encode_idents_with_hygiene: false,
2014-02-06 22:38:33 +00:00
}
}
2014-10-27 22:37:07 +00:00
#[allow(non_upper_case_globals)]
pub const indent_unit: usize = 4;
2014-10-27 22:37:07 +00:00
#[allow(non_upper_case_globals)]
pub const default_columns: usize = 78;
2014-06-09 20:12:30 +00:00
/// Requires you to pass an input filename and reader so that
/// it can scan the input text for comments and literals to
/// copy forward.
pub fn print_crate<'a>(cm: &'a CodeMap,
span_diagnostic: &diagnostic::SpanHandler,
krate: &ast::Crate,
filename: String,
input: &mut Read,
out: Box<Write+'a>,
ann: &'a PpAnn,
is_expanded: bool) -> io::Result<()> {
let mut s = State::new_from_input(cm,
span_diagnostic,
filename,
input,
out,
ann,
is_expanded);
if is_expanded && std_inject::use_std(krate) {
// We need to print `#![no_std]` (and its feature gate) so that
// compiling pretty-printed source won't inject libstd again.
// However we don't want these attributes in the AST because
// of the feature gate, so we fake them up here.
let no_std_meta = attr::mk_word_item(InternedString::new("no_std"));
// #![feature(no_std)]
let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(),
attr::mk_list_item(InternedString::new("feature"),
vec![no_std_meta.clone()]));
try!(s.print_attribute(&fake_attr));
// #![no_std]
let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), no_std_meta);
try!(s.print_attribute(&fake_attr));
}
2015-02-18 23:58:07 +00:00
try!(s.print_mod(&krate.module, &krate.attrs));
2014-03-16 18:58:11 +00:00
try!(s.print_remaining_comments());
eof(&mut s.s)
2012-02-21 23:34:26 +00:00
}
impl<'a> State<'a> {
pub fn new_from_input(cm: &'a CodeMap,
span_diagnostic: &diagnostic::SpanHandler,
filename: String,
input: &mut Read,
out: Box<Write+'a>,
ann: &'a PpAnn,
is_expanded: bool) -> State<'a> {
let (cmnts, lits) = comments::gather_comments_and_literals(
span_diagnostic,
filename,
input);
State::new(
cm,
out,
ann,
Some(cmnts),
// If the code is post expansion, don't use the table of
// literals, since it doesn't correspond with the literals
// in the AST anymore.
if is_expanded { None } else { Some(lits) })
}
pub fn new(cm: &'a CodeMap,
out: Box<Write+'a>,
ann: &'a PpAnn,
comments: Option<Vec<comments::Comment>>,
literals: Option<Vec<comments::Literal>>) -> State<'a> {
State {
s: pp::mk_printer(out, default_columns),
cm: Some(cm),
comments: comments,
literals: literals,
cur_cmnt_and_lit: CurrentCommentAndLiteral {
cur_cmnt: 0,
cur_lit: 0
},
boxes: Vec::new(),
ann: ann,
encode_idents_with_hygiene: false,
}
}
}
2014-12-08 18:28:32 +00:00
pub fn to_string<F>(f: F) -> String where
F: FnOnce(&mut State) -> io::Result<()>,
2014-12-08 18:28:32 +00:00
{
DST coercions and DST structs [breaking-change] 1. The internal layout for traits has changed from (vtable, data) to (data, vtable). If you were relying on this in unsafe transmutes, you might get some very weird and apparently unrelated errors. You should not be doing this! Prefer not to do this at all, but if you must, you should use raw::TraitObject rather than hardcoding rustc's internal representation into your code. 2. The minimal type of reference-to-vec-literals (e.g., `&[1, 2, 3]`) is now a fixed size vec (e.g., `&[int, ..3]`) where it used to be an unsized vec (e.g., `&[int]`). If you want the unszied type, you must explicitly give the type (e.g., `let x: &[_] = &[1, 2, 3]`). Note in particular where multiple blocks must have the same type (e.g., if and else clauses, vec elements), the compiler will not coerce to the unsized type without a hint. E.g., `[&[1], &[1, 2]]` used to be a valid expression of type '[&[int]]'. It no longer type checks since the first element now has type `&[int, ..1]` and the second has type &[int, ..2]` which are incompatible. 3. The type of blocks (including functions) must be coercible to the expected type (used to be a subtype). Mostly this makes things more flexible and not less (in particular, in the case of coercing function bodies to the return type). However, in some rare cases, this is less flexible. TBH, I'm not exactly sure of the exact effects. I think the change causes us to resolve inferred type variables slightly earlier which might make us slightly more restrictive. Possibly it only affects blocks with unreachable code. E.g., `if ... { fail!(); "Hello" }` used to type check, it no longer does. The fix is to add a semicolon after the string.
2014-08-04 12:20:11 +00:00
use std::raw::TraitObject;
let mut s = rust_printer(box Vec::new());
f(&mut s).unwrap();
eof(&mut s.s).unwrap();
2014-10-25 17:33:54 +00:00
let wr = unsafe {
// FIXME(pcwalton): A nasty function to extract the string from an `Write`
// that we "know" to be a `Vec<u8>` that works around the lack of checked
// downcasts.
2014-10-25 17:33:54 +00:00
let obj: &TraitObject = mem::transmute(&s.s.out);
mem::transmute::<*mut (), &Vec<u8>>(obj.data)
2014-10-25 17:33:54 +00:00
};
String::from_utf8(wr.clone()).unwrap()
}
pub fn binop_to_string(op: BinOpToken) -> &'static str {
match op {
token::Plus => "+",
token::Minus => "-",
token::Star => "*",
token::Slash => "/",
token::Percent => "%",
token::Caret => "^",
token::And => "&",
token::Or => "|",
token::Shl => "<<",
token::Shr => ">>",
}
}
pub fn token_to_string(tok: &Token) -> String {
match *tok {
2014-12-11 03:46:38 +00:00
token::Eq => "=".to_string(),
token::Lt => "<".to_string(),
token::Le => "<=".to_string(),
token::EqEq => "==".to_string(),
token::Ne => "!=".to_string(),
token::Ge => ">=".to_string(),
token::Gt => ">".to_string(),
token::Not => "!".to_string(),
token::Tilde => "~".to_string(),
token::OrOr => "||".to_string(),
token::AndAnd => "&&".to_string(),
token::BinOp(op) => binop_to_string(op).to_string(),
token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
/* Structural symbols */
2014-12-11 03:46:38 +00:00
token::At => "@".to_string(),
token::Dot => ".".to_string(),
token::DotDot => "..".to_string(),
token::DotDotDot => "...".to_string(),
token::Comma => ",".to_string(),
token::Semi => ";".to_string(),
token::Colon => ":".to_string(),
token::ModSep => "::".to_string(),
token::RArrow => "->".to_string(),
token::LArrow => "<-".to_string(),
token::FatArrow => "=>".to_string(),
token::OpenDelim(token::Paren) => "(".to_string(),
token::CloseDelim(token::Paren) => ")".to_string(),
token::OpenDelim(token::Bracket) => "[".to_string(),
token::CloseDelim(token::Bracket) => "]".to_string(),
token::OpenDelim(token::Brace) => "{".to_string(),
token::CloseDelim(token::Brace) => "}".to_string(),
token::Pound => "#".to_string(),
token::Dollar => "$".to_string(),
token::Question => "?".to_string(),
/* Literals */
token::Literal(lit, suf) => {
let mut out = match lit {
token::Byte(b) => format!("b'{}'", b.as_str()),
token::Char(c) => format!("'{}'", c.as_str()),
2014-12-11 03:46:38 +00:00
token::Float(c) => c.as_str().to_string(),
token::Integer(c) => c.as_str().to_string(),
token::Str_(s) => format!("\"{}\"", s.as_str()),
token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
2014-12-11 03:46:38 +00:00
delim=repeat("#", n),
string=s.as_str()),
token::Binary(v) => format!("b\"{}\"", v.as_str()),
token::BinaryRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
2014-12-11 03:46:38 +00:00
delim=repeat("#", n),
string=s.as_str()),
};
if let Some(s) = suf {
out.push_str(s.as_str())
}
out
}
/* Name components */
2015-02-03 22:31:06 +00:00
token::Ident(s, _) => token::get_ident(s).to_string(),
token::Lifetime(s) => format!("{}", token::get_ident(s)),
2014-12-11 03:46:38 +00:00
token::Underscore => "_".to_string(),
/* Other */
2014-12-11 03:46:38 +00:00
token::DocComment(s) => s.as_str().to_string(),
2014-10-06 22:00:56 +00:00
token::SubstNt(s, _) => format!("${}", s),
token::MatchNt(s, t, _, _) => format!("${}:{}", s, t),
2014-12-11 03:46:38 +00:00
token::Eof => "<eof>".to_string(),
token::Whitespace => " ".to_string(),
token::Comment => "/* */".to_string(),
token::Shebang(s) => format!("/* shebang: {}*/", s.as_str()),
2014-09-16 01:27:28 +00:00
token::SpecialVarNt(var) => format!("${}", var.as_str()),
token::Interpolated(ref nt) => match *nt {
token::NtExpr(ref e) => expr_to_string(&**e),
token::NtMeta(ref e) => meta_item_to_string(&**e),
token::NtTy(ref e) => ty_to_string(&**e),
token::NtPath(ref e) => path_to_string(&**e),
2014-12-11 03:46:38 +00:00
token::NtItem(..) => "an interpolated item".to_string(),
token::NtBlock(..) => "an interpolated block".to_string(),
token::NtStmt(..) => "an interpolated statement".to_string(),
token::NtPat(..) => "an interpolated pattern".to_string(),
token::NtIdent(..) => "an interpolated identifier".to_string(),
token::NtTT(..) => "an interpolated tt".to_string(),
}
}
}
// FIXME (Issue #16472): the thing_to_string_impls macro should go away
// after we revise the syntax::ext::quote::ToToken impls to go directly
// to token-trees instead of thing -> string -> token-trees.
macro_rules! thing_to_string_impls {
($to_string:ident) => {
pub fn ty_to_string(ty: &ast::Ty) -> String {
$to_string(|s| s.print_type(ty))
}
pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
$to_string(|s| s.print_bounds("", bounds))
}
pub fn pat_to_string(pat: &ast::Pat) -> String {
$to_string(|s| s.print_pat(pat))
}
pub fn arm_to_string(arm: &ast::Arm) -> String {
$to_string(|s| s.print_arm(arm))
}
pub fn expr_to_string(e: &ast::Expr) -> String {
$to_string(|s| s.print_expr(e))
}
pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
$to_string(|s| s.print_lifetime(e))
}
pub fn tt_to_string(tt: &ast::TokenTree) -> String {
$to_string(|s| s.print_tt(tt))
}
pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
$to_string(|s| s.print_tts(tts))
}
pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
$to_string(|s| s.print_stmt(stmt))
}
pub fn item_to_string(i: &ast::Item) -> String {
$to_string(|s| s.print_item(i))
}
pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
$to_string(|s| s.print_impl_item(i))
}
pub fn generics_to_string(generics: &ast::Generics) -> String {
$to_string(|s| s.print_generics(generics))
}
pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
$to_string(|s| s.print_fn_block_args(p))
}
pub fn path_to_string(p: &ast::Path) -> String {
$to_string(|s| s.print_path(p, false, 0))
}
pub fn ident_to_string(id: &ast::Ident) -> String {
$to_string(|s| s.print_ident(*id))
}
2014-12-09 15:36:46 +00:00
pub fn fun_to_string(decl: &ast::FnDecl, unsafety: ast::Unsafety, name: ast::Ident,
2014-09-13 16:06:01 +00:00
opt_explicit_self: Option<&ast::ExplicitSelf_>,
generics: &ast::Generics) -> String {
$to_string(|s| {
try!(s.head(""));
try!(s.print_fn(decl, unsafety, abi::Rust, Some(name),
generics, opt_explicit_self, ast::Inherited));
try!(s.end()); // Close the head box
s.end() // Close the outer box
})
}
pub fn block_to_string(blk: &ast::Block) -> String {
$to_string(|s| {
// containing cbox, will be closed by print-block at }
try!(s.cbox(indent_unit));
// head-ibox, will be closed by print-block after {
try!(s.ibox(0));
s.print_block(blk)
})
}
pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
$to_string(|s| s.print_meta_item(mi))
}
pub fn attribute_to_string(attr: &ast::Attribute) -> String {
$to_string(|s| s.print_attribute(attr))
}
pub fn lit_to_string(l: &ast::Lit) -> String {
$to_string(|s| s.print_literal(l))
}
2014-09-13 16:06:01 +00:00
pub fn explicit_self_to_string(explicit_self: &ast::ExplicitSelf_) -> String {
$to_string(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
}
pub fn variant_to_string(var: &ast::Variant) -> String {
$to_string(|s| s.print_variant(var))
}
pub fn arg_to_string(arg: &ast::Arg) -> String {
$to_string(|s| s.print_arg(arg))
}
pub fn mac_to_string(arg: &ast::Mac) -> String {
$to_string(|s| s.print_mac(arg, ::parse::token::Paren))
}
} }
thing_to_string_impls! { to_string }
// FIXME (Issue #16472): the whole `with_hygiene` mod should go away
// after we revise the syntax::ext::quote::ToToken impls to go directly
// to token-trees instea of thing -> string -> token-trees.
pub mod with_hygiene {
use abi;
use ast;
use std::io;
use super::indent_unit;
// This function is the trick that all the rest of the routines
// hang on.
2014-12-08 18:28:32 +00:00
pub fn to_string_hyg<F>(f: F) -> String where
F: FnOnce(&mut super::State) -> io::Result<()>,
2014-12-08 18:28:32 +00:00
{
super::to_string(move |s| {
s.encode_idents_with_hygiene = true;
f(s)
})
}
thing_to_string_impls! { to_string_hyg }
}
pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
2014-03-16 18:58:11 +00:00
match vis {
ast::Public => format!("pub {}", s),
ast::Inherited => s.to_string()
2014-03-16 18:58:11 +00:00
}
2014-01-30 01:39:21 +00:00
}
2011-05-29 02:16:18 +00:00
fn needs_parentheses(expr: &ast::Expr) -> bool {
match expr.node {
ast::ExprAssign(..) | ast::ExprBinary(..) |
ast::ExprClosure(..) |
ast::ExprAssignOp(..) | ast::ExprCast(..) => true,
_ => false,
}
}
impl<'a> State<'a> {
pub fn ibox(&mut self, u: usize) -> io::Result<()> {
self.boxes.push(pp::Breaks::Inconsistent);
2014-03-16 18:58:11 +00:00
pp::ibox(&mut self.s, u)
}
2011-05-29 02:16:18 +00:00
pub fn end(&mut self) -> io::Result<()> {
2014-03-27 17:31:00 +00:00
self.boxes.pop().unwrap();
2014-03-16 18:58:11 +00:00
pp::end(&mut self.s)
}
2011-05-29 02:16:18 +00:00
pub fn cbox(&mut self, u: usize) -> io::Result<()> {
self.boxes.push(pp::Breaks::Consistent);
2014-03-16 18:58:11 +00:00
pp::cbox(&mut self.s, u)
}
2011-05-29 02:16:18 +00:00
2014-03-16 18:58:11 +00:00
// "raw box"
pub fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
2014-03-27 17:31:00 +00:00
self.boxes.push(b);
2014-03-16 18:58:11 +00:00
pp::rbox(&mut self.s, u, b)
}
2011-05-29 02:16:18 +00:00
pub fn nbsp(&mut self) -> io::Result<()> { word(&mut self.s, " ") }
2011-05-29 02:16:18 +00:00
pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, w));
self.nbsp()
}
2011-05-29 02:16:18 +00:00
pub fn word_space(&mut self, w: &str) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, w));
space(&mut self.s)
}
pub fn popen(&mut self) -> io::Result<()> { word(&mut self.s, "(") }
pub fn pclose(&mut self) -> io::Result<()> { word(&mut self.s, ")") }
pub fn head(&mut self, w: &str) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
// outer-box is consistent
try!(self.cbox(indent_unit));
// head-box is inconsistent
try!(self.ibox(w.len() + 1));
// keyword that starts the head
if !w.is_empty() {
try!(self.word_nbsp(w));
}
Ok(())
}
pub fn bopen(&mut self) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "{"));
self.end() // close the head-box
}
2014-03-16 18:58:11 +00:00
pub fn bclose_(&mut self, span: codemap::Span,
indented: usize) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
self.bclose_maybe_open(span, indented, true)
}
pub fn bclose_maybe_open (&mut self, span: codemap::Span,
indented: usize, close_box: bool) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.maybe_print_comment(span.hi));
try!(self.break_offset_if_not_bol(1, -(indented as isize)));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "}"));
if close_box {
try!(self.end()); // close the outer-box
}
Ok(())
}
pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
self.bclose_(span, indent_unit)
}
2014-01-30 01:39:21 +00:00
2014-03-16 18:58:11 +00:00
pub fn is_begin(&mut self) -> bool {
match self.s.last_token() {
pp::Token::Begin(_) => true,
_ => false,
}
2014-03-16 18:58:11 +00:00
}
2014-03-16 18:58:11 +00:00
pub fn is_end(&mut self) -> bool {
match self.s.last_token() {
pp::Token::End => true,
_ => false,
}
2014-03-16 18:58:11 +00:00
}
// is this the beginning of a line?
2014-03-16 18:58:11 +00:00
pub fn is_bol(&mut self) -> bool {
self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok()
}
2014-03-27 17:31:00 +00:00
pub fn in_cbox(&self) -> bool {
match self.boxes.last() {
Some(&last_box) => last_box == pp::Breaks::Consistent,
2014-03-16 18:58:11 +00:00
None => false
}
}
pub fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
if !self.is_bol() {
try!(hardbreak(&mut self.s))
}
Ok(())
}
pub fn space_if_not_bol(&mut self) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
if !self.is_bol() { try!(space(&mut self.s)); }
Ok(())
}
2015-01-17 23:33:05 +00:00
pub fn break_offset_if_not_bol(&mut self, n: usize,
off: isize) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
if !self.is_bol() {
break_offset(&mut self.s, n, off)
} else {
if off != 0 && self.s.last_token().is_hardbreak_tok() {
// We do something pretty sketchy here: tuck the nonzero
// offset-adjustment we were going to deposit along with the
// break into the previous hardbreak.
self.s.replace_last_token(pp::hardbreak_tok_offset(off));
}
Ok(())
}
2014-01-30 01:39:21 +00:00
}
2014-03-16 18:58:11 +00:00
// Synthesizes a comment that was not textually present in the original source
// file.
pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "/*"));
try!(space(&mut self.s));
try!(word(&mut self.s, &text[..]));
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
word(&mut self.s, "*/")
2014-01-30 01:39:21 +00:00
}
2014-03-16 18:58:11 +00:00
pub fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()> where
F: FnMut(&mut State, &T) -> io::Result<()>,
2014-12-08 18:28:32 +00:00
{
try!(self.rbox(0, b));
2014-03-16 18:58:11 +00:00
let mut first = true;
2015-01-31 17:20:46 +00:00
for elt in elts {
2014-03-16 18:58:11 +00:00
if first { first = false; } else { try!(self.word_space(",")); }
try!(op(self, elt));
}
self.end()
}
2014-12-08 18:28:32 +00:00
pub fn commasep_cmnt<T, F, G>(&mut self,
b: Breaks,
elts: &[T],
mut op: F,
mut get_span: G) -> io::Result<()> where
F: FnMut(&mut State, &T) -> io::Result<()>,
2014-12-08 18:28:32 +00:00
G: FnMut(&T) -> codemap::Span,
{
try!(self.rbox(0, b));
2014-03-16 18:58:11 +00:00
let len = elts.len();
let mut i = 0;
2015-01-31 17:20:46 +00:00
for elt in elts {
2014-03-16 18:58:11 +00:00
try!(self.maybe_print_comment(get_span(elt).hi));
try!(op(self, elt));
i += 1;
2014-03-16 18:58:11 +00:00
if i < len {
try!(word(&mut self.s, ","));
try!(self.maybe_print_trailing_comment(get_span(elt),
Some(get_span(&elts[i]).hi)));
try!(self.space_if_not_bol());
}
}
self.end()
}
2014-03-16 18:58:11 +00:00
pub fn commasep_exprs(&mut self, b: Breaks,
exprs: &[P<ast::Expr>]) -> io::Result<()> {
2014-05-16 07:16:13 +00:00
self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
}
2014-03-16 18:58:11 +00:00
pub fn print_mod(&mut self, _mod: &ast::Mod,
attrs: &[ast::Attribute]) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.print_inner_attributes(attrs));
2015-01-31 17:20:46 +00:00
for item in &_mod.items {
2014-05-16 07:16:13 +00:00
try!(self.print_item(&**item));
}
2014-03-16 18:58:11 +00:00
Ok(())
}
pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
attrs: &[ast::Attribute]) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.print_inner_attributes(attrs));
2015-01-31 17:20:46 +00:00
for item in &nmod.items {
2014-05-16 07:16:13 +00:00
try!(self.print_foreign_item(&**item));
}
2014-03-16 18:58:11 +00:00
Ok(())
}
pub fn print_opt_lifetime(&mut self,
lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
2015-01-31 17:20:46 +00:00
if let Some(l) = *lifetime {
try!(self.print_lifetime(&l));
2014-03-16 18:58:11 +00:00
try!(self.nbsp());
}
2014-03-16 18:58:11 +00:00
Ok(())
}
pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.maybe_print_comment(ty.span.lo));
try!(self.ibox(0));
2014-03-16 18:58:11 +00:00
match ty.node {
2014-05-16 07:16:13 +00:00
ast::TyVec(ref ty) => {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "["));
2014-05-16 07:16:13 +00:00
try!(self.print_type(&**ty));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "]"));
}
ast::TyPtr(ref mt) => {
try!(word(&mut self.s, "*"));
2014-06-25 19:47:34 +00:00
match mt.mutbl {
ast::MutMutable => try!(self.word_nbsp("mut")),
ast::MutImmutable => try!(self.word_nbsp("const")),
}
try!(self.print_type(&*mt.ty));
2014-03-16 18:58:11 +00:00
}
ast::TyRptr(ref lifetime, ref mt) => {
try!(word(&mut self.s, "&"));
try!(self.print_opt_lifetime(lifetime));
try!(self.print_mt(mt));
}
ast::TyTup(ref elts) => {
try!(self.popen());
try!(self.commasep(Inconsistent, &elts[..],
2014-09-13 16:06:01 +00:00
|s, ty| s.print_type(&**ty)));
2014-03-16 18:58:11 +00:00
if elts.len() == 1 {
try!(word(&mut self.s, ","));
}
try!(self.pclose());
}
ast::TyParen(ref typ) => {
try!(self.popen());
try!(self.print_type(&**typ));
try!(self.pclose());
}
2014-09-13 16:06:01 +00:00
ast::TyBareFn(ref f) => {
2014-03-16 18:58:11 +00:00
let generics = ast::Generics {
lifetimes: f.lifetimes.clone(),
ty_params: OwnedSlice::empty(),
where_clause: ast::WhereClause {
id: ast::DUMMY_NODE_ID,
predicates: Vec::new(),
},
2014-03-16 18:58:11 +00:00
};
try!(self.print_ty_fn(f.abi,
2014-12-09 15:36:46 +00:00
f.unsafety,
2014-05-16 07:16:13 +00:00
&*f.decl,
None,
&generics,
None));
2014-03-16 18:58:11 +00:00
}
ast::TyPath(None, ref path) => {
try!(self.print_path(path, false, 0));
}
ast::TyPath(Some(ref qself), ref path) => {
try!(self.print_qpath(path, qself, false))
}
ast::TyObjectSum(ref ty, ref bounds) => {
try!(self.print_type(&**ty));
try!(self.print_bounds("+", &bounds[..]));
2014-03-16 18:58:11 +00:00
}
ast::TyPolyTraitRef(ref bounds) => {
try!(self.print_bounds("", &bounds[..]));
2014-11-07 11:53:45 +00:00
}
2014-05-16 07:16:13 +00:00
ast::TyFixedLengthVec(ref ty, ref v) => {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "["));
2014-05-16 07:16:13 +00:00
try!(self.print_type(&**ty));
try!(word(&mut self.s, "; "));
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**v));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "]"));
}
2014-05-16 07:16:13 +00:00
ast::TyTypeof(ref e) => {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "typeof("));
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**e));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, ")"));
}
ast::TyInfer => {
try!(word(&mut self.s, "_"));
}
}
self.end()
}
2014-03-16 18:58:11 +00:00
pub fn print_foreign_item(&mut self,
item: &ast::ForeignItem) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(item.span.lo));
2015-02-18 23:58:07 +00:00
try!(self.print_outer_attributes(&item.attrs));
2014-03-16 18:58:11 +00:00
match item.node {
2014-05-16 07:16:13 +00:00
ast::ForeignItemFn(ref decl, ref generics) => {
try!(self.head(""));
try!(self.print_fn(&**decl, ast::Unsafety::Normal,
abi::Rust, Some(item.ident),
generics, None, item.vis));
2014-03-16 18:58:11 +00:00
try!(self.end()); // end head-ibox
try!(word(&mut self.s, ";"));
self.end() // end the outer fn box
}
2014-05-16 07:16:13 +00:00
ast::ForeignItemStatic(ref t, m) => {
2015-01-07 16:58:31 +00:00
try!(self.head(&visibility_qualified(item.vis,
2015-02-18 23:58:07 +00:00
"static")));
2014-03-16 18:58:11 +00:00
if m {
try!(self.word_space("mut"));
}
try!(self.print_ident(item.ident));
try!(self.word_space(":"));
2014-05-16 07:16:13 +00:00
try!(self.print_type(&**t));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, ";"));
try!(self.end()); // end the head-ibox
self.end() // end the outer cbox
}
}
}
fn print_associated_type(&mut self,
ident: ast::Ident,
bounds: Option<&ast::TyParamBounds>,
ty: Option<&ast::Ty>)
-> io::Result<()> {
try!(self.word_space("type"));
try!(self.print_ident(ident));
if let Some(bounds) = bounds {
try!(self.print_bounds(":", bounds));
}
if let Some(ty) = ty {
try!(space(&mut self.s));
try!(self.word_space("="));
try!(self.print_type(ty));
}
word(&mut self.s, ";")
}
/// Pretty-print an item
pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(item.span.lo));
2015-02-18 23:58:07 +00:00
try!(self.print_outer_attributes(&item.attrs));
2014-03-16 18:58:11 +00:00
try!(self.ann.pre(self, NodeItem(item)));
match item.node {
ast::ItemExternCrate(ref optional_path) => {
try!(self.head(&visibility_qualified(item.vis,
2015-02-18 23:58:07 +00:00
"extern crate")));
2015-01-31 17:20:46 +00:00
if let Some((ref p, style)) = *optional_path {
2015-02-03 22:31:06 +00:00
try!(self.print_string(p, style));
try!(space(&mut self.s));
try!(word(&mut self.s, "as"));
try!(space(&mut self.s));
}
try!(self.print_ident(item.ident));
try!(word(&mut self.s, ";"));
try!(self.end()); // end inner head-block
try!(self.end()); // end outer head-block
}
ast::ItemUse(ref vp) => {
try!(self.head(&visibility_qualified(item.vis,
2015-02-18 23:58:07 +00:00
"use")));
try!(self.print_view_path(&**vp));
try!(word(&mut self.s, ";"));
try!(self.end()); // end inner head-block
try!(self.end()); // end outer head-block
}
2014-05-16 07:16:13 +00:00
ast::ItemStatic(ref ty, m, ref expr) => {
2015-01-07 16:58:31 +00:00
try!(self.head(&visibility_qualified(item.vis,
2015-02-18 23:58:07 +00:00
"static")));
2014-03-16 18:58:11 +00:00
if m == ast::MutMutable {
try!(self.word_space("mut"));
}
2014-03-16 18:58:11 +00:00
try!(self.print_ident(item.ident));
try!(self.word_space(":"));
2014-05-16 07:16:13 +00:00
try!(self.print_type(&**ty));
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
try!(self.end()); // end the head-ibox
try!(self.word_space("="));
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**expr));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, ";"));
try!(self.end()); // end the outer cbox
}
rustc: Add `const` globals to the language This change is an implementation of [RFC 69][rfc] which adds a third kind of global to the language, `const`. This global is most similar to what the old `static` was, and if you're unsure about what to use then you should use a `const`. The semantics of these three kinds of globals are: * A `const` does not represent a memory location, but only a value. Constants are translated as rvalues, which means that their values are directly inlined at usage location (similar to a #define in C/C++). Constant values are, well, constant, and can not be modified. Any "modification" is actually a modification to a local value on the stack rather than the actual constant itself. Almost all values are allowed inside constants, whether they have interior mutability or not. There are a few minor restrictions listed in the RFC, but they should in general not come up too often. * A `static` now always represents a memory location (unconditionally). Any references to the same `static` are actually a reference to the same memory location. Only values whose types ascribe to `Sync` are allowed in a `static`. This restriction is in place because many threads may access a `static` concurrently. Lifting this restriction (and allowing unsafe access) is a future extension not implemented at this time. * A `static mut` continues to always represent a memory location. All references to a `static mut` continue to be `unsafe`. This is a large breaking change, and many programs will need to be updated accordingly. A summary of the breaking changes is: * Statics may no longer be used in patterns. Statics now always represent a memory location, which can sometimes be modified. To fix code, repurpose the matched-on-`static` to a `const`. static FOO: uint = 4; match n { FOO => { /* ... */ } _ => { /* ... */ } } change this code to: const FOO: uint = 4; match n { FOO => { /* ... */ } _ => { /* ... */ } } * Statics may no longer refer to other statics by value. Due to statics being able to change at runtime, allowing them to reference one another could possibly lead to confusing semantics. If you are in this situation, use a constant initializer instead. Note, however, that statics may reference other statics by address, however. * Statics may no longer be used in constant expressions, such as array lengths. This is due to the same restrictions as listed above. Use a `const` instead. [breaking-change] [rfc]: https://github.com/rust-lang/rfcs/pull/246
2014-10-06 15:17:01 +00:00
ast::ItemConst(ref ty, ref expr) => {
2015-01-07 16:58:31 +00:00
try!(self.head(&visibility_qualified(item.vis,
2015-02-18 23:58:07 +00:00
"const")));
rustc: Add `const` globals to the language This change is an implementation of [RFC 69][rfc] which adds a third kind of global to the language, `const`. This global is most similar to what the old `static` was, and if you're unsure about what to use then you should use a `const`. The semantics of these three kinds of globals are: * A `const` does not represent a memory location, but only a value. Constants are translated as rvalues, which means that their values are directly inlined at usage location (similar to a #define in C/C++). Constant values are, well, constant, and can not be modified. Any "modification" is actually a modification to a local value on the stack rather than the actual constant itself. Almost all values are allowed inside constants, whether they have interior mutability or not. There are a few minor restrictions listed in the RFC, but they should in general not come up too often. * A `static` now always represents a memory location (unconditionally). Any references to the same `static` are actually a reference to the same memory location. Only values whose types ascribe to `Sync` are allowed in a `static`. This restriction is in place because many threads may access a `static` concurrently. Lifting this restriction (and allowing unsafe access) is a future extension not implemented at this time. * A `static mut` continues to always represent a memory location. All references to a `static mut` continue to be `unsafe`. This is a large breaking change, and many programs will need to be updated accordingly. A summary of the breaking changes is: * Statics may no longer be used in patterns. Statics now always represent a memory location, which can sometimes be modified. To fix code, repurpose the matched-on-`static` to a `const`. static FOO: uint = 4; match n { FOO => { /* ... */ } _ => { /* ... */ } } change this code to: const FOO: uint = 4; match n { FOO => { /* ... */ } _ => { /* ... */ } } * Statics may no longer refer to other statics by value. Due to statics being able to change at runtime, allowing them to reference one another could possibly lead to confusing semantics. If you are in this situation, use a constant initializer instead. Note, however, that statics may reference other statics by address, however. * Statics may no longer be used in constant expressions, such as array lengths. This is due to the same restrictions as listed above. Use a `const` instead. [breaking-change] [rfc]: https://github.com/rust-lang/rfcs/pull/246
2014-10-06 15:17:01 +00:00
try!(self.print_ident(item.ident));
try!(self.word_space(":"));
try!(self.print_type(&**ty));
try!(space(&mut self.s));
try!(self.end()); // end the head-ibox
try!(self.word_space("="));
try!(self.print_expr(&**expr));
try!(word(&mut self.s, ";"));
try!(self.end()); // end the outer cbox
}
2014-12-09 15:36:46 +00:00
ast::ItemFn(ref decl, unsafety, abi, ref typarams, ref body) => {
try!(self.head(""));
2014-03-16 18:58:11 +00:00
try!(self.print_fn(
decl,
unsafety,
2014-03-16 18:58:11 +00:00
abi,
Some(item.ident),
2014-03-16 18:58:11 +00:00
typarams,
None,
item.vis
));
try!(word(&mut self.s, " "));
2015-02-18 23:58:07 +00:00
try!(self.print_block_with_attrs(&**body, &item.attrs));
2014-03-16 18:58:11 +00:00
}
ast::ItemMod(ref _mod) => {
2015-01-07 16:58:31 +00:00
try!(self.head(&visibility_qualified(item.vis,
2015-02-18 23:58:07 +00:00
"mod")));
2014-03-16 18:58:11 +00:00
try!(self.print_ident(item.ident));
try!(self.nbsp());
try!(self.bopen());
2015-02-18 23:58:07 +00:00
try!(self.print_mod(_mod, &item.attrs));
2014-03-16 18:58:11 +00:00
try!(self.bclose(item.span));
}
ast::ItemForeignMod(ref nmod) => {
try!(self.head("extern"));
2015-02-18 23:58:07 +00:00
try!(self.word_nbsp(&nmod.abi.to_string()));
2014-03-16 18:58:11 +00:00
try!(self.bopen());
2015-02-18 23:58:07 +00:00
try!(self.print_foreign_mod(nmod, &item.attrs));
2014-03-16 18:58:11 +00:00
try!(self.bclose(item.span));
}
2014-05-16 07:16:13 +00:00
ast::ItemTy(ref ty, ref params) => {
2014-03-16 18:58:11 +00:00
try!(self.ibox(indent_unit));
try!(self.ibox(0));
2015-02-18 23:58:07 +00:00
try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
2014-03-16 18:58:11 +00:00
try!(self.print_ident(item.ident));
try!(self.print_generics(params));
try!(self.end()); // end the inner ibox
try!(space(&mut self.s));
try!(self.word_space("="));
2014-05-16 07:16:13 +00:00
try!(self.print_type(&**ty));
try!(self.print_where_clause(params));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, ";"));
try!(self.end()); // end the outer ibox
}
ast::ItemEnum(ref enum_definition, ref params) => {
try!(self.print_enum_def(
enum_definition,
params,
item.ident,
item.span,
item.vis
));
}
2014-05-16 07:16:13 +00:00
ast::ItemStruct(ref struct_def, ref generics) => {
2015-02-18 23:58:07 +00:00
try!(self.head(&visibility_qualified(item.vis,"struct")));
2014-09-13 16:06:01 +00:00
try!(self.print_struct(&**struct_def, generics, item.ident, item.span));
2014-03-16 18:58:11 +00:00
}
2015-02-07 13:24:34 +00:00
ast::ItemDefaultImpl(unsafety, ref trait_ref) => {
try!(self.head(""));
try!(self.print_visibility(item.vis));
try!(self.print_unsafety(unsafety));
try!(self.word_nbsp("impl"));
try!(self.print_trait_ref(trait_ref));
try!(space(&mut self.s));
try!(self.word_space("for"));
try!(self.word_space(".."));
try!(self.bopen());
try!(self.bclose(item.span));
}
ast::ItemImpl(unsafety,
polarity,
ref generics,
ref opt_trait,
ref ty,
ref impl_items) => {
try!(self.head(""));
try!(self.print_visibility(item.vis));
try!(self.print_unsafety(unsafety));
try!(self.word_nbsp("impl"));
2014-03-16 18:58:11 +00:00
if generics.is_parameterized() {
try!(self.print_generics(generics));
try!(space(&mut self.s));
}
match polarity {
ast::ImplPolarity::Negative => {
try!(word(&mut self.s, "!"));
},
_ => {}
}
2014-03-16 18:58:11 +00:00
match opt_trait {
&Some(ref t) => {
try!(self.print_trait_ref(t));
try!(space(&mut self.s));
try!(self.word_space("for"));
}
&None => {}
}
2014-05-16 07:16:13 +00:00
try!(self.print_type(&**ty));
try!(self.print_where_clause(generics));
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
try!(self.bopen());
2015-02-18 23:58:07 +00:00
try!(self.print_inner_attributes(&item.attrs));
2015-01-31 17:20:46 +00:00
for impl_item in impl_items {
try!(self.print_impl_item(impl_item));
2014-03-16 18:58:11 +00:00
}
try!(self.bclose(item.span));
}
ast::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
try!(self.head(""));
try!(self.print_visibility(item.vis));
try!(self.print_unsafety(unsafety));
try!(self.word_nbsp("trait"));
2014-03-16 18:58:11 +00:00
try!(self.print_ident(item.ident));
try!(self.print_generics(generics));
2014-12-24 09:34:57 +00:00
let mut real_bounds = Vec::with_capacity(bounds.len());
for b in bounds.iter() {
if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
2014-12-24 09:34:57 +00:00
try!(space(&mut self.s));
try!(self.word_space("for ?"));
try!(self.print_trait_ref(&ptr.trait_ref));
} else {
real_bounds.push(b.clone());
2014-12-24 09:34:57 +00:00
}
}
try!(self.print_bounds(":", &real_bounds[..]));
try!(self.print_where_clause(generics));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, " "));
try!(self.bopen());
for trait_item in trait_items {
try!(self.print_trait_item(trait_item));
2014-03-16 18:58:11 +00:00
}
try!(self.bclose(item.span));
}
// I think it's reasonable to hide the context here:
ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
..}) => {
try!(self.print_visibility(item.vis));
try!(self.print_path(pth, false, 0));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "! "));
try!(self.print_ident(item.ident));
try!(self.cbox(indent_unit));
try!(self.popen());
try!(self.print_tts(&tts[..]));
2014-03-16 18:58:11 +00:00
try!(self.pclose());
try!(word(&mut self.s, ";"));
2014-03-16 18:58:11 +00:00
try!(self.end());
}
}
self.ann.post(self, NodeItem(item))
}
fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
self.print_path(&t.path, false, 0)
2014-03-16 18:58:11 +00:00
}
fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
2015-02-09 03:49:27 +00:00
if !lifetimes.is_empty() {
2014-11-07 11:53:45 +00:00
try!(word(&mut self.s, "for<"));
2014-12-14 03:11:04 +00:00
let mut comma = false;
2015-02-09 03:49:27 +00:00
for lifetime_def in lifetimes {
2014-12-14 03:11:04 +00:00
if comma {
try!(self.word_space(","))
}
2014-11-07 11:53:45 +00:00
try!(self.print_lifetime_def(lifetime_def));
2014-12-14 03:11:04 +00:00
comma = true;
2014-11-07 11:53:45 +00:00
}
try!(word(&mut self.s, ">"));
}
2015-02-09 03:49:27 +00:00
Ok(())
}
2014-11-07 11:53:45 +00:00
fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
2015-02-09 03:49:27 +00:00
try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
2014-11-07 11:53:45 +00:00
self.print_trait_ref(&t.trait_ref)
}
2014-03-16 18:58:11 +00:00
pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
generics: &ast::Generics, ident: ast::Ident,
span: codemap::Span,
visibility: ast::Visibility) -> io::Result<()> {
2015-02-18 23:58:07 +00:00
try!(self.head(&visibility_qualified(visibility, "enum")));
2014-03-16 18:58:11 +00:00
try!(self.print_ident(ident));
try!(self.print_generics(generics));
try!(self.print_where_clause(generics));
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
2015-02-18 23:58:07 +00:00
self.print_variants(&enum_definition.variants, span)
2014-03-16 18:58:11 +00:00
}
pub fn print_variants(&mut self,
variants: &[P<ast::Variant>],
span: codemap::Span) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.bopen());
2015-01-31 17:20:46 +00:00
for v in variants {
2014-03-16 18:58:11 +00:00
try!(self.space_if_not_bol());
try!(self.maybe_print_comment(v.span.lo));
2015-02-18 23:58:07 +00:00
try!(self.print_outer_attributes(&v.node.attrs));
2014-03-16 18:58:11 +00:00
try!(self.ibox(indent_unit));
2014-05-16 07:16:13 +00:00
try!(self.print_variant(&**v));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, ","));
try!(self.end());
try!(self.maybe_print_trailing_comment(v.span, None));
}
self.bclose(span)
}
pub fn print_visibility(&mut self, vis: ast::Visibility) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
match vis {
ast::Public => self.word_nbsp("pub"),
ast::Inherited => Ok(())
}
}
pub fn print_struct(&mut self,
struct_def: &ast::StructDef,
generics: &ast::Generics,
ident: ast::Ident,
span: codemap::Span) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.print_ident(ident));
try!(self.print_generics(generics));
if ast_util::struct_def_is_tuple_like(struct_def) {
if !struct_def.fields.is_empty() {
try!(self.popen());
try!(self.commasep(
2015-02-18 23:58:07 +00:00
Inconsistent, &struct_def.fields,
2014-03-16 18:58:11 +00:00
|s, field| {
match field.node.kind {
ast::NamedField(..) => panic!("unexpected named field"),
ast::UnnamedField(vis) => {
try!(s.print_visibility(vis));
2014-03-16 18:58:11 +00:00
try!(s.maybe_print_comment(field.span.lo));
2014-05-16 07:16:13 +00:00
s.print_type(&*field.node.ty)
2014-03-16 18:58:11 +00:00
}
}
}
));
try!(self.pclose());
}
2015-01-04 10:35:14 +00:00
try!(self.print_where_clause(generics));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, ";"));
try!(self.end());
self.end() // close the outer-box
} else {
2015-01-04 10:35:14 +00:00
try!(self.print_where_clause(generics));
2014-03-16 18:58:11 +00:00
try!(self.nbsp());
try!(self.bopen());
try!(self.hardbreak_if_not_bol());
2015-01-31 17:20:46 +00:00
for field in &struct_def.fields {
2014-03-16 18:58:11 +00:00
match field.node.kind {
ast::UnnamedField(..) => panic!("unexpected unnamed field"),
2014-03-16 18:58:11 +00:00
ast::NamedField(ident, visibility) => {
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(field.span.lo));
2015-02-18 23:58:07 +00:00
try!(self.print_outer_attributes(&field.node.attrs));
2014-03-16 18:58:11 +00:00
try!(self.print_visibility(visibility));
try!(self.print_ident(ident));
try!(self.word_nbsp(":"));
2014-05-16 07:16:13 +00:00
try!(self.print_type(&*field.node.ty));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, ","));
}
}
}
2014-03-16 18:58:11 +00:00
self.bclose(span)
}
}
2014-03-16 18:58:11 +00:00
/// This doesn't deserve to be called "pretty" printing, but it should be
/// meaning-preserving. A quick hack that might help would be to look at the
/// spans embedded in the TTs to decide where to put spaces and newlines.
/// But it'd be better to parse these according to the grammar of the
/// appropriate macro, transcribe back into the grammar we just parsed from,
/// and then pretty-print the resulting AST nodes (so, e.g., we print
/// expression arguments as expressions). It can be done! I think.
pub fn print_tt(&mut self, tt: &ast::TokenTree) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
match *tt {
ast::TtToken(_, ref tk) => {
2015-02-18 23:58:07 +00:00
try!(word(&mut self.s, &token_to_string(tk)));
match *tk {
2014-10-27 08:22:52 +00:00
parse::token::DocComment(..) => {
hardbreak(&mut self.s)
}
_ => Ok(())
}
2014-03-16 18:58:11 +00:00
}
2014-10-06 22:00:56 +00:00
ast::TtDelimited(_, ref delimed) => {
2015-02-18 23:58:07 +00:00
try!(word(&mut self.s, &token_to_string(&delimed.open_token())));
2014-10-06 22:00:56 +00:00
try!(space(&mut self.s));
2015-02-18 23:58:07 +00:00
try!(self.print_tts(&delimed.tts));
2014-10-06 22:00:56 +00:00
try!(space(&mut self.s));
2015-02-18 23:58:07 +00:00
word(&mut self.s, &token_to_string(&delimed.close_token()))
2014-10-06 22:00:56 +00:00
},
2014-11-02 11:21:16 +00:00
ast::TtSequence(_, ref seq) => {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "$("));
2015-01-31 17:20:46 +00:00
for tt_elt in &seq.tts {
2014-03-16 18:58:11 +00:00
try!(self.print_tt(tt_elt));
}
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, ")"));
2014-11-02 11:21:16 +00:00
match seq.separator {
2014-03-16 18:58:11 +00:00
Some(ref tk) => {
2015-02-18 23:58:07 +00:00
try!(word(&mut self.s, &token_to_string(tk)));
2014-03-16 18:58:11 +00:00
}
None => {},
}
2014-11-02 11:21:16 +00:00
match seq.op {
2014-10-23 00:24:20 +00:00
ast::ZeroOrMore => word(&mut self.s, "*"),
ast::OneOrMore => word(&mut self.s, "+"),
}
2014-03-16 18:58:11 +00:00
}
}
}
pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.ibox(0));
let mut suppress_space = false;
2014-03-16 18:58:11 +00:00
for (i, tt) in tts.iter().enumerate() {
if i != 0 && !suppress_space {
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
}
try!(self.print_tt(tt));
// There should be no space between the module name and the following `::` in paths,
2015-01-23 19:27:16 +00:00
// otherwise imported macros get re-parsed from crate metadata incorrectly (#20701)
suppress_space = match tt {
&ast::TtToken(_, token::Ident(_, token::ModName)) |
&ast::TtToken(_, token::MatchNt(_, _, _, token::ModName)) |
&ast::TtToken(_, token::SubstNt(_, token::ModName)) => true,
_ => false
}
2014-03-16 18:58:11 +00:00
}
self.end()
}
pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.print_visibility(v.node.vis));
match v.node.kind {
ast::TupleVariantKind(ref args) => {
try!(self.print_ident(v.node.name));
if !args.is_empty() {
try!(self.popen());
try!(self.commasep(Consistent,
&args[..],
2014-05-16 07:16:13 +00:00
|s, arg| s.print_type(&*arg.ty)));
2014-03-16 18:58:11 +00:00
try!(self.pclose());
2014-01-30 01:39:21 +00:00
}
}
2014-05-16 07:16:13 +00:00
ast::StructVariantKind(ref struct_def) => {
2014-03-16 18:58:11 +00:00
try!(self.head(""));
let generics = ast_util::empty_generics();
2014-05-16 07:16:13 +00:00
try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
2014-03-16 18:58:11 +00:00
}
2014-01-30 01:39:21 +00:00
}
2014-03-16 18:58:11 +00:00
match v.node.disr_expr {
2014-05-16 07:16:13 +00:00
Some(ref d) => {
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
try!(self.word_space("="));
2014-05-16 07:16:13 +00:00
self.print_expr(&**d)
2014-03-16 18:58:11 +00:00
}
_ => Ok(())
}
}
pub fn print_method_sig(&mut self,
ident: ast::Ident,
m: &ast::MethodSig,
vis: ast::Visibility)
-> io::Result<()> {
self.print_fn(&m.decl,
m.unsafety,
m.abi,
Some(ident),
&m.generics,
Some(&m.explicit_self.node),
vis)
2014-03-16 18:58:11 +00:00
}
pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
-> io::Result<()> {
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(ti.span.lo));
try!(self.print_outer_attributes(&ti.attrs));
match ti.node {
ast::MethodTraitItem(ref sig, ref body) => {
if body.is_some() {
try!(self.head(""));
}
try!(self.print_method_sig(ti.ident, sig, ast::Inherited));
if let Some(ref body) = *body {
try!(self.nbsp());
self.print_block_with_attrs(body, &ti.attrs)
} else {
word(&mut self.s, ";")
}
}
ast::TypeTraitItem(ref bounds, ref default) => {
self.print_associated_type(ti.ident, Some(bounds),
default.as_ref().map(|ty| &**ty))
}
}
}
pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(ii.span.lo));
try!(self.print_outer_attributes(&ii.attrs));
match ii.node {
ast::MethodImplItem(ref sig, ref body) => {
try!(self.head(""));
try!(self.print_method_sig(ii.ident, sig, ii.vis));
try!(self.nbsp());
self.print_block_with_attrs(body, &ii.attrs)
}
ast::TypeImplItem(ref ty) => {
self.print_associated_type(ii.ident, None, Some(ty))
}
ast::MacImplItem(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
..}) => {
// code copied from ItemMac:
try!(self.print_path(pth, false, 0));
try!(word(&mut self.s, "! "));
try!(self.cbox(indent_unit));
try!(self.popen());
try!(self.print_tts(&tts[..]));
try!(self.pclose());
try!(word(&mut self.s, ";"));
self.end()
}
}
2014-03-16 18:58:11 +00:00
}
pub fn print_outer_attributes(&mut self,
attrs: &[ast::Attribute]) -> io::Result<()> {
let mut count = 0;
2015-01-31 17:20:46 +00:00
for attr in attrs {
2014-03-16 18:58:11 +00:00
match attr.node.style {
ast::AttrOuter => {
try!(self.print_attribute(attr));
count += 1;
}
_ => {/* fallthrough */ }
}
2012-07-28 00:38:01 +00:00
}
2014-03-16 18:58:11 +00:00
if count > 0 {
try!(self.hardbreak_if_not_bol());
}
2014-03-16 18:58:11 +00:00
Ok(())
}
2014-03-16 18:58:11 +00:00
pub fn print_inner_attributes(&mut self,
attrs: &[ast::Attribute]) -> io::Result<()> {
let mut count = 0;
2015-01-31 17:20:46 +00:00
for attr in attrs {
2014-03-16 18:58:11 +00:00
match attr.node.style {
ast::AttrInner => {
try!(self.print_attribute(attr));
count += 1;
}
2014-03-16 18:58:11 +00:00
_ => {/* fallthrough */ }
}
2012-01-26 01:22:08 +00:00
}
2014-03-16 18:58:11 +00:00
if count > 0 {
try!(self.hardbreak_if_not_bol());
}
2014-03-16 18:58:11 +00:00
Ok(())
2012-01-26 01:22:08 +00:00
}
pub fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(attr.span.lo));
if attr.node.is_sugared_doc {
word(&mut self.s, &attr.value_str().unwrap())
2014-03-16 18:58:11 +00:00
} else {
2014-04-04 20:45:24 +00:00
match attr.node.style {
ast::AttrInner => try!(word(&mut self.s, "#![")),
ast::AttrOuter => try!(word(&mut self.s, "#[")),
}
2014-05-16 07:16:13 +00:00
try!(self.print_meta_item(&*attr.meta()));
2014-03-16 18:58:11 +00:00
word(&mut self.s, "]")
}
}
2014-03-16 18:58:11 +00:00
pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.maybe_print_comment(st.span.lo));
match st.node {
2014-05-16 07:16:13 +00:00
ast::StmtDecl(ref decl, _) => {
try!(self.print_decl(&**decl));
2014-03-16 18:58:11 +00:00
}
2014-05-16 07:16:13 +00:00
ast::StmtExpr(ref expr, _) => {
2014-03-16 18:58:11 +00:00
try!(self.space_if_not_bol());
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**expr));
2014-03-16 18:58:11 +00:00
}
2014-05-16 07:16:13 +00:00
ast::StmtSemi(ref expr, _) => {
2014-03-16 18:58:11 +00:00
try!(self.space_if_not_bol());
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**expr));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, ";"));
}
ast::StmtMac(ref mac, style) => {
2014-03-16 18:58:11 +00:00
try!(self.space_if_not_bol());
let delim = match style {
ast::MacStmtWithBraces => token::Brace,
_ => token::Paren
};
try!(self.print_mac(&**mac, delim));
match style {
ast::MacStmtWithBraces => {}
_ => try!(word(&mut self.s, ";")),
2014-03-16 18:58:11 +00:00
}
}
}
2014-09-13 16:06:01 +00:00
if parse::classify::stmt_ends_with_semi(&st.node) {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, ";"));
}
self.maybe_print_trailing_comment(st.span, None)
}
pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
self.print_block_with_attrs(blk, &[])
}
pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
self.print_block_unclosed_indent(blk, indent_unit)
}
2014-03-16 18:58:11 +00:00
pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
indented: usize) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
self.print_block_maybe_unclosed(blk, indented, &[], false)
}
2011-08-15 21:42:33 +00:00
2014-03-16 18:58:11 +00:00
pub fn print_block_with_attrs(&mut self,
blk: &ast::Block,
attrs: &[ast::Attribute]) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
}
2014-03-16 18:58:11 +00:00
pub fn print_block_maybe_unclosed(&mut self,
blk: &ast::Block,
2015-01-17 23:33:05 +00:00
indented: usize,
attrs: &[ast::Attribute],
close_box: bool) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
match blk.rules {
ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
ast::DefaultBlock => ()
}
try!(self.maybe_print_comment(blk.span.lo));
try!(self.ann.pre(self, NodeBlock(blk)));
try!(self.bopen());
try!(self.print_inner_attributes(attrs));
2015-01-31 17:20:46 +00:00
for st in &blk.stmts {
2014-05-16 07:16:13 +00:00
try!(self.print_stmt(&**st));
2014-03-16 18:58:11 +00:00
}
match blk.expr {
2014-05-16 07:16:13 +00:00
Some(ref expr) => {
2014-03-16 18:58:11 +00:00
try!(self.space_if_not_bol());
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**expr));
2014-03-16 18:58:11 +00:00
try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
}
_ => ()
}
try!(self.bclose_maybe_open(blk.span, indented, close_box));
self.ann.post(self, NodeBlock(blk))
}
fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
2012-08-06 19:34:08 +00:00
match els {
2014-01-30 01:39:21 +00:00
Some(_else) => {
match _else.node {
// "another else-if"
2014-09-13 16:06:01 +00:00
ast::ExprIf(ref i, ref then, ref e) => {
try!(self.cbox(indent_unit - 1));
try!(self.ibox(0));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, " else if "));
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**i));
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
2014-09-13 16:06:01 +00:00
try!(self.print_block(&**then));
self.print_else(e.as_ref().map(|e| &**e))
2014-01-30 01:39:21 +00:00
}
2014-08-25 01:04:29 +00:00
// "another else-if-let"
ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => {
try!(self.cbox(indent_unit - 1));
try!(self.ibox(0));
2014-08-25 01:04:29 +00:00
try!(word(&mut self.s, " else if let "));
try!(self.print_pat(&**pat));
try!(space(&mut self.s));
try!(self.word_space("="));
try!(self.print_expr(&**expr));
try!(space(&mut self.s));
try!(self.print_block(&**then));
self.print_else(e.as_ref().map(|e| &**e))
}
2014-01-30 01:39:21 +00:00
// "final else"
2014-05-16 07:16:13 +00:00
ast::ExprBlock(ref b) => {
try!(self.cbox(indent_unit - 1));
try!(self.ibox(0));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, " else "));
2014-05-16 07:16:13 +00:00
self.print_block(&**b)
2014-01-30 01:39:21 +00:00
}
// BLEAH, constraints would be great here
_ => {
panic!("print_if saw if with weird alternative");
2014-01-30 01:39:21 +00:00
}
}
2011-06-16 21:08:17 +00:00
}
2014-03-16 18:58:11 +00:00
_ => Ok(())
2011-06-16 21:08:17 +00:00
}
}
2014-03-16 18:58:11 +00:00
pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
elseopt: Option<&ast::Expr>) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.head("if"));
try!(self.print_expr(test));
try!(space(&mut self.s));
try!(self.print_block(blk));
self.print_else(elseopt)
}
2014-08-25 01:04:29 +00:00
pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
elseopt: Option<&ast::Expr>) -> io::Result<()> {
2014-08-25 01:04:29 +00:00
try!(self.head("if let"));
try!(self.print_pat(pat));
try!(space(&mut self.s));
try!(self.word_space("="));
try!(self.print_expr(expr));
try!(space(&mut self.s));
try!(self.print_block(blk));
self.print_else(elseopt)
}
pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
-> io::Result<()> {
2014-03-16 18:58:11 +00:00
match m.node {
// I think it's reasonable to hide the ctxt here:
ast::MacInvocTT(ref pth, ref tts, _) => {
try!(self.print_path(pth, false, 0));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "!"));
match delim {
token::Paren => try!(self.popen()),
token::Bracket => try!(word(&mut self.s, "[")),
token::Brace => try!(self.bopen()),
}
try!(self.print_tts(tts));
match delim {
token::Paren => self.pclose(),
token::Bracket => word(&mut self.s, "]"),
token::Brace => self.bclose(m.span),
}
2014-03-16 18:58:11 +00:00
}
}
}
fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.popen());
try!(self.commasep_exprs(Inconsistent, args));
self.pclose()
}
pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
let needs_par = needs_parentheses(expr);
if needs_par {
try!(self.popen());
}
try!(self.print_expr(expr));
if needs_par {
try!(self.pclose());
}
Ok(())
}
fn print_expr_box(&mut self,
place: &Option<P<ast::Expr>>,
expr: &ast::Expr) -> io::Result<()> {
try!(word(&mut self.s, "box"));
try!(word(&mut self.s, "("));
try!(place.as_ref().map_or(Ok(()), |e|self.print_expr(&**e)));
try!(self.word_space(")"));
self.print_expr(expr)
}
fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) -> io::Result<()> {
try!(self.ibox(indent_unit));
try!(word(&mut self.s, "["));
try!(self.commasep_exprs(Inconsistent, &exprs[..]));
try!(word(&mut self.s, "]"));
self.end()
}
fn print_expr_repeat(&mut self,
element: &ast::Expr,
count: &ast::Expr) -> io::Result<()> {
try!(self.ibox(indent_unit));
try!(word(&mut self.s, "["));
try!(self.print_expr(element));
try!(self.word_space(";"));
try!(self.print_expr(count));
try!(word(&mut self.s, "]"));
self.end()
}
fn print_expr_struct(&mut self,
path: &ast::Path,
fields: &[ast::Field],
wth: &Option<P<ast::Expr>>) -> io::Result<()> {
try!(self.print_path(path, true, 0));
if !(fields.is_empty() && wth.is_none()) {
try!(word(&mut self.s, "{"));
try!(self.commasep_cmnt(
Consistent,
&fields[..],
|s, field| {
try!(s.ibox(indent_unit));
try!(s.print_ident(field.ident.node));
try!(s.word_space(":"));
try!(s.print_expr(&*field.expr));
s.end()
},
|f| f.span));
match *wth {
Some(ref expr) => {
try!(self.ibox(indent_unit));
if !fields.is_empty() {
try!(word(&mut self.s, ","));
try!(space(&mut self.s));
}
try!(word(&mut self.s, ".."));
try!(self.print_expr(&**expr));
try!(self.end());
}
_ => try!(word(&mut self.s, ",")),
}
try!(word(&mut self.s, "}"));
}
Ok(())
}
fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) -> io::Result<()> {
try!(self.popen());
try!(self.commasep_exprs(Inconsistent, &exprs[..]));
if exprs.len() == 1 {
try!(word(&mut self.s, ","));
}
self.pclose()
}
fn print_expr_call(&mut self,
func: &ast::Expr,
args: &[P<ast::Expr>]) -> io::Result<()> {
try!(self.print_expr_maybe_paren(func));
self.print_call_post(args)
}
fn print_expr_method_call(&mut self,
ident: ast::SpannedIdent,
tys: &[P<ast::Ty>],
args: &[P<ast::Expr>]) -> io::Result<()> {
2015-01-18 00:15:52 +00:00
let base_args = &args[1..];
try!(self.print_expr(&*args[0]));
try!(word(&mut self.s, "."));
try!(self.print_ident(ident.node));
if tys.len() > 0 {
try!(word(&mut self.s, "::<"));
try!(self.commasep(Inconsistent, tys,
|s, ty| s.print_type(&**ty)));
try!(word(&mut self.s, ">"));
}
self.print_call_post(base_args)
}
fn print_expr_binary(&mut self,
op: ast::BinOp,
lhs: &ast::Expr,
rhs: &ast::Expr) -> io::Result<()> {
try!(self.print_expr(lhs));
try!(space(&mut self.s));
try!(self.word_space(ast_util::binop_to_string(op.node)));
self.print_expr(rhs)
}
fn print_expr_unary(&mut self,
op: ast::UnOp,
expr: &ast::Expr) -> io::Result<()> {
try!(word(&mut self.s, ast_util::unop_to_string(op)));
self.print_expr_maybe_paren(expr)
}
fn print_expr_addr_of(&mut self,
mutability: ast::Mutability,
expr: &ast::Expr) -> io::Result<()> {
try!(word(&mut self.s, "&"));
try!(self.print_mutability(mutability));
self.print_expr_maybe_paren(expr)
}
pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.maybe_print_comment(expr.span.lo));
try!(self.ibox(indent_unit));
try!(self.ann.pre(self, NodeExpr(expr)));
match expr.node {
ast::ExprBox(ref place, ref expr) => {
try!(self.print_expr_box(place, &**expr));
2014-03-16 18:58:11 +00:00
}
ast::ExprVec(ref exprs) => {
try!(self.print_expr_vec(&exprs[..]));
2014-03-16 18:58:11 +00:00
}
2014-05-16 07:16:13 +00:00
ast::ExprRepeat(ref element, ref count) => {
try!(self.print_expr_repeat(&**element, &**count));
2014-03-16 18:58:11 +00:00
}
2014-09-13 16:06:01 +00:00
ast::ExprStruct(ref path, ref fields, ref wth) => {
try!(self.print_expr_struct(path, &fields[..], wth));
2014-03-16 18:58:11 +00:00
}
ast::ExprTup(ref exprs) => {
try!(self.print_expr_tup(&exprs[..]));
}
2014-05-16 07:16:13 +00:00
ast::ExprCall(ref func, ref args) => {
try!(self.print_expr_call(&**func, &args[..]));
}
2014-03-16 18:58:11 +00:00
ast::ExprMethodCall(ident, ref tys, ref args) => {
try!(self.print_expr_method_call(ident, &tys[..], &args[..]));
}
2014-05-16 07:16:13 +00:00
ast::ExprBinary(op, ref lhs, ref rhs) => {
try!(self.print_expr_binary(op, &**lhs, &**rhs));
}
2014-05-16 07:16:13 +00:00
ast::ExprUnary(op, ref expr) => {
try!(self.print_expr_unary(op, &**expr));
2014-03-16 18:58:11 +00:00
}
2014-05-16 07:16:13 +00:00
ast::ExprAddrOf(m, ref expr) => {
try!(self.print_expr_addr_of(m, &**expr));
}
ast::ExprLit(ref lit) => {
try!(self.print_literal(&**lit));
2014-03-16 18:58:11 +00:00
}
2014-05-16 07:16:13 +00:00
ast::ExprCast(ref expr, ref ty) => {
try!(self.print_expr(&**expr));
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
try!(self.word_space("as"));
2014-05-16 07:16:13 +00:00
try!(self.print_type(&**ty));
2014-03-16 18:58:11 +00:00
}
2014-09-13 16:06:01 +00:00
ast::ExprIf(ref test, ref blk, ref elseopt) => {
2014-08-25 01:04:29 +00:00
try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
}
ast::ExprIfLet(ref pat, ref expr, ref blk, ref elseopt) => {
try!(self.print_if_let(&**pat, &**expr, &** blk, elseopt.as_ref().map(|e| &**e)));
2014-03-16 18:58:11 +00:00
}
2014-07-26 00:12:51 +00:00
ast::ExprWhile(ref test, ref blk, opt_ident) => {
2015-01-31 17:20:46 +00:00
if let Some(ident) = opt_ident {
try!(self.print_ident(ident));
2014-07-26 00:12:51 +00:00
try!(self.word_space(":"));
}
2014-03-16 18:58:11 +00:00
try!(self.head("while"));
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**test));
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
2014-05-16 07:16:13 +00:00
try!(self.print_block(&**blk));
2014-03-16 18:58:11 +00:00
}
2014-10-03 02:45:46 +00:00
ast::ExprWhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2015-01-31 17:20:46 +00:00
if let Some(ident) = opt_ident {
try!(self.print_ident(ident));
2014-10-03 02:45:46 +00:00
try!(self.word_space(":"));
}
try!(self.head("while let"));
try!(self.print_pat(&**pat));
try!(space(&mut self.s));
try!(self.word_space("="));
try!(self.print_expr(&**expr));
try!(space(&mut self.s));
try!(self.print_block(&**blk));
}
2014-05-16 07:16:13 +00:00
ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2015-01-31 17:20:46 +00:00
if let Some(ident) = opt_ident {
try!(self.print_ident(ident));
2014-03-16 18:58:11 +00:00
try!(self.word_space(":"));
}
try!(self.head("for"));
2014-05-16 07:16:13 +00:00
try!(self.print_pat(&**pat));
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
try!(self.word_space("in"));
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**iter));
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
2014-05-16 07:16:13 +00:00
try!(self.print_block(&**blk));
2014-03-16 18:58:11 +00:00
}
2014-05-16 07:16:13 +00:00
ast::ExprLoop(ref blk, opt_ident) => {
2015-01-31 17:20:46 +00:00
if let Some(ident) = opt_ident {
try!(self.print_ident(ident));
2014-03-16 18:58:11 +00:00
try!(self.word_space(":"));
}
try!(self.head("loop"));
try!(space(&mut self.s));
2014-05-16 07:16:13 +00:00
try!(self.print_block(&**blk));
2014-03-16 18:58:11 +00:00
}
ast::ExprMatch(ref expr, ref arms, _) => {
2014-03-16 18:58:11 +00:00
try!(self.cbox(indent_unit));
try!(self.ibox(4));
try!(self.word_nbsp("match"));
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**expr));
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
try!(self.bopen());
2015-01-31 17:20:46 +00:00
for arm in arms {
try!(self.print_arm(arm));
2014-03-16 18:58:11 +00:00
}
try!(self.bclose_(expr.span, indent_unit));
}
ast::ExprClosure(capture_clause, ref decl, ref body) => {
try!(self.print_capture_clause(capture_clause));
try!(self.print_fn_block_args(&**decl));
try!(space(&mut self.s));
let default_return = match decl.output {
ast::DefaultReturn(..) => true,
_ => false
};
if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
2014-05-16 07:16:13 +00:00
try!(self.print_block_unclosed(&**body));
} else {
// we extract the block, so as not to create another set of boxes
2014-09-13 16:06:01 +00:00
match body.expr.as_ref().unwrap().node {
2014-05-16 07:16:13 +00:00
ast::ExprBlock(ref blk) => {
try!(self.print_block_unclosed(&**blk));
}
_ => {
// this is a bare expression
2014-09-13 16:06:01 +00:00
try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
try!(self.end()); // need to close a box
}
2014-03-16 18:58:11 +00:00
}
}
// a box will be closed by print_expr, but we didn't want an overall
// wrapper so we closed the corresponding opening. so create an
// empty box to satisfy the close.
try!(self.ibox(0));
}
2014-05-16 07:16:13 +00:00
ast::ExprBlock(ref blk) => {
2014-03-16 18:58:11 +00:00
// containing cbox, will be closed by print-block at }
try!(self.cbox(indent_unit));
// head-box, will be closed by print-block after {
try!(self.ibox(0));
2014-05-16 07:16:13 +00:00
try!(self.print_block(&**blk));
2014-03-16 18:58:11 +00:00
}
2014-05-16 07:16:13 +00:00
ast::ExprAssign(ref lhs, ref rhs) => {
try!(self.print_expr(&**lhs));
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
try!(self.word_space("="));
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**rhs));
2014-03-16 18:58:11 +00:00
}
2014-05-16 07:16:13 +00:00
ast::ExprAssignOp(op, ref lhs, ref rhs) => {
try!(self.print_expr(&**lhs));
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
try!(word(&mut self.s, ast_util::binop_to_string(op.node)));
2014-03-16 18:58:11 +00:00
try!(self.word_space("="));
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**rhs));
2014-03-16 18:58:11 +00:00
}
ast::ExprField(ref expr, id) => {
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**expr));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "."));
try!(self.print_ident(id.node));
2014-03-16 18:58:11 +00:00
}
ast::ExprTupField(ref expr, id) => {
try!(self.print_expr(&**expr));
try!(word(&mut self.s, "."));
try!(self.print_usize(id.node));
}
2014-05-16 07:16:13 +00:00
ast::ExprIndex(ref expr, ref index) => {
try!(self.print_expr(&**expr));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "["));
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**index));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "]"));
}
ast::ExprRange(ref start, ref end) => {
if let &Some(ref e) = start {
try!(self.print_expr(&**e));
}
try!(word(&mut self.s, ".."));
if let &Some(ref e) = end {
try!(self.print_expr(&**e));
}
2014-12-13 05:41:02 +00:00
}
ast::ExprPath(None, ref path) => {
try!(self.print_path(path, true, 0))
}
ast::ExprPath(Some(ref qself), ref path) => {
try!(self.print_qpath(path, qself, true))
}
2014-03-16 18:58:11 +00:00
ast::ExprBreak(opt_ident) => {
try!(word(&mut self.s, "break"));
try!(space(&mut self.s));
2015-01-31 17:20:46 +00:00
if let Some(ident) = opt_ident {
try!(self.print_ident(ident));
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
}
}
ast::ExprAgain(opt_ident) => {
try!(word(&mut self.s, "continue"));
try!(space(&mut self.s));
2015-01-31 17:20:46 +00:00
if let Some(ident) = opt_ident {
try!(self.print_ident(ident));
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s))
}
}
2014-05-16 07:16:13 +00:00
ast::ExprRet(ref result) => {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "return"));
2014-05-16 07:16:13 +00:00
match *result {
Some(ref expr) => {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, " "));
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**expr));
2014-03-16 18:58:11 +00:00
}
_ => ()
}
}
ast::ExprInlineAsm(ref a) => {
2014-12-17 13:02:50 +00:00
try!(word(&mut self.s, "asm!"));
2014-03-16 18:58:11 +00:00
try!(self.popen());
try!(self.print_string(&a.asm, a.asm_str_style));
2014-03-16 18:58:11 +00:00
try!(self.word_space(":"));
2014-04-17 08:35:40 +00:00
2015-02-18 23:58:07 +00:00
try!(self.commasep(Inconsistent, &a.outputs,
|s, &(ref co, ref o, is_rw)| {
2015-02-03 22:31:06 +00:00
match co.slice_shift_char() {
Some(('=', operand)) if is_rw => {
2015-02-18 23:58:07 +00:00
try!(s.print_string(&format!("+{}", operand),
ast::CookedStr))
}
_ => try!(s.print_string(&co, ast::CookedStr))
}
2014-04-17 08:35:40 +00:00
try!(s.popen());
2014-05-16 07:16:13 +00:00
try!(s.print_expr(&**o));
2014-04-17 08:35:40 +00:00
try!(s.pclose());
Ok(())
}));
try!(space(&mut self.s));
2014-03-16 18:58:11 +00:00
try!(self.word_space(":"));
2014-04-17 08:35:40 +00:00
2015-02-18 23:58:07 +00:00
try!(self.commasep(Inconsistent, &a.inputs,
2014-05-16 07:16:13 +00:00
|s, &(ref co, ref o)| {
try!(s.print_string(&co, ast::CookedStr));
2014-04-17 08:35:40 +00:00
try!(s.popen());
2014-05-16 07:16:13 +00:00
try!(s.print_expr(&**o));
2014-04-17 08:35:40 +00:00
try!(s.pclose());
Ok(())
}));
try!(space(&mut self.s));
2014-03-16 18:58:11 +00:00
try!(self.word_space(":"));
2014-04-17 08:35:40 +00:00
2015-02-18 23:58:07 +00:00
try!(self.commasep(Inconsistent, &a.clobbers,
|s, co| {
try!(s.print_string(&co, ast::CookedStr));
Ok(())
}));
2014-12-17 13:02:50 +00:00
let mut options = vec!();
if a.volatile {
options.push("volatile");
}
if a.alignstack {
options.push("alignstack");
}
if a.dialect == ast::AsmDialect::AsmIntel {
options.push("intel");
}
if options.len() > 0 {
try!(space(&mut self.s));
try!(self.word_space(":"));
try!(self.commasep(Inconsistent, &*options,
|s, &co| {
try!(s.print_string(co, ast::CookedStr));
Ok(())
}));
}
2014-03-16 18:58:11 +00:00
try!(self.pclose());
}
ast::ExprMac(ref m) => try!(self.print_mac(m, token::Paren)),
2014-05-16 07:16:13 +00:00
ast::ExprParen(ref e) => {
2014-03-16 18:58:11 +00:00
try!(self.popen());
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**e));
2014-03-16 18:58:11 +00:00
try!(self.pclose());
}
}
try!(self.ann.post(self, NodeExpr(expr)));
self.end()
}
pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2014-05-16 07:16:13 +00:00
try!(self.print_pat(&*loc.pat));
2015-01-02 11:55:31 +00:00
if let Some(ref ty) = loc.ty {
try!(self.word_space(":"));
try!(self.print_type(&**ty));
}
2015-01-02 11:55:31 +00:00
Ok(())
}
pub fn print_decl(&mut self, decl: &ast::Decl) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.maybe_print_comment(decl.span.lo));
match decl.node {
2014-05-16 07:16:13 +00:00
ast::DeclLocal(ref loc) => {
2014-03-16 18:58:11 +00:00
try!(self.space_if_not_bol());
try!(self.ibox(indent_unit));
try!(self.word_nbsp("let"));
2014-03-16 18:58:11 +00:00
try!(self.ibox(indent_unit));
2014-05-16 07:16:13 +00:00
try!(self.print_local_decl(&**loc));
2014-03-16 18:58:11 +00:00
try!(self.end());
if let Some(ref init) = loc.init {
try!(self.nbsp());
try!(self.word_space("="));
try!(self.print_expr(&**init));
2014-03-16 18:58:11 +00:00
}
self.end()
}
2014-05-16 07:16:13 +00:00
ast::DeclItem(ref item) => self.print_item(&**item)
2014-03-16 18:58:11 +00:00
}
}
2014-01-30 01:39:21 +00:00
pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
if self.encode_idents_with_hygiene {
let encoded = ident.encode_with_hygiene();
try!(word(&mut self.s, &encoded[..]))
} else {
try!(word(&mut self.s, &token::get_ident(ident)))
}
self.ann.post(self, NodeIdent(&ident))
2014-03-16 18:58:11 +00:00
}
pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2015-02-18 23:58:07 +00:00
word(&mut self.s, &i.to_string())
}
pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
try!(word(&mut self.s, &token::get_name(name)));
self.ann.post(self, NodeName(&name))
2014-03-16 18:58:11 +00:00
}
2014-03-16 18:58:11 +00:00
pub fn print_for_decl(&mut self, loc: &ast::Local,
coll: &ast::Expr) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.print_local_decl(loc));
try!(space(&mut self.s));
try!(self.word_space("in"));
self.print_expr(coll)
}
fn print_path(&mut self,
path: &ast::Path,
colons_before_params: bool,
depth: usize)
-> io::Result<()>
{
2014-03-16 18:58:11 +00:00
try!(self.maybe_print_comment(path.span.lo));
let mut first = !path.global;
for segment in &path.segments[..path.segments.len()-depth] {
2014-03-16 18:58:11 +00:00
if first {
first = false
} else {
try!(word(&mut self.s, "::"))
}
2014-03-16 18:58:11 +00:00
try!(self.print_ident(segment.identifier));
try!(self.print_path_parameters(&segment.parameters, colons_before_params));
}
Ok(())
}
fn print_qpath(&mut self,
path: &ast::Path,
qself: &ast::QSelf,
colons_before_params: bool)
-> io::Result<()>
{
try!(word(&mut self.s, "<"));
try!(self.print_type(&qself.ty));
if qself.position > 0 {
try!(space(&mut self.s));
try!(self.word_space("as"));
let depth = path.segments.len() - qself.position;
try!(self.print_path(&path, false, depth));
}
try!(word(&mut self.s, ">"));
try!(word(&mut self.s, "::"));
let item_segment = path.segments.last().unwrap();
try!(self.print_ident(item_segment.identifier));
self.print_path_parameters(&item_segment.parameters, colons_before_params)
}
fn print_path_parameters(&mut self,
parameters: &ast::PathParameters,
colons_before_params: bool)
-> io::Result<()>
{
if parameters.is_empty() {
return Ok(());
}
if colons_before_params {
try!(word(&mut self.s, "::"))
}
match *parameters {
ast::AngleBracketedParameters(ref data) => {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "<"));
let mut comma = false;
2015-01-31 17:20:46 +00:00
for lifetime in &data.lifetimes {
2014-03-16 18:58:11 +00:00
if comma {
try!(self.word_space(","))
}
try!(self.print_lifetime(lifetime));
comma = true;
}
if !data.types.is_empty() {
2014-03-16 18:58:11 +00:00
if comma {
try!(self.word_space(","))
}
try!(self.commasep(
Inconsistent,
2015-02-18 23:58:07 +00:00
&data.types,
2014-09-13 16:06:01 +00:00
|s, ty| s.print_type(&**ty)));
comma = true;
}
2015-01-31 17:20:46 +00:00
for binding in &*data.bindings {
if comma {
try!(self.word_space(","))
}
try!(self.print_ident(binding.ident));
try!(space(&mut self.s));
try!(self.word_space("="));
try!(self.print_type(&*binding.ty));
comma = true;
2014-03-16 18:58:11 +00:00
}
try!(word(&mut self.s, ">"))
}
ast::ParenthesizedParameters(ref data) => {
try!(word(&mut self.s, "("));
try!(self.commasep(
Inconsistent,
2015-02-18 23:58:07 +00:00
&data.inputs,
|s, ty| s.print_type(&**ty)));
try!(word(&mut self.s, ")"));
match data.output {
None => { }
Some(ref ty) => {
try!(self.space_if_not_bol());
try!(self.word_space("->"));
try!(self.print_type(&**ty));
}
}
}
}
Ok(())
}
pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.maybe_print_comment(pat.span.lo));
try!(self.ann.pre(self, NodePat(pat)));
/* Pat isn't normalized, but the beauty of it
is that it doesn't matter */
match pat.node {
ast::PatWild(ast::PatWildSingle) => try!(word(&mut self.s, "_")),
ast::PatWild(ast::PatWildMulti) => try!(word(&mut self.s, "..")),
2014-09-13 16:06:01 +00:00
ast::PatIdent(binding_mode, ref path1, ref sub) => {
2014-03-16 18:58:11 +00:00
match binding_mode {
ast::BindByRef(mutbl) => {
try!(self.word_nbsp("ref"));
try!(self.print_mutability(mutbl));
}
ast::BindByValue(ast::MutImmutable) => {}
ast::BindByValue(ast::MutMutable) => {
try!(self.word_nbsp("mut"));
}
}
try!(self.print_ident(path1.node));
2014-09-13 16:06:01 +00:00
match *sub {
2014-05-16 07:16:13 +00:00
Some(ref p) => {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "@"));
2014-05-16 07:16:13 +00:00
try!(self.print_pat(&**p));
2014-03-16 18:58:11 +00:00
}
None => ()
}
}
ast::PatEnum(ref path, ref args_) => {
try!(self.print_path(path, true, 0));
2014-03-16 18:58:11 +00:00
match *args_ {
None => try!(word(&mut self.s, "(..)")),
Some(ref args) => {
if !args.is_empty() {
try!(self.popen());
try!(self.commasep(Inconsistent, &args[..],
2014-05-16 07:16:13 +00:00
|s, p| s.print_pat(&**p)));
2014-03-16 18:58:11 +00:00
try!(self.pclose());
}
}
2013-11-08 03:25:39 +00:00
}
}
2014-03-16 18:58:11 +00:00
ast::PatStruct(ref path, ref fields, etc) => {
try!(self.print_path(path, true, 0));
try!(self.nbsp());
try!(self.word_space("{"));
2014-03-16 18:58:11 +00:00
try!(self.commasep_cmnt(
Consistent, &fields[..],
2014-03-16 18:58:11 +00:00
|s, f| {
try!(s.cbox(indent_unit));
if !f.node.is_shorthand {
try!(s.print_ident(f.node.ident));
try!(s.word_nbsp(":"));
}
try!(s.print_pat(&*f.node.pat));
2014-03-16 18:58:11 +00:00
s.end()
},
|f| f.node.pat.span));
2014-03-16 18:58:11 +00:00
if etc {
if fields.len() != 0 { try!(self.word_space(",")); }
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, ".."));
}
try!(space(&mut self.s));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "}"));
}
ast::PatTup(ref elts) => {
try!(self.popen());
try!(self.commasep(Inconsistent,
&elts[..],
2014-05-16 07:16:13 +00:00
|s, p| s.print_pat(&**p)));
2014-03-16 18:58:11 +00:00
if elts.len() == 1 {
try!(word(&mut self.s, ","));
}
try!(self.pclose());
}
2014-05-16 07:16:13 +00:00
ast::PatBox(ref inner) => {
try!(word(&mut self.s, "box "));
2014-05-16 07:16:13 +00:00
try!(self.print_pat(&**inner));
2014-03-16 18:58:11 +00:00
}
ast::PatRegion(ref inner, mutbl) => {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "&"));
if mutbl == ast::MutMutable {
try!(word(&mut self.s, "mut "));
}
2014-05-16 07:16:13 +00:00
try!(self.print_pat(&**inner));
2014-03-16 18:58:11 +00:00
}
2014-05-16 07:16:13 +00:00
ast::PatLit(ref e) => try!(self.print_expr(&**e)),
ast::PatRange(ref begin, ref end) => {
try!(self.print_expr(&**begin));
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
try!(word(&mut self.s, "..."));
2014-05-16 07:16:13 +00:00
try!(self.print_expr(&**end));
2014-03-16 18:58:11 +00:00
}
2014-09-13 16:06:01 +00:00
ast::PatVec(ref before, ref slice, ref after) => {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "["));
try!(self.commasep(Inconsistent,
&before[..],
2014-05-16 07:16:13 +00:00
|s, p| s.print_pat(&**p)));
2015-01-31 17:20:46 +00:00
if let Some(ref p) = *slice {
2014-03-16 18:58:11 +00:00
if !before.is_empty() { try!(self.word_space(",")); }
try!(self.print_pat(&**p));
2014-05-16 07:16:13 +00:00
match **p {
ast::Pat { node: ast::PatWild(ast::PatWildMulti), .. } => {
2014-03-16 18:58:11 +00:00
// this case is handled by print_pat
}
_ => try!(word(&mut self.s, "..")),
}
if !after.is_empty() { try!(self.word_space(",")); }
}
try!(self.commasep(Inconsistent,
&after[..],
2014-05-16 07:16:13 +00:00
|s, p| s.print_pat(&**p)));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "]"));
}
ast::PatMac(ref m) => try!(self.print_mac(m, token::Paren)),
}
2014-03-16 18:58:11 +00:00
self.ann.post(self, NodePat(pat))
}
fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
// I have no idea why this check is necessary, but here it
// is :(
if arm.attrs.is_empty() {
try!(space(&mut self.s));
}
try!(self.cbox(indent_unit));
try!(self.ibox(0));
2015-02-18 23:58:07 +00:00
try!(self.print_outer_attributes(&arm.attrs));
let mut first = true;
2015-01-31 17:20:46 +00:00
for p in &arm.pats {
if first {
first = false;
} else {
try!(space(&mut self.s));
try!(self.word_space("|"));
}
try!(self.print_pat(&**p));
}
try!(space(&mut self.s));
2014-11-22 15:24:58 +00:00
if let Some(ref e) = arm.guard {
try!(self.word_space("if"));
try!(self.print_expr(&**e));
try!(space(&mut self.s));
}
try!(self.word_space("=>"));
match arm.body.node {
ast::ExprBlock(ref blk) => {
// the block will close the pattern's ibox
2014-11-22 15:24:58 +00:00
try!(self.print_block_unclosed_indent(&**blk, indent_unit));
// If it is a user-provided unsafe block, print a comma after it
if let ast::UnsafeBlock(ast::UserProvided) = blk.rules {
try!(word(&mut self.s, ","));
}
}
_ => {
try!(self.end()); // close the ibox for the pattern
try!(self.print_expr(&*arm.body));
try!(word(&mut self.s, ","));
}
}
self.end() // close enclosing cbox
}
2014-03-16 18:58:11 +00:00
// Returns whether it printed anything
fn print_explicit_self(&mut self,
2014-09-13 16:06:01 +00:00
explicit_self: &ast::ExplicitSelf_,
mutbl: ast::Mutability) -> io::Result<bool> {
2014-03-16 18:58:11 +00:00
try!(self.print_mutability(mutbl));
2014-09-13 16:06:01 +00:00
match *explicit_self {
2014-03-16 18:58:11 +00:00
ast::SelfStatic => { return Ok(false); }
ast::SelfValue(_) => {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "self"));
}
ast::SelfRegion(ref lt, m, _) => {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "&"));
try!(self.print_opt_lifetime(lt));
try!(self.print_mutability(m));
try!(word(&mut self.s, "self"));
}
ast::SelfExplicit(ref typ, _) => {
try!(word(&mut self.s, "self"));
try!(self.word_space(":"));
try!(self.print_type(&**typ));
}
}
2014-03-16 18:58:11 +00:00
return Ok(true);
}
2014-03-16 18:58:11 +00:00
pub fn print_fn(&mut self,
decl: &ast::FnDecl,
unsafety: ast::Unsafety,
abi: abi::Abi,
name: Option<ast::Ident>,
2014-03-16 18:58:11 +00:00
generics: &ast::Generics,
2014-09-13 16:06:01 +00:00
opt_explicit_self: Option<&ast::ExplicitSelf_>,
vis: ast::Visibility) -> io::Result<()> {
try!(self.print_fn_header_info(unsafety, abi, vis));
if let Some(name) = name {
try!(self.nbsp());
try!(self.print_ident(name));
}
2014-03-16 18:58:11 +00:00
try!(self.print_generics(generics));
try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
self.print_where_clause(generics)
2014-03-16 18:58:11 +00:00
}
pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
2014-09-13 16:06:01 +00:00
opt_explicit_self: Option<&ast::ExplicitSelf_>)
-> io::Result<()> {
2014-03-16 18:58:11 +00:00
// It is unfortunate to duplicate the commasep logic, but we want the
// self type and the args all in the same box.
try!(self.rbox(0, Inconsistent));
2014-03-16 18:58:11 +00:00
let mut first = true;
2015-01-31 17:20:46 +00:00
if let Some(explicit_self) = opt_explicit_self {
2014-03-16 18:58:11 +00:00
let m = match explicit_self {
2014-09-13 16:06:01 +00:00
&ast::SelfStatic => ast::MutImmutable,
_ => match decl.inputs[0].pat.node {
2014-03-16 18:58:11 +00:00
ast::PatIdent(ast::BindByValue(m), _, _) => m,
_ => ast::MutImmutable
}
};
first = !try!(self.print_explicit_self(explicit_self, m));
}
2014-03-16 18:58:11 +00:00
// HACK(eddyb) ignore the separately printed self argument.
let args = if first {
&decl.inputs[..]
2014-03-16 18:58:11 +00:00
} else {
2015-01-18 00:15:52 +00:00
&decl.inputs[1..]
};
2015-01-31 17:20:46 +00:00
for arg in args {
2014-03-16 18:58:11 +00:00
if first { first = false; } else { try!(self.word_space(",")); }
try!(self.print_arg(arg));
}
2014-03-16 18:58:11 +00:00
self.end()
}
2014-03-16 18:58:11 +00:00
pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
2014-09-13 16:06:01 +00:00
opt_explicit_self: Option<&ast::ExplicitSelf_>)
-> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.popen());
try!(self.print_fn_args(decl, opt_explicit_self));
if decl.variadic {
try!(word(&mut self.s, ", ..."));
}
try!(self.pclose());
self.print_fn_output(decl)
}
pub fn print_fn_block_args(
&mut self,
decl: &ast::FnDecl)
-> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "|"));
try!(self.print_fn_args(decl, None));
try!(word(&mut self.s, "|"));
if let ast::DefaultReturn(..) = decl.output {
return Ok(());
}
2014-03-16 18:58:11 +00:00
try!(self.space_if_not_bol());
try!(self.word_space("->"));
match decl.output {
ast::Return(ref ty) => {
try!(self.print_type(&**ty));
self.maybe_print_comment(ty.span.lo)
}
ast::DefaultReturn(..) => unreachable!(),
ast::NoReturn(span) => {
try!(self.word_nbsp("!"));
self.maybe_print_comment(span.lo)
}
}
}
pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
-> io::Result<()> {
match capture_clause {
ast::CaptureByValue => self.word_space("move"),
ast::CaptureByRef => Ok(()),
}
}
pub fn print_bounds(&mut self,
prefix: &str,
bounds: &[ast::TyParamBound])
-> io::Result<()> {
if !bounds.is_empty() {
try!(word(&mut self.s, prefix));
2014-03-16 18:58:11 +00:00
let mut first = true;
2015-01-31 17:20:46 +00:00
for bound in bounds {
2014-03-16 18:58:11 +00:00
try!(self.nbsp());
if first {
first = false;
} else {
try!(self.word_space("+"));
}
2014-03-16 18:58:11 +00:00
try!(match *bound {
TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
self.print_poly_trait_ref(tref)
}
TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
try!(word(&mut self.s, "?"));
2014-11-07 11:53:45 +00:00
self.print_poly_trait_ref(tref)
}
RegionTyParamBound(ref lt) => {
self.print_lifetime(lt)
}
2014-03-16 18:58:11 +00:00
})
}
Ok(())
} else {
Ok(())
}
}
2014-03-16 18:58:11 +00:00
pub fn print_lifetime(&mut self,
lifetime: &ast::Lifetime)
-> io::Result<()>
{
2014-03-16 18:58:11 +00:00
self.print_name(lifetime.name)
}
pub fn print_lifetime_def(&mut self,
lifetime: &ast::LifetimeDef)
-> io::Result<()>
{
try!(self.print_lifetime(&lifetime.lifetime));
let mut sep = ":";
2015-01-31 17:20:46 +00:00
for v in &lifetime.bounds {
try!(word(&mut self.s, sep));
try!(self.print_lifetime(v));
sep = "+";
}
Ok(())
}
pub fn print_generics(&mut self,
generics: &ast::Generics)
-> io::Result<()>
{
let total = generics.lifetimes.len() + generics.ty_params.len();
if total == 0 {
return Ok(());
}
try!(word(&mut self.s, "<"));
let mut ints = Vec::new();
for i in 0..total {
ints.push(i);
}
2014-03-16 18:58:11 +00:00
try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
if idx < generics.lifetimes.len() {
let lifetime = &generics.lifetimes[idx];
s.print_lifetime_def(lifetime)
} else {
let idx = idx - generics.lifetimes.len();
let param = &generics.ty_params[idx];
s.print_ty_param(param)
}
}));
try!(word(&mut self.s, ">"));
Ok(())
2011-08-03 04:26:54 +00:00
}
pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
try!(self.print_ident(param.ident));
2015-02-18 23:58:07 +00:00
try!(self.print_bounds(":", &param.bounds));
match param.default {
Some(ref default) => {
try!(space(&mut self.s));
try!(self.word_space("="));
self.print_type(&**default)
}
_ => Ok(())
}
}
pub fn print_where_clause(&mut self, generics: &ast::Generics)
-> io::Result<()> {
if generics.where_clause.predicates.len() == 0 {
return Ok(())
}
try!(space(&mut self.s));
try!(self.word_space("where"));
for (i, predicate) in generics.where_clause
.predicates
.iter()
.enumerate() {
if i != 0 {
try!(self.word_space(","));
}
match predicate {
2015-02-09 03:49:27 +00:00
&ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
ref bounded_ty,
ref bounds,
..}) => {
2015-02-09 03:49:27 +00:00
try!(self.print_formal_lifetime_list(bound_lifetimes));
try!(self.print_type(&**bounded_ty));
try!(self.print_bounds(":", bounds));
}
&ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
ref bounds,
..}) => {
try!(self.print_lifetime(lifetime));
try!(word(&mut self.s, ":"));
for (i, bound) in bounds.iter().enumerate() {
try!(self.print_lifetime(bound));
if i != 0 {
try!(word(&mut self.s, ":"));
}
}
}
&ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
try!(self.print_path(path, false, 0));
try!(space(&mut self.s));
try!(self.word_space("="));
try!(self.print_type(&**ty));
}
}
}
Ok(())
}
pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.ibox(indent_unit));
match item.node {
ast::MetaWord(ref name) => {
try!(word(&mut self.s, &name));
2014-03-16 18:58:11 +00:00
}
ast::MetaNameValue(ref name, ref value) => {
try!(self.word_space(&name[..]));
2014-03-16 18:58:11 +00:00
try!(self.word_space("="));
try!(self.print_literal(value));
}
ast::MetaList(ref name, ref items) => {
try!(word(&mut self.s, &name));
2014-03-16 18:58:11 +00:00
try!(self.popen());
try!(self.commasep(Consistent,
&items[..],
2014-05-16 07:16:13 +00:00
|s, i| s.print_meta_item(&**i)));
2014-03-16 18:58:11 +00:00
try!(self.pclose());
}
}
2014-03-16 18:58:11 +00:00
self.end()
}
pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
match vp.node {
ast::ViewPathSimple(ident, ref path) => {
try!(self.print_path(path, false, 0));
2014-03-16 18:58:11 +00:00
// FIXME(#6993) can't compare identifiers directly here
if path.segments.last().unwrap().identifier.name !=
ident.name {
2014-03-16 18:58:11 +00:00
try!(space(&mut self.s));
try!(self.word_space("as"));
try!(self.print_ident(ident));
2014-03-16 18:58:11 +00:00
}
Ok(())
2014-03-16 18:58:11 +00:00
}
ast::ViewPathGlob(ref path) => {
try!(self.print_path(path, false, 0));
2014-03-16 18:58:11 +00:00
word(&mut self.s, "::*")
}
ast::ViewPathList(ref path, ref idents) => {
2014-03-16 18:58:11 +00:00
if path.segments.is_empty() {
try!(word(&mut self.s, "{"));
} else {
try!(self.print_path(path, false, 0));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, "::{"));
}
try!(self.commasep(Inconsistent, &idents[..], |s, w| {
match w.node {
ast::PathListIdent { name, .. } => {
s.print_ident(name)
},
ast::PathListMod { .. } => {
word(&mut s.s, "self")
}
}
2014-03-16 18:58:11 +00:00
}));
word(&mut self.s, "}")
}
}
}
2014-03-16 18:58:11 +00:00
pub fn print_mutability(&mut self,
mutbl: ast::Mutability) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
match mutbl {
ast::MutMutable => self.word_nbsp("mut"),
ast::MutImmutable => Ok(()),
}
}
pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.print_mutability(mt.mutbl));
2014-05-16 07:16:13 +00:00
self.print_type(&*mt.ty)
}
pub fn print_arg(&mut self, input: &ast::Arg) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.ibox(indent_unit));
match input.ty.node {
2014-05-16 07:16:13 +00:00
ast::TyInfer => try!(self.print_pat(&*input.pat)),
2014-03-16 18:58:11 +00:00
_ => {
match input.pat.node {
ast::PatIdent(_, ref path1, _) if
path1.node.name ==
2014-03-16 18:58:11 +00:00
parse::token::special_idents::invalid.name => {
// Do nothing.
}
_ => {
2014-05-16 07:16:13 +00:00
try!(self.print_pat(&*input.pat));
2014-03-16 18:58:11 +00:00
try!(word(&mut self.s, ":"));
try!(space(&mut self.s));
}
}
2014-05-16 07:16:13 +00:00
try!(self.print_type(&*input.ty));
}
2012-05-04 19:33:04 +00:00
}
2014-03-16 18:58:11 +00:00
self.end()
}
pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
if let ast::DefaultReturn(..) = decl.output {
return Ok(());
}
try!(self.space_if_not_bol());
try!(self.ibox(indent_unit));
try!(self.word_space("->"));
match decl.output {
ast::NoReturn(_) =>
try!(self.word_nbsp("!")),
ast::DefaultReturn(..) => unreachable!(),
ast::Return(ref ty) =>
try!(self.print_type(&**ty))
}
try!(self.end());
match decl.output {
ast::Return(ref output) => self.maybe_print_comment(output.span.lo),
_ => Ok(())
}
}
2014-03-16 18:58:11 +00:00
pub fn print_ty_fn(&mut self,
abi: abi::Abi,
2014-12-09 15:36:46 +00:00
unsafety: ast::Unsafety,
2014-03-16 18:58:11 +00:00
decl: &ast::FnDecl,
name: Option<ast::Ident>,
generics: &ast::Generics,
opt_explicit_self: Option<&ast::ExplicitSelf_>)
-> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.ibox(indent_unit));
try!(self.print_fn(decl, unsafety, abi, name,
generics, opt_explicit_self,
ast::Inherited));
2014-03-16 18:58:11 +00:00
self.end()
2014-01-30 01:39:21 +00:00
}
2014-03-16 18:58:11 +00:00
pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
next_pos: Option<BytePos>)
-> io::Result<()> {
2014-03-16 18:58:11 +00:00
let cm = match self.cm {
Some(cm) => cm,
_ => return Ok(())
};
match self.next_comment() {
2014-01-30 01:39:21 +00:00
Some(ref cmnt) => {
2014-03-16 18:58:11 +00:00
if (*cmnt).style != comments::Trailing { return Ok(()) }
let span_line = cm.lookup_char_pos(span.hi);
let comment_line = cm.lookup_char_pos((*cmnt).pos);
let mut next = (*cmnt).pos + BytePos(1);
match next_pos { None => (), Some(p) => next = p }
if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
span_line.line == comment_line.line {
try!(self.print_comment(cmnt));
self.cur_cmnt_and_lit.cur_cmnt += 1;
2014-03-16 18:58:11 +00:00
}
2014-01-30 01:39:21 +00:00
}
2014-03-16 18:58:11 +00:00
_ => ()
}
2014-03-16 18:58:11 +00:00
Ok(())
}
pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
// If there aren't any remaining comments, then we need to manually
// make sure there is a line break at the end.
if self.next_comment().is_none() {
try!(hardbreak(&mut self.s));
}
loop {
match self.next_comment() {
Some(ref cmnt) => {
try!(self.print_comment(cmnt));
self.cur_cmnt_and_lit.cur_cmnt += 1;
2014-03-16 18:58:11 +00:00
}
_ => break
}
}
Ok(())
}
pub fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
try!(self.maybe_print_comment(lit.span.lo));
match self.next_lit(lit.span.lo) {
Some(ref ltrl) => {
2015-02-18 23:58:07 +00:00
return word(&mut self.s, &(*ltrl).lit);
2014-03-16 18:58:11 +00:00
}
_ => ()
}
match lit.node {
ast::LitStr(ref st, style) => self.print_string(&st, style),
2014-06-06 15:04:04 +00:00
ast::LitByte(byte) => {
let mut res = String::from_str("b'");
res.extend(ascii::escape_default(byte).map(|c| c as char));
res.push('\'');
word(&mut self.s, &res[..])
2014-06-06 15:04:04 +00:00
}
2014-03-16 18:58:11 +00:00
ast::LitChar(ch) => {
let mut res = String::from_str("'");
res.extend(ch.escape_default());
res.push('\'');
word(&mut self.s, &res[..])
2014-03-16 18:58:11 +00:00
}
ast::LitInt(i, t) => {
match t {
ast::SignedIntLit(st, ast::Plus) => {
word(&mut self.s,
2015-02-18 23:58:07 +00:00
&ast_util::int_ty_to_string(st, Some(i as i64)))
}
ast::SignedIntLit(st, ast::Minus) => {
let istr = ast_util::int_ty_to_string(st, Some(-(i as i64)));
word(&mut self.s,
2015-02-18 23:58:07 +00:00
&format!("-{}", istr))
}
ast::UnsignedIntLit(ut) => {
word(&mut self.s, &ast_util::uint_ty_to_string(ut, Some(i)))
}
ast::UnsuffixedIntLit(ast::Plus) => {
2015-02-18 23:58:07 +00:00
word(&mut self.s, &format!("{}", i))
}
ast::UnsuffixedIntLit(ast::Minus) => {
2015-02-18 23:58:07 +00:00
word(&mut self.s, &format!("-{}", i))
}
}
2014-03-16 18:58:11 +00:00
}
ast::LitFloat(ref f, t) => {
word(&mut self.s,
2015-01-07 16:58:31 +00:00
&format!(
"{}{}",
&f,
2015-02-18 23:58:07 +00:00
&ast_util::float_ty_to_string(t)))
2014-03-16 18:58:11 +00:00
}
ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, &f[..]),
2014-03-16 18:58:11 +00:00
ast::LitBool(val) => {
if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
}
ast::LitBinary(ref v) => {
let mut escaped: String = String::new();
2015-01-31 17:20:46 +00:00
for &ch in &**v {
escaped.extend(ascii::escape_default(ch as u8)
.map(|c| c as char));
}
2015-02-18 23:58:07 +00:00
word(&mut self.s, &format!("b\"{}\"", escaped))
2014-03-16 18:58:11 +00:00
}
}
}
2014-03-16 18:58:11 +00:00
pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
match self.literals {
Some(ref lits) => {
while self.cur_cmnt_and_lit.cur_lit < lits.len() {
let ltrl = (*lits)[self.cur_cmnt_and_lit.cur_lit].clone();
2014-03-16 18:58:11 +00:00
if ltrl.pos > pos { return None; }
self.cur_cmnt_and_lit.cur_lit += 1;
2014-03-16 18:58:11 +00:00
if ltrl.pos == pos { return Some(ltrl); }
}
None
}
_ => None
}
}
pub fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
loop {
match self.next_comment() {
Some(ref cmnt) => {
if (*cmnt).pos < pos {
try!(self.print_comment(cmnt));
self.cur_cmnt_and_lit.cur_cmnt += 1;
2014-03-16 18:58:11 +00:00
} else { break; }
2014-01-30 01:39:21 +00:00
}
2014-03-16 18:58:11 +00:00
_ => break
}
}
2014-03-16 18:58:11 +00:00
Ok(())
}
pub fn print_comment(&mut self,
cmnt: &comments::Comment) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
match cmnt.style {
comments::Mixed => {
assert_eq!(cmnt.lines.len(), 1);
2014-03-16 18:58:11 +00:00
try!(zerobreak(&mut self.s));
2015-02-18 23:58:07 +00:00
try!(word(&mut self.s, &cmnt.lines[0]));
2014-03-16 18:58:11 +00:00
zerobreak(&mut self.s)
}
comments::Isolated => {
try!(self.hardbreak_if_not_bol());
2015-01-31 17:20:46 +00:00
for line in &cmnt.lines {
2014-03-16 18:58:11 +00:00
// Don't print empty lines because they will end up as trailing
// whitespace
2014-01-30 01:39:21 +00:00
if !line.is_empty() {
try!(word(&mut self.s, &line[..]));
2014-01-30 01:39:21 +00:00
}
2014-03-16 18:58:11 +00:00
try!(hardbreak(&mut self.s));
}
2014-03-16 18:58:11 +00:00
Ok(())
}
2014-03-16 18:58:11 +00:00
comments::Trailing => {
try!(word(&mut self.s, " "));
if cmnt.lines.len() == 1 {
2015-02-18 23:58:07 +00:00
try!(word(&mut self.s, &cmnt.lines[0]));
2014-03-16 18:58:11 +00:00
hardbreak(&mut self.s)
} else {
try!(self.ibox(0));
2015-01-31 17:20:46 +00:00
for line in &cmnt.lines {
2014-03-16 18:58:11 +00:00
if !line.is_empty() {
try!(word(&mut self.s, &line[..]));
2014-03-16 18:58:11 +00:00
}
try!(hardbreak(&mut self.s));
}
self.end()
}
}
comments::BlankLine => {
// We need to do at least one, possibly two hardbreaks.
let is_semi = match self.s.last_token() {
pp::Token::String(s, _) => ";" == s,
2014-03-16 18:58:11 +00:00
_ => false
};
if is_semi || self.is_begin() || self.is_end() {
try!(hardbreak(&mut self.s));
}
hardbreak(&mut self.s)
2014-01-30 01:39:21 +00:00
}
}
}
2014-03-16 18:58:11 +00:00
pub fn print_string(&mut self, st: &str,
style: ast::StrStyle) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
let st = match style {
ast::CookedStr => {
(format!("\"{}\"", st.escape_default()))
}
ast::RawStr(n) => {
(format!("r{delim}\"{string}\"{delim}",
2014-12-11 03:46:38 +00:00
delim=repeat("#", n),
string=st))
}
2014-03-16 18:58:11 +00:00
};
word(&mut self.s, &st[..])
2013-12-27 22:28:54 +00:00
}
2014-03-16 18:58:11 +00:00
pub fn next_comment(&mut self) -> Option<comments::Comment> {
match self.comments {
Some(ref cmnts) => {
if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
Some(cmnts[self.cur_cmnt_and_lit.cur_cmnt].clone())
2014-03-16 18:58:11 +00:00
} else {
None
}
}
2014-03-16 18:58:11 +00:00
_ => None
2013-07-02 19:47:32 +00:00
}
}
pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
opt_abi: Option<abi::Abi>)
-> io::Result<()> {
match opt_abi {
Some(abi::Rust) => Ok(()),
Some(abi) => {
2014-03-16 18:58:11 +00:00
try!(self.word_nbsp("extern"));
2015-02-18 23:58:07 +00:00
self.word_nbsp(&abi.to_string())
2014-03-16 18:58:11 +00:00
}
None => Ok(())
}
2014-03-16 18:58:11 +00:00
}
pub fn print_extern_opt_abi(&mut self,
opt_abi: Option<abi::Abi>) -> io::Result<()> {
match opt_abi {
Some(abi) => {
2014-03-16 18:58:11 +00:00
try!(self.word_nbsp("extern"));
2015-02-18 23:58:07 +00:00
self.word_nbsp(&abi.to_string())
2014-03-16 18:58:11 +00:00
}
None => Ok(())
}
2014-01-30 01:39:21 +00:00
}
2014-03-16 18:58:11 +00:00
pub fn print_fn_header_info(&mut self,
unsafety: ast::Unsafety,
abi: abi::Abi,
vis: ast::Visibility) -> io::Result<()> {
try!(word(&mut self.s, &visibility_qualified(vis, "")));
try!(self.print_unsafety(unsafety));
if abi != abi::Rust {
2014-03-16 18:58:11 +00:00
try!(self.word_nbsp("extern"));
2015-02-18 23:58:07 +00:00
try!(self.word_nbsp(&abi.to_string()));
}
2014-04-09 12:33:42 +00:00
word(&mut self.s, "fn")
2012-05-25 06:44:58 +00:00
}
pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
match s {
2014-12-09 15:36:46 +00:00
ast::Unsafety::Normal => Ok(()),
ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2014-03-16 18:58:11 +00:00
}
2012-05-25 06:44:58 +00:00
}
}
2015-01-17 23:33:05 +00:00
fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
2014-12-11 03:46:38 +00:00
#[cfg(test)]
mod test {
use super::*;
use ast;
use ast_util;
use codemap;
use parse::token;
#[test]
fn test_fun_to_string() {
let abba_ident = token::str_to_ident("abba");
let decl = ast::FnDecl {
inputs: Vec::new(),
output: ast::DefaultReturn(codemap::DUMMY_SP),
variadic: false
};
let generics = ast_util::empty_generics();
2014-12-09 15:36:46 +00:00
assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal, abba_ident,
None, &generics),
"fn abba()");
}
#[test]
fn test_variant_to_string() {
let ident = token::str_to_ident("principal_skinner");
let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
name: ident,
attrs: Vec::new(),
// making this up as I go.... ?
kind: ast::TupleVariantKind(Vec::new()),
id: 0,
disr_expr: None,
vis: ast::Public,
});
let varstr = variant_to_string(&var);
assert_eq!(varstr, "pub principal_skinner");
}
#[test]
fn test_signed_int_to_string() {
let pos_int = ast::LitInt(42, ast::SignedIntLit(ast::TyI32, ast::Plus));
let neg_int = ast::LitInt((-42) as u64, ast::SignedIntLit(ast::TyI32, ast::Minus));
assert_eq!(format!("-{}", lit_to_string(&codemap::dummy_spanned(pos_int))),
lit_to_string(&codemap::dummy_spanned(neg_int)));
}
}