1
Fork 0

Rollup merge of #65363 - Centril:less-pprust, r=Mark-Simulacrum

Remove implicit dependencies on syntax::pprust

Part of https://github.com/rust-lang/rust/pull/65324.

The main goal here is to facilitate the eventual move of pprust out from libsyntax and because an AST definition typically should not depend on its pretty printer.

r? @estebank
This commit is contained in:
Mazdak Farrokhzad 2019-10-14 07:36:57 +02:00 committed by GitHub
commit 2800bc240e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 101 additions and 99 deletions

View file

@ -12,6 +12,7 @@ use rustc_data_structures::stable_hasher::{HashStable, ToStableHashKey, StableHa
use syntax::ast; use syntax::ast;
use syntax::attr; use syntax::attr;
use syntax::feature_gate; use syntax::feature_gate;
use syntax::print::pprust;
use syntax::source_map::MultiSpan; use syntax::source_map::MultiSpan;
use syntax::symbol::{Symbol, sym}; use syntax::symbol::{Symbol, sym};
@ -285,7 +286,7 @@ impl<'a> LintLevelsBuilder<'a> {
tool_ident.span, tool_ident.span,
E0710, E0710,
"an unknown tool name found in scoped lint: `{}`", "an unknown tool name found in scoped lint: `{}`",
meta_item.path pprust::path_to_string(&meta_item.path),
); );
continue; continue;
} }

View file

@ -45,7 +45,7 @@ use syntax::feature_gate::{Stability, deprecated_attributes};
use syntax_pos::{BytePos, Span}; use syntax_pos::{BytePos, Span};
use syntax::symbol::{Symbol, kw, sym}; use syntax::symbol::{Symbol, kw, sym};
use syntax::errors::{Applicability, DiagnosticBuilder}; use syntax::errors::{Applicability, DiagnosticBuilder};
use syntax::print::pprust::expr_to_string; use syntax::print::pprust::{self, expr_to_string};
use syntax::visit::FnKind; use syntax::visit::FnKind;
use rustc::hir::{self, GenericParamKind, PatKind}; use rustc::hir::{self, GenericParamKind, PatKind};
@ -701,7 +701,8 @@ impl EarlyLintPass for DeprecatedAttr {
} }
} }
if attr.check_name(sym::no_start) || attr.check_name(sym::crate_id) { if attr.check_name(sym::no_start) || attr.check_name(sym::crate_id) {
let msg = format!("use of deprecated attribute `{}`: no longer used.", attr.path); let path_str = pprust::path_to_string(&attr.path);
let msg = format!("use of deprecated attribute `{}`: no longer used.", path_str);
lint_deprecated_attr(cx, attr, &msg, None); lint_deprecated_attr(cx, attr, &msg, None);
} }
} }

View file

@ -1,4 +1,5 @@
use syntax::ast::{self, MetaItem}; use syntax::ast::{self, MetaItem};
use syntax::print::pprust;
use syntax::symbol::{Symbol, sym}; use syntax::symbol::{Symbol, sym};
use rustc_index::bit_set::{BitSet, HybridBitSet}; use rustc_index::bit_set::{BitSet, HybridBitSet};
@ -159,9 +160,8 @@ where
if let Some(s) = item.value_str() { if let Some(s) = item.value_str() {
return Some(s.to_string()) return Some(s.to_string())
} else { } else {
sess.span_err( let path = pprust::path_to_string(&item.path);
item.span, sess.span_err(item.span, &format!("{} attribute requires a path", path));
&format!("{} attribute requires a path", item.path));
return None; return None;
} }
} }

View file

@ -263,7 +263,8 @@ impl<'a> AstValidator<'a> {
let mut err = self.err_handler().struct_span_err(poly.span, let mut err = self.err_handler().struct_span_err(poly.span,
&format!("`?Trait` is not permitted in {}", where_)); &format!("`?Trait` is not permitted in {}", where_));
if is_trait { if is_trait {
err.note(&format!("traits are `?{}` by default", poly.trait_ref.path)); let path_str = pprust::path_to_string(&poly.trait_ref.path);
err.note(&format!("traits are `?{}` by default", path_str));
} }
err.emit(); err.emit();
} }

View file

@ -37,6 +37,7 @@ use syntax::ext::expand::AstFragment;
use syntax::ext::hygiene::ExpnId; use syntax::ext::hygiene::ExpnId;
use syntax::feature_gate::is_builtin_attr; use syntax::feature_gate::is_builtin_attr;
use syntax::parse::token::{self, Token}; use syntax::parse::token::{self, Token};
use syntax::print::pprust;
use syntax::{span_err, struct_span_err}; use syntax::{span_err, struct_span_err};
use syntax::source_map::{respan, Spanned}; use syntax::source_map::{respan, Spanned};
use syntax::symbol::{kw, sym}; use syntax::symbol::{kw, sym};
@ -228,7 +229,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
.span_suggestion( .span_suggestion(
path.span, path.span,
"try", "try",
format!("crate::{}", path), format!("crate::{}", pprust::path_to_string(&path)),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
) )
.emit(); .emit();

View file

@ -38,6 +38,7 @@ use rustc_metadata::cstore::CStore;
use syntax::ext::hygiene::{ExpnId, Transparency, SyntaxContext}; use syntax::ext::hygiene::{ExpnId, Transparency, SyntaxContext};
use syntax::ast::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy}; use syntax::ast::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy};
use syntax::ext::base::{SyntaxExtension, MacroKind, SpecialDerives}; use syntax::ext::base::{SyntaxExtension, MacroKind, SpecialDerives};
use syntax::print::pprust;
use syntax::symbol::{kw, sym}; use syntax::symbol::{kw, sym};
use syntax::visit::{self, Visitor}; use syntax::visit::{self, Visitor};
@ -2011,13 +2012,13 @@ impl<'a> Resolver<'a> {
let mut candidates = let mut candidates =
self.lookup_import_candidates(ident, TypeNS, is_mod); self.lookup_import_candidates(ident, TypeNS, is_mod);
candidates.sort_by_cached_key(|c| { candidates.sort_by_cached_key(|c| {
(c.path.segments.len(), c.path.to_string()) (c.path.segments.len(), pprust::path_to_string(&c.path))
}); });
if let Some(candidate) = candidates.get(0) { if let Some(candidate) = candidates.get(0) {
( (
String::from("unresolved import"), String::from("unresolved import"),
Some(( Some((
vec![(ident.span, candidate.path.to_string())], vec![(ident.span, pprust::path_to_string(&candidate.path))],
String::from("a similar path exists"), String::from("a similar path exists"),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
)), )),

View file

@ -21,6 +21,7 @@ use syntax::ext::hygiene::{self, ExpnId, ExpnData, ExpnKind};
use syntax::ext::compile_declarative_macro; use syntax::ext::compile_declarative_macro;
use syntax::feature_gate::{emit_feature_err, is_builtin_attr_name}; use syntax::feature_gate::{emit_feature_err, is_builtin_attr_name};
use syntax::feature_gate::GateIssue; use syntax::feature_gate::GateIssue;
use syntax::print::pprust;
use syntax::symbol::{Symbol, kw, sym}; use syntax::symbol::{Symbol, kw, sym};
use syntax_pos::{Span, DUMMY_SP}; use syntax_pos::{Span, DUMMY_SP};
@ -324,7 +325,8 @@ impl<'a> Resolver<'a> {
Ok(if ext.macro_kind() != kind { Ok(if ext.macro_kind() != kind {
let expected = kind.descr_expected(); let expected = kind.descr_expected();
let msg = format!("expected {}, found {} `{}`", expected, res.descr(), path); let path_str = pprust::path_to_string(path);
let msg = format!("expected {}, found {} `{}`", expected, res.descr(), path_str);
self.session.struct_span_err(path.span, &msg) self.session.struct_span_err(path.span, &msg)
.span_label(path.span, format!("not {} {}", kind.article(), expected)) .span_label(path.span, format!("not {} {}", kind.article(), expected))
.emit(); .emit();
@ -805,14 +807,16 @@ impl<'a> Resolver<'a> {
} }
} }
if let Some(depr) = &stability.rustc_depr { if let Some(depr) = &stability.rustc_depr {
let (message, lint) = stability::rustc_deprecation_message(depr, &path.to_string()); let path = pprust::path_to_string(path);
let (message, lint) = stability::rustc_deprecation_message(depr, &path);
stability::early_report_deprecation( stability::early_report_deprecation(
self.session, &message, depr.suggestion, lint, span self.session, &message, depr.suggestion, lint, span
); );
} }
} }
if let Some(depr) = &ext.deprecation { if let Some(depr) = &ext.deprecation {
let (message, lint) = stability::deprecation_message(depr, &path.to_string()); let path = pprust::path_to_string(&path);
let (message, lint) = stability::deprecation_message(depr, &path);
stability::early_report_deprecation(self.session, &message, None, lint, span); stability::early_report_deprecation(self.session, &message, None, lint, span);
} }
} }

View file

@ -46,6 +46,7 @@ use serialize::json::{ToJson, Json, as_json};
use syntax::ast; use syntax::ast;
use syntax::edition::Edition; use syntax::edition::Edition;
use syntax::ext::base::MacroKind; use syntax::ext::base::MacroKind;
use syntax::print::pprust;
use syntax::source_map::FileName; use syntax::source_map::FileName;
use syntax::feature_gate::UnstableFeatures; use syntax::feature_gate::UnstableFeatures;
use syntax::symbol::{Symbol, sym}; use syntax::symbol::{Symbol, sym};
@ -2957,7 +2958,7 @@ fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum) {
} }
fn render_attribute(attr: &ast::MetaItem) -> Option<String> { fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
let path = attr.path.to_string(); let path = pprust::path_to_string(&attr.path);
if attr.is_word() { if attr.is_word() {
Some(path) Some(path)

View file

@ -7,7 +7,6 @@ pub use crate::util::parser::ExprPrecedence;
use crate::ext::hygiene::ExpnId; use crate::ext::hygiene::ExpnId;
use crate::parse::token::{self, DelimToken}; use crate::parse::token::{self, DelimToken};
use crate::print::pprust;
use crate::ptr::P; use crate::ptr::P;
use crate::source_map::{dummy_spanned, respan, Spanned}; use crate::source_map::{dummy_spanned, respan, Spanned};
use crate::symbol::{kw, sym, Symbol}; use crate::symbol::{kw, sym, Symbol};
@ -70,7 +69,7 @@ impl fmt::Display for Lifetime {
/// along with a bunch of supporting information. /// along with a bunch of supporting information.
/// ///
/// E.g., `std::cmp::PartialEq`. /// E.g., `std::cmp::PartialEq`.
#[derive(Clone, RustcEncodable, RustcDecodable)] #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Path { pub struct Path {
pub span: Span, pub span: Span,
/// The segments in the path: the things separated by `::`. /// The segments in the path: the things separated by `::`.
@ -86,18 +85,6 @@ impl PartialEq<Symbol> for Path {
} }
} }
impl fmt::Debug for Path {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "path({})", pprust::path_to_string(self))
}
}
impl fmt::Display for Path {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", pprust::path_to_string(self))
}
}
impl Path { impl Path {
// Convert a span and an identifier to the corresponding // Convert a span and an identifier to the corresponding
// one-segment path. // one-segment path.
@ -507,19 +494,13 @@ pub struct Block {
pub span: Span, pub span: Span,
} }
#[derive(Clone, RustcEncodable, RustcDecodable)] #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Pat { pub struct Pat {
pub id: NodeId, pub id: NodeId,
pub kind: PatKind, pub kind: PatKind,
pub span: Span, pub span: Span,
} }
impl fmt::Debug for Pat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
}
}
impl Pat { impl Pat {
/// Attempt reparsing the pattern as a type. /// Attempt reparsing the pattern as a type.
/// This is intended for use by diagnostics. /// This is intended for use by diagnostics.
@ -831,7 +812,7 @@ impl UnOp {
} }
/// A statement /// A statement
#[derive(Clone, RustcEncodable, RustcDecodable)] #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Stmt { pub struct Stmt {
pub id: NodeId, pub id: NodeId,
pub kind: StmtKind, pub kind: StmtKind,
@ -865,18 +846,7 @@ impl Stmt {
} }
} }
impl fmt::Debug for Stmt { #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"stmt({}: {})",
self.id.to_string(),
pprust::stmt_to_string(self)
)
}
}
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub enum StmtKind { pub enum StmtKind {
/// A local (let) binding. /// A local (let) binding.
Local(P<Local>), Local(P<Local>),
@ -973,7 +943,7 @@ pub struct AnonConst {
} }
/// An expression. /// An expression.
#[derive(Clone, RustcEncodable, RustcDecodable)] #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Expr { pub struct Expr {
pub id: NodeId, pub id: NodeId,
pub kind: ExprKind, pub kind: ExprKind,
@ -1100,12 +1070,6 @@ impl Expr {
} }
} }
impl fmt::Debug for Expr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
}
}
/// Limit types of a range (inclusive or exclusive) /// Limit types of a range (inclusive or exclusive)
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)] #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
pub enum RangeLimits { pub enum RangeLimits {
@ -1660,19 +1624,13 @@ pub enum AssocTyConstraintKind {
}, },
} }
#[derive(Clone, RustcEncodable, RustcDecodable)] #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Ty { pub struct Ty {
pub id: NodeId, pub id: NodeId,
pub kind: TyKind, pub kind: TyKind,
pub span: Span, pub span: Span,
} }
impl fmt::Debug for Ty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "type({})", pprust::ty_to_string(self))
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)] #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct BareFnTy { pub struct BareFnTy {
pub unsafety: Unsafety, pub unsafety: Unsafety,

View file

@ -5,6 +5,7 @@ use crate::early_buffered_lints::BufferedEarlyLintId;
use crate::ext::base::ExtCtxt; use crate::ext::base::ExtCtxt;
use crate::feature_gate::{Features, GatedCfg}; use crate::feature_gate::{Features, GatedCfg};
use crate::parse::ParseSess; use crate::parse::ParseSess;
use crate::print::pprust;
use errors::{Applicability, Handler}; use errors::{Applicability, Handler};
use syntax_pos::hygiene::Transparency; use syntax_pos::hygiene::Transparency;
@ -243,7 +244,11 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
let meta = meta.as_ref().unwrap(); let meta = meta.as_ref().unwrap();
let get = |meta: &MetaItem, item: &mut Option<Symbol>| { let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
if item.is_some() { if item.is_some() {
handle_errors(sess, meta.span, AttrError::MultipleItem(meta.path.to_string())); handle_errors(
sess,
meta.span,
AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
);
return false return false
} }
if let Some(v) = meta.value_str() { if let Some(v) = meta.value_str() {
@ -271,7 +276,10 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
handle_errors( handle_errors(
sess, sess,
mi.span, mi.span,
AttrError::UnknownMetaItem(mi.path.to_string(), expected), AttrError::UnknownMetaItem(
pprust::path_to_string(&mi.path),
expected,
),
); );
continue 'outer continue 'outer
} }
@ -362,7 +370,7 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
sess, sess,
meta.span(), meta.span(),
AttrError::UnknownMetaItem( AttrError::UnknownMetaItem(
mi.path.to_string(), pprust::path_to_string(&mi.path),
&["feature", "reason", "issue", "soft"] &["feature", "reason", "issue", "soft"]
), ),
); );
@ -434,7 +442,8 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
sess, sess,
meta.span(), meta.span(),
AttrError::UnknownMetaItem( AttrError::UnknownMetaItem(
mi.path.to_string(), &["since", "note"], pprust::path_to_string(&mi.path),
&["since", "note"],
), ),
); );
continue 'outer continue 'outer
@ -597,8 +606,11 @@ pub fn eval_condition<F>(cfg: &ast::MetaItem, sess: &ParseSess, eval: &mut F)
!eval_condition(mis[0].meta_item().unwrap(), sess, eval) !eval_condition(mis[0].meta_item().unwrap(), sess, eval)
}, },
_ => { _ => {
span_err!(sess.span_diagnostic, cfg.span, E0537, span_err!(
"invalid predicate `{}`", cfg.path); sess.span_diagnostic, cfg.span, E0537,
"invalid predicate `{}`",
pprust::path_to_string(&cfg.path)
);
false false
} }
} }
@ -653,7 +665,9 @@ fn find_deprecation_generic<'a, I>(sess: &ParseSess,
let get = |meta: &MetaItem, item: &mut Option<Symbol>| { let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
if item.is_some() { if item.is_some() {
handle_errors( handle_errors(
sess, meta.span, AttrError::MultipleItem(meta.path.to_string()) sess,
meta.span,
AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
); );
return false return false
} }
@ -691,8 +705,10 @@ fn find_deprecation_generic<'a, I>(sess: &ParseSess,
handle_errors( handle_errors(
sess, sess,
meta.span(), meta.span(),
AttrError::UnknownMetaItem(mi.path.to_string(), AttrError::UnknownMetaItem(
&["since", "note"]), pprust::path_to_string(&mi.path),
&["since", "note"],
),
); );
continue 'outer continue 'outer
} }

View file

@ -13,6 +13,7 @@ use crate::mut_visit::*;
use crate::parse::{DirectoryOwnership, PResult, ParseSess}; use crate::parse::{DirectoryOwnership, PResult, ParseSess};
use crate::parse::token; use crate::parse::token;
use crate::parse::parser::Parser; use crate::parse::parser::Parser;
use crate::print::pprust;
use crate::ptr::P; use crate::ptr::P;
use crate::symbol::{sym, Symbol}; use crate::symbol::{sym, Symbol};
use crate::tokenstream::{TokenStream, TokenTree}; use crate::tokenstream::{TokenStream, TokenTree};
@ -388,7 +389,8 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
"`derive` may only be applied to structs, enums and unions"); "`derive` may only be applied to structs, enums and unions");
if let ast::AttrStyle::Inner = attr.style { if let ast::AttrStyle::Inner = attr.style {
let trait_list = derives.iter() let trait_list = derives.iter()
.map(|t| t.to_string()).collect::<Vec<_>>(); .map(|t| pprust::path_to_string(t))
.collect::<Vec<_>>();
let suggestion = format!("#[derive({})]", trait_list.join(", ")); let suggestion = format!("#[derive({})]", trait_list.join(", "));
err.span_suggestion( err.span_suggestion(
span, "try an outer attribute", suggestion, span, "try an outer attribute", suggestion,
@ -587,8 +589,11 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
let result = if let Some(result) = fragment_kind.make_from(tok_result) { let result = if let Some(result) = fragment_kind.make_from(tok_result) {
result result
} else { } else {
let msg = format!("non-{kind} macro in {kind} position: {path}", let msg = format!(
kind = fragment_kind.name(), path = mac.path); "non-{kind} macro in {kind} position: {path}",
kind = fragment_kind.name(),
path = pprust::path_to_string(&mac.path),
);
self.cx.span_err(span, &msg); self.cx.span_err(span, &msg);
self.cx.trace_macros_diag(); self.cx.trace_macros_diag();
fragment_kind.dummy(span) fragment_kind.dummy(span)
@ -878,7 +883,7 @@ impl<'a> Parser<'a> {
err.span_label(span, "caused by the macro expansion here"); err.span_label(span, "caused by the macro expansion here");
let msg = format!( let msg = format!(
"the usage of `{}!` is likely invalid in {} context", "the usage of `{}!` is likely invalid in {} context",
macro_path, pprust::path_to_string(&macro_path),
kind_name, kind_name,
); );
err.note(&msg); err.note(&msg);

View file

@ -174,7 +174,8 @@ fn generic_extension<'cx>(
rhses: &[mbe::TokenTree], rhses: &[mbe::TokenTree],
) -> Box<dyn MacResult + 'cx> { ) -> Box<dyn MacResult + 'cx> {
if cx.trace_macros() { if cx.trace_macros() {
trace_macros_note(cx, sp, format!("expanding `{}! {{ {} }}`", name, arg)); let msg = format!("expanding `{}! {{ {} }}`", name, pprust::tts_to_string(arg.clone()));
trace_macros_note(cx, sp, msg);
} }
// Which arm's failure should we report? (the one furthest along) // Which arm's failure should we report? (the one furthest along)
@ -212,7 +213,8 @@ fn generic_extension<'cx>(
} }
if cx.trace_macros() { if cx.trace_macros() {
trace_macros_note(cx, sp, format!("to `{}`", tts)); let msg = format!("to `{}`", pprust::tts_to_string(tts.clone()));
trace_macros_note(cx, sp, msg);
} }
let directory = Directory { let directory = Directory {

View file

@ -2,6 +2,7 @@ use crate::ast;
use crate::ext::base::ExtCtxt; use crate::ext::base::ExtCtxt;
use crate::parse::{self, token, ParseSess}; use crate::parse::{self, token, ParseSess};
use crate::parse::lexer::comments; use crate::parse::lexer::comments;
use crate::print::pprust;
use crate::tokenstream::{self, DelimSpan, IsJoint::*, TokenStream, TreeAndJoint}; use crate::tokenstream::{self, DelimSpan, IsJoint::*, TokenStream, TreeAndJoint};
use errors::Diagnostic; use errors::Diagnostic;
@ -407,7 +408,7 @@ impl server::TokenStream for Rustc<'_> {
) )
} }
fn to_string(&mut self, stream: &Self::TokenStream) -> String { fn to_string(&mut self, stream: &Self::TokenStream) -> String {
stream.to_string() pprust::tts_to_string(stream.clone())
} }
fn from_token_tree( fn from_token_tree(
&mut self, &mut self,

View file

@ -856,7 +856,7 @@ impl<'a> Parser<'a> {
// This is a best-effort recovery. // This is a best-effort recovery.
path.span, path.span,
"try", "try",
format!("<{}>::{}", ty_str, path), format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
) )
.emit(); .emit();

View file

@ -1177,12 +1177,14 @@ impl<'a> Parser<'a> {
`pub(super)`: visible only in the current module's parent `pub(super)`: visible only in the current module's parent
`pub(in path::to::module)`: visible only on the specified path"##; `pub(in path::to::module)`: visible only on the specified path"##;
let path_str = pprust::path_to_string(&path);
struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg) struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
.help(suggestion) .help(suggestion)
.span_suggestion( .span_suggestion(
path.span, path.span,
&format!("make this visible only to module `{}` with `in`", path), &format!("make this visible only to module `{}` with `in`", path_str),
format!("in {}", path), format!("in {}", path_str),
Applicability::MachineApplicable, Applicability::MachineApplicable,
) )
.emit(); .emit();

View file

@ -552,8 +552,11 @@ impl<'a> Parser<'a> {
// Report non-fatal diagnostics, keep `x as usize` as an expression // Report non-fatal diagnostics, keep `x as usize` as an expression
// in AST and continue parsing. // in AST and continue parsing.
let msg = format!("`<` is interpreted as a start of generic \ let msg = format!(
arguments for `{}`, not a {}", path, op_noun); "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
pprust::path_to_string(&path),
op_noun,
);
let span_after_type = parser_snapshot_after_type.token.span; let span_after_type = parser_snapshot_after_type.token.span;
let expr = mk_expr(self, P(Ty { let expr = mk_expr(self, P(Ty {
span: path.span, span: path.span,

View file

@ -14,7 +14,6 @@
//! ownership of the original. //! ownership of the original.
use crate::parse::token::{self, DelimToken, Token, TokenKind}; use crate::parse::token::{self, DelimToken, Token, TokenKind};
use crate::print::pprust;
use syntax_pos::{BytePos, Span, DUMMY_SP}; use syntax_pos::{BytePos, Span, DUMMY_SP};
#[cfg(target_arch = "x86_64")] #[cfg(target_arch = "x86_64")]
@ -23,7 +22,7 @@ use rustc_data_structures::sync::Lrc;
use rustc_serialize::{Decoder, Decodable, Encoder, Encodable}; use rustc_serialize::{Decoder, Decodable, Encoder, Encodable};
use smallvec::{SmallVec, smallvec}; use smallvec::{SmallVec, smallvec};
use std::{fmt, iter, mem}; use std::{iter, mem};
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
@ -507,12 +506,6 @@ impl Cursor {
} }
} }
impl fmt::Display for TokenStream {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&pprust::tts_to_string(self.clone()))
}
}
impl Encodable for TokenStream { impl Encodable for TokenStream {
fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> { fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
self.trees().collect::<Vec<_>>().encode(encoder) self.trees().collect::<Vec<_>>().encode(encoder)

View file

@ -7,6 +7,7 @@ use syntax::ext::base::ExtCtxt;
use syntax::ext::expand::{AstFragment, ExpansionConfig}; use syntax::ext::expand::{AstFragment, ExpansionConfig};
use syntax::ext::proc_macro::is_proc_macro_attr; use syntax::ext::proc_macro::is_proc_macro_attr;
use syntax::parse::ParseSess; use syntax::parse::ParseSess;
use syntax::print::pprust;
use syntax::ptr::P; use syntax::ptr::P;
use syntax::symbol::{kw, sym}; use syntax::symbol::{kw, sym};
use syntax::visit::{self, Visitor}; use syntax::visit::{self, Visitor};
@ -248,13 +249,20 @@ impl<'a> Visitor<'a> for CollectProcMacros<'a> {
for attr in &item.attrs { for attr in &item.attrs {
if is_proc_macro_attr(&attr) { if is_proc_macro_attr(&attr) {
if let Some(prev_attr) = found_attr { if let Some(prev_attr) = found_attr {
let path_str = pprust::path_to_string(&attr.path);
let msg = if attr.path.segments[0].ident.name == let msg = if attr.path.segments[0].ident.name ==
prev_attr.path.segments[0].ident.name { prev_attr.path.segments[0].ident.name {
format!("only one `#[{}]` attribute is allowed on any given function", format!(
attr.path) "only one `#[{}]` attribute is allowed on any given function",
path_str,
)
} else { } else {
format!("`#[{}]` and `#[{}]` attributes cannot both be applied \ format!(
to the same function", attr.path, prev_attr.path) "`#[{}]` and `#[{}]` attributes cannot both be applied
to the same function",
path_str,
pprust::path_to_string(&prev_attr.path),
)
}; };
self.handler.struct_span_err(attr.span, &msg) self.handler.struct_span_err(attr.span, &msg)
@ -280,8 +288,10 @@ impl<'a> Visitor<'a> for CollectProcMacros<'a> {
}; };
if !is_fn { if !is_fn {
let msg = format!("the `#[{}]` attribute may only be used on bare functions", let msg = format!(
attr.path); "the `#[{}]` attribute may only be used on bare functions",
pprust::path_to_string(&attr.path),
);
self.handler.span_err(attr.span, &msg); self.handler.span_err(attr.span, &msg);
return; return;
@ -292,8 +302,10 @@ impl<'a> Visitor<'a> for CollectProcMacros<'a> {
} }
if !self.is_proc_macro_crate { if !self.is_proc_macro_crate {
let msg = format!("the `#[{}]` attribute is only usable with crates of the \ let msg = format!(
`proc-macro` crate type", attr.path); "the `#[{}]` attribute is only usable with crates of the `proc-macro` crate type",
pprust::path_to_string(&attr.path),
);
self.handler.span_err(attr.span, &msg); self.handler.span_err(attr.span, &msg);
return; return;