Fix clippy lints (#477)

This PR fixes all reported clippy lints. In most cases I have made the
suggested changes. In a few cases (e.g., `blacklisted_name` and
`cognitive_complexity`) I've just silenced the warning.

I can make stylistic changes or discard some of the lint fixes if
preferred.
This commit is contained in:
Darin Morrison 2019-12-20 18:03:34 -07:00 committed by Eliza Weisman
parent d63b026f0f
commit 048b85cf3b
31 changed files with 78 additions and 64 deletions

4
clippy.toml Normal file
View File

@ -0,0 +1,4 @@
blacklisted-names = []
cognitive-complexity-threshold = 100
too-many-arguments-threshold = 8
type-complexity-threshold = 375

View File

@ -7,7 +7,7 @@ use tracing_attributes::instrument;
#[inline]
fn suggest_band() -> String {
debug!("Suggesting a band.");
format!("Wild Pink")
String::from("Wild Pink")
}
fn main() {

View File

@ -34,7 +34,7 @@ impl<'a> Visit for Count<'a> {
if value > 0 {
counter.fetch_add(value as usize, Ordering::Release);
} else {
counter.fetch_sub((value * -1) as usize, Ordering::Release);
counter.fetch_sub(-value as usize, Ordering::Release);
}
};
}

View File

@ -11,7 +11,7 @@ pub fn shave(yak: usize) -> Result<(), Box<dyn Error + 'static>> {
);
if yak == 3 {
warn!(target: "yak_events", "could not locate yak!");
Err(ShaveError::new(yak, YakError::new("could not locate yak")))?;
return Err(ShaveError::new(yak, YakError::new("could not locate yak")).into());
} else {
trace!(target: "yak_events", "yak shaved successfully");
}

View File

@ -28,7 +28,7 @@ fn echo(req: Request<Body>) -> Instrumented<BoxFut> {
let (rsp_span, fut): (_, BoxFut) = match (req.method(), req.uri().path()) {
// Serve some instructions at /
(&Method::GET, "/") => {
const BODY: &'static str = "Try POSTing data to /echo";
const BODY: &str = "Try POSTing data to /echo";
*response.body_mut() = Body::from(BODY);
(
span!(Level::INFO, "response", body = %(&BODY)),

View File

@ -91,12 +91,12 @@ struct ColorLevel<'a>(&'a Level);
impl<'a> fmt::Display for ColorLevel<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
&Level::TRACE => Color::Purple.paint("TRACE"),
&Level::DEBUG => Color::Blue.paint("DEBUG"),
&Level::INFO => Color::Green.paint("INFO "),
&Level::WARN => Color::Yellow.paint("WARN "),
&Level::ERROR => Color::Red.paint("ERROR"),
match *self.0 {
Level::TRACE => Color::Purple.paint("TRACE"),
Level::DEBUG => Color::Blue.paint("DEBUG"),
Level::INFO => Color::Green.paint("INFO "),
Level::WARN => Color::Yellow.paint("WARN "),
Level::ERROR => Color::Red.paint("ERROR"),
}
.fmt(f)
}
@ -228,10 +228,7 @@ impl Subscriber for SloggishSubscriber {
let spans = self.spans.lock().unwrap();
let data = spans.get(span_id);
let parent = data.and_then(|span| span.parent.as_ref());
if stack.iter().any(|id| id == span_id) {
// We are already in this span, do nothing.
return;
} else {
if !stack.iter().any(|id| id == span_id) {
let indent = if let Some(idx) = stack
.iter()
.position(|id| parent.map(|p| id == p).unwrap_or(false))
@ -249,7 +246,7 @@ impl Subscriber for SloggishSubscriber {
self.print_kvs(&mut stderr, data.kvs.iter().map(|(k, v)| (k, v)), "")
.unwrap();
}
write!(&mut stderr, "\n").unwrap();
writeln!(&mut stderr).unwrap();
}
}
@ -270,7 +267,7 @@ impl Subscriber for SloggishSubscriber {
comma: false,
};
event.record(&mut visitor);
write!(&mut visitor.stderr, "\n").unwrap();
writeln!(&mut visitor.stderr).unwrap();
}
#[inline]

View File

@ -271,7 +271,7 @@ fn param_names(pat: Pat) -> Box<dyn Iterator<Item = Ident>> {
}
}
fn skips(args: &AttributeArgs) -> Result<HashSet<Ident>, impl ToTokens> {
fn skips(args: &[NestedMeta]) -> Result<HashSet<Ident>, impl ToTokens> {
let mut skips = args.iter().filter_map(|arg| match arg {
NestedMeta::Meta(Meta::List(MetaList {
ref path,
@ -301,7 +301,7 @@ fn skips(args: &AttributeArgs) -> Result<HashSet<Ident>, impl ToTokens> {
.collect())
}
fn level(args: &AttributeArgs) -> impl ToTokens {
fn level(args: &[NestedMeta]) -> impl ToTokens {
let mut levels = args.iter().filter_map(|arg| match arg {
NestedMeta::Meta(Meta::NameValue(MetaNameValue {
ref path, ref lit, ..
@ -355,7 +355,7 @@ fn level(args: &AttributeArgs) -> impl ToTokens {
}
}
fn target(args: &AttributeArgs) -> impl ToTokens {
fn target(args: &[NestedMeta]) -> impl ToTokens {
let mut levels = args.iter().filter_map(|arg| match arg {
NestedMeta::Meta(Meta::NameValue(MetaNameValue {
ref path, ref lit, ..
@ -382,7 +382,7 @@ fn target(args: &AttributeArgs) -> impl ToTokens {
}
}
fn name(args: &AttributeArgs, default_name: String) -> impl ToTokens {
fn name(args: &[NestedMeta], default_name: String) -> impl ToTokens {
let mut names = args.iter().filter_map(|arg| match arg {
NestedMeta::Meta(Meta::NameValue(MetaNameValue {
ref path, ref lit, ..

View File

@ -1,3 +1,5 @@
#[path = "../../tracing/tests/support/mod.rs"]
// path attribute requires referenced module to have same name so allow module inception here
#[allow(clippy::module_inception)]
mod support;
pub use self::support::*;

View File

@ -805,7 +805,7 @@ mod test {
fn exit(&self, _: &span::Id) {}
}
with_default(&Dispatch::new(TestSubscriber), || mk_span())
with_default(&Dispatch::new(TestSubscriber), mk_span)
}
#[test]

View File

@ -68,6 +68,8 @@ impl Id {
Id(NonZeroU64::new(u).expect("span IDs must be > 0"))
}
// Allow `into` by-ref since we don't want to impl Copy for Id
#[allow(clippy::wrong_self_convention)]
/// Returns the span's ID as a `u64`.
pub fn into_u64(&self) -> u64 {
self.0.get()

View File

@ -369,7 +369,7 @@ pub trait Subscriber: 'static {
/// [`drop_span`]: trait.Subscriber.html#method.drop_span
fn try_close(&self, id: span::Id) -> bool {
#[allow(deprecated)]
let _ = self.drop_span(id);
self.drop_span(id);
false
}

View File

@ -216,7 +216,7 @@ struct Fields {
line: field::Field,
}
static FIELD_NAMES: &'static [&'static str] = &[
static FIELD_NAMES: &[&str] = &[
"message",
"log.target",
"log.module_path",

View File

@ -18,6 +18,7 @@ fn factorial(n: u32) -> u32 {
fn main() {
env_logger::Builder::new().parse("trace").init();
#[allow(deprecated)]
let subscriber = tracing_log::TraceLogger::new();
tracing::subscriber::with_default(subscriber, || dbg!(factorial(4)));

View File

@ -13,7 +13,7 @@ struct EnabledSubscriber;
impl tracing::Subscriber for EnabledSubscriber {
fn new_span(&self, span: &span::Attributes<'_>) -> Id {
let _ = span;
Id::from_u64(0xDEADFACE)
Id::from_u64(0xDEAD_FACE)
}
fn event(&self, event: &Event<'_>) {

View File

@ -76,7 +76,7 @@ fn bench_new_span(c: &mut Criterion) {
type Group<'a> = criterion::BenchmarkGroup<'a, criterion::measurement::WallTime>;
fn bench_thrpt(c: &mut Criterion, name: &'static str, mut f: impl FnMut(&mut Group<'_>, &usize)) {
const N_SPANS: &'static [usize] = &[1, 10, 50];
const N_SPANS: &[usize] = &[1, 10, 50];
let mut group = c.benchmark_group(name);
for spans in N_SPANS {

View File

@ -391,7 +391,7 @@ impl<T> DirectiveSet<T> {
self.directives.is_empty()
}
pub(crate) fn iter<'a>(&'a self) -> btree_set::Iter<'a, T> {
pub(crate) fn iter(&self) -> btree_set::Iter<'_, T> {
self.directives.iter()
}
}
@ -417,7 +417,7 @@ impl<T: Match + Ord> DirectiveSet<T> {
pub(crate) fn add(&mut self, directive: T) {
let level = directive.level();
if level > &self.max_level {
if *level > self.max_level {
self.max_level = level.clone();
}
let _ = self.directives.replace(directive);
@ -437,7 +437,7 @@ impl<T: Match + Ord> Extend<T> for DirectiveSet<T> {
let max_level = &mut self.max_level;
let ds = iter.into_iter().inspect(|d| {
let level = d.level();
if level > &*max_level {
if *level > *max_level {
*max_level = level.clone();
}
});
@ -457,7 +457,7 @@ impl Dynamics {
return Some(f);
}
match base_level {
Some(ref b) if &d.level > b => base_level = Some(d.level.clone()),
Some(ref b) if d.level > *b => base_level = Some(d.level.clone()),
None => base_level = Some(d.level.clone()),
_ => {}
}
@ -556,7 +556,7 @@ impl Match for StaticDirective {
if meta.is_event() && !self.field_names.is_empty() {
let fields = meta.fields();
for name in &self.field_names {
if !fields.field(name).is_some() {
if fields.field(name).is_none() {
return false;
}
}

View File

@ -41,7 +41,7 @@ pub(crate) enum ValueMatch {
Bool(bool),
U64(u64),
I64(i64),
Pat(MatchPattern),
Pat(Box<MatchPattern>),
}
#[derive(Debug, Clone)]
@ -130,7 +130,10 @@ impl FromStr for ValueMatch {
.map(ValueMatch::Bool)
.or_else(|_| s.parse::<u64>().map(ValueMatch::U64))
.or_else(|_| s.parse::<i64>().map(ValueMatch::I64))
.or_else(|_| s.parse::<MatchPattern>().map(ValueMatch::Pat))
.or_else(|_| {
s.parse::<MatchPattern>()
.map(|p| ValueMatch::Pat(Box::new(p)))
})
}
}
@ -233,7 +236,7 @@ impl CallsiteMatch {
}
impl SpanMatch {
pub(crate) fn visitor<'a>(&'a self) -> MatchVisitor<'a> {
pub(crate) fn visitor(&self) -> MatchVisitor<'_> {
MatchVisitor { inner: self }
}

View File

@ -406,7 +406,7 @@ mod tests {
#[test]
fn callsite_enabled_no_span_directive() {
let filter = EnvFilter::new("app=debug").with_subscriber(NoSubscriber);
static META: &'static Metadata<'static> = &Metadata::new(
static META: &Metadata<'static> = &Metadata::new(
"mySpan",
"app",
Level::TRACE,
@ -424,7 +424,7 @@ mod tests {
#[test]
fn callsite_off() {
let filter = EnvFilter::new("app=off").with_subscriber(NoSubscriber);
static META: &'static Metadata<'static> = &Metadata::new(
static META: &Metadata<'static> = &Metadata::new(
"mySpan",
"app",
Level::ERROR,
@ -442,7 +442,7 @@ mod tests {
#[test]
fn callsite_enabled_includes_span_directive() {
let filter = EnvFilter::new("app[mySpan]=debug").with_subscriber(NoSubscriber);
static META: &'static Metadata<'static> = &Metadata::new(
static META: &Metadata<'static> = &Metadata::new(
"mySpan",
"app",
Level::TRACE,
@ -461,7 +461,7 @@ mod tests {
fn callsite_enabled_includes_span_directive_field() {
let filter =
EnvFilter::new("app[mySpan{field=\"value\"}]=debug").with_subscriber(NoSubscriber);
static META: &'static Metadata<'static> = &Metadata::new(
static META: &Metadata<'static> = &Metadata::new(
"mySpan",
"app",
Level::TRACE,
@ -480,7 +480,7 @@ mod tests {
fn callsite_enabled_includes_span_directive_multiple_fields() {
let filter = EnvFilter::new("app[mySpan{field=\"value\",field2=2}]=debug")
.with_subscriber(NoSubscriber);
static META: &'static Metadata<'static> = &Metadata::new(
static META: &Metadata<'static> = &Metadata::new(
"mySpan",
"app",
Level::TRACE,

View File

@ -408,7 +408,7 @@ pub struct Layered<L, I, S = I> {
}
/// A layer that does nothing.
#[derive(Clone, Debug)]
#[derive(Clone, Debug, Default)]
pub struct Identity {
_p: (),
}
@ -512,12 +512,16 @@ where
#[cfg(feature = "registry")]
let mut guard = subscriber
.downcast_ref::<Registry>()
.and_then(|registry| Some(registry.start_close(id.clone())));
.map(|registry| registry.start_close(id.clone()));
if self.inner.try_close(id.clone()) {
// If we have a registry's close guard, indicate that the span is
// closing.
#[cfg(feature = "registry")]
guard.as_mut().map(|g| g.is_closing());
{
if let Some(g) = guard.as_mut() {
g.is_closing()
};
}
self.layer.on_close(id, self.ctx());
true
@ -924,6 +928,7 @@ pub(crate) mod tests {
struct NopLayer;
impl<S: Subscriber> Layer<S> for NopLayer {}
#[allow(dead_code)]
struct NopLayer2;
impl<S: Subscriber> Layer<S> for NopLayer2 {}

View File

@ -87,8 +87,8 @@ macro_rules! try_lock {
($lock:expr, else $els:expr) => {
match $lock {
Ok(l) => l,
Err(_) if std::thread::panicking() => $els,
Err(_) => panic!("lock poisoned"),
Err(_err) if std::thread::panicking() => $els,
Err(_err) => panic!("lock poisoned"),
}
};
}

View File

@ -468,8 +468,8 @@ pub(crate) mod tests {
drop(span);
});
assert!(span1_removed2.load(Ordering::Acquire) == true);
assert!(span2_removed2.load(Ordering::Acquire) == true);
assert!(span1_removed2.load(Ordering::Acquire));
assert!(span2_removed2.load(Ordering::Acquire));
// Ensure the registry itself outlives the span.
drop(dispatch);
@ -506,11 +506,11 @@ pub(crate) mod tests {
span2_clone
});
assert!(span1_removed2.load(Ordering::Acquire) == true);
assert!(span2_removed2.load(Ordering::Acquire) == false);
assert!(span1_removed2.load(Ordering::Acquire));
assert!(!span2_removed2.load(Ordering::Acquire));
drop(span2);
assert!(span2_removed2.load(Ordering::Acquire) == true);
assert!(span2_removed2.load(Ordering::Acquire));
// Ensure the registry itself outlives the span.
drop(dispatch);

View File

@ -59,7 +59,7 @@ impl<T> Local<T> {
}
#[cold]
fn new_thread<'a>(&'a self, i: usize, new: impl FnOnce() -> T) {
fn new_thread(&self, i: usize, new: impl FnOnce() -> T) {
let mut lock = try_lock!(self.inner.write());
let this = &mut *lock;
this.resize_with(i + 1, || None);
@ -107,7 +107,7 @@ impl Id {
.unwrap_or_else(|_| Self::poisoned())
}
pub(crate) fn as_usize(&self) -> usize {
pub(crate) fn as_usize(self) -> usize {
self.id
}
@ -132,7 +132,7 @@ impl Id {
}
/// Returns true if the local thread ID was accessed while unwinding.
pub(crate) fn is_poisoned(&self) -> bool {
pub(crate) fn is_poisoned(self) -> bool {
self.id == std::usize::MAX
}
}

View File

@ -3,4 +3,6 @@ pub use self::support::*;
// This has to have the same name as the module in `tracing`.
#[path = "../../tracing/tests/support/mod.rs"]
#[cfg(test)]
// path attribute requires referenced module to have same name so allow module inception here
#[allow(clippy::module_inception)]
mod support;

View File

@ -16,7 +16,7 @@ struct EnabledSubscriber;
impl tracing::Subscriber for EnabledSubscriber {
fn new_span(&self, span: &span::Attributes<'_>) -> Id {
let _ = span;
Id::from_u64(0xDEADFACE)
Id::from_u64(0xDEAD_FACE)
}
fn event(&self, event: &Event<'_>) {
@ -61,7 +61,7 @@ impl tracing::Subscriber for VisitingSubscriber {
fn new_span(&self, span: &span::Attributes<'_>) -> Id {
let mut visitor = Visitor(self.0.lock().unwrap());
span.record(&mut visitor);
Id::from_u64(0xDEADFACE)
Id::from_u64(0xDEAD_FACE)
}
fn record(&self, _span: &Id, values: &span::Record<'_>) {
@ -104,6 +104,7 @@ fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("enter_span", |b| {
tracing::subscriber::with_default(EnabledSubscriber, || {
let span = span!(Level::TRACE, "span");
#[allow(clippy::unit_arg)]
b.iter(|| black_box(span.in_scope(|| {})))
});
});

View File

@ -584,7 +584,7 @@ impl Span {
/// [`Subscriber::enter`]: ../subscriber/trait.Subscriber.html#method.enter
/// [`Subscriber::exit`]: ../subscriber/trait.Subscriber.html#method.exit
/// [`Id`]: ../struct.Id.html
pub fn enter<'a>(&'a self) -> Entered<'a> {
pub fn enter(&self) -> Entered<'_> {
if let Some(ref inner) = self.inner.as_ref() {
inner.subscriber.enter(&inner.id);
}
@ -796,7 +796,7 @@ impl Span {
/// Returns this span's `Metadata`, if it is enabled.
pub fn metadata(&self) -> Option<&'static Metadata<'static>> {
self.meta.clone()
self.meta
}
#[cfg(feature = "log")]

View File

@ -125,7 +125,7 @@ fn one_with_everything() {
field::mock("message")
.with_value(&tracing::field::debug(format_args!(
"{:#x} make me one with{what:.>20}",
4277009102u64,
4_277_009_102u64,
what = "everything"
)))
.and(field::mock("foo").with_value(&666))
@ -143,7 +143,7 @@ fn one_with_everything() {
target: "whatever",
Level::ERROR,
{ foo = 666, bar = false },
"{:#x} make me one with{what:.>20}", 4277009102u64, what = "everything"
"{:#x} make me one with{what:.>20}", 4_277_009_102u64, what = "everything"
);
});

View File

@ -85,7 +85,7 @@ impl MockEvent {
.check(meta, format_args!("event \"{}\"", name));
assert!(meta.is_event(), "expected {}, but got {:?}", self, event);
if let Some(ref mut expected_fields) = self.fields {
let mut checker = expected_fields.checker(format!("{}", name));
let mut checker = expected_fields.checker(name.to_string());
event.record(&mut checker);
checker.finish();
}

View File

@ -108,7 +108,7 @@ impl Expect {
}
}
pub fn checker<'a>(&'a mut self, ctx: String) -> CheckVisitor<'a> {
pub fn checker(&mut self, ctx: String) -> CheckVisitor<'_> {
CheckVisitor { expect: self, ctx }
}

View File

@ -35,7 +35,7 @@ impl Expect {
if let Some(ref expected_target) = self.target {
let target = actual.target();
assert!(
expected_target == &target,
expected_target == target,
"expected {} to have target `{}`, but it had target `{}` instead",
ctx,
expected_target,

View File

@ -34,7 +34,6 @@ impl MockSpan {
name: Some(name.into()),
..self.metadata
},
..self
}
}
@ -44,7 +43,6 @@ impl MockSpan {
level: Some(level),
..self.metadata
},
..self
}
}
@ -57,7 +55,6 @@ impl MockSpan {
target: Some(target.into()),
..self.metadata
},
..self
}
}

View File

@ -260,7 +260,7 @@ where
.span
.metadata
.check(meta, format_args!("span `{}`", name));
let mut checker = expected.fields.checker(format!("{}", name));
let mut checker = expected.fields.checker(name.to_string());
span.record(&mut checker);
checker.finish();
match expected.parent {