1
Fork 0

Use Cow in Token::String.

`Printer::word` takes a `&str` and converts it into a `String`, which
causes an allocation. But that allocation is rarely necessary, because
`&str` is almost always a `&'static str` or a `String` that won't be
used again.

This commit changes `Token::String` so it holds a `Cow<'static, str>`
instead of a `String`, which avoids a lot of allocations.
This commit is contained in:
Nicholas Nethercote 2018-11-29 11:36:58 +11:00
parent deb9195e57
commit 787959c20d
7 changed files with 101 additions and 88 deletions

View file

@ -25,6 +25,7 @@ use hir;
use hir::{PatKind, GenericBound, TraitBoundModifier, RangeEnd}; use hir::{PatKind, GenericBound, TraitBoundModifier, RangeEnd};
use hir::{GenericParam, GenericParamKind, GenericArg}; use hir::{GenericParam, GenericParamKind, GenericArg};
use std::borrow::Cow;
use std::cell::Cell; use std::cell::Cell;
use std::io::{self, Write, Read}; use std::io::{self, Write, Read};
use std::iter::Peekable; use std::iter::Peekable;
@ -209,7 +210,7 @@ pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
String::from_utf8(wr).unwrap() String::from_utf8(wr).unwrap()
} }
pub fn visibility_qualified(vis: &hir::Visibility, w: &str) -> String { pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility, w: S) -> String {
to_string(NO_ANN, |s| { to_string(NO_ANN, |s| {
s.print_visibility(vis)?; s.print_visibility(vis)?;
s.s.word(w) s.s.word(w)
@ -226,12 +227,13 @@ impl<'a> State<'a> {
self.s.word(" ") self.s.word(" ")
} }
pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> { pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
self.s.word(w)?; self.s.word(w)?;
self.nbsp() self.nbsp()
} }
pub fn head(&mut self, w: &str) -> io::Result<()> { pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
let w = w.into();
// outer-box is consistent // outer-box is consistent
self.cbox(indent_unit)?; self.cbox(indent_unit)?;
// head-box is inconsistent // head-box is inconsistent
@ -303,7 +305,7 @@ impl<'a> State<'a> {
pub fn synth_comment(&mut self, text: String) -> io::Result<()> { pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
self.s.word("/*")?; self.s.word("/*")?;
self.s.space()?; self.s.space()?;
self.s.word(&text[..])?; self.s.word(text)?;
self.s.space()?; self.s.space()?;
self.s.word("*/") self.s.word("*/")
} }
@ -468,7 +470,7 @@ impl<'a> State<'a> {
self.end() // end the outer fn box self.end() // end the outer fn box
} }
hir::ForeignItemKind::Static(ref t, m) => { hir::ForeignItemKind::Static(ref t, m) => {
self.head(&visibility_qualified(&item.vis, "static"))?; self.head(visibility_qualified(&item.vis, "static"))?;
if m { if m {
self.word_space("mut")?; self.word_space("mut")?;
} }
@ -480,7 +482,7 @@ impl<'a> State<'a> {
self.end() // end the outer cbox self.end() // end the outer cbox
} }
hir::ForeignItemKind::Type => { hir::ForeignItemKind::Type => {
self.head(&visibility_qualified(&item.vis, "type"))?; self.head(visibility_qualified(&item.vis, "type"))?;
self.print_name(item.name)?; self.print_name(item.name)?;
self.s.word(";")?; self.s.word(";")?;
self.end()?; // end the head-ibox self.end()?; // end the head-ibox
@ -495,7 +497,7 @@ impl<'a> State<'a> {
default: Option<hir::BodyId>, default: Option<hir::BodyId>,
vis: &hir::Visibility) vis: &hir::Visibility)
-> io::Result<()> { -> io::Result<()> {
self.s.word(&visibility_qualified(vis, ""))?; self.s.word(visibility_qualified(vis, ""))?;
self.word_space("const")?; self.word_space("const")?;
self.print_ident(ident)?; self.print_ident(ident)?;
self.word_space(":")?; self.word_space(":")?;
@ -534,7 +536,7 @@ impl<'a> State<'a> {
self.ann.pre(self, AnnNode::Item(item))?; self.ann.pre(self, AnnNode::Item(item))?;
match item.node { match item.node {
hir::ItemKind::ExternCrate(orig_name) => { hir::ItemKind::ExternCrate(orig_name) => {
self.head(&visibility_qualified(&item.vis, "extern crate"))?; self.head(visibility_qualified(&item.vis, "extern crate"))?;
if let Some(orig_name) = orig_name { if let Some(orig_name) = orig_name {
self.print_name(orig_name)?; self.print_name(orig_name)?;
self.s.space()?; self.s.space()?;
@ -547,7 +549,7 @@ impl<'a> State<'a> {
self.end()?; // end outer head-block self.end()?; // end outer head-block
} }
hir::ItemKind::Use(ref path, kind) => { hir::ItemKind::Use(ref path, kind) => {
self.head(&visibility_qualified(&item.vis, "use"))?; self.head(visibility_qualified(&item.vis, "use"))?;
self.print_path(path, false)?; self.print_path(path, false)?;
match kind { match kind {
@ -566,7 +568,7 @@ impl<'a> State<'a> {
self.end()?; // end outer head-block self.end()?; // end outer head-block
} }
hir::ItemKind::Static(ref ty, m, expr) => { hir::ItemKind::Static(ref ty, m, expr) => {
self.head(&visibility_qualified(&item.vis, "static"))?; self.head(visibility_qualified(&item.vis, "static"))?;
if m == hir::MutMutable { if m == hir::MutMutable {
self.word_space("mut")?; self.word_space("mut")?;
} }
@ -582,7 +584,7 @@ impl<'a> State<'a> {
self.end()?; // end the outer cbox self.end()?; // end the outer cbox
} }
hir::ItemKind::Const(ref ty, expr) => { hir::ItemKind::Const(ref ty, expr) => {
self.head(&visibility_qualified(&item.vis, "const"))?; self.head(visibility_qualified(&item.vis, "const"))?;
self.print_name(item.name)?; self.print_name(item.name)?;
self.word_space(":")?; self.word_space(":")?;
self.print_type(&ty)?; self.print_type(&ty)?;
@ -609,7 +611,7 @@ impl<'a> State<'a> {
self.ann.nested(self, Nested::Body(body))?; self.ann.nested(self, Nested::Body(body))?;
} }
hir::ItemKind::Mod(ref _mod) => { hir::ItemKind::Mod(ref _mod) => {
self.head(&visibility_qualified(&item.vis, "mod"))?; self.head(visibility_qualified(&item.vis, "mod"))?;
self.print_name(item.name)?; self.print_name(item.name)?;
self.nbsp()?; self.nbsp()?;
self.bopen()?; self.bopen()?;
@ -618,18 +620,18 @@ impl<'a> State<'a> {
} }
hir::ItemKind::ForeignMod(ref nmod) => { hir::ItemKind::ForeignMod(ref nmod) => {
self.head("extern")?; self.head("extern")?;
self.word_nbsp(&nmod.abi.to_string())?; self.word_nbsp(nmod.abi.to_string())?;
self.bopen()?; self.bopen()?;
self.print_foreign_mod(nmod, &item.attrs)?; self.print_foreign_mod(nmod, &item.attrs)?;
self.bclose(item.span)?; self.bclose(item.span)?;
} }
hir::ItemKind::GlobalAsm(ref ga) => { hir::ItemKind::GlobalAsm(ref ga) => {
self.head(&visibility_qualified(&item.vis, "global asm"))?; self.head(visibility_qualified(&item.vis, "global asm"))?;
self.s.word(&ga.asm.as_str())?; self.s.word(ga.asm.as_str().get())?;
self.end()? self.end()?
} }
hir::ItemKind::Ty(ref ty, ref generics) => { hir::ItemKind::Ty(ref ty, ref generics) => {
self.head(&visibility_qualified(&item.vis, "type"))?; self.head(visibility_qualified(&item.vis, "type"))?;
self.print_name(item.name)?; self.print_name(item.name)?;
self.print_generic_params(&generics.params)?; self.print_generic_params(&generics.params)?;
self.end()?; // end the inner ibox self.end()?; // end the inner ibox
@ -642,7 +644,7 @@ impl<'a> State<'a> {
self.end()?; // end the outer ibox self.end()?; // end the outer ibox
} }
hir::ItemKind::Existential(ref exist) => { hir::ItemKind::Existential(ref exist) => {
self.head(&visibility_qualified(&item.vis, "existential type"))?; self.head(visibility_qualified(&item.vis, "existential type"))?;
self.print_name(item.name)?; self.print_name(item.name)?;
self.print_generic_params(&exist.generics.params)?; self.print_generic_params(&exist.generics.params)?;
self.end()?; // end the inner ibox self.end()?; // end the inner ibox
@ -668,11 +670,11 @@ impl<'a> State<'a> {
self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?; self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
} }
hir::ItemKind::Struct(ref struct_def, ref generics) => { hir::ItemKind::Struct(ref struct_def, ref generics) => {
self.head(&visibility_qualified(&item.vis, "struct"))?; self.head(visibility_qualified(&item.vis, "struct"))?;
self.print_struct(struct_def, generics, item.name, item.span, true)?; self.print_struct(struct_def, generics, item.name, item.span, true)?;
} }
hir::ItemKind::Union(ref struct_def, ref generics) => { hir::ItemKind::Union(ref struct_def, ref generics) => {
self.head(&visibility_qualified(&item.vis, "union"))?; self.head(visibility_qualified(&item.vis, "union"))?;
self.print_struct(struct_def, generics, item.name, item.span, true)?; self.print_struct(struct_def, generics, item.name, item.span, true)?;
} }
hir::ItemKind::Impl(unsafety, hir::ItemKind::Impl(unsafety,
@ -795,7 +797,7 @@ impl<'a> State<'a> {
span: syntax_pos::Span, span: syntax_pos::Span,
visibility: &hir::Visibility) visibility: &hir::Visibility)
-> io::Result<()> { -> io::Result<()> {
self.head(&visibility_qualified(visibility, "enum"))?; self.head(visibility_qualified(visibility, "enum"))?;
self.print_name(name)?; self.print_name(name)?;
self.print_generic_params(&generics.params)?; self.print_generic_params(&generics.params)?;
self.print_where_clause(&generics.where_clause)?; self.print_where_clause(&generics.where_clause)?;
@ -1587,14 +1589,14 @@ impl<'a> State<'a> {
} }
pub fn print_usize(&mut self, i: usize) -> io::Result<()> { pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
self.s.word(&i.to_string()) self.s.word(i.to_string())
} }
pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> { pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
if ident.is_raw_guess() { if ident.is_raw_guess() {
self.s.word(&format!("r#{}", ident.name))?; self.s.word(format!("r#{}", ident.name))?;
} else { } else {
self.s.word(&ident.as_str())?; self.s.word(ident.as_str().get())?;
} }
self.ann.post(self, AnnNode::Name(&ident.name)) self.ann.post(self, AnnNode::Name(&ident.name))
} }
@ -2010,7 +2012,7 @@ impl<'a> State<'a> {
self.commasep(Inconsistent, &decl.inputs, |s, ty| { self.commasep(Inconsistent, &decl.inputs, |s, ty| {
s.ibox(indent_unit)?; s.ibox(indent_unit)?;
if let Some(arg_name) = arg_names.get(i) { if let Some(arg_name) = arg_names.get(i) {
s.s.word(&arg_name.as_str())?; s.s.word(arg_name.as_str().get())?;
s.s.word(":")?; s.s.word(":")?;
s.s.space()?; s.s.space()?;
} else if let Some(body_id) = body_id { } else if let Some(body_id) = body_id {
@ -2073,7 +2075,8 @@ impl<'a> State<'a> {
} }
} }
pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::GenericBound]) -> io::Result<()> { pub fn print_bounds(&mut self, prefix: &'static str, bounds: &[hir::GenericBound])
-> io::Result<()> {
if !bounds.is_empty() { if !bounds.is_empty() {
self.s.word(prefix)?; self.s.word(prefix)?;
let mut first = true; let mut first = true;
@ -2322,7 +2325,7 @@ impl<'a> State<'a> {
Some(Abi::Rust) => Ok(()), Some(Abi::Rust) => Ok(()),
Some(abi) => { Some(abi) => {
self.word_nbsp("extern")?; self.word_nbsp("extern")?;
self.word_nbsp(&abi.to_string()) self.word_nbsp(abi.to_string())
} }
None => Ok(()), None => Ok(()),
} }
@ -2332,7 +2335,7 @@ impl<'a> State<'a> {
match opt_abi { match opt_abi {
Some(abi) => { Some(abi) => {
self.word_nbsp("extern")?; self.word_nbsp("extern")?;
self.word_nbsp(&abi.to_string()) self.word_nbsp(abi.to_string())
} }
None => Ok(()), None => Ok(()),
} }
@ -2342,7 +2345,7 @@ impl<'a> State<'a> {
header: hir::FnHeader, header: hir::FnHeader,
vis: &hir::Visibility) vis: &hir::Visibility)
-> io::Result<()> { -> io::Result<()> {
self.s.word(&visibility_qualified(vis, ""))?; self.s.word(visibility_qualified(vis, ""))?;
match header.constness { match header.constness {
hir::Constness::NotConst => {} hir::Constness::NotConst => {}
@ -2358,7 +2361,7 @@ impl<'a> State<'a> {
if header.abi != Abi::Rust { if header.abi != Abi::Rust {
self.word_nbsp("extern")?; self.word_nbsp("extern")?;
self.word_nbsp(&header.abi.to_string())?; self.word_nbsp(header.abi.to_string())?;
} }
self.s.word("fn") self.s.word("fn")

View file

@ -530,7 +530,7 @@ impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
s.s.space()?; s.s.space()?;
s.s.word("as")?; s.s.word("as")?;
s.s.space()?; s.s.space()?;
s.s.word(&self.tables.get().expr_ty(expr).to_string())?; s.s.word(self.tables.get().expr_ty(expr).to_string())?;
s.pclose() s.pclose()
} }
_ => Ok(()), _ => Ok(()),

View file

@ -185,7 +185,7 @@ fn unused_crates_lint<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>) {
Some(orig_name) => format!("use {} as {};", orig_name, item.name), Some(orig_name) => format!("use {} as {};", orig_name, item.name),
None => format!("use {};", item.name), None => format!("use {};", item.name),
}; };
let replacement = visibility_qualified(&item.vis, &base_replacement); let replacement = visibility_qualified(&item.vis, base_replacement);
tcx.struct_span_lint_node(lint, id, extern_crate.span, msg) tcx.struct_span_lint_node(lint, id, extern_crate.span, msg)
.span_suggestion_short_with_applicability( .span_suggestion_short_with_applicability(
extern_crate.span, extern_crate.span,

View file

@ -2795,7 +2795,7 @@ impl<'a> Parser<'a> {
s.print_usize(float.trunc() as usize)?; s.print_usize(float.trunc() as usize)?;
s.pclose()?; s.pclose()?;
s.s.word(".")?; s.s.word(".")?;
s.s.word(fstr.splitn(2, ".").last().unwrap()) s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
}); });
err.span_suggestion_with_applicability( err.span_suggestion_with_applicability(
lo.to(self.prev_span), lo.to(self.prev_span),

View file

@ -147,6 +147,7 @@
use std::collections::VecDeque; use std::collections::VecDeque;
use std::fmt; use std::fmt;
use std::io; use std::io;
use std::borrow::Cow;
/// How to break. Described in more detail in the module docs. /// How to break. Described in more detail in the module docs.
#[derive(Clone, Copy, PartialEq)] #[derive(Clone, Copy, PartialEq)]
@ -169,7 +170,10 @@ pub struct BeginToken {
#[derive(Clone)] #[derive(Clone)]
pub enum Token { pub enum Token {
String(String, isize), // In practice a string token contains either a `&'static str` or a
// `String`. `Cow` is overkill for this because we never modify the data,
// but it's more convenient than rolling our own more specialized type.
String(Cow<'static, str>, isize),
Break(BreakToken), Break(BreakToken),
Begin(BeginToken), Begin(BeginToken),
End, End,
@ -644,8 +648,10 @@ impl<'a> Printer<'a> {
self.pretty_print(Token::Eof) self.pretty_print(Token::Eof)
} }
pub fn word(&mut self, wrd: &str) -> io::Result<()> { pub fn word<S: Into<Cow<'static, str>>>(&mut self, wrd: S) -> io::Result<()> {
self.pretty_print(Token::String(wrd.to_string(), wrd.len() as isize)) let s = wrd.into();
let len = s.len() as isize;
self.pretty_print(Token::String(s, len))
} }
fn spaces(&mut self, n: usize) -> io::Result<()> { fn spaces(&mut self, n: usize) -> io::Result<()> {

View file

@ -29,6 +29,7 @@ use syntax_pos::{DUMMY_SP, FileName};
use tokenstream::{self, TokenStream, TokenTree}; use tokenstream::{self, TokenStream, TokenTree};
use std::ascii; use std::ascii;
use std::borrow::Cow;
use std::io::{self, Write, Read}; use std::io::{self, Write, Read};
use std::iter::Peekable; use std::iter::Peekable;
use std::vec; use std::vec;
@ -444,7 +445,7 @@ pub trait PrintState<'a> {
fn cur_lit(&mut self) -> Option<&comments::Literal>; fn cur_lit(&mut self) -> Option<&comments::Literal>;
fn bump_lit(&mut self) -> Option<comments::Literal>; fn bump_lit(&mut self) -> Option<comments::Literal>;
fn word_space(&mut self, w: &str) -> io::Result<()> { fn word_space<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
self.writer().word(w)?; self.writer().word(w)?;
self.writer().space() self.writer().space()
} }
@ -539,7 +540,7 @@ pub trait PrintState<'a> {
comments::Mixed => { comments::Mixed => {
assert_eq!(cmnt.lines.len(), 1); assert_eq!(cmnt.lines.len(), 1);
self.writer().zerobreak()?; self.writer().zerobreak()?;
self.writer().word(&cmnt.lines[0])?; self.writer().word(cmnt.lines[0].clone())?;
self.writer().zerobreak() self.writer().zerobreak()
} }
comments::Isolated => { comments::Isolated => {
@ -548,7 +549,7 @@ pub trait PrintState<'a> {
// Don't print empty lines because they will end up as trailing // Don't print empty lines because they will end up as trailing
// whitespace // whitespace
if !line.is_empty() { if !line.is_empty() {
self.writer().word(&line[..])?; self.writer().word(line.clone())?;
} }
self.writer().hardbreak()?; self.writer().hardbreak()?;
} }
@ -559,13 +560,13 @@ pub trait PrintState<'a> {
self.writer().word(" ")?; self.writer().word(" ")?;
} }
if cmnt.lines.len() == 1 { if cmnt.lines.len() == 1 {
self.writer().word(&cmnt.lines[0])?; self.writer().word(cmnt.lines[0].clone())?;
self.writer().hardbreak() self.writer().hardbreak()
} else { } else {
self.ibox(0)?; self.ibox(0)?;
for line in &cmnt.lines { for line in &cmnt.lines {
if !line.is_empty() { if !line.is_empty() {
self.writer().word(&line[..])?; self.writer().word(line.clone())?;
} }
self.writer().hardbreak()?; self.writer().hardbreak()?;
} }
@ -610,7 +611,7 @@ pub trait PrintState<'a> {
fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> { fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
self.maybe_print_comment(lit.span.lo())?; self.maybe_print_comment(lit.span.lo())?;
if let Some(ltrl) = self.next_lit(lit.span.lo()) { if let Some(ltrl) = self.next_lit(lit.span.lo()) {
return self.writer().word(&ltrl.lit); return self.writer().word(ltrl.lit.clone());
} }
match lit.node { match lit.node {
ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style), ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style),
@ -618,31 +619,31 @@ pub trait PrintState<'a> {
let mut res = String::from("b'"); let mut res = String::from("b'");
res.extend(ascii::escape_default(byte).map(|c| c as char)); res.extend(ascii::escape_default(byte).map(|c| c as char));
res.push('\''); res.push('\'');
self.writer().word(&res[..]) self.writer().word(res)
} }
ast::LitKind::Char(ch) => { ast::LitKind::Char(ch) => {
let mut res = String::from("'"); let mut res = String::from("'");
res.extend(ch.escape_default()); res.extend(ch.escape_default());
res.push('\''); res.push('\'');
self.writer().word(&res[..]) self.writer().word(res)
} }
ast::LitKind::Int(i, t) => { ast::LitKind::Int(i, t) => {
match t { match t {
ast::LitIntType::Signed(st) => { ast::LitIntType::Signed(st) => {
self.writer().word(&st.val_to_string(i as i128)) self.writer().word(st.val_to_string(i as i128))
} }
ast::LitIntType::Unsigned(ut) => { ast::LitIntType::Unsigned(ut) => {
self.writer().word(&ut.val_to_string(i)) self.writer().word(ut.val_to_string(i))
} }
ast::LitIntType::Unsuffixed => { ast::LitIntType::Unsuffixed => {
self.writer().word(&i.to_string()) self.writer().word(i.to_string())
} }
} }
} }
ast::LitKind::Float(ref f, t) => { ast::LitKind::Float(ref f, t) => {
self.writer().word(&format!("{}{}", &f, t.ty_to_string())) self.writer().word(format!("{}{}", &f, t.ty_to_string()))
} }
ast::LitKind::FloatUnsuffixed(ref f) => self.writer().word(&f.as_str()), ast::LitKind::FloatUnsuffixed(ref f) => self.writer().word(f.as_str().get()),
ast::LitKind::Bool(val) => { ast::LitKind::Bool(val) => {
if val { self.writer().word("true") } else { self.writer().word("false") } if val { self.writer().word("true") } else { self.writer().word("false") }
} }
@ -652,7 +653,7 @@ pub trait PrintState<'a> {
escaped.extend(ascii::escape_default(ch) escaped.extend(ascii::escape_default(ch)
.map(|c| c as char)); .map(|c| c as char));
} }
self.writer().word(&format!("b\"{}\"", escaped)) self.writer().word(format!("b\"{}\"", escaped))
} }
} }
} }
@ -669,7 +670,7 @@ pub trait PrintState<'a> {
string=st)) string=st))
} }
}; };
self.writer().word(&st[..]) self.writer().word(st)
} }
fn print_inner_attributes(&mut self, fn print_inner_attributes(&mut self,
@ -727,7 +728,7 @@ pub trait PrintState<'a> {
if segment.ident.name != keywords::CrateRoot.name() && if segment.ident.name != keywords::CrateRoot.name() &&
segment.ident.name != keywords::DollarCrate.name() segment.ident.name != keywords::DollarCrate.name()
{ {
self.writer().word(&segment.ident.as_str())?; self.writer().word(segment.ident.as_str().get())?;
} else if segment.ident.name == keywords::DollarCrate.name() { } else if segment.ident.name == keywords::DollarCrate.name() {
self.print_dollar_crate(segment.ident.span.ctxt())?; self.print_dollar_crate(segment.ident.span.ctxt())?;
} }
@ -746,7 +747,7 @@ pub trait PrintState<'a> {
} }
self.maybe_print_comment(attr.span.lo())?; self.maybe_print_comment(attr.span.lo())?;
if attr.is_sugared_doc { if attr.is_sugared_doc {
self.writer().word(&attr.value_str().unwrap().as_str())?; self.writer().word(attr.value_str().unwrap().as_str().get())?;
self.writer().hardbreak() self.writer().hardbreak()
} else { } else {
match attr.style { match attr.style {
@ -807,7 +808,7 @@ pub trait PrintState<'a> {
fn print_tt(&mut self, tt: tokenstream::TokenTree) -> io::Result<()> { fn print_tt(&mut self, tt: tokenstream::TokenTree) -> io::Result<()> {
match tt { match tt {
TokenTree::Token(_, ref tk) => { TokenTree::Token(_, ref tk) => {
self.writer().word(&token_to_string(tk))?; self.writer().word(token_to_string(tk))?;
match *tk { match *tk {
parse::token::DocComment(..) => { parse::token::DocComment(..) => {
self.writer().hardbreak() self.writer().hardbreak()
@ -816,11 +817,11 @@ pub trait PrintState<'a> {
} }
} }
TokenTree::Delimited(_, ref delimed) => { TokenTree::Delimited(_, ref delimed) => {
self.writer().word(&token_to_string(&delimed.open_token()))?; self.writer().word(token_to_string(&delimed.open_token()))?;
self.writer().space()?; self.writer().space()?;
self.print_tts(delimed.stream())?; self.print_tts(delimed.stream())?;
self.writer().space()?; self.writer().space()?;
self.writer().word(&token_to_string(&delimed.close_token())) self.writer().word(token_to_string(&delimed.close_token()))
}, },
} }
} }
@ -889,12 +890,13 @@ impl<'a> State<'a> {
self.s.cbox(u) self.s.cbox(u)
} }
pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> { pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
self.s.word(w)?; self.s.word(w)?;
self.nbsp() self.nbsp()
} }
pub fn head(&mut self, w: &str) -> io::Result<()> { pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) -> io::Result<()> {
let w = w.into();
// outer-box is consistent // outer-box is consistent
self.cbox(INDENT_UNIT)?; self.cbox(INDENT_UNIT)?;
// head-box is inconsistent // head-box is inconsistent
@ -956,7 +958,7 @@ impl<'a> State<'a> {
pub fn synth_comment(&mut self, text: String) -> io::Result<()> { pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
self.s.word("/*")?; self.s.word("/*")?;
self.s.space()?; self.s.space()?;
self.s.word(&text[..])?; self.s.word(text)?;
self.s.space()?; self.s.space()?;
self.s.word("*/") self.s.word("*/")
} }
@ -1129,7 +1131,7 @@ impl<'a> State<'a> {
self.end() // end the outer fn box self.end() // end the outer fn box
} }
ast::ForeignItemKind::Static(ref t, m) => { ast::ForeignItemKind::Static(ref t, m) => {
self.head(&visibility_qualified(&item.vis, "static"))?; self.head(visibility_qualified(&item.vis, "static"))?;
if m { if m {
self.word_space("mut")?; self.word_space("mut")?;
} }
@ -1141,7 +1143,7 @@ impl<'a> State<'a> {
self.end() // end the outer cbox self.end() // end the outer cbox
} }
ast::ForeignItemKind::Ty => { ast::ForeignItemKind::Ty => {
self.head(&visibility_qualified(&item.vis, "type"))?; self.head(visibility_qualified(&item.vis, "type"))?;
self.print_ident(item.ident)?; self.print_ident(item.ident)?;
self.s.word(";")?; self.s.word(";")?;
self.end()?; // end the head-ibox self.end()?; // end the head-ibox
@ -1164,7 +1166,7 @@ impl<'a> State<'a> {
vis: &ast::Visibility) vis: &ast::Visibility)
-> io::Result<()> -> io::Result<()>
{ {
self.s.word(&visibility_qualified(vis, ""))?; self.s.word(visibility_qualified(vis, ""))?;
self.word_space("const")?; self.word_space("const")?;
self.print_ident(ident)?; self.print_ident(ident)?;
self.word_space(":")?; self.word_space(":")?;
@ -1203,7 +1205,7 @@ impl<'a> State<'a> {
self.ann.pre(self, AnnNode::Item(item))?; self.ann.pre(self, AnnNode::Item(item))?;
match item.node { match item.node {
ast::ItemKind::ExternCrate(orig_name) => { ast::ItemKind::ExternCrate(orig_name) => {
self.head(&visibility_qualified(&item.vis, "extern crate"))?; self.head(visibility_qualified(&item.vis, "extern crate"))?;
if let Some(orig_name) = orig_name { if let Some(orig_name) = orig_name {
self.print_name(orig_name)?; self.print_name(orig_name)?;
self.s.space()?; self.s.space()?;
@ -1216,14 +1218,14 @@ impl<'a> State<'a> {
self.end()?; // end outer head-block self.end()?; // end outer head-block
} }
ast::ItemKind::Use(ref tree) => { ast::ItemKind::Use(ref tree) => {
self.head(&visibility_qualified(&item.vis, "use"))?; self.head(visibility_qualified(&item.vis, "use"))?;
self.print_use_tree(tree)?; self.print_use_tree(tree)?;
self.s.word(";")?; self.s.word(";")?;
self.end()?; // end inner head-block self.end()?; // end inner head-block
self.end()?; // end outer head-block self.end()?; // end outer head-block
} }
ast::ItemKind::Static(ref ty, m, ref expr) => { ast::ItemKind::Static(ref ty, m, ref expr) => {
self.head(&visibility_qualified(&item.vis, "static"))?; self.head(visibility_qualified(&item.vis, "static"))?;
if m == ast::Mutability::Mutable { if m == ast::Mutability::Mutable {
self.word_space("mut")?; self.word_space("mut")?;
} }
@ -1239,7 +1241,7 @@ impl<'a> State<'a> {
self.end()?; // end the outer cbox self.end()?; // end the outer cbox
} }
ast::ItemKind::Const(ref ty, ref expr) => { ast::ItemKind::Const(ref ty, ref expr) => {
self.head(&visibility_qualified(&item.vis, "const"))?; self.head(visibility_qualified(&item.vis, "const"))?;
self.print_ident(item.ident)?; self.print_ident(item.ident)?;
self.word_space(":")?; self.word_space(":")?;
self.print_type(ty)?; self.print_type(ty)?;
@ -1264,7 +1266,7 @@ impl<'a> State<'a> {
self.print_block_with_attrs(body, &item.attrs)?; self.print_block_with_attrs(body, &item.attrs)?;
} }
ast::ItemKind::Mod(ref _mod) => { ast::ItemKind::Mod(ref _mod) => {
self.head(&visibility_qualified(&item.vis, "mod"))?; self.head(visibility_qualified(&item.vis, "mod"))?;
self.print_ident(item.ident)?; self.print_ident(item.ident)?;
if _mod.inline || self.is_expanded { if _mod.inline || self.is_expanded {
@ -1281,18 +1283,18 @@ impl<'a> State<'a> {
} }
ast::ItemKind::ForeignMod(ref nmod) => { ast::ItemKind::ForeignMod(ref nmod) => {
self.head("extern")?; self.head("extern")?;
self.word_nbsp(&nmod.abi.to_string())?; self.word_nbsp(nmod.abi.to_string())?;
self.bopen()?; self.bopen()?;
self.print_foreign_mod(nmod, &item.attrs)?; self.print_foreign_mod(nmod, &item.attrs)?;
self.bclose(item.span)?; self.bclose(item.span)?;
} }
ast::ItemKind::GlobalAsm(ref ga) => { ast::ItemKind::GlobalAsm(ref ga) => {
self.head(&visibility_qualified(&item.vis, "global_asm!"))?; self.head(visibility_qualified(&item.vis, "global_asm!"))?;
self.s.word(&ga.asm.as_str())?; self.s.word(ga.asm.as_str().get())?;
self.end()?; self.end()?;
} }
ast::ItemKind::Ty(ref ty, ref generics) => { ast::ItemKind::Ty(ref ty, ref generics) => {
self.head(&visibility_qualified(&item.vis, "type"))?; self.head(visibility_qualified(&item.vis, "type"))?;
self.print_ident(item.ident)?; self.print_ident(item.ident)?;
self.print_generic_params(&generics.params)?; self.print_generic_params(&generics.params)?;
self.end()?; // end the inner ibox self.end()?; // end the inner ibox
@ -1305,7 +1307,7 @@ impl<'a> State<'a> {
self.end()?; // end the outer ibox self.end()?; // end the outer ibox
} }
ast::ItemKind::Existential(ref bounds, ref generics) => { ast::ItemKind::Existential(ref bounds, ref generics) => {
self.head(&visibility_qualified(&item.vis, "existential type"))?; self.head(visibility_qualified(&item.vis, "existential type"))?;
self.print_ident(item.ident)?; self.print_ident(item.ident)?;
self.print_generic_params(&generics.params)?; self.print_generic_params(&generics.params)?;
self.end()?; // end the inner ibox self.end()?; // end the inner ibox
@ -1326,11 +1328,11 @@ impl<'a> State<'a> {
)?; )?;
} }
ast::ItemKind::Struct(ref struct_def, ref generics) => { ast::ItemKind::Struct(ref struct_def, ref generics) => {
self.head(&visibility_qualified(&item.vis, "struct"))?; self.head(visibility_qualified(&item.vis, "struct"))?;
self.print_struct(struct_def, generics, item.ident, item.span, true)?; self.print_struct(struct_def, generics, item.ident, item.span, true)?;
} }
ast::ItemKind::Union(ref struct_def, ref generics) => { ast::ItemKind::Union(ref struct_def, ref generics) => {
self.head(&visibility_qualified(&item.vis, "union"))?; self.head(visibility_qualified(&item.vis, "union"))?;
self.print_struct(struct_def, generics, item.ident, item.span, true)?; self.print_struct(struct_def, generics, item.ident, item.span, true)?;
} }
ast::ItemKind::Impl(unsafety, ast::ItemKind::Impl(unsafety,
@ -1479,7 +1481,7 @@ impl<'a> State<'a> {
generics: &ast::Generics, ident: ast::Ident, generics: &ast::Generics, ident: ast::Ident,
span: syntax_pos::Span, span: syntax_pos::Span,
visibility: &ast::Visibility) -> io::Result<()> { visibility: &ast::Visibility) -> io::Result<()> {
self.head(&visibility_qualified(visibility, "enum"))?; self.head(visibility_qualified(visibility, "enum"))?;
self.print_ident(ident)?; self.print_ident(ident)?;
self.print_generic_params(&generics.params)?; self.print_generic_params(&generics.params)?;
self.print_where_clause(&generics.where_clause)?; self.print_where_clause(&generics.where_clause)?;
@ -1514,9 +1516,9 @@ impl<'a> State<'a> {
ast::VisibilityKind::Restricted { ref path, .. } => { ast::VisibilityKind::Restricted { ref path, .. } => {
let path = to_string(|s| s.print_path(path, false, 0)); let path = to_string(|s| s.print_path(path, false, 0));
if path == "self" || path == "super" { if path == "self" || path == "super" {
self.word_nbsp(&format!("pub({})", path)) self.word_nbsp(format!("pub({})", path))
} else { } else {
self.word_nbsp(&format!("pub(in {})", path)) self.word_nbsp(format!("pub(in {})", path))
} }
} }
ast::VisibilityKind::Inherited => Ok(()) ast::VisibilityKind::Inherited => Ok(())
@ -2415,19 +2417,19 @@ impl<'a> State<'a> {
pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> { pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
if ident.is_raw_guess() { if ident.is_raw_guess() {
self.s.word(&format!("r#{}", ident))?; self.s.word(format!("r#{}", ident))?;
} else { } else {
self.s.word(&ident.as_str())?; self.s.word(ident.as_str().get())?;
} }
self.ann.post(self, AnnNode::Ident(&ident)) self.ann.post(self, AnnNode::Ident(&ident))
} }
pub fn print_usize(&mut self, i: usize) -> io::Result<()> { pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
self.s.word(&i.to_string()) self.s.word(i.to_string())
} }
pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> { pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
self.s.word(&name.as_str())?; self.s.word(name.as_str().get())?;
self.ann.post(self, AnnNode::Name(&name)) self.ann.post(self, AnnNode::Name(&name))
} }
@ -2851,10 +2853,8 @@ impl<'a> State<'a> {
} }
} }
pub fn print_type_bounds(&mut self, pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound])
prefix: &str, -> io::Result<()> {
bounds: &[ast::GenericBound])
-> io::Result<()> {
if !bounds.is_empty() { if !bounds.is_empty() {
self.s.word(prefix)?; self.s.word(prefix)?;
let mut first = true; let mut first = true;
@ -3146,7 +3146,7 @@ impl<'a> State<'a> {
Some(Abi::Rust) => Ok(()), Some(Abi::Rust) => Ok(()),
Some(abi) => { Some(abi) => {
self.word_nbsp("extern")?; self.word_nbsp("extern")?;
self.word_nbsp(&abi.to_string()) self.word_nbsp(abi.to_string())
} }
None => Ok(()) None => Ok(())
} }
@ -3157,7 +3157,7 @@ impl<'a> State<'a> {
match opt_abi { match opt_abi {
Some(abi) => { Some(abi) => {
self.word_nbsp("extern")?; self.word_nbsp("extern")?;
self.word_nbsp(&abi.to_string()) self.word_nbsp(abi.to_string())
} }
None => Ok(()) None => Ok(())
} }
@ -3166,7 +3166,7 @@ impl<'a> State<'a> {
pub fn print_fn_header_info(&mut self, pub fn print_fn_header_info(&mut self,
header: ast::FnHeader, header: ast::FnHeader,
vis: &ast::Visibility) -> io::Result<()> { vis: &ast::Visibility) -> io::Result<()> {
self.s.word(&visibility_qualified(vis, ""))?; self.s.word(visibility_qualified(vis, ""))?;
match header.constness.node { match header.constness.node {
ast::Constness::NotConst => {} ast::Constness::NotConst => {}
@ -3178,7 +3178,7 @@ impl<'a> State<'a> {
if header.abi != Abi::Rust { if header.abi != Abi::Rust {
self.word_nbsp("extern")?; self.word_nbsp("extern")?;
self.word_nbsp(&header.abi.to_string())?; self.word_nbsp(header.abi.to_string())?;
} }
self.s.word("fn") self.s.word("fn")

View file

@ -493,6 +493,10 @@ impl LocalInternedString {
symbol: Symbol::intern(self.string) symbol: Symbol::intern(self.string)
} }
} }
pub fn get(&self) -> &'static str {
self.string
}
} }
impl<U: ?Sized> ::std::convert::AsRef<U> for LocalInternedString impl<U: ?Sized> ::std::convert::AsRef<U> for LocalInternedString