rust/src/libsyntax/print/pprust.rs

3187 lines
113 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::{self, Abi};
use ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax};
2016-03-06 12:54:44 +00:00
use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
2015-11-15 16:17:50 +00:00
use ast::Attribute;
2017-07-20 20:53:56 +00:00
use util::parser::{self, AssocOp, Fixity};
use attr;
use codemap::{self, CodeMap};
use syntax_pos::{self, BytePos};
use parse::token::{self, BinOpToken, Token};
2014-05-21 23:57:31 +00:00
use parse::lexer::comments;
use parse::{self, ParseSess};
use print::pp::{self, Breaks};
use print::pp::Breaks::{Consistent, Inconsistent};
2014-09-13 16:06:01 +00:00
use ptr::P;
use std_inject;
use symbol::{Symbol, keywords};
use syntax_pos::DUMMY_SP;
use tokenstream::{self, TokenStream, TokenTree};
use std::ascii;
use std::io::{self, Write, Read};
use std::iter::{self, Peekable};
use std::vec;
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),
2015-03-24 01:52:55 +00:00
NodeSubItem(ast::NodeId),
2014-03-16 18:58:11 +00:00
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(()) }
}
2015-03-30 13:38:59 +00:00
#[derive(Copy, Clone)]
pub struct NoAnn;
impl PpAnn for NoAnn {}
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: Peekable<vec::IntoIter<comments::Literal>>,
cur_cmnt: usize,
2014-03-27 17:31:00 +00:00
boxes: Vec<pp::Breaks>,
ann: &'a (PpAnn+'a),
}
2017-06-25 13:51:55 +00:00
fn rust_printer<'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: vec![].into_iter().peekable(),
cur_cmnt: 0,
2014-03-27 17:31:00 +00:00
boxes: Vec::new(),
ann,
2014-02-06 22:38:33 +00:00
}
}
pub const INDENT_UNIT: usize = 4;
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,
sess: &ParseSess,
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, sess, filename, input, out, ann, is_expanded);
if is_expanded && !std_inject::injected_crate_name(krate).is_none() {
// 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.
std: Stabilize APIs for the 1.6 release This commit is the standard API stabilization commit for the 1.6 release cycle. The list of issues and APIs below have all been through their cycle-long FCP and the libs team decisions are listed below Stabilized APIs * `Read::read_exact` * `ErrorKind::UnexpectedEof` (renamed from `UnexpectedEOF`) * libcore -- this was a bit of a nuanced stabilization, the crate itself is now marked as `#[stable]` and the methods appearing via traits for primitives like `char` and `str` are now also marked as stable. Note that the extension traits themeselves are marked as unstable as they're imported via the prelude. The `try!` macro was also moved from the standard library into libcore to have the same interface. Otherwise the functions all have copied stability from the standard library now. * The `#![no_std]` attribute * `fs::DirBuilder` * `fs::DirBuilder::new` * `fs::DirBuilder::recursive` * `fs::DirBuilder::create` * `os::unix::fs::DirBuilderExt` * `os::unix::fs::DirBuilderExt::mode` * `vec::Drain` * `vec::Vec::drain` * `string::Drain` * `string::String::drain` * `vec_deque::Drain` * `vec_deque::VecDeque::drain` * `collections::hash_map::Drain` * `collections::hash_map::HashMap::drain` * `collections::hash_set::Drain` * `collections::hash_set::HashSet::drain` * `collections::binary_heap::Drain` * `collections::binary_heap::BinaryHeap::drain` * `Vec::extend_from_slice` (renamed from `push_all`) * `Mutex::get_mut` * `Mutex::into_inner` * `RwLock::get_mut` * `RwLock::into_inner` * `Iterator::min_by_key` (renamed from `min_by`) * `Iterator::max_by_key` (renamed from `max_by`) Deprecated APIs * `ErrorKind::UnexpectedEOF` (renamed to `UnexpectedEof`) * `OsString::from_bytes` * `OsStr::to_cstring` * `OsStr::to_bytes` * `fs::walk_dir` and `fs::WalkDir` * `path::Components::peek` * `slice::bytes::MutableByteVector` * `slice::bytes::copy_memory` * `Vec::push_all` (renamed to `extend_from_slice`) * `Duration::span` * `IpAddr` * `SocketAddr::ip` * `Read::tee` * `io::Tee` * `Write::broadcast` * `io::Broadcast` * `Iterator::min_by` (renamed to `min_by_key`) * `Iterator::max_by` (renamed to `max_by_key`) * `net::lookup_addr` New APIs (still unstable) * `<[T]>::sort_by_key` (added to mirror `min_by_key`) Closes #27585 Closes #27704 Closes #27707 Closes #27710 Closes #27711 Closes #27727 Closes #27740 Closes #27744 Closes #27799 Closes #27801 cc #27801 (doesn't close as `Chars` is still unstable) Closes #28968
2015-12-03 01:31:49 +00:00
// #![feature(prelude_import)]
let prelude_import_meta = attr::mk_list_word_item(Symbol::intern("prelude_import"));
let list = attr::mk_list_item(Symbol::intern("feature"), vec![prelude_import_meta]);
let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), list);
s.print_attribute(&fake_attr)?;
// #![no_std]
let no_std_meta = attr::mk_word_item(Symbol::intern("no_std"));
let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), no_std_meta);
s.print_attribute(&fake_attr)?;
}
s.print_mod(&krate.module, &krate.attrs)?;
s.print_remaining_comments()?;
s.s.eof()
2012-02-21 23:34:26 +00:00
}
impl<'a> State<'a> {
pub fn new_from_input(cm: &'a CodeMap,
sess: &ParseSess,
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(sess, 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,
literals: literals.unwrap_or_default().into_iter().peekable(),
cur_cmnt: 0,
boxes: Vec::new(),
ann,
}
}
}
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
{
let mut wr = Vec::new();
{
2017-06-25 13:51:55 +00:00
let ann = NoAnn;
let mut printer = rust_printer(Box::new(&mut wr), &ann);
f(&mut printer).unwrap();
printer.s.eof().unwrap();
}
String::from_utf8(wr).unwrap()
}
2017-06-25 13:51:55 +00:00
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::DotDotEq => "..=".to_string(),
token::DotEq => ".=".to_string(),
2014-12-11 03:46:38 +00:00
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::OpenDelim(token::NoDelim) |
token::CloseDelim(token::NoDelim) => " ".to_string(),
2014-12-11 03:46:38 +00:00
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),
token::Char(c) => format!("'{}'", c),
token::Float(c) |
token::Integer(c) => c.to_string(),
token::Str_(s) => format!("\"{}\"", s),
token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
2014-12-11 03:46:38 +00:00
delim=repeat("#", n),
string=s),
token::ByteStr(v) => format!("b\"{}\"", v),
token::ByteStrRaw(s, n) => format!("br{delim}\"{string}\"{delim}",
2014-12-11 03:46:38 +00:00
delim=repeat("#", n),
string=s),
};
if let Some(s) = suf {
out.push_str(&s.as_str())
}
out
}
/* Name components */
2016-04-16 01:12:02 +00:00
token::Ident(s) => s.to_string(),
token::Lifetime(s) => s.to_string(),
2014-12-11 03:46:38 +00:00
token::Underscore => "_".to_string(),
/* Other */
token::DocComment(s) => s.to_string(),
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),
2017-03-29 01:55:01 +00:00
token::Interpolated(ref nt) => match nt.0 {
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),
token::NtItem(ref e) => item_to_string(e),
token::NtBlock(ref e) => block_to_string(e),
token::NtStmt(ref e) => stmt_to_string(e),
token::NtPat(ref e) => pat_to_string(e),
2016-04-16 01:12:02 +00:00
token::NtIdent(ref e) => ident_to_string(e.node),
2017-02-21 05:05:59 +00:00
token::NtTT(ref tree) => tt_to_string(tree.clone()),
token::NtArm(ref e) => arm_to_string(e),
token::NtImplItem(ref e) => impl_item_to_string(e),
token::NtTraitItem(ref e) => trait_item_to_string(e),
token::NtGenerics(ref e) => generics_to_string(e),
token::NtWhereClause(ref e) => where_clause_to_string(e),
token::NtArg(ref e) => arg_to_string(e),
token::NtVis(ref e) => vis_to_string(e),
}
}
}
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))
}
2017-02-21 05:05:59 +00:00
pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
to_string(|s| s.print_tt(tt))
}
pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
2017-02-21 05:05:59 +00:00
to_string(|s| s.print_tts(tts.iter().cloned().collect()))
}
pub fn tokens_to_string(tokens: TokenStream) -> String {
to_string(|s| s.print_tts(tokens))
}
pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
to_string(|s| s.print_stmt(stmt))
}
2015-04-14 19:18:37 +00:00
pub fn attr_to_string(attr: &ast::Attribute) -> String {
to_string(|s| s.print_attribute(attr))
}
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 trait_item_to_string(i: &ast::TraitItem) -> String {
to_string(|s| s.print_trait_item(i))
}
pub fn generics_to_string(generics: &ast::Generics) -> String {
to_string(|s| s.print_generics(generics))
}
pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
to_string(|s| s.print_where_clause(i))
}
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, false))
}
pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
to_string(|s| s.print_path_segment(p, false))
}
pub fn ident_to_string(id: ast::Ident) -> String {
to_string(|s| s.print_ident(id))
}
pub fn vis_to_string(v: &ast::Visibility) -> String {
to_string(|s| s.print_visibility(v))
}
pub fn fun_to_string(decl: &ast::FnDecl,
unsafety: ast::Unsafety,
constness: ast::Constness,
name: ast::Ident,
generics: &ast::Generics)
-> String {
to_string(|s| {
s.head("")?;
s.print_fn(decl, unsafety, constness, Abi::Rust, Some(name),
generics, &ast::Visibility::Inherited)?;
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 }
s.cbox(INDENT_UNIT)?;
// head-ibox, will be closed by print-block after {
s.ibox(0)?;
s.print_block(blk)
})
}
pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
to_string(|s| s.print_meta_list_item(li))
}
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))
}
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, false))
}
pub fn mac_to_string(arg: &ast::Mac) -> String {
to_string(|s| s.print_mac(arg, ::parse::token::Paren))
}
2016-03-23 10:17:34 +00:00
pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
2014-01-30 01:39:21 +00:00
}
2011-05-29 02:16:18 +00:00
pub trait PrintState<'a> {
fn writer(&mut self) -> &mut pp::Printer<'a>;
fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
fn cur_cmnt(&mut self) -> &mut usize;
fn cur_lit(&mut self) -> Option<&comments::Literal>;
fn bump_lit(&mut self) -> Option<comments::Literal>;
fn word_space(&mut self, w: &str) -> io::Result<()> {
self.writer().word(w)?;
self.writer().space()
2014-03-16 18:58:11 +00:00
}
2011-05-29 02:16:18 +00:00
fn popen(&mut self) -> io::Result<()> { self.writer().word("(") }
fn pclose(&mut self) -> io::Result<()> { self.writer().word(")") }
fn is_begin(&mut self) -> bool {
match self.writer().last_token() {
pp::Token::Begin(_) => true,
_ => false,
}
2014-03-16 18:58:11 +00:00
}
2011-05-29 02:16:18 +00:00
fn is_end(&mut self) -> bool {
match self.writer().last_token() {
pp::Token::End => true,
_ => false,
}
}
// is this the beginning of a line?
fn is_bol(&mut self) -> bool {
self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
}
fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
if !self.is_bol() {
self.writer().hardbreak()?
}
Ok(())
2014-03-16 18:58:11 +00:00
}
2011-05-29 02:16:18 +00:00
2014-03-16 18:58:11 +00:00
// "raw box"
fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
self.boxes().push(b);
self.writer().rbox(u, b)
}
2011-05-29 02:16:18 +00:00
fn ibox(&mut self, u: usize) -> io::Result<()> {
self.boxes().push(pp::Breaks::Inconsistent);
self.writer().ibox(u)
}
2011-05-29 02:16:18 +00:00
fn end(&mut self) -> io::Result<()> {
self.boxes().pop().unwrap();
self.writer().end()
2014-03-16 18:58:11 +00:00
}
2011-05-29 02:16:18 +00:00
fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
where F: FnMut(&mut Self, &T) -> io::Result<()>,
{
self.rbox(0, b)?;
let mut first = true;
for elt in elts {
if first { first = false; } else { self.word_space(",")?; }
op(self, elt)?;
}
self.end()
}
fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
while let Some(ltrl) = self.cur_lit().cloned() {
if ltrl.pos > pos { break; }
// we don't need the value here since we're forced to clone cur_lit
// due to lack of NLL.
self.bump_lit();
if ltrl.pos == pos {
return Some(ltrl);
}
}
None
}
fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
2016-10-12 17:54:41 +00:00
while let Some(ref cmnt) = self.next_comment() {
if cmnt.pos < pos {
self.print_comment(cmnt)?;
2016-10-12 17:54:41 +00:00
} else {
break
}
}
Ok(())
}
fn print_comment(&mut self,
cmnt: &comments::Comment) -> io::Result<()> {
let r = match cmnt.style {
comments::Mixed => {
assert_eq!(cmnt.lines.len(), 1);
self.writer().zerobreak()?;
self.writer().word(&cmnt.lines[0])?;
self.writer().zerobreak()
}
comments::Isolated => {
self.hardbreak_if_not_bol()?;
for line in &cmnt.lines {
// Don't print empty lines because they will end up as trailing
// whitespace
if !line.is_empty() {
self.writer().word(&line[..])?;
}
self.writer().hardbreak()?;
}
Ok(())
}
comments::Trailing => {
2016-10-12 17:54:41 +00:00
if !self.is_bol() {
self.writer().word(" ")?;
2016-10-12 17:54:41 +00:00
}
if cmnt.lines.len() == 1 {
self.writer().word(&cmnt.lines[0])?;
self.writer().hardbreak()
} else {
self.ibox(0)?;
for line in &cmnt.lines {
if !line.is_empty() {
self.writer().word(&line[..])?;
}
self.writer().hardbreak()?;
}
self.end()
}
}
comments::BlankLine => {
// We need to do at least one, possibly two hardbreaks.
let is_semi = match self.writer().last_token() {
pp::Token::String(s, _) => ";" == s,
_ => false
};
if is_semi || self.is_begin() || self.is_end() {
self.writer().hardbreak()?;
}
self.writer().hardbreak()
}
};
match r {
Ok(()) => {
*self.cur_cmnt() = *self.cur_cmnt() + 1;
Ok(())
}
Err(e) => Err(e),
}
}
fn next_comment(&mut self) -> Option<comments::Comment> {
let cur_cmnt = *self.cur_cmnt();
match *self.comments() {
Some(ref cmnts) => {
if cur_cmnt < cmnts.len() {
Some(cmnts[cur_cmnt].clone())
} else {
None
}
}
_ => None
}
}
fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(lit.span.lo())?;
if let Some(ltrl) = self.next_lit(lit.span.lo()) {
return self.writer().word(&ltrl.lit);
}
match lit.node {
ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style),
ast::LitKind::Byte(byte) => {
let mut res = String::from("b'");
res.extend(ascii::escape_default(byte).map(|c| c as char));
res.push('\'');
self.writer().word(&res[..])
}
ast::LitKind::Char(ch) => {
let mut res = String::from("'");
res.extend(ch.escape_default());
res.push('\'');
self.writer().word(&res[..])
}
ast::LitKind::Int(i, t) => {
match t {
ast::LitIntType::Signed(st) => {
self.writer().word(&st.val_to_string(i as i128))
}
ast::LitIntType::Unsigned(ut) => {
self.writer().word(&ut.val_to_string(i))
}
ast::LitIntType::Unsuffixed => {
self.writer().word(&format!("{}", i))
}
}
}
ast::LitKind::Float(ref f, t) => {
self.writer().word(&format!("{}{}", &f, t.ty_to_string()))
}
ast::LitKind::FloatUnsuffixed(ref f) => self.writer().word(&f.as_str()),
ast::LitKind::Bool(val) => {
if val { self.writer().word("true") } else { self.writer().word("false") }
}
ast::LitKind::ByteStr(ref v) => {
let mut escaped: String = String::new();
for &ch in v.iter() {
escaped.extend(ascii::escape_default(ch)
.map(|c| c as char));
}
self.writer().word(&format!("b\"{}\"", escaped))
}
}
}
fn print_string(&mut self, st: &str,
style: ast::StrStyle) -> io::Result<()> {
let st = match style {
ast::StrStyle::Cooked => {
2017-05-03 17:54:03 +00:00
(format!("\"{}\"", parse::escape_default(st)))
}
ast::StrStyle::Raw(n) => {
(format!("r{delim}\"{string}\"{delim}",
delim=repeat("#", n),
string=st))
}
};
self.writer().word(&st[..])
}
fn print_inner_attributes(&mut self,
attrs: &[ast::Attribute]) -> io::Result<()> {
self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
}
fn print_inner_attributes_no_trailing_hardbreak(&mut self,
attrs: &[ast::Attribute])
-> io::Result<()> {
self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
}
fn print_outer_attributes(&mut self,
attrs: &[ast::Attribute]) -> io::Result<()> {
self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
}
fn print_inner_attributes_inline(&mut self,
attrs: &[ast::Attribute]) -> io::Result<()> {
self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
}
fn print_outer_attributes_inline(&mut self,
attrs: &[ast::Attribute]) -> io::Result<()> {
self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
}
fn print_either_attributes(&mut self,
attrs: &[ast::Attribute],
kind: ast::AttrStyle,
is_inline: bool,
trailing_hardbreak: bool) -> io::Result<()> {
let mut count = 0;
for attr in attrs {
2016-11-14 12:00:25 +00:00
if attr.style == kind {
self.print_attribute_inline(attr, is_inline)?;
if is_inline {
self.nbsp()?;
}
count += 1;
}
}
if count > 0 && trailing_hardbreak && !is_inline {
self.hardbreak_if_not_bol()?;
}
Ok(())
}
fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
self.print_attribute_inline(attr, false)
}
fn print_attribute_inline(&mut self, attr: &ast::Attribute,
is_inline: bool) -> io::Result<()> {
if !is_inline {
self.hardbreak_if_not_bol()?;
}
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(attr.span.lo())?;
2016-11-14 12:00:25 +00:00
if attr.is_sugared_doc {
self.writer().word(&attr.value_str().unwrap().as_str())?;
self.writer().hardbreak()
} else {
2016-11-14 12:00:25 +00:00
match attr.style {
ast::AttrStyle::Inner => self.writer().word("#![")?,
ast::AttrStyle::Outer => self.writer().word("#[")?,
}
if let Some(mi) = attr.meta() {
self.print_meta_item(&mi)?
} else {
for (i, segment) in attr.path.segments.iter().enumerate() {
if i > 0 {
self.writer().word("::")?
}
if segment.identifier.name != keywords::CrateRoot.name() &&
2017-06-25 17:34:49 +00:00
segment.identifier.name != keywords::DollarCrate.name() {
self.writer().word(&segment.identifier.name.as_str())?;
}
}
self.writer().space()?;
self.print_tts(attr.tokens.clone())?;
}
self.writer().word("]")
}
}
fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> {
match item.node {
ast::NestedMetaItemKind::MetaItem(ref mi) => {
self.print_meta_item(mi)
},
ast::NestedMetaItemKind::Literal(ref lit) => {
self.print_literal(lit)
}
}
}
fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
self.ibox(INDENT_UNIT)?;
match item.node {
ast::MetaItemKind::Word => {
self.writer().word(&item.name.as_str())?;
}
ast::MetaItemKind::NameValue(ref value) => {
self.word_space(&item.name.as_str())?;
self.word_space("=")?;
self.print_literal(value)?;
}
ast::MetaItemKind::List(ref items) => {
self.writer().word(&item.name.as_str())?;
self.popen()?;
self.commasep(Consistent,
2016-03-22 22:58:45 +00:00
&items[..],
|s, i| s.print_meta_list_item(i))?;
self.pclose()?;
}
}
self.end()
}
/// 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.
fn print_tt(&mut self, tt: tokenstream::TokenTree) -> io::Result<()> {
match tt {
TokenTree::Token(_, ref tk) => {
self.writer().word(&token_to_string(tk))?;
match *tk {
parse::token::DocComment(..) => {
self.writer().hardbreak()
}
_ => Ok(())
}
}
TokenTree::Delimited(_, ref delimed) => {
self.writer().word(&token_to_string(&delimed.open_token()))?;
self.writer().space()?;
self.print_tts(delimed.stream())?;
self.writer().space()?;
self.writer().word(&token_to_string(&delimed.close_token()))
},
}
}
fn print_tts(&mut self, tts: tokenstream::TokenStream) -> io::Result<()> {
self.ibox(0)?;
for (i, tt) in tts.into_trees().enumerate() {
if i != 0 {
self.writer().space()?;
}
self.print_tt(tt)?;
}
self.end()
}
fn space_if_not_bol(&mut self) -> io::Result<()> {
if !self.is_bol() { self.writer().space()?; }
Ok(())
}
fn nbsp(&mut self) -> io::Result<()> { self.writer().word(" ") }
}
impl<'a> PrintState<'a> for State<'a> {
fn writer(&mut self) -> &mut pp::Printer<'a> {
&mut self.s
}
fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
&mut self.boxes
}
fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
&mut self.comments
}
fn cur_cmnt(&mut self) -> &mut usize {
&mut self.cur_cmnt
}
fn cur_lit(&mut self) -> Option<&comments::Literal> {
self.literals.peek()
2014-03-16 18:58:11 +00:00
}
fn bump_lit(&mut self) -> Option<comments::Literal> {
self.literals.next()
}
}
impl<'a> State<'a> {
pub fn cbox(&mut self, u: usize) -> io::Result<()> {
self.boxes.push(pp::Breaks::Consistent);
self.s.cbox(u)
}
pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
self.s.word(w)?;
self.nbsp()
}
pub fn head(&mut self, w: &str) -> io::Result<()> {
2014-03-16 18:58:11 +00:00
// outer-box is consistent
self.cbox(INDENT_UNIT)?;
2014-03-16 18:58:11 +00:00
// head-box is inconsistent
self.ibox(w.len() + 1)?;
2014-03-16 18:58:11 +00:00
// keyword that starts the head
if !w.is_empty() {
self.word_nbsp(w)?;
2014-03-16 18:58:11 +00:00
}
Ok(())
}
pub fn bopen(&mut self) -> io::Result<()> {
self.s.word("{")?;
2014-03-16 18:58:11 +00:00
self.end() // close the head-box
}
pub fn bclose_(&mut self, span: syntax_pos::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: syntax_pos::Span,
2015-12-23 16:51:03 +00:00
indented: usize, close_box: bool) -> io::Result<()> {
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(span.hi())?;
self.break_offset_if_not_bol(1, -(indented as isize))?;
self.s.word("}")?;
2014-03-16 18:58:11 +00:00
if close_box {
self.end()?; // close the outer-box
2014-03-16 18:58:11 +00:00
}
Ok(())
}
pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
self.bclose_(span, INDENT_UNIT)
2014-03-16 18:58:11 +00:00
}
2014-01-30 01:39:21 +00:00
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
}
}
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() {
self.s.break_offset(n, off)
2014-03-16 18:58:11 +00:00
} 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::Printer::hardbreak_tok_offset(off));
2014-03-16 18:58:11 +00:00
}
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<()> {
self.s.word("/*")?;
self.s.space()?;
self.s.word(&text[..])?;
self.s.space()?;
self.s.word("*/")
2014-01-30 01:39:21 +00:00
}
2014-03-16 18:58:11 +00:00
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<()>,
G: FnMut(&T) -> syntax_pos::Span,
2014-12-08 18:28:32 +00:00
{
self.rbox(0, b)?;
2014-03-16 18:58:11 +00:00
let len = elts.len();
2017-05-16 07:21:30 +00:00
let mut i = 0;
for elt in elts {
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(get_span(elt).hi())?;
op(self, elt)?;
2017-05-16 07:21:30 +00:00
i += 1;
2014-03-16 18:58:11 +00:00
if i < len {
self.s.word(",")?;
self.maybe_print_trailing_comment(get_span(elt),
2017-07-31 20:04:34 +00:00
Some(get_span(&elts[i]).hi()))?;
self.space_if_not_bol()?;
2014-03-16 18:58:11 +00:00
}
}
self.end()
}
2014-03-16 18:58:11 +00:00
pub fn commasep_exprs(&mut self, b: Breaks,
exprs: &[P<ast::Expr>]) -> io::Result<()> {
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<()> {
self.print_inner_attributes(attrs)?;
2015-01-31 17:20:46 +00:00
for item in &_mod.items {
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<()> {
self.print_inner_attributes(attrs)?;
2015-01-31 17:20:46 +00:00
for item in &nmod.items {
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 {
self.print_lifetime(&l)?;
self.nbsp()?;
}
2014-03-16 18:58:11 +00:00
Ok(())
}
pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(ty.span.lo())?;
self.ibox(0)?;
2014-03-16 18:58:11 +00:00
match ty.node {
ast::TyKind::Slice(ref ty) => {
self.s.word("[")?;
self.print_type(ty)?;
self.s.word("]")?;
2014-03-16 18:58:11 +00:00
}
ast::TyKind::Ptr(ref mt) => {
self.s.word("*")?;
2014-06-25 19:47:34 +00:00
match mt.mutbl {
ast::Mutability::Mutable => self.word_nbsp("mut")?,
ast::Mutability::Immutable => self.word_nbsp("const")?,
2014-06-25 19:47:34 +00:00
}
self.print_type(&mt.ty)?;
2014-03-16 18:58:11 +00:00
}
ast::TyKind::Rptr(ref lifetime, ref mt) => {
self.s.word("&")?;
self.print_opt_lifetime(lifetime)?;
self.print_mt(mt)?;
2014-03-16 18:58:11 +00:00
}
ast::TyKind::Never => {
self.s.word("!")?;
},
ast::TyKind::Tup(ref elts) => {
self.popen()?;
self.commasep(Inconsistent, &elts[..],
|s, ty| s.print_type(ty))?;
2014-03-16 18:58:11 +00:00
if elts.len() == 1 {
self.s.word(",")?;
2014-03-16 18:58:11 +00:00
}
self.pclose()?;
2014-03-16 18:58:11 +00:00
}
ast::TyKind::Paren(ref typ) => {
self.popen()?;
self.print_type(typ)?;
self.pclose()?;
}
ast::TyKind::BareFn(ref f) => {
2014-03-16 18:58:11 +00:00
let generics = ast::Generics {
lifetimes: f.lifetimes.clone(),
ty_params: Vec::new(),
where_clause: ast::WhereClause {
id: ast::DUMMY_NODE_ID,
predicates: Vec::new(),
2017-07-27 04:37:35 +00:00
span: syntax_pos::DUMMY_SP,
},
2016-08-10 17:39:12 +00:00
span: syntax_pos::DUMMY_SP,
2014-03-16 18:58:11 +00:00
};
self.print_ty_fn(f.abi,
2016-03-22 22:58:45 +00:00
f.unsafety,
&f.decl,
None,
&generics)?;
2014-03-16 18:58:11 +00:00
}
ast::TyKind::Path(None, ref path) => {
self.print_path(path, false, 0, false)?;
}
ast::TyKind::Path(Some(ref qself), ref path) => {
self.print_qpath(path, qself, false)?
}
2017-10-10 14:33:19 +00:00
ast::TyKind::TraitObject(ref bounds, syntax) => {
let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn " } else { "" };
self.print_bounds(prefix, &bounds[..])?;
2014-11-07 11:53:45 +00:00
}
ast::TyKind::ImplTrait(ref bounds) => {
self.print_bounds("impl ", &bounds[..])?;
}
ast::TyKind::Array(ref ty, ref v) => {
self.s.word("[")?;
self.print_type(ty)?;
self.s.word("; ")?;
self.print_expr(v)?;
self.s.word("]")?;
2014-03-16 18:58:11 +00:00
}
ast::TyKind::Typeof(ref e) => {
self.s.word("typeof(")?;
self.print_expr(e)?;
self.s.word(")")?;
2014-03-16 18:58:11 +00:00
}
ast::TyKind::Infer => {
self.s.word("_")?;
2014-03-16 18:58:11 +00:00
}
ast::TyKind::Err => {
self.s.word("?")?;
}
ast::TyKind::ImplicitSelf => {
self.s.word("Self")?;
}
ast::TyKind::Mac(ref m) => {
self.print_mac(m, token::Paren)?;
}
2014-03-16 18:58:11 +00:00
}
self.end()
}
2014-03-16 18:58:11 +00:00
pub fn print_foreign_item(&mut self,
item: &ast::ForeignItem) -> io::Result<()> {
self.hardbreak_if_not_bol()?;
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(item.span.lo())?;
self.print_outer_attributes(&item.attrs)?;
2014-03-16 18:58:11 +00:00
match item.node {
ast::ForeignItemKind::Fn(ref decl, ref generics) => {
self.head("")?;
self.print_fn(decl, ast::Unsafety::Normal,
2016-03-22 22:58:45 +00:00
ast::Constness::NotConst,
Abi::Rust, Some(item.ident),
generics, &item.vis)?;
self.end()?; // end head-ibox
self.s.word(";")?;
2014-03-16 18:58:11 +00:00
self.end() // end the outer fn box
}
ast::ForeignItemKind::Static(ref t, m) => {
self.head(&visibility_qualified(&item.vis, "static"))?;
2014-03-16 18:58:11 +00:00
if m {
self.word_space("mut")?;
2014-03-16 18:58:11 +00:00
}
self.print_ident(item.ident)?;
self.word_space(":")?;
self.print_type(t)?;
self.s.word(";")?;
self.end()?; // end the head-ibox
2014-03-16 18:58:11 +00:00
self.end() // end the outer cbox
}
2017-09-03 18:53:58 +00:00
ast::ForeignItemKind::Ty => {
self.head(&visibility_qualified(&item.vis, "type"))?;
self.print_ident(item.ident)?;
self.s.word(";")?;
self.end()?; // end the head-ibox
self.end() // end the outer cbox
}
2014-03-16 18:58:11 +00:00
}
}
fn print_associated_const(&mut self,
ident: ast::Ident,
ty: &ast::Ty,
default: Option<&ast::Expr>,
2016-03-23 10:17:34 +00:00
vis: &ast::Visibility)
-> io::Result<()>
{
self.s.word(&visibility_qualified(vis, ""))?;
self.word_space("const")?;
self.print_ident(ident)?;
self.word_space(":")?;
self.print_type(ty)?;
if let Some(expr) = default {
self.s.space()?;
self.word_space("=")?;
self.print_expr(expr)?;
}
self.s.word(";")
}
fn print_associated_type(&mut self,
ident: ast::Ident,
bounds: Option<&ast::TyParamBounds>,
ty: Option<&ast::Ty>)
-> io::Result<()> {
self.word_space("type")?;
self.print_ident(ident)?;
if let Some(bounds) = bounds {
self.print_bounds(":", bounds)?;
}
if let Some(ty) = ty {
self.s.space()?;
self.word_space("=")?;
self.print_type(ty)?;
}
self.s.word(";")
}
/// Pretty-print an item
pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
self.hardbreak_if_not_bol()?;
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(item.span.lo())?;
self.print_outer_attributes(&item.attrs)?;
self.ann.pre(self, NodeItem(item))?;
2014-03-16 18:58:11 +00:00
match item.node {
ast::ItemKind::ExternCrate(ref optional_path) => {
self.head(&visibility_qualified(&item.vis, "extern crate"))?;
if let Some(p) = *optional_path {
let val = p.as_str();
if val.contains('-') {
self.print_string(&val, ast::StrStyle::Cooked)?;
} else {
self.print_name(p)?;
}
self.s.space()?;
self.s.word("as")?;
self.s.space()?;
}
self.print_ident(item.ident)?;
self.s.word(";")?;
self.end()?; // end inner head-block
self.end()?; // end outer head-block
}
ast::ItemKind::Use(ref vp) => {
self.head(&visibility_qualified(&item.vis, "use"))?;
self.print_view_path(vp)?;
self.s.word(";")?;
self.end()?; // end inner head-block
self.end()?; // end outer head-block
}
ast::ItemKind::Static(ref ty, m, ref expr) => {
self.head(&visibility_qualified(&item.vis, "static"))?;
if m == ast::Mutability::Mutable {
self.word_space("mut")?;
}
self.print_ident(item.ident)?;
self.word_space(":")?;
self.print_type(ty)?;
self.s.space()?;
self.end()?; // end the head-ibox
2014-03-16 18:58:11 +00:00
self.word_space("=")?;
self.print_expr(expr)?;
self.s.word(";")?;
self.end()?; // end the outer cbox
2014-03-16 18:58:11 +00:00
}
ast::ItemKind::Const(ref ty, ref expr) => {
self.head(&visibility_qualified(&item.vis, "const"))?;
self.print_ident(item.ident)?;
self.word_space(":")?;
self.print_type(ty)?;
self.s.space()?;
self.end()?; // end the head-ibox
self.word_space("=")?;
self.print_expr(expr)?;
self.s.word(";")?;
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::ItemKind::Fn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
self.head("")?;
self.print_fn(
decl,
unsafety,
2016-08-10 23:20:12 +00:00
constness.node,
2014-03-16 18:58:11 +00:00
abi,
Some(item.ident),
2014-03-16 18:58:11 +00:00
typarams,
2016-03-23 10:17:34 +00:00
&item.vis
)?;
self.s.word(" ")?;
self.print_block_with_attrs(body, &item.attrs)?;
2014-03-16 18:58:11 +00:00
}
ast::ItemKind::Mod(ref _mod) => {
self.head(&visibility_qualified(&item.vis, "mod"))?;
self.print_ident(item.ident)?;
self.nbsp()?;
self.bopen()?;
self.print_mod(_mod, &item.attrs)?;
self.bclose(item.span)?;
2014-03-16 18:58:11 +00:00
}
ast::ItemKind::ForeignMod(ref nmod) => {
self.head("extern")?;
self.word_nbsp(&nmod.abi.to_string())?;
self.bopen()?;
self.print_foreign_mod(nmod, &item.attrs)?;
self.bclose(item.span)?;
2014-03-16 18:58:11 +00:00
}
2017-03-16 02:27:40 +00:00
ast::ItemKind::GlobalAsm(ref ga) => {
self.head(&visibility_qualified(&item.vis, "global_asm!"))?;
self.s.word(&ga.asm.as_str())?;
2017-03-16 02:27:40 +00:00
self.end()?;
}
ast::ItemKind::Ty(ref ty, ref params) => {
self.ibox(INDENT_UNIT)?;
self.ibox(0)?;
self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
self.print_ident(item.ident)?;
self.print_generics(params)?;
self.end()?; // end the inner ibox
self.print_where_clause(&params.where_clause)?;
self.s.space()?;
self.word_space("=")?;
self.print_type(ty)?;
self.s.word(";")?;
self.end()?; // end the outer ibox
2014-03-16 18:58:11 +00:00
}
ast::ItemKind::Enum(ref enum_definition, ref params) => {
self.print_enum_def(
2014-03-16 18:58:11 +00:00
enum_definition,
params,
item.ident,
item.span,
2016-03-23 10:17:34 +00:00
&item.vis
)?;
2014-03-16 18:58:11 +00:00
}
ast::ItemKind::Struct(ref struct_def, ref generics) => {
self.head(&visibility_qualified(&item.vis, "struct"))?;
self.print_struct(struct_def, generics, item.ident, item.span, true)?;
2014-03-16 18:58:11 +00:00
}
2016-08-29 05:04:31 +00:00
ast::ItemKind::Union(ref struct_def, ref generics) => {
self.head(&visibility_qualified(&item.vis, "union"))?;
self.print_struct(struct_def, generics, item.ident, item.span, true)?;
2016-08-29 05:04:31 +00:00
}
ast::ItemKind::AutoImpl(unsafety, ref trait_ref) => {
self.head("")?;
self.print_visibility(&item.vis)?;
self.print_unsafety(unsafety)?;
self.word_nbsp("impl")?;
self.print_trait_ref(trait_ref)?;
self.s.space()?;
self.word_space("for")?;
self.word_space("..")?;
self.bopen()?;
self.bclose(item.span)?;
}
ast::ItemKind::Impl(unsafety,
polarity,
defaultness,
ref generics,
ref opt_trait,
ref ty,
ref impl_items) => {
self.head("")?;
self.print_visibility(&item.vis)?;
self.print_defaultness(defaultness)?;
self.print_unsafety(unsafety)?;
self.word_nbsp("impl")?;
2014-03-16 18:58:11 +00:00
if generics.is_parameterized() {
self.print_generics(generics)?;
self.s.space()?;
2014-03-16 18:58:11 +00:00
}
if polarity == ast::ImplPolarity::Negative {
self.s.word("!")?;
}
if let Some(ref t) = *opt_trait {
self.print_trait_ref(t)?;
self.s.space()?;
self.word_space("for")?;
2014-03-16 18:58:11 +00:00
}
self.print_type(ty)?;
self.print_where_clause(&generics.where_clause)?;
self.s.space()?;
self.bopen()?;
self.print_inner_attributes(&item.attrs)?;
2015-01-31 17:20:46 +00:00
for impl_item in impl_items {
self.print_impl_item(impl_item)?;
2014-03-16 18:58:11 +00:00
}
self.bclose(item.span)?;
2014-03-16 18:58:11 +00:00
}
ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
self.head("")?;
self.print_visibility(&item.vis)?;
self.print_unsafety(unsafety)?;
self.print_is_auto(is_auto)?;
self.word_nbsp("trait")?;
self.print_ident(item.ident)?;
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 {
self.s.space()?;
self.word_space("for ?")?;
self.print_trait_ref(&ptr.trait_ref)?;
2014-12-24 09:34:57 +00:00
} else {
real_bounds.push(b.clone());
2014-12-24 09:34:57 +00:00
}
}
self.print_bounds(":", &real_bounds[..])?;
self.print_where_clause(&generics.where_clause)?;
self.s.word(" ")?;
self.bopen()?;
for trait_item in trait_items {
self.print_trait_item(trait_item)?;
2014-03-16 18:58:11 +00:00
}
self.bclose(item.span)?;
2014-03-16 18:58:11 +00:00
}
ast::ItemKind::Mac(codemap::Spanned { ref node, .. }) => {
self.print_path(&node.path, false, 0, false)?;
self.s.word("! ")?;
self.print_ident(item.ident)?;
self.cbox(INDENT_UNIT)?;
self.popen()?;
2017-02-21 05:05:59 +00:00
self.print_tts(node.stream())?;
self.pclose()?;
self.s.word(";")?;
self.end()?;
2014-03-16 18:58:11 +00:00
}
ast::ItemKind::MacroDef(ref tts) => {
self.s.word("macro_rules! ")?;
self.print_ident(item.ident)?;
self.cbox(INDENT_UNIT)?;
self.popen()?;
2017-03-17 21:58:48 +00:00
self.print_tts(tts.stream())?;
self.pclose()?;
self.s.word(";")?;
self.end()?;
}
2014-03-16 18:58:11 +00:00
}
self.ann.post(self, NodeItem(item))
}
fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
self.print_path(&t.path, false, 0, false)
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() {
self.s.word("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 {
self.word_space(",")?
2014-12-14 03:11:04 +00:00
}
self.print_outer_attributes_inline(&lifetime_def.attrs)?;
self.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)?;
2014-12-14 03:11:04 +00:00
comma = true;
2014-11-07 11:53:45 +00:00
}
self.s.word(">")?;
2014-11-07 11:53:45 +00:00
}
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<()> {
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: syntax_pos::Span,
2016-03-23 10:17:34 +00:00
visibility: &ast::Visibility) -> io::Result<()> {
self.head(&visibility_qualified(visibility, "enum"))?;
self.print_ident(ident)?;
self.print_generics(generics)?;
self.print_where_clause(&generics.where_clause)?;
self.s.space()?;
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: &[ast::Variant],
span: syntax_pos::Span) -> io::Result<()> {
self.bopen()?;
2015-01-31 17:20:46 +00:00
for v in variants {
self.space_if_not_bol()?;
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(v.span.lo())?;
self.print_outer_attributes(&v.node.attrs)?;
self.ibox(INDENT_UNIT)?;
self.print_variant(v)?;
self.s.word(",")?;
self.end()?;
self.maybe_print_trailing_comment(v.span, None)?;
2014-03-16 18:58:11 +00:00
}
self.bclose(span)
}
2016-03-23 10:17:34 +00:00
pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
match *vis {
ast::Visibility::Public => self.word_nbsp("pub"),
ast::Visibility::Crate(_, sugar) => match sugar {
ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
ast::CrateSugar::JustCrate => self.word_nbsp("crate")
}
ast::Visibility::Restricted { ref path, .. } => {
let path = to_string(|s| s.print_path(path, false, 0, true));
if path == "self" || path == "super" {
self.word_nbsp(&format!("pub({})", path))
} else {
self.word_nbsp(&format!("pub(in {})", path))
}
}
ast::Visibility::Inherited => Ok(())
2014-03-16 18:58:11 +00:00
}
}
pub fn print_defaultness(&mut self, defatulness: ast::Defaultness) -> io::Result<()> {
if let ast::Defaultness::Default = defatulness {
try!(self.word_nbsp("default"));
}
Ok(())
}
2014-03-16 18:58:11 +00:00
pub fn print_struct(&mut self,
struct_def: &ast::VariantData,
2014-03-16 18:58:11 +00:00
generics: &ast::Generics,
ident: ast::Ident,
span: syntax_pos::Span,
print_finalizer: bool) -> io::Result<()> {
self.print_ident(ident)?;
self.print_generics(generics)?;
2015-10-08 20:45:46 +00:00
if !struct_def.is_struct() {
if struct_def.is_tuple() {
self.popen()?;
self.commasep(
2015-10-08 20:45:46 +00:00
Inconsistent, struct_def.fields(),
2014-03-16 18:58:11 +00:00
|s, field| {
2017-07-31 20:04:34 +00:00
s.maybe_print_comment(field.span.lo())?;
s.print_outer_attributes(&field.attrs)?;
s.print_visibility(&field.vis)?;
2016-04-06 08:19:10 +00:00
s.print_type(&field.ty)
2014-03-16 18:58:11 +00:00
}
)?;
self.pclose()?;
2014-03-16 18:58:11 +00:00
}
self.print_where_clause(&generics.where_clause)?;
if print_finalizer {
self.s.word(";")?;
}
self.end()?;
2014-03-16 18:58:11 +00:00
self.end() // close the outer-box
} else {
self.print_where_clause(&generics.where_clause)?;
self.nbsp()?;
self.bopen()?;
self.hardbreak_if_not_bol()?;
2015-10-08 20:45:46 +00:00
for field in struct_def.fields() {
self.hardbreak_if_not_bol()?;
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(field.span.lo())?;
self.print_outer_attributes(&field.attrs)?;
self.print_visibility(&field.vis)?;
self.print_ident(field.ident.unwrap())?;
self.word_nbsp(":")?;
self.print_type(&field.ty)?;
self.s.word(",")?;
2014-03-16 18:58:11 +00:00
}
2014-03-16 18:58:11 +00:00
self.bclose(span)
}
}
pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
self.head("")?;
let generics = ast::Generics::default();
self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
2014-03-16 18:58:11 +00:00
match v.node.disr_expr {
2014-05-16 07:16:13 +00:00
Some(ref d) => {
self.s.space()?;
self.word_space("=")?;
self.print_expr(d)
2014-03-16 18:58:11 +00:00
}
_ => Ok(())
}
}
pub fn print_method_sig(&mut self,
ident: ast::Ident,
generics: &ast::Generics,
m: &ast::MethodSig,
2016-03-23 10:17:34 +00:00
vis: &ast::Visibility)
-> io::Result<()> {
self.print_fn(&m.decl,
m.unsafety,
2016-08-10 23:20:12 +00:00
m.constness.node,
m.abi,
Some(ident),
&generics,
vis)
2014-03-16 18:58:11 +00:00
}
pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
-> io::Result<()> {
self.ann.pre(self, NodeSubItem(ti.id))?;
self.hardbreak_if_not_bol()?;
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(ti.span.lo())?;
self.print_outer_attributes(&ti.attrs)?;
match ti.node {
ast::TraitItemKind::Const(ref ty, ref default) => {
self.print_associated_const(ti.ident, ty,
2016-03-22 22:58:45 +00:00
default.as_ref().map(|expr| &**expr),
&ast::Visibility::Inherited)?;
}
ast::TraitItemKind::Method(ref sig, ref body) => {
if body.is_some() {
self.head("")?;
}
self.print_method_sig(ti.ident, &ti.generics, sig, &ast::Visibility::Inherited)?;
if let Some(ref body) = *body {
self.nbsp()?;
self.print_block_with_attrs(body, &ti.attrs)?;
} else {
self.s.word(";")?;
}
}
ast::TraitItemKind::Type(ref bounds, ref default) => {
self.print_associated_type(ti.ident, Some(bounds),
default.as_ref().map(|ty| &**ty))?;
}
ast::TraitItemKind::Macro(codemap::Spanned { ref node, .. }) => {
// code copied from ItemKind::Mac:
self.print_path(&node.path, false, 0, false)?;
self.s.word("! ")?;
self.cbox(INDENT_UNIT)?;
self.popen()?;
2017-02-21 05:05:59 +00:00
self.print_tts(node.stream())?;
self.pclose()?;
self.s.word(";")?;
self.end()?
}
}
2015-03-24 01:52:55 +00:00
self.ann.post(self, NodeSubItem(ti.id))
}
pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
self.ann.pre(self, NodeSubItem(ii.id))?;
self.hardbreak_if_not_bol()?;
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(ii.span.lo())?;
self.print_outer_attributes(&ii.attrs)?;
self.print_defaultness(ii.defaultness)?;
match ii.node {
ast::ImplItemKind::Const(ref ty, ref expr) => {
self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis)?;
}
ast::ImplItemKind::Method(ref sig, ref body) => {
self.head("")?;
self.print_method_sig(ii.ident, &ii.generics, sig, &ii.vis)?;
self.nbsp()?;
self.print_block_with_attrs(body, &ii.attrs)?;
}
ast::ImplItemKind::Type(ref ty) => {
self.print_associated_type(ii.ident, None, Some(ty))?;
}
ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
// code copied from ItemKind::Mac:
self.print_path(&node.path, false, 0, false)?;
self.s.word("! ")?;
self.cbox(INDENT_UNIT)?;
self.popen()?;
2017-02-21 05:05:59 +00:00
self.print_tts(node.stream())?;
self.pclose()?;
self.s.word(";")?;
self.end()?
}
}
2015-03-24 01:52:55 +00:00
self.ann.post(self, NodeSubItem(ii.id))
2014-03-16 18:58:11 +00:00
}
pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(st.span.lo())?;
2014-03-16 18:58:11 +00:00
match st.node {
2016-06-17 02:30:01 +00:00
ast::StmtKind::Local(ref loc) => {
self.print_outer_attributes(&loc.attrs)?;
self.space_if_not_bol()?;
self.ibox(INDENT_UNIT)?;
self.word_nbsp("let")?;
self.ibox(INDENT_UNIT)?;
self.print_local_decl(loc)?;
self.end()?;
2016-06-17 02:30:01 +00:00
if let Some(ref init) = loc.init {
self.nbsp()?;
self.word_space("=")?;
self.print_expr(init)?;
2016-06-17 02:30:01 +00:00
}
self.s.word(";")?;
2016-06-17 02:30:01 +00:00
self.end()?;
2014-03-16 18:58:11 +00:00
}
ast::StmtKind::Item(ref item) => self.print_item(item)?,
2016-06-17 02:30:01 +00:00
ast::StmtKind::Expr(ref expr) => {
self.space_if_not_bol()?;
self.print_expr_outer_attr_style(expr, false)?;
if parse::classify::expr_requires_semi_to_be_stmt(expr) {
self.s.word(";")?;
}
2014-03-16 18:58:11 +00:00
}
2016-06-17 02:30:01 +00:00
ast::StmtKind::Semi(ref expr) => {
self.space_if_not_bol()?;
self.print_expr_outer_attr_style(expr, false)?;
self.s.word(";")?;
2014-03-16 18:58:11 +00:00
}
2016-06-17 02:30:01 +00:00
ast::StmtKind::Mac(ref mac) => {
let (ref mac, style, ref attrs) = **mac;
self.space_if_not_bol()?;
self.print_outer_attributes(attrs)?;
let delim = match style {
ast::MacStmtStyle::Braces => token::Brace,
_ => token::Paren
};
self.print_mac(mac, delim)?;
2016-07-05 11:21:25 +00:00
if style == ast::MacStmtStyle::Semicolon {
self.s.word(";")?;
2014-03-16 18:58:11 +00:00
}
}
}
2014-03-16 18:58:11 +00:00
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<()> {
self.print_block_unclosed_indent(blk, INDENT_UNIT)
}
pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
attrs: &[ast::Attribute])
-> io::Result<()> {
self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
2014-03-16 18:58:11 +00:00
}
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<()> {
self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
2014-03-16 18:58:11 +00:00
}
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 {
BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
BlockCheckMode::Default => ()
2014-03-16 18:58:11 +00:00
}
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(blk.span.lo())?;
self.ann.pre(self, NodeBlock(blk))?;
self.bopen()?;
2014-03-16 18:58:11 +00:00
self.print_inner_attributes(attrs)?;
2014-03-16 18:58:11 +00:00
for (i, st) in blk.stmts.iter().enumerate() {
match st.node {
ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(st.span.lo())?;
self.space_if_not_bol()?;
self.print_expr_outer_attr_style(expr, false)?;
2017-07-31 20:04:34 +00:00
self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
}
_ => self.print_stmt(st)?,
2014-03-16 18:58:11 +00:00
}
}
self.bclose_maybe_open(blk.span, indented, close_box)?;
2014-03-16 18:58:11 +00:00
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"
ast::ExprKind::If(ref i, ref then, ref e) => {
self.cbox(INDENT_UNIT - 1)?;
self.ibox(0)?;
self.s.word(" else if ")?;
2017-07-20 20:53:56 +00:00
self.print_expr_as_cond(i)?;
self.s.space()?;
self.print_block(then)?;
2014-09-13 16:06:01 +00:00
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::ExprKind::IfLet(ref pat, ref expr, ref then, ref e) => {
self.cbox(INDENT_UNIT - 1)?;
self.ibox(0)?;
self.s.word(" else if let ")?;
self.print_pat(pat)?;
self.s.space()?;
self.word_space("=")?;
2017-07-20 20:53:56 +00:00
self.print_expr_as_cond(expr)?;
self.s.space()?;
self.print_block(then)?;
2014-08-25 01:04:29 +00:00
self.print_else(e.as_ref().map(|e| &**e))
}
2014-01-30 01:39:21 +00:00
// "final else"
ast::ExprKind::Block(ref b) => {
self.cbox(INDENT_UNIT - 1)?;
self.ibox(0)?;
self.s.word(" else ")?;
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<()> {
self.head("if")?;
2017-07-20 20:53:56 +00:00
self.print_expr_as_cond(test)?;
self.s.space()?;
self.print_block(blk)?;
2014-03-16 18:58:11 +00:00
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<()> {
self.head("if let")?;
self.print_pat(pat)?;
self.s.space()?;
self.word_space("=")?;
2017-07-20 20:53:56 +00:00
self.print_expr_as_cond(expr)?;
self.s.space()?;
self.print_block(blk)?;
2014-08-25 01:04:29 +00:00
self.print_else(elseopt)
}
pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
-> io::Result<()> {
self.print_path(&m.node.path, false, 0, false)?;
self.s.word("!")?;
match delim {
token::Paren => self.popen()?,
token::Bracket => self.s.word("[")?,
token::Brace => {
self.head("")?;
self.bopen()?;
}
token::NoDelim => {}
}
2017-02-21 05:05:59 +00:00
self.print_tts(m.node.stream())?;
match delim {
token::Paren => self.pclose(),
token::Bracket => self.s.word("]"),
token::Brace => self.bclose(m.span),
token::NoDelim => Ok(()),
2014-03-16 18:58:11 +00:00
}
}
fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
self.popen()?;
self.commasep_exprs(Inconsistent, args)?;
2014-03-16 18:58:11 +00:00
self.pclose()
}
2017-07-20 20:53:56 +00:00
pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) -> io::Result<()> {
let needs_par = parser::expr_precedence(expr) < prec;
if needs_par {
self.popen()?;
}
2017-07-20 20:53:56 +00:00
self.print_expr(expr)?;
if needs_par {
self.pclose()?;
}
Ok(())
}
2017-07-20 20:53:56 +00:00
/// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
/// `if cond { ... }`.
pub fn print_expr_as_cond(&mut self, expr: &ast::Expr) -> io::Result<()> {
let needs_par = match expr.node {
// These cases need parens due to the parse error observed in #26461: `if return {}`
// parses as the erroneous construct `if (return {})`, not `if (return) {}`.
ast::ExprKind::Closure(..) |
ast::ExprKind::Ret(..) |
ast::ExprKind::Break(..) => true,
_ => parser::contains_exterior_struct_lit(expr),
};
if needs_par {
self.popen()?;
}
self.print_expr(expr)?;
if needs_par {
self.pclose()?;
}
Ok(())
}
fn print_expr_in_place(&mut self,
place: &ast::Expr,
expr: &ast::Expr) -> io::Result<()> {
2017-07-20 20:53:56 +00:00
let prec = AssocOp::Inplace.precedence() as i8;
self.print_expr_maybe_paren(place, prec + 1)?;
self.s.space()?;
self.word_space("<-")?;
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(expr, prec)
}
fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
attrs: &[Attribute]) -> io::Result<()> {
self.ibox(INDENT_UNIT)?;
self.s.word("[")?;
self.print_inner_attributes_inline(attrs)?;
self.commasep_exprs(Inconsistent, &exprs[..])?;
self.s.word("]")?;
self.end()
}
fn print_expr_repeat(&mut self,
element: &ast::Expr,
count: &ast::Expr,
attrs: &[Attribute]) -> io::Result<()> {
self.ibox(INDENT_UNIT)?;
self.s.word("[")?;
self.print_inner_attributes_inline(attrs)?;
self.print_expr(element)?;
self.word_space(";")?;
self.print_expr(count)?;
self.s.word("]")?;
self.end()
}
fn print_expr_struct(&mut self,
path: &ast::Path,
fields: &[ast::Field],
wth: &Option<P<ast::Expr>>,
attrs: &[Attribute]) -> io::Result<()> {
self.print_path(path, true, 0, false)?;
self.s.word("{")?;
self.print_inner_attributes_inline(attrs)?;
self.commasep_cmnt(
Consistent,
&fields[..],
|s, field| {
s.ibox(INDENT_UNIT)?;
if !field.is_shorthand {
s.print_ident(field.ident.node)?;
s.word_space(":")?;
}
s.print_expr(&field.expr)?;
s.end()
},
|f| f.span)?;
match *wth {
Some(ref expr) => {
self.ibox(INDENT_UNIT)?;
if !fields.is_empty() {
self.s.word(",")?;
self.s.space()?;
}
self.s.word("..")?;
self.print_expr(expr)?;
self.end()?;
}
_ => if !fields.is_empty() {
self.s.word(",")?
}
}
self.s.word("}")?;
Ok(())
}
fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
attrs: &[Attribute]) -> io::Result<()> {
self.popen()?;
self.print_inner_attributes_inline(attrs)?;
self.commasep_exprs(Inconsistent, &exprs[..])?;
if exprs.len() == 1 {
self.s.word(",")?;
}
self.pclose()
}
fn print_expr_call(&mut self,
func: &ast::Expr,
args: &[P<ast::Expr>]) -> io::Result<()> {
2017-07-20 20:53:56 +00:00
let prec =
match func.node {
ast::ExprKind::Field(..) |
ast::ExprKind::TupField(..) => parser::PREC_FORCE_PAREN,
_ => parser::PREC_POSTFIX,
};
self.print_expr_maybe_paren(func, prec)?;
self.print_call_post(args)
}
fn print_expr_method_call(&mut self,
segment: &ast::PathSegment,
args: &[P<ast::Expr>]) -> io::Result<()> {
2015-01-18 00:15:52 +00:00
let base_args = &args[1..];
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
self.s.word(".")?;
self.print_ident(segment.identifier)?;
if let Some(ref parameters) = segment.parameters {
self.print_path_parameters(parameters, true)?;
}
self.print_call_post(base_args)
}
fn print_expr_binary(&mut self,
op: ast::BinOp,
lhs: &ast::Expr,
rhs: &ast::Expr) -> io::Result<()> {
2017-07-20 20:53:56 +00:00
let assoc_op = AssocOp::from_ast_binop(op.node);
let prec = assoc_op.precedence() as i8;
let fixity = assoc_op.fixity();
let (left_prec, right_prec) = match fixity {
Fixity::Left => (prec, prec + 1),
Fixity::Right => (prec + 1, prec),
Fixity::None => (prec + 1, prec + 1),
};
let left_prec = match (&lhs.node, op.node) {
// These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
// the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
// of `(x as i32) < ...`. We need to convince it _not_ to do that.
(&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) |
(&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
_ => left_prec,
};
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(lhs, left_prec)?;
self.s.space()?;
self.word_space(op.node.to_string())?;
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(rhs, right_prec)
}
fn print_expr_unary(&mut self,
op: ast::UnOp,
expr: &ast::Expr) -> io::Result<()> {
self.s.word(ast::UnOp::to_string(op))?;
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
}
fn print_expr_addr_of(&mut self,
mutability: ast::Mutability,
expr: &ast::Expr) -> io::Result<()> {
self.s.word("&")?;
self.print_mutability(mutability)?;
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
}
pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
self.print_expr_outer_attr_style(expr, true)
}
fn print_expr_outer_attr_style(&mut self,
expr: &ast::Expr,
is_inline: bool) -> io::Result<()> {
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(expr.span.lo())?;
let attrs = &expr.attrs;
if is_inline {
self.print_outer_attributes_inline(attrs)?;
} else {
self.print_outer_attributes(attrs)?;
}
self.ibox(INDENT_UNIT)?;
self.ann.pre(self, NodeExpr(expr))?;
2014-03-16 18:58:11 +00:00
match expr.node {
ast::ExprKind::Box(ref expr) => {
self.word_space("box")?;
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
}
ast::ExprKind::InPlace(ref place, ref expr) => {
self.print_expr_in_place(place, expr)?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::Array(ref exprs) => {
self.print_expr_vec(&exprs[..], attrs)?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::Repeat(ref element, ref count) => {
self.print_expr_repeat(element, count, attrs)?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
self.print_expr_struct(path, &fields[..], wth, attrs)?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::Tup(ref exprs) => {
self.print_expr_tup(&exprs[..], attrs)?;
}
ast::ExprKind::Call(ref func, ref args) => {
self.print_expr_call(func, &args[..])?;
}
ast::ExprKind::MethodCall(ref segment, ref args) => {
self.print_expr_method_call(segment, &args[..])?;
}
ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
self.print_expr_binary(op, lhs, rhs)?;
}
ast::ExprKind::Unary(op, ref expr) => {
self.print_expr_unary(op, expr)?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::AddrOf(m, ref expr) => {
self.print_expr_addr_of(m, expr)?;
}
ast::ExprKind::Lit(ref lit) => {
self.print_literal(lit)?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::Cast(ref expr, ref ty) => {
2017-07-20 20:53:56 +00:00
let prec = AssocOp::As.precedence() as i8;
self.print_expr_maybe_paren(expr, prec)?;
self.s.space()?;
self.word_space("as")?;
self.print_type(ty)?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::Type(ref expr, ref ty) => {
2017-07-20 20:53:56 +00:00
let prec = AssocOp::Colon.precedence() as i8;
self.print_expr_maybe_paren(expr, prec)?;
self.word_space(":")?;
self.print_type(ty)?;
2015-02-01 07:59:46 +00:00
}
ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
self.print_if(test, blk, elseopt.as_ref().map(|e| &**e))?;
2014-08-25 01:04:29 +00:00
}
ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => {
self.print_if_let(pat, expr, blk, elseopt.as_ref().map(|e| &**e))?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::While(ref test, ref blk, opt_ident) => {
2015-01-31 17:20:46 +00:00
if let Some(ident) = opt_ident {
self.print_ident(ident.node)?;
self.word_space(":")?;
2014-07-26 00:12:51 +00:00
}
self.head("while")?;
2017-07-20 20:53:56 +00:00
self.print_expr_as_cond(test)?;
self.s.space()?;
self.print_block_with_attrs(blk, attrs)?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2015-01-31 17:20:46 +00:00
if let Some(ident) = opt_ident {
self.print_ident(ident.node)?;
self.word_space(":")?;
2014-10-03 02:45:46 +00:00
}
self.head("while let")?;
self.print_pat(pat)?;
self.s.space()?;
self.word_space("=")?;
2017-07-20 20:53:56 +00:00
self.print_expr_as_cond(expr)?;
self.s.space()?;
self.print_block_with_attrs(blk, attrs)?;
2014-10-03 02:45:46 +00:00
}
ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2015-01-31 17:20:46 +00:00
if let Some(ident) = opt_ident {
self.print_ident(ident.node)?;
self.word_space(":")?;
2014-03-16 18:58:11 +00:00
}
self.head("for")?;
self.print_pat(pat)?;
self.s.space()?;
self.word_space("in")?;
2017-07-20 20:53:56 +00:00
self.print_expr_as_cond(iter)?;
self.s.space()?;
self.print_block_with_attrs(blk, attrs)?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::Loop(ref blk, opt_ident) => {
2015-01-31 17:20:46 +00:00
if let Some(ident) = opt_ident {
self.print_ident(ident.node)?;
self.word_space(":")?;
2014-03-16 18:58:11 +00:00
}
self.head("loop")?;
self.s.space()?;
self.print_block_with_attrs(blk, attrs)?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::Match(ref expr, ref arms) => {
self.cbox(INDENT_UNIT)?;
self.ibox(4)?;
self.word_nbsp("match")?;
2017-07-20 20:53:56 +00:00
self.print_expr_as_cond(expr)?;
self.s.space()?;
self.bopen()?;
self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
2015-01-31 17:20:46 +00:00
for arm in arms {
self.print_arm(arm)?;
2014-03-16 18:58:11 +00:00
}
self.bclose_(expr.span, INDENT_UNIT)?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => {
self.print_capture_clause(capture_clause)?;
self.print_fn_block_args(decl)?;
self.s.space()?;
self.print_expr(body)?;
self.end()?; // need to close a box
2016-06-23 09:51:18 +00:00
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.
self.ibox(0)?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::Block(ref blk) => {
2014-03-16 18:58:11 +00:00
// containing cbox, will be closed by print-block at }
self.cbox(INDENT_UNIT)?;
2014-03-16 18:58:11 +00:00
// head-box, will be closed by print-block after {
self.ibox(0)?;
self.print_block_with_attrs(blk, attrs)?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::Assign(ref lhs, ref rhs) => {
2017-07-20 20:53:56 +00:00
let prec = AssocOp::Assign.precedence() as i8;
self.print_expr_maybe_paren(lhs, prec + 1)?;
self.s.space()?;
self.word_space("=")?;
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(rhs, prec)?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2017-07-20 20:53:56 +00:00
let prec = AssocOp::Assign.precedence() as i8;
self.print_expr_maybe_paren(lhs, prec + 1)?;
self.s.space()?;
self.s.word(op.node.to_string())?;
self.word_space("=")?;
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(rhs, prec)?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::Field(ref expr, id) => {
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
self.s.word(".")?;
self.print_ident(id.node)?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::TupField(ref expr, id) => {
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
self.s.word(".")?;
self.print_usize(id.node)?;
}
ast::ExprKind::Index(ref expr, ref index) => {
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
self.s.word("[")?;
self.print_expr(index)?;
self.s.word("]")?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::Range(ref start, ref end, limits) => {
2017-07-20 20:53:56 +00:00
// Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
// than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
// Here we use a fake precedence value so that any child with lower precedence than
// a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
let fake_prec = AssocOp::LOr.precedence() as i8;
if let Some(ref e) = *start {
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(e, fake_prec)?;
}
2016-01-13 06:23:31 +00:00
if limits == ast::RangeLimits::HalfOpen {
self.s.word("..")?;
2016-01-13 06:23:31 +00:00
} else {
self.s.word("..=")?;
2016-01-13 06:23:31 +00:00
}
if let Some(ref e) = *end {
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(e, fake_prec)?;
}
2014-12-13 05:41:02 +00:00
}
ast::ExprKind::Path(None, ref path) => {
self.print_path(path, true, 0, false)?
}
ast::ExprKind::Path(Some(ref qself), ref path) => {
self.print_qpath(path, qself, true)?
}
ast::ExprKind::Break(opt_ident, ref opt_expr) => {
self.s.word("break")?;
self.s.space()?;
2015-01-31 17:20:46 +00:00
if let Some(ident) = opt_ident {
self.print_ident(ident.node)?;
self.s.space()?;
2014-03-16 18:58:11 +00:00
}
if let Some(ref expr) = *opt_expr {
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
self.s.space()?;
}
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::Continue(opt_ident) => {
self.s.word("continue")?;
self.s.space()?;
2015-01-31 17:20:46 +00:00
if let Some(ident) = opt_ident {
self.print_ident(ident.node)?;
self.s.space()?
2014-03-16 18:58:11 +00:00
}
}
ast::ExprKind::Ret(ref result) => {
self.s.word("return")?;
if let Some(ref expr) = *result {
self.s.word(" ")?;
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2014-03-16 18:58:11 +00:00
}
}
ast::ExprKind::InlineAsm(ref a) => {
self.s.word("asm!")?;
self.popen()?;
self.print_string(&a.asm.as_str(), a.asm_str_style)?;
self.word_space(":")?;
2014-04-17 08:35:40 +00:00
self.commasep(Inconsistent, &a.outputs, |s, out| {
let constraint = out.constraint.as_str();
let mut ch = constraint.chars();
std: Stabilize APIs for the 1.9 release This commit applies all stabilizations, renamings, and deprecations that the library team has decided on for the upcoming 1.9 release. All tracking issues have gone through a cycle-long "final comment period" and the specific APIs stabilized/deprecated are: Stable * `std::panic` * `std::panic::catch_unwind` (renamed from `recover`) * `std::panic::resume_unwind` (renamed from `propagate`) * `std::panic::AssertUnwindSafe` (renamed from `AssertRecoverSafe`) * `std::panic::UnwindSafe` (renamed from `RecoverSafe`) * `str::is_char_boundary` * `<*const T>::as_ref` * `<*mut T>::as_ref` * `<*mut T>::as_mut` * `AsciiExt::make_ascii_uppercase` * `AsciiExt::make_ascii_lowercase` * `char::decode_utf16` * `char::DecodeUtf16` * `char::DecodeUtf16Error` * `char::DecodeUtf16Error::unpaired_surrogate` * `BTreeSet::take` * `BTreeSet::replace` * `BTreeSet::get` * `HashSet::take` * `HashSet::replace` * `HashSet::get` * `OsString::with_capacity` * `OsString::clear` * `OsString::capacity` * `OsString::reserve` * `OsString::reserve_exact` * `OsStr::is_empty` * `OsStr::len` * `std::os::unix::thread` * `RawPthread` * `JoinHandleExt` * `JoinHandleExt::as_pthread_t` * `JoinHandleExt::into_pthread_t` * `HashSet::hasher` * `HashMap::hasher` * `CommandExt::exec` * `File::try_clone` * `SocketAddr::set_ip` * `SocketAddr::set_port` * `SocketAddrV4::set_ip` * `SocketAddrV4::set_port` * `SocketAddrV6::set_ip` * `SocketAddrV6::set_port` * `SocketAddrV6::set_flowinfo` * `SocketAddrV6::set_scope_id` * `<[T]>::copy_from_slice` * `ptr::read_volatile` * `ptr::write_volatile` * The `#[deprecated]` attribute * `OpenOptions::create_new` Deprecated * `std::raw::Slice` - use raw parts of `slice` module instead * `std::raw::Repr` - use raw parts of `slice` module instead * `str::char_range_at` - use slicing plus `chars()` plus `len_utf8` * `str::char_range_at_reverse` - use slicing plus `chars().rev()` plus `len_utf8` * `str::char_at` - use slicing plus `chars()` * `str::char_at_reverse` - use slicing plus `chars().rev()` * `str::slice_shift_char` - use `chars()` plus `Chars::as_str` * `CommandExt::session_leader` - use `before_exec` instead. Closes #27719 cc #27751 (deprecating the `Slice` bits) Closes #27754 Closes #27780 Closes #27809 Closes #27811 Closes #27830 Closes #28050 Closes #29453 Closes #29791 Closes #29935 Closes #30014 Closes #30752 Closes #31262 cc #31398 (still need to deal with `before_exec`) Closes #31405 Closes #31572 Closes #31755 Closes #31756
2016-04-07 17:42:53 +00:00
match ch.next() {
Some('=') if out.is_rw => {
s.print_string(&format!("+{}", ch.as_str()),
ast::StrStyle::Cooked)?
}
_ => s.print_string(&constraint, ast::StrStyle::Cooked)?
}
s.popen()?;
s.print_expr(&out.expr)?;
s.pclose()?;
2014-04-17 08:35:40 +00:00
Ok(())
})?;
self.s.space()?;
self.word_space(":")?;
self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
s.popen()?;
s.print_expr(o)?;
s.pclose()?;
2014-04-17 08:35:40 +00:00
Ok(())
})?;
self.s.space()?;
self.word_space(":")?;
2014-04-17 08:35:40 +00:00
self.commasep(Inconsistent, &a.clobbers,
|s, co| {
s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
Ok(())
})?;
2014-12-17 13:02:50 +00:00
let mut options = vec![];
2014-12-17 13:02:50 +00:00
if a.volatile {
options.push("volatile");
}
if a.alignstack {
options.push("alignstack");
}
if a.dialect == ast::AsmDialect::Intel {
2014-12-17 13:02:50 +00:00
options.push("intel");
}
if !options.is_empty() {
self.s.space()?;
self.word_space(":")?;
self.commasep(Inconsistent, &options,
2016-03-22 22:58:45 +00:00
|s, &co| {
s.print_string(co, ast::StrStyle::Cooked)?;
2016-03-22 22:58:45 +00:00
Ok(())
})?;
2014-12-17 13:02:50 +00:00
}
self.pclose()?;
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
ast::ExprKind::Paren(ref e) => {
self.popen()?;
self.print_inner_attributes_inline(attrs)?;
self.print_expr(e)?;
self.pclose()?;
},
2016-12-26 13:34:03 +00:00
ast::ExprKind::Yield(ref e) => {
2017-07-13 04:29:26 +00:00
self.s.word("yield")?;
2016-12-26 13:34:03 +00:00
match *e {
Some(ref expr) => {
2017-07-13 04:29:26 +00:00
self.s.space()?;
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
2016-12-26 13:34:03 +00:00
}
_ => ()
}
}
ast::ExprKind::Try(ref e) => {
2017-07-20 20:53:56 +00:00
self.print_expr_maybe_paren(e, parser::PREC_POSTFIX)?;
self.s.word("?")?
2014-03-16 18:58:11 +00:00
}
ast::ExprKind::Catch(ref blk) => {
self.head("do catch")?;
self.s.space()?;
self.print_block_with_attrs(blk, attrs)?
}
2014-03-16 18:58:11 +00:00
}
self.ann.post(self, NodeExpr(expr))?;
2014-03-16 18:58:11 +00:00
self.end()
}
pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
self.print_pat(&loc.pat)?;
2015-01-02 11:55:31 +00:00
if let Some(ref ty) = loc.ty {
self.word_space(":")?;
self.print_type(ty)?;
}
2015-01-02 11:55:31 +00:00
Ok(())
}
pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
self.s.word(&ident.name.as_str())?;
self.ann.post(self, NodeIdent(&ident))
2014-03-16 18:58:11 +00:00
}
pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
self.s.word(&i.to_string())
}
pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
self.s.word(&name.as_str())?;
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<()> {
self.print_local_decl(loc)?;
self.s.space()?;
self.word_space("in")?;
2014-03-16 18:58:11 +00:00
self.print_expr(coll)
}
fn print_path(&mut self,
path: &ast::Path,
colons_before_params: bool,
depth: usize,
defaults_to_global: bool)
-> io::Result<()>
{
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(path.span.lo())?;
let mut segments = path.segments[..path.segments.len()-depth].iter();
if defaults_to_global && path.is_global() {
segments.next();
}
for (i, segment) in segments.enumerate() {
if i > 0 {
self.s.word("::")?
}
self.print_path_segment(segment, colons_before_params)?;
}
Ok(())
}
fn print_path_segment(&mut self,
segment: &ast::PathSegment,
colons_before_params: bool)
-> io::Result<()>
{
if segment.identifier.name != keywords::CrateRoot.name() &&
2017-06-25 17:34:49 +00:00
segment.identifier.name != keywords::DollarCrate.name() {
self.print_ident(segment.identifier)?;
if let Some(ref parameters) = segment.parameters {
self.print_path_parameters(parameters, colons_before_params)?;
}
}
Ok(())
}
fn print_qpath(&mut self,
path: &ast::Path,
qself: &ast::QSelf,
colons_before_params: bool)
-> io::Result<()>
{
self.s.word("<")?;
self.print_type(&qself.ty)?;
if qself.position > 0 {
self.s.space()?;
self.word_space("as")?;
let depth = path.segments.len() - qself.position;
self.print_path(path, false, depth, false)?;
}
self.s.word(">")?;
self.s.word("::")?;
let item_segment = path.segments.last().unwrap();
self.print_ident(item_segment.identifier)?;
2016-12-10 06:45:58 +00:00
match item_segment.parameters {
Some(ref parameters) => self.print_path_parameters(parameters, colons_before_params),
None => Ok(()),
}
}
fn print_path_parameters(&mut self,
parameters: &ast::PathParameters,
colons_before_params: bool)
-> io::Result<()>
{
if colons_before_params {
self.s.word("::")?
}
match *parameters {
ast::PathParameters::AngleBracketed(ref data) => {
self.s.word("<")?;
2014-03-16 18:58:11 +00:00
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 {
self.word_space(",")?
2014-03-16 18:58:11 +00:00
}
self.print_lifetime(lifetime)?;
2014-03-16 18:58:11 +00:00
comma = true;
}
if !data.types.is_empty() {
2014-03-16 18:58:11 +00:00
if comma {
self.word_space(",")?
2014-03-16 18:58:11 +00:00
}
self.commasep(
2014-03-16 18:58:11 +00:00
Inconsistent,
2015-02-18 23:58:07 +00:00
&data.types,
|s, ty| s.print_type(ty))?;
comma = true;
}
for binding in data.bindings.iter() {
if comma {
self.word_space(",")?
}
self.print_ident(binding.ident)?;
self.s.space()?;
self.word_space("=")?;
self.print_type(&binding.ty)?;
comma = true;
2014-03-16 18:58:11 +00:00
}
self.s.word(">")?
2014-03-16 18:58:11 +00:00
}
ast::PathParameters::Parenthesized(ref data) => {
self.s.word("(")?;
self.commasep(
Inconsistent,
2015-02-18 23:58:07 +00:00
&data.inputs,
|s, ty| s.print_type(ty))?;
self.s.word(")")?;
if let Some(ref ty) = data.output {
self.space_if_not_bol()?;
self.word_space("->")?;
self.print_type(ty)?;
}
}
}
Ok(())
}
pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(pat.span.lo())?;
self.ann.pre(self, NodePat(pat))?;
2014-03-16 18:58:11 +00:00
/* Pat isn't normalized, but the beauty of it
is that it doesn't matter */
match pat.node {
PatKind::Wild => self.s.word("_")?,
2016-02-11 18:16:33 +00:00
PatKind::Ident(binding_mode, ref path1, ref sub) => {
2014-03-16 18:58:11 +00:00
match binding_mode {
ast::BindingMode::ByRef(mutbl) => {
self.word_nbsp("ref")?;
self.print_mutability(mutbl)?;
2014-03-16 18:58:11 +00:00
}
ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
self.word_nbsp("mut")?;
2014-03-16 18:58:11 +00:00
}
}
self.print_ident(path1.node)?;
if let Some(ref p) = *sub {
self.s.word("@")?;
self.print_pat(p)?;
2014-03-16 18:58:11 +00:00
}
}
PatKind::TupleStruct(ref path, ref elts, ddpos) => {
self.print_path(path, true, 0, false)?;
self.popen()?;
if let Some(ddpos) = ddpos {
self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
if ddpos != 0 {
self.word_space(",")?;
}
self.s.word("..")?;
if ddpos != elts.len() {
self.s.word(",")?;
self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
2014-03-16 18:58:11 +00:00
}
} else {
self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
2013-11-08 03:25:39 +00:00
}
self.pclose()?;
2013-11-08 03:25:39 +00:00
}
PatKind::Path(None, ref path) => {
self.print_path(path, true, 0, false)?;
}
PatKind::Path(Some(ref qself), ref path) => {
self.print_qpath(path, qself, false)?;
}
2016-02-11 18:16:33 +00:00
PatKind::Struct(ref path, ref fields, etc) => {
self.print_path(path, true, 0, false)?;
self.nbsp()?;
self.word_space("{")?;
self.commasep_cmnt(
Consistent, &fields[..],
2014-03-16 18:58:11 +00:00
|s, f| {
s.cbox(INDENT_UNIT)?;
if !f.node.is_shorthand {
s.print_ident(f.node.ident)?;
s.word_nbsp(":")?;
}
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.is_empty() { self.word_space(",")?; }
self.s.word("..")?;
2014-03-16 18:58:11 +00:00
}
self.s.space()?;
self.s.word("}")?;
2014-03-16 18:58:11 +00:00
}
PatKind::Tuple(ref elts, ddpos) => {
self.popen()?;
if let Some(ddpos) = ddpos {
self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
if ddpos != 0 {
self.word_space(",")?;
}
self.s.word("..")?;
if ddpos != elts.len() {
self.s.word(",")?;
self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
}
} else {
self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
if elts.len() == 1 {
self.s.word(",")?;
}
2014-03-16 18:58:11 +00:00
}
self.pclose()?;
2014-03-16 18:58:11 +00:00
}
2016-02-11 18:16:33 +00:00
PatKind::Box(ref inner) => {
self.s.word("box ")?;
self.print_pat(inner)?;
2014-03-16 18:58:11 +00:00
}
2016-02-11 18:16:33 +00:00
PatKind::Ref(ref inner, mutbl) => {
self.s.word("&")?;
if mutbl == ast::Mutability::Mutable {
self.s.word("mut ")?;
}
self.print_pat(inner)?;
2014-03-16 18:58:11 +00:00
}
PatKind::Lit(ref e) => self.print_expr(&**e)?,
PatKind::Range(ref begin, ref end, ref end_kind) => {
self.print_expr(begin)?;
self.s.space()?;
match *end_kind {
RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("...")?,
RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..=")?,
RangeEnd::Excluded => self.s.word("..")?,
}
self.print_expr(end)?;
2014-03-16 18:58:11 +00:00
}
PatKind::Slice(ref before, ref slice, ref after) => {
self.s.word("[")?;
self.commasep(Inconsistent,
&before[..],
|s, p| s.print_pat(p))?;
2015-01-31 17:20:46 +00:00
if let Some(ref p) = *slice {
if !before.is_empty() { self.word_space(",")?; }
2016-02-11 18:16:33 +00:00
if p.node != PatKind::Wild {
self.print_pat(p)?;
2014-03-16 18:58:11 +00:00
}
self.s.word("..")?;
if !after.is_empty() { self.word_space(",")?; }
2014-03-16 18:58:11 +00:00
}
self.commasep(Inconsistent,
&after[..],
|s, p| s.print_pat(p))?;
self.s.word("]")?;
2014-03-16 18:58:11 +00:00
}
PatKind::Mac(ref m) => 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() {
self.s.space()?;
}
self.cbox(INDENT_UNIT)?;
self.ibox(0)?;
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(arm.pats[0].span.lo())?;
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 {
self.s.space()?;
self.word_space("|")?;
}
self.print_pat(p)?;
}
self.s.space()?;
2014-11-22 15:24:58 +00:00
if let Some(ref e) = arm.guard {
self.word_space("if")?;
self.print_expr(e)?;
self.s.space()?;
}
self.word_space("=>")?;
match arm.body.node {
ast::ExprKind::Block(ref blk) => {
// the block will close the pattern's ibox
self.print_block_unclosed_indent(blk, INDENT_UNIT)?;
2014-11-22 15:24:58 +00:00
// If it is a user-provided unsafe block, print a comma after it
if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
self.s.word(",")?;
2014-11-22 15:24:58 +00:00
}
}
_ => {
self.end()?; // close the ibox for the pattern
self.print_expr(&arm.body)?;
self.s.word(",")?;
}
}
self.end() // close enclosing cbox
}
2016-03-06 12:54:44 +00:00
fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
match explicit_self.node {
SelfKind::Value(m) => {
self.print_mutability(m)?;
self.s.word("self")
2014-03-16 18:58:11 +00:00
}
2016-03-06 12:54:44 +00:00
SelfKind::Region(ref lt, m) => {
self.s.word("&")?;
self.print_opt_lifetime(lt)?;
self.print_mutability(m)?;
self.s.word("self")
2014-03-16 18:58:11 +00:00
}
2016-03-06 12:54:44 +00:00
SelfKind::Explicit(ref typ, m) => {
self.print_mutability(m)?;
self.s.word("self")?;
self.word_space(":")?;
self.print_type(typ)
}
}
}
2014-03-16 18:58:11 +00:00
pub fn print_fn(&mut self,
decl: &ast::FnDecl,
unsafety: ast::Unsafety,
constness: ast::Constness,
abi: abi::Abi,
name: Option<ast::Ident>,
2014-03-16 18:58:11 +00:00
generics: &ast::Generics,
2016-03-23 10:17:34 +00:00
vis: &ast::Visibility) -> io::Result<()> {
self.print_fn_header_info(unsafety, constness, abi, vis)?;
if let Some(name) = name {
self.nbsp()?;
self.print_ident(name)?;
}
self.print_generics(generics)?;
self.print_fn_args_and_ret(decl)?;
self.print_where_clause(&generics.where_clause)
2014-03-16 18:58:11 +00:00
}
2016-03-06 12:54:44 +00:00
pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
-> io::Result<()> {
self.popen()?;
self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
2014-03-16 18:58:11 +00:00
if decl.variadic {
self.s.word(", ...")?;
2014-03-16 18:58:11 +00:00
}
self.pclose()?;
self.print_fn_output(decl)
}
pub fn print_fn_block_args(
&mut self,
decl: &ast::FnDecl)
-> io::Result<()> {
self.s.word("|")?;
self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
self.s.word("|")?;
2014-03-16 18:58:11 +00:00
if let ast::FunctionRetTy::Default(..) = decl.output {
return Ok(());
}
2014-03-16 18:58:11 +00:00
self.space_if_not_bol()?;
self.word_space("->")?;
match decl.output {
ast::FunctionRetTy::Ty(ref ty) => {
self.print_type(ty)?;
2017-07-31 20:04:34 +00:00
self.maybe_print_comment(ty.span.lo())
}
ast::FunctionRetTy::Default(..) => unreachable!(),
}
}
pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
-> io::Result<()> {
match capture_clause {
ast::CaptureBy::Value => self.word_space("move"),
ast::CaptureBy::Ref => Ok(()),
}
}
pub fn print_bounds(&mut self,
prefix: &str,
bounds: &[ast::TyParamBound])
-> io::Result<()> {
if !bounds.is_empty() {
self.s.word(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 {
self.nbsp()?;
2014-03-16 18:58:11 +00:00
if first {
first = false;
} else {
self.word_space("+")?;
2014-03-16 18:58:11 +00:00
}
(match *bound {
TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
self.print_poly_trait_ref(tref)
}
TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
self.s.word("?")?;
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<()>
{
2017-03-25 21:14:18 +00:00
self.print_name(lifetime.ident.name)
2014-03-16 18:58:11 +00:00
}
2016-06-29 12:53:01 +00:00
pub fn print_lifetime_bounds(&mut self,
lifetime: &ast::Lifetime,
bounds: &[ast::Lifetime])
-> io::Result<()>
{
self.print_lifetime(lifetime)?;
2016-06-29 12:53:01 +00:00
if !bounds.is_empty() {
self.s.word(": ")?;
2016-06-29 12:53:01 +00:00
for (i, bound) in bounds.iter().enumerate() {
if i != 0 {
self.s.word(" + ")?;
2016-06-29 12:53:01 +00:00
}
self.print_lifetime(bound)?;
2016-06-29 12:53:01 +00:00
}
}
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(());
}
self.s.word("<")?;
let mut ints = Vec::new();
for i in 0..total {
ints.push(i);
}
2014-03-16 18:58:11 +00:00
self.commasep(Inconsistent, &ints[..], |s, &idx| {
if idx < generics.lifetimes.len() {
2016-06-29 12:53:01 +00:00
let lifetime_def = &generics.lifetimes[idx];
s.print_outer_attributes_inline(&lifetime_def.attrs)?;
2016-06-29 12:53:01 +00:00
s.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)
} else {
let idx = idx - generics.lifetimes.len();
let param = &generics.ty_params[idx];
s.print_ty_param(param)
}
})?;
self.s.word(">")?;
Ok(())
2011-08-03 04:26:54 +00:00
}
pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
self.print_outer_attributes_inline(&param.attrs)?;
self.print_ident(param.ident)?;
self.print_bounds(":", &param.bounds)?;
match param.default {
Some(ref default) => {
self.s.space()?;
self.word_space("=")?;
self.print_type(default)
}
_ => Ok(())
}
}
pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
-> io::Result<()> {
if where_clause.predicates.is_empty() {
return Ok(())
}
self.s.space()?;
self.word_space("where")?;
for (i, predicate) in where_clause.predicates.iter().enumerate() {
if i != 0 {
self.word_space(",")?;
}
2015-11-17 14:24:49 +00:00
match *predicate {
ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
ref bounded_ty,
ref bounds,
..}) => {
self.print_formal_lifetime_list(bound_lifetimes)?;
self.print_type(bounded_ty)?;
self.print_bounds(":", bounds)?;
}
2015-11-17 14:24:49 +00:00
ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
ref bounds,
..}) => {
self.print_lifetime_bounds(lifetime, bounds)?;
}
ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
ref rhs_ty,
..}) => {
self.print_type(lhs_ty)?;
self.s.space()?;
self.word_space("=")?;
self.print_type(rhs_ty)?;
}
}
}
Ok(())
}
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) => {
self.print_path(path, false, 0, true)?;
if path.segments.last().unwrap().identifier.name !=
ident.name {
self.s.space()?;
self.word_space("as")?;
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) => {
self.print_path(path, false, 0, true)?;
self.s.word("::*")
2014-03-16 18:58:11 +00:00
}
ast::ViewPathList(ref path, ref idents) => {
2014-03-16 18:58:11 +00:00
if path.segments.is_empty() {
self.s.word("{")?;
2014-03-16 18:58:11 +00:00
} else {
self.print_path(path, false, 0, true)?;
self.s.word("::{")?;
2014-03-16 18:58:11 +00:00
}
self.commasep(Inconsistent, &idents[..], |s, w| {
s.print_ident(w.node.name)?;
if let Some(ident) = w.node.rename {
s.s.space()?;
s.word_space("as")?;
s.print_ident(ident)?;
}
Ok(())
})?;
self.s.word("}")
2014-03-16 18:58:11 +00:00
}
}
}
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::Mutability::Mutable => self.word_nbsp("mut"),
ast::Mutability::Immutable => Ok(()),
}
}
pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
self.print_mutability(mt.mutbl)?;
2016-02-08 22:55:55 +00:00
self.print_type(&mt.ty)
}
pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
self.ibox(INDENT_UNIT)?;
2014-03-16 18:58:11 +00:00
match input.ty.node {
ast::TyKind::Infer if is_closure => self.print_pat(&input.pat)?,
2014-03-16 18:58:11 +00:00
_ => {
if let Some(eself) = input.to_self() {
self.print_explicit_self(&eself)?;
} else {
2016-03-06 12:54:44 +00:00
let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
ident.node.name == keywords::Invalid.name()
} else {
false
};
if !invalid {
self.print_pat(&input.pat)?;
self.s.word(":")?;
self.s.space()?;
2014-03-16 18:58:11 +00:00
}
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::FunctionRetTy::Default(..) = decl.output {
return Ok(());
}
self.space_if_not_bol()?;
self.ibox(INDENT_UNIT)?;
self.word_space("->")?;
match decl.output {
ast::FunctionRetTy::Default(..) => unreachable!(),
ast::FunctionRetTy::Ty(ref ty) =>
self.print_type(ty)?
}
self.end()?;
match decl.output {
2017-07-31 20:04:34 +00:00
ast::FunctionRetTy::Ty(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>,
2016-03-06 12:54:44 +00:00
generics: &ast::Generics)
-> io::Result<()> {
self.ibox(INDENT_UNIT)?;
if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
self.s.word("for")?;
self.print_generics(generics)?;
}
let generics = ast::Generics {
lifetimes: Vec::new(),
ty_params: Vec::new(),
where_clause: ast::WhereClause {
id: ast::DUMMY_NODE_ID,
predicates: Vec::new(),
2017-07-27 04:37:35 +00:00
span: syntax_pos::DUMMY_SP,
},
2016-08-10 17:39:12 +00:00
span: syntax_pos::DUMMY_SP,
};
self.print_fn(decl,
2016-03-22 22:58:45 +00:00
unsafety,
ast::Constness::NotConst,
abi,
name,
&generics,
&ast::Visibility::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: syntax_pos::Span,
2014-03-16 18:58:11 +00:00
next_pos: Option<BytePos>)
-> io::Result<()> {
2014-03-16 18:58:11 +00:00
let cm = match self.cm {
Some(cm) => cm,
_ => return Ok(())
};
if let Some(ref cmnt) = self.next_comment() {
2016-10-12 17:54:41 +00:00
if cmnt.style != comments::Trailing { return Ok(()) }
2017-07-31 20:04:34 +00:00
let span_line = cm.lookup_char_pos(span.hi());
2016-10-12 17:54:41 +00:00
let comment_line = cm.lookup_char_pos(cmnt.pos);
let next = next_pos.unwrap_or(cmnt.pos + BytePos(1));
2017-07-31 20:04:34 +00:00
if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
self.print_comment(cmnt)?;
2014-01-30 01:39:21 +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() {
self.s.hardbreak()?;
2014-03-16 18:58:11 +00:00
}
while let Some(ref cmnt) = self.next_comment() {
self.print_comment(cmnt)?;
2014-03-16 18:58:11 +00:00
}
Ok(())
}
pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
opt_abi: Option<Abi>)
-> io::Result<()> {
match opt_abi {
Some(Abi::Rust) => Ok(()),
Some(abi) => {
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>) -> io::Result<()> {
match opt_abi {
Some(abi) => {
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,
constness: ast::Constness,
abi: Abi,
2016-03-23 10:17:34 +00:00
vis: &ast::Visibility) -> io::Result<()> {
self.s.word(&visibility_qualified(vis, ""))?;
match constness {
ast::Constness::NotConst => {}
ast::Constness::Const => self.word_nbsp("const")?
}
self.print_unsafety(unsafety)?;
if abi != Abi::Rust {
self.word_nbsp("extern")?;
self.word_nbsp(&abi.to_string())?;
}
self.s.word("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
}
pub fn print_is_auto(&mut self, s: ast::IsAuto) -> io::Result<()> {
match s {
ast::IsAuto::Yes => self.word_nbsp("auto"),
ast::IsAuto::No => Ok(()),
}
}
}
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 tests {
use super::*;
use ast;
use codemap;
2016-06-22 16:50:19 +00:00
use syntax_pos;
#[test]
fn test_fun_to_string() {
2016-11-17 14:04:36 +00:00
let abba_ident = ast::Ident::from_str("abba");
let decl = ast::FnDecl {
inputs: Vec::new(),
output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
variadic: false
};
let generics = ast::Generics::default();
assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
ast::Constness::NotConst,
2016-03-06 12:54:44 +00:00
abba_ident, &generics),
"fn abba()");
}
#[test]
fn test_variant_to_string() {
2016-11-17 14:04:36 +00:00
let ident = ast::Ident::from_str("principal_skinner");
2016-06-22 16:50:19 +00:00
let var = codemap::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
name: ident,
attrs: Vec::new(),
// making this up as I go.... ?
data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
disr_expr: None,
});
let varstr = variant_to_string(&var);
assert_eq!(varstr, "principal_skinner");
}
}