From 17e333d31b6237c2e3775b254e3808d1137c6b94 Mon Sep 17 00:00:00 2001 From: Eduard Burtescu Date: Wed, 17 Jun 2015 09:56:27 +0300 Subject: [PATCH] Move AST Repr impls to Debug impls in libsyntax. --- src/librustc/middle/check_const.rs | 3 +- src/librustc/middle/ty.rs | 48 +++++++++++++++- src/librustc/util/ppaux.rs | 54 ++++-------------- src/librustc_typeck/coherence/orphan.rs | 9 ++- src/librustc_typeck/variance.rs | 5 +- src/libsyntax/ast.rs | 76 ++++++++++++++++++++++--- src/libsyntax/codemap.rs | 18 +++++- 7 files changed, 150 insertions(+), 63 deletions(-) diff --git a/src/librustc/middle/check_const.rs b/src/librustc/middle/check_const.rs index 9100f45a5de..8af6946d3c3 100644 --- a/src/librustc/middle/check_const.rs +++ b/src/librustc/middle/check_const.rs @@ -33,7 +33,6 @@ use middle::mem_categorization as mc; use middle::traits; use middle::ty::{self, Ty}; use util::nodemap::NodeMap; -use util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; @@ -300,7 +299,7 @@ impl<'a, 'tcx> CheckCrateVisitor<'a, 'tcx> { impl<'a, 'tcx, 'v> Visitor<'v> for CheckCrateVisitor<'a, 'tcx> { fn visit_item(&mut self, i: &ast::Item) { - debug!("visit_item(item={})", i.repr()); + debug!("visit_item(item={})", self.tcx.map.node_to_string(i.id)); match i.node { ast::ItemStatic(_, ast::MutImmutable, ref expr) => { self.check_static_type(&**expr); diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index e9f1fbeef90..293043af539 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -927,9 +927,14 @@ impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Binder { } pub mod tls { + use ast_map; use middle::ty; use session::Session; + use std::fmt; + use syntax::ast; + use syntax::codemap; + /// Marker type used for the scoped TLS slot. /// The type context cannot be used directly because the scoped TLS /// in libstd doesn't allow types generic over lifetimes. @@ -937,10 +942,49 @@ pub mod tls { scoped_thread_local!(static TLS_TCX: ThreadLocalTyCx); + fn def_id_debug(def_id: ast::DefId, f: &mut fmt::Formatter) -> fmt::Result { + // Unfortunately, there seems to be no way to attempt to print + // a path for a def-id, so I'll just make a best effort for now + // and otherwise fallback to just printing the crate/node pair + with(|tcx| { + if def_id.krate == ast::LOCAL_CRATE { + match tcx.map.find(def_id.node) { + Some(ast_map::NodeItem(..)) | + Some(ast_map::NodeForeignItem(..)) | + Some(ast_map::NodeImplItem(..)) | + Some(ast_map::NodeTraitItem(..)) | + Some(ast_map::NodeVariant(..)) | + Some(ast_map::NodeStructCtor(..)) => { + return write!(f, "{}", ty::item_path_str(tcx, def_id)); + } + _ => {} + } + } + Ok(()) + }) + } + + fn span_debug(span: codemap::Span, f: &mut fmt::Formatter) -> fmt::Result { + with(|tcx| { + write!(f, "{}", tcx.sess.codemap().span_to_string(span)) + }) + } + pub fn enter<'tcx, F: FnOnce(&ty::ctxt<'tcx>) -> R, R>(tcx: ty::ctxt<'tcx>, f: F) -> (Session, R) { - let tls_ptr = &tcx as *const _ as *const ThreadLocalTyCx; - let result = TLS_TCX.set(unsafe { &*tls_ptr }, || f(&tcx)); + let result = ast::DEF_ID_DEBUG.with(|def_id_dbg| { + codemap::SPAN_DEBUG.with(|span_dbg| { + let original_def_id_debug = def_id_dbg.get(); + def_id_dbg.set(def_id_debug); + let original_span_debug = span_dbg.get(); + span_dbg.set(span_debug); + let tls_ptr = &tcx as *const _ as *const ThreadLocalTyCx; + let result = TLS_TCX.set(unsafe { &*tls_ptr }, || f(&tcx)); + def_id_dbg.set(original_def_id_debug); + span_dbg.set(original_span_debug); + result + }) + }); (tcx.sess, result) } diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index 7b82b49dadb..3851eb6573b 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -9,7 +9,6 @@ // except according to those terms. -use ast_map; use middle::def; use middle::region; use middle::subst::{VecPerParamSpace,Subst}; @@ -34,7 +33,6 @@ use std::rc::Rc; use syntax::abi; use syntax::codemap::Span; use syntax::parse::token; -use syntax::print::pprust; use syntax::ptr::P; use syntax::{ast, ast_util}; use syntax::owned_slice::OwnedSlice; @@ -469,51 +467,43 @@ impl<'tcx> Repr for ty::TraitDef<'tcx> { impl Repr for ast::Expr { fn repr(&self) -> String { - format!("expr({}: {})", self.id, pprust::expr_to_string(self)) + format!("{:?}", *self) } } impl Repr for ast::Path { fn repr(&self) -> String { - format!("path({})", pprust::path_to_string(self)) + format!("{:?}", *self) } } impl UserString for ast::Path { fn user_string(&self) -> String { - pprust::path_to_string(self) + format!("{}", *self) } } impl Repr for ast::Ty { fn repr(&self) -> String { - format!("type({})", pprust::ty_to_string(self)) - } -} - -impl Repr for ast::Item { - fn repr(&self) -> String { - format!("item({})", ty::tls::with(|tcx| tcx.map.node_to_string(self.id))) + format!("{:?}", *self) } } impl Repr for ast::Lifetime { fn repr(&self) -> String { - format!("lifetime({}: {})", self.id, pprust::lifetime_to_string(self)) + format!("{:?}", *self) } } impl Repr for ast::Stmt { fn repr(&self) -> String { - format!("stmt({}: {})", - ast_util::stmt_id(self), - pprust::stmt_to_string(self)) + format!("{:?}", *self) } } impl Repr for ast::Pat { fn repr(&self) -> String { - format!("pat({}: {})", self.id, pprust::pat_to_string(self)) + format!("{:?}", *self) } } @@ -646,27 +636,7 @@ impl Repr for region::DestructionScopeData { impl Repr for ast::DefId { fn repr(&self) -> String { - // Unfortunately, there seems to be no way to attempt to print - // a path for a def-id, so I'll just make a best effort for now - // and otherwise fallback to just printing the crate/node pair - ty::tls::with(|tcx| { - if self.krate == ast::LOCAL_CRATE { - match tcx.map.find(self.node) { - Some(ast_map::NodeItem(..)) | - Some(ast_map::NodeForeignItem(..)) | - Some(ast_map::NodeImplItem(..)) | - Some(ast_map::NodeTraitItem(..)) | - Some(ast_map::NodeVariant(..)) | - Some(ast_map::NodeStructCtor(..)) => { - return format!("{:?}:{}", - *self, - ty::item_path_str(tcx, *self)); - } - _ => {} - } - } - format!("{:?}", *self) - }) + format!("{:?}", *self) } } @@ -765,13 +735,13 @@ impl<'tcx> Repr for ty::Method<'tcx> { impl Repr for ast::Name { fn repr(&self) -> String { - token::get_name(*self).to_string() + format!("{:?}", *self) } } impl UserString for ast::Name { fn user_string(&self) -> String { - token::get_name(*self).to_string() + format!("{}", *self) } } @@ -878,7 +848,7 @@ impl UserString for ty::BuiltinBound { impl Repr for Span { fn repr(&self) -> String { - ty::tls::with(|tcx| tcx.sess.codemap().span_to_string(*self).to_string()) + format!("{:?}", *self) } } @@ -1163,7 +1133,7 @@ impl<'tcx> UserString for ty::TyS<'tcx> { impl UserString for ast::Ident { fn user_string(&self) -> String { - token::get_name(self.name).to_string() + format!("{}", *self) } } diff --git a/src/librustc_typeck/coherence/orphan.rs b/src/librustc_typeck/coherence/orphan.rs index 5c99998b953..3068bb9923d 100644 --- a/src/librustc_typeck/coherence/orphan.rs +++ b/src/librustc_typeck/coherence/orphan.rs @@ -66,7 +66,8 @@ impl<'cx, 'tcx> OrphanChecker<'cx, 'tcx> { ast::ItemImpl(_, _, _, None, _, _) => { // For inherent impls, self type must be a nominal type // defined in this crate. - debug!("coherence2::orphan check: inherent impl {}", item.repr()); + debug!("coherence2::orphan check: inherent impl {}", + self.tcx.map.node_to_string(item.id)); let self_ty = ty::lookup_item_type(self.tcx, def_id).ty; match self_ty.sty { ty::TyEnum(def_id, _) | @@ -208,7 +209,8 @@ impl<'cx, 'tcx> OrphanChecker<'cx, 'tcx> { } ast::ItemImpl(_, _, _, Some(_), _, _) => { // "Trait" impl - debug!("coherence2::orphan check: trait impl {}", item.repr()); + debug!("coherence2::orphan check: trait impl {}", + self.tcx.map.node_to_string(item.id)); let trait_ref = ty::impl_trait_ref(self.tcx, def_id).unwrap(); let trait_def_id = trait_ref.def_id; match traits::orphan_check(self.tcx, def_id) { @@ -329,7 +331,8 @@ impl<'cx, 'tcx> OrphanChecker<'cx, 'tcx> { } ast::ItemDefaultImpl(..) => { // "Trait" impl - debug!("coherence2::orphan check: default trait impl {}", item.repr()); + debug!("coherence2::orphan check: default trait impl {}", + self.tcx.map.node_to_string(item.id)); let trait_ref = ty::impl_trait_ref(self.tcx, def_id).unwrap(); if trait_ref.def_id.krate != ast::LOCAL_CRATE { span_err!(self.tcx.sess, item.span, E0318, diff --git a/src/librustc_typeck/variance.rs b/src/librustc_typeck/variance.rs index 3085598e4a3..91ec676c095 100644 --- a/src/librustc_typeck/variance.rs +++ b/src/librustc_typeck/variance.rs @@ -518,7 +518,7 @@ impl<'a, 'tcx> TermsContext<'a, 'tcx> { impl<'a, 'tcx, 'v> Visitor<'v> for TermsContext<'a, 'tcx> { fn visit_item(&mut self, item: &ast::Item) { - debug!("add_inferreds for item {}", item.repr()); + debug!("add_inferreds for item {}", self.tcx.map.node_to_string(item.id)); match item.node { ast::ItemEnum(_, ref generics) | @@ -600,8 +600,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for ConstraintContext<'a, 'tcx> { let did = ast_util::local_def(item.id); let tcx = self.terms_cx.tcx; - debug!("visit_item item={}", - item.repr()); + debug!("visit_item item={}", tcx.map.node_to_string(item.id)); match item.node { ast::ItemEnum(ref enum_definition, _) => { diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 5b03b3bf038..e844b206cc0 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -63,8 +63,10 @@ use owned_slice::OwnedSlice; use parse::token::{InternedString, str_to_ident}; use parse::token; use parse::lexer; +use print::pprust; use ptr::P; +use std::cell::Cell; use std::fmt; use std::rc::Rc; use serialize::{Encodable, Decodable, Encoder, Decoder}; @@ -200,14 +202,19 @@ impl Decodable for Ident { /// Function name (not all functions have names) pub type FnIdent = Option; -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, - Debug, Copy)] +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] pub struct Lifetime { pub id: NodeId, pub span: Span, pub name: Name } +impl fmt::Debug for Lifetime { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self)) + } +} + /// A lifetime definition, eg `'a: 'b+'c+'d` #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct LifetimeDef { @@ -218,7 +225,7 @@ pub struct LifetimeDef { /// A "Path" is essentially Rust's notion of a name; for instance: /// std::cmp::PartialEq . It's represented as a sequence of identifiers, /// along with a bunch of supporting information. -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)] pub struct Path { pub span: Span, /// A `::foo` path, is relative to the crate root rather than current @@ -228,6 +235,18 @@ pub struct Path { pub segments: Vec, } +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)) + } +} + /// A segment of a path: an identifier, an optional lifetime, and a set of /// types. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] @@ -358,12 +377,25 @@ pub type CrateNum = u32; pub type NodeId = u32; #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable, - RustcDecodable, Hash, Debug, Copy)] + RustcDecodable, Hash, Copy)] pub struct DefId { pub krate: CrateNum, pub node: NodeId, } +fn default_def_id_debug(_: DefId, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) } + +thread_local!(pub static DEF_ID_DEBUG: Cell fmt::Result> = + Cell::new(default_def_id_debug)); + +impl fmt::Debug for DefId { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(write!(f, "DefId {{ krate: {}, node: {} }}", + self.krate, self.node)); + DEF_ID_DEBUG.with(|def_id_debug| def_id_debug.get()(*self, f)) + } +} + impl DefId { /// Read the node id, asserting that this def-id is krate-local. pub fn local_id(&self) -> NodeId { @@ -539,13 +571,19 @@ pub struct Block { pub span: Span, } -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)] pub struct Pat { pub id: NodeId, pub node: Pat_, 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)) + } +} + /// A single field in a struct pattern /// /// Patterns like the fields of Foo `{ x, ref y, ref mut z }` @@ -682,7 +720,16 @@ pub enum UnOp { /// A statement pub type Stmt = Spanned; -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +impl fmt::Debug for Stmt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "stmt({}: {})", + ast_util::stmt_id(self), + pprust::stmt_to_string(self)) + } +} + + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)] pub enum Stmt_ { /// Could be an item or a local (let) binding: StmtDecl(P, NodeId), @@ -695,7 +742,6 @@ pub enum Stmt_ { StmtMac(P, MacStmtStyle), } - #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub enum MacStmtStyle { /// The macro statement had a trailing semicolon, e.g. `foo! { ... };` @@ -772,13 +818,19 @@ pub enum UnsafeSource { } /// An expression -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)] pub struct Expr { pub id: NodeId, pub node: Expr_, pub span: Span, } +impl fmt::Debug for Expr { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self)) + } +} + #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub enum Expr_ { /// First expr is the place; second expr is the value. @@ -1357,13 +1409,19 @@ pub struct TypeBinding { // NB PartialEq method appears below. -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)] pub struct Ty { pub id: NodeId, pub node: Ty_, 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)) + } +} + /// Not represented directly in the AST, referred to by name through a ty_path. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] pub enum PrimTy { diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index ea27ed6b360..5ddcfaef9ea 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -19,7 +19,7 @@ pub use self::ExpnFormat::*; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::ops::{Add, Sub}; use std::path::Path; use std::rc::Rc; @@ -115,7 +115,7 @@ impl Sub for CharPos { /// are *absolute* positions from the beginning of the codemap, not positions /// relative to FileMaps. Methods on the CodeMap can be used to relate spans back /// to the original source. -#[derive(Clone, Copy, Debug, Hash)] +#[derive(Clone, Copy, Hash)] pub struct Span { pub lo: BytePos, pub hi: BytePos, @@ -164,6 +164,20 @@ impl Decodable for Span { } } +fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Span {{ lo: {:?}, hi: {:?}, expn_id: {:?} }}", + span.lo, span.hi, span.expn_id) +} + +thread_local!(pub static SPAN_DEBUG: Cell fmt::Result> = + Cell::new(default_span_debug)); + +impl fmt::Debug for Span { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f)) + } +} + pub fn spanned(lo: BytePos, hi: BytePos, t: T) -> Spanned { respan(mk_sp(lo, hi), t) }