From c297a37096ae1562d453624984aa5f924ab490a1 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Sun, 7 Sep 2025 22:44:18 +0200 Subject: [PATCH] tracing-subscriber: Switch to unconditional no_std --- tracing-subscriber/src/filter/directive.rs | 7 +++--- tracing-subscriber/src/filter/env/builder.rs | 7 +++++- .../src/filter/env/directive.rs | 2 ++ tracing-subscriber/src/filter/env/field.rs | 23 +++++++++++-------- tracing-subscriber/src/filter/env/mod.rs | 6 ++++- .../src/filter/layer_filters/mod.rs | 7 +++--- tracing-subscriber/src/filter/targets.rs | 22 ++++++++++-------- tracing-subscriber/src/fmt/fmt_layer.rs | 10 ++++---- tracing-subscriber/src/fmt/format/json.rs | 8 ++++--- tracing-subscriber/src/fmt/format/mod.rs | 15 +++++++++--- tracing-subscriber/src/fmt/mod.rs | 8 +++++-- .../src/fmt/time/chrono_crate.rs | 8 +++---- tracing-subscriber/src/fmt/time/datetime.rs | 6 +++-- tracing-subscriber/src/fmt/writer.rs | 13 +++++++---- tracing-subscriber/src/layer/mod.rs | 3 --- tracing-subscriber/src/layer/tests.rs | 2 ++ tracing-subscriber/src/lib.rs | 5 +++- tracing-subscriber/src/registry/extensions.rs | 6 ++--- tracing-subscriber/src/registry/mod.rs | 5 +++- tracing-subscriber/src/registry/sharded.rs | 5 +++- tracing-subscriber/src/registry/stack.rs | 1 + tracing-subscriber/src/util.rs | 3 +++ 22 files changed, 108 insertions(+), 64 deletions(-) diff --git a/tracing-subscriber/src/filter/directive.rs b/tracing-subscriber/src/filter/directive.rs index 9ee2ce5a..d2faf6ea 100644 --- a/tracing-subscriber/src/filter/directive.rs +++ b/tracing-subscriber/src/filter/directive.rs @@ -1,7 +1,6 @@ use crate::filter::level::{self, LevelFilter}; -#[cfg(not(feature = "smallvec"))] -use alloc::vec; -#[cfg(not(feature = "std"))] +#[cfg(feature = "std")] +use alloc::boxed::Box; use alloc::{string::String, vec::Vec}; use core::{cmp::Ordering, fmt, iter::FromIterator, slice, str::FromStr}; @@ -126,7 +125,7 @@ impl IntoIterator for DirectiveSet { #[cfg(feature = "smallvec")] type IntoIter = smallvec::IntoIter<[T; 8]>; #[cfg(not(feature = "smallvec"))] - type IntoIter = vec::IntoIter; + type IntoIter = alloc::vec::IntoIter; fn into_iter(self) -> Self::IntoIter { self.directives.into_iter() diff --git a/tracing-subscriber/src/filter/env/builder.rs b/tracing-subscriber/src/filter/env/builder.rs index 2c11edff..9cb1e401 100644 --- a/tracing-subscriber/src/filter/env/builder.rs +++ b/tracing-subscriber/src/filter/env/builder.rs @@ -3,7 +3,12 @@ use super::{ EnvFilter, FromEnvError, }; use crate::sync::RwLock; -use std::env; +use alloc::{ + format, + string::{String, ToString}, + vec::Vec, +}; +use std::{env, eprintln}; use thread_local::ThreadLocal; use tracing::level_filters::STATIC_MAX_LEVEL; diff --git a/tracing-subscriber/src/filter/env/directive.rs b/tracing-subscriber/src/filter/env/directive.rs index 7c348fd4..290b85ae 100644 --- a/tracing-subscriber/src/filter/env/directive.rs +++ b/tracing-subscriber/src/filter/env/directive.rs @@ -4,6 +4,7 @@ use crate::filter::{ env::{field, FieldMap}, level::LevelFilter, }; +use alloc::{borrow::ToOwned, string::String, vec::Vec}; use std::{cmp::Ordering, fmt, iter::FromIterator, str::FromStr}; use tracing_core::{span, Level, Metadata}; @@ -481,6 +482,7 @@ impl SpanMatcher { #[cfg(test)] mod test { use super::*; + use alloc::{format, string::ToString, vec}; fn parse_directives(dirs: impl AsRef) -> Vec { dirs.as_ref() diff --git a/tracing-subscriber/src/filter/env/field.rs b/tracing-subscriber/src/filter/env/field.rs index 1a49b958..45348bc4 100644 --- a/tracing-subscriber/src/filter/env/field.rs +++ b/tracing-subscriber/src/filter/env/field.rs @@ -1,14 +1,17 @@ -use matchers::Pattern; -use std::{ +use alloc::{ + borrow::ToOwned, + boxed::Box, + string::{String, ToString}, + sync::Arc, +}; +use core::{ cmp::Ordering, - error::Error, fmt::{self, Write}, str::FromStr, - sync::{ - atomic::{AtomicBool, Ordering::*}, - Arc, - }, + sync::atomic::{AtomicBool, Ordering::*}, }; +use matchers::Pattern; +use std::error::Error; use super::{FieldMap, LevelFilter}; use tracing_core::field::{Field, Visit}; @@ -507,9 +510,7 @@ impl Visit for MatchVisitor<'_> { Some((ValueMatch::NaN, ref matched)) if value.is_nan() => { matched.store(true, Release); } - Some((ValueMatch::F64(ref e), ref matched)) - if (value - *e).abs() < f64::EPSILON => - { + Some((ValueMatch::F64(ref e), ref matched)) if (value - *e).abs() < f64::EPSILON => { matched.store(true, Release); } _ => {} @@ -576,6 +577,8 @@ impl Visit for MatchVisitor<'_> { #[cfg(test)] mod tests { use super::*; + use alloc::format; + #[derive(Debug)] #[allow(dead_code)] struct MyStruct { diff --git a/tracing-subscriber/src/filter/env/mod.rs b/tracing-subscriber/src/filter/env/mod.rs index a9d93793..04abd591 100644 --- a/tracing-subscriber/src/filter/env/mod.rs +++ b/tracing-subscriber/src/filter/env/mod.rs @@ -14,8 +14,10 @@ use crate::{ layer::{Context, Layer}, sync::RwLock, }; +use alloc::{fmt, str::FromStr, vec::Vec}; +use core::cell::RefCell; use directive::ParseError; -use std::{cell::RefCell, collections::HashMap, env, error::Error, fmt, str::FromStr}; +use std::{collections::HashMap, env, error::Error}; use thread_local::ThreadLocal; use tracing_core::{ callsite, @@ -835,6 +837,8 @@ impl Error for FromEnvError { #[cfg(test)] mod tests { use super::*; + use alloc::format; + use std::println; use tracing_core::field::FieldSet; use tracing_core::*; diff --git a/tracing-subscriber/src/filter/layer_filters/mod.rs b/tracing-subscriber/src/filter/layer_filters/mod.rs index 078051c7..238ec932 100644 --- a/tracing-subscriber/src/filter/layer_filters/mod.rs +++ b/tracing-subscriber/src/filter/layer_filters/mod.rs @@ -32,15 +32,14 @@ use crate::{ layer::{self, Context, Layer}, registry, }; -use std::{ +use alloc::{boxed::Box, fmt, sync::Arc}; +use core::{ any::TypeId, cell::{Cell, RefCell}, - fmt, marker::PhantomData, ops::Deref, - sync::Arc, - thread_local, }; +use std::thread_local; use tracing_core::{ span, subscriber::{Interest, Subscriber}, diff --git a/tracing-subscriber/src/filter/targets.rs b/tracing-subscriber/src/filter/targets.rs index 19f2d990..43198645 100644 --- a/tracing-subscriber/src/filter/targets.rs +++ b/tracing-subscriber/src/filter/targets.rs @@ -13,7 +13,6 @@ use crate::{ }, layer, }; -#[cfg(not(feature = "std"))] use alloc::string::String; use core::{ fmt, @@ -596,16 +595,17 @@ impl<'a> Iterator for Iter<'a> { #[cfg(test)] mod tests { use super::*; + use alloc::{string::ToString, vec, vec::Vec}; + #[cfg(feature = "std")] + use std::dbg; - feature! { - #![not(feature = "std")] - use alloc::{vec, vec::Vec, string::ToString}; - - // `dbg!` is only available with `libstd`; just nop it out when testing - // with alloc only. - macro_rules! dbg { - ($x:expr) => { $x } - } + // `dbg!` is only available with `libstd`; just nop it out when testing + // with alloc only. + #[cfg(not(feature = "std"))] + macro_rules! dbg { + ($x:expr) => { + $x + }; } fn expect_parse(s: &str) -> Targets { @@ -775,6 +775,8 @@ mod tests { // `println!` is only available with `libstd`. #[cfg(feature = "std")] fn size_of_filters() { + use std::println; + fn print_sz(s: &str) { let filter = s.parse::().expect("filter should parse"); println!( diff --git a/tracing-subscriber/src/fmt/fmt_layer.rs b/tracing-subscriber/src/fmt/fmt_layer.rs index 9dbc0fe8..d0233810 100644 --- a/tracing-subscriber/src/fmt/fmt_layer.rs +++ b/tracing-subscriber/src/fmt/fmt_layer.rs @@ -4,10 +4,10 @@ use crate::{ layer::{self, Context}, registry::{self, LookupSpan, SpanRef}, }; +use alloc::{fmt, format, string::String}; +use core::{any::TypeId, marker::PhantomData, ops::Deref}; use format::{FmtSpan, TimingDisplay}; -use std::{ - any::TypeId, cell::RefCell, env, fmt, io, marker::PhantomData, ops::Deref, time::Instant, -}; +use std::{cell::RefCell, env, eprintln, io, thread_local, time::Instant}; use tracing_core::{ field, span::{Attributes, Current, Id, Record}, @@ -1257,6 +1257,7 @@ mod test { time, }; use crate::Registry; + use alloc::{string::ToString, vec, vec::Vec}; use format::FmtSpan; use regex::Regex; use tracing::subscriber::with_default; @@ -1631,8 +1632,7 @@ mod test { .with_timer(MockTime) .with_span_events(FmtSpan::ACTIVE); - let (reloadable_layer, reload_handle) = - crate::reload::Layer::new(inner_layer); + let (reloadable_layer, reload_handle) = crate::reload::Layer::new(inner_layer); let reload = reloadable_layer.with_subscriber(Registry::default()); with_default(reload, || { diff --git a/tracing-subscriber/src/fmt/format/json.rs b/tracing-subscriber/src/fmt/format/json.rs index 3ef0fcd6..6266b475 100644 --- a/tracing-subscriber/src/fmt/format/json.rs +++ b/tracing-subscriber/src/fmt/format/json.rs @@ -7,12 +7,14 @@ use crate::{ }, registry::LookupSpan, }; -use serde::ser::{SerializeMap, Serializer as _}; -use serde_json::Serializer; -use std::{ +use alloc::{ collections::BTreeMap, fmt::{self, Write}, + format, + string::String, }; +use serde::ser::{SerializeMap, Serializer as _}; +use serde_json::Serializer; use tracing_core::{ field::{self, Field}, span::Record, diff --git a/tracing-subscriber/src/fmt/format/mod.rs b/tracing-subscriber/src/fmt/format/mod.rs index f72422bf..ea2a2eca 100644 --- a/tracing-subscriber/src/fmt/format/mod.rs +++ b/tracing-subscriber/src/fmt/format/mod.rs @@ -48,7 +48,6 @@ use tracing_log::NormalizeEvent; #[cfg(feature = "ansi")] use nu_ansi_term::{Color, Style}; - mod escape; use escape::Escape; @@ -433,6 +432,8 @@ impl<'writer> Writer<'writer> { /// value implementing [`fmt::Write`] is a [`String`], it will contain /// the formatted output of [`Format::format_event`], which may then be /// used for other purposes. + /// + /// [`String`]: alloc::string::String #[must_use] pub fn new(writer: &'writer mut impl fmt::Write) -> Self { Self { @@ -1269,7 +1270,10 @@ impl field::Visit for DefaultVisitor<'_> { ), ) } else { - self.record_debug(field, &format_args!("{}", Escape(&format_args!("{}", value)))) + self.record_debug( + field, + &format_args!("{}", Escape(&format_args!("{}", value))), + ) } } @@ -1294,7 +1298,7 @@ impl field::Visit for DefaultVisitor<'_> { "message" => { // Escape ANSI characters to prevent malicious patterns (e.g., terminal injection attacks) write!(self.writer, "{:?}", Escape(value)) - }, + } name if name.starts_with("r#") => write!( self.writer, "{}{}{:?}", @@ -1750,6 +1754,11 @@ impl Display for TimingDisplay { #[cfg(test)] pub(super) mod test { use crate::fmt::{test::MockMakeWriter, time::FormatTime}; + use alloc::{ + borrow::ToOwned, + format, + string::{String, ToString}, + }; use tracing::{ self, dispatcher::{set_default, Dispatch}, diff --git a/tracing-subscriber/src/fmt/mod.rs b/tracing-subscriber/src/fmt/mod.rs index 94ebd49c..785b6c43 100644 --- a/tracing-subscriber/src/fmt/mod.rs +++ b/tracing-subscriber/src/fmt/mod.rs @@ -189,7 +189,10 @@ //! https://docs.rs/tracing/latest/tracing/trait.Subscriber.html //! [`tracing`]: https://crates.io/crates/tracing //! [`fmt::format`]: mod@crate::fmt::format -use std::{any::TypeId, error::Error, io}; + +use alloc::boxed::Box; +use core::any::TypeId; +use std::{error::Error, io}; use tracing_core::{span, subscriber::Interest, Event, Metadata}; mod fmt_layer; @@ -1196,7 +1199,7 @@ pub fn try_init() -> Result<(), Box> { #[cfg(not(feature = "env-filter"))] let subscriber = { use crate::{filter::Targets, layer::SubscriberExt}; - use std::{env, str::FromStr}; + use std::{env, eprintln, str::FromStr}; let targets = match env::var("RUST_LOG") { Ok(var) => Targets::from_str(&var) .map_err(|e| { @@ -1255,6 +1258,7 @@ mod test { Subscriber, }, }; + use alloc::{borrow::ToOwned, string::String, vec::Vec}; use std::{ io, sync::{Arc, Mutex, MutexGuard, TryLockError}, diff --git a/tracing-subscriber/src/fmt/time/chrono_crate.rs b/tracing-subscriber/src/fmt/time/chrono_crate.rs index def3b3b6..8b78bd28 100644 --- a/tracing-subscriber/src/fmt/time/chrono_crate.rs +++ b/tracing-subscriber/src/fmt/time/chrono_crate.rs @@ -1,7 +1,7 @@ use crate::fmt::format::Writer; use crate::fmt::time::FormatTime; -use std::sync::Arc; +use alloc::{format, string::String, sync::Arc}; /// Formats [local time]s and [UTC time]s with `FormatTime` implementations /// that use the [`chrono` crate]. @@ -108,8 +108,7 @@ impl FormatTime for ChronoUtc { /// the supported syntax. /// /// [`chrono::format::strftime`]: https://docs.rs/chrono/0.4.9/chrono/format/strftime/index.html -#[derive(Debug, Clone, Eq, PartialEq)] -#[derive(Default)] +#[derive(Debug, Clone, Eq, PartialEq, Default)] enum ChronoFmtType { /// Format according to the RFC 3339 convention. #[default] @@ -118,13 +117,12 @@ enum ChronoFmtType { Custom(String), } - #[cfg(test)] mod tests { use crate::fmt::format::Writer; use crate::fmt::time::FormatTime; - use std::sync::Arc; + use alloc::{borrow::ToOwned, string::String, sync::Arc}; use super::ChronoFmtType; use super::ChronoLocal; diff --git a/tracing-subscriber/src/fmt/time/datetime.rs b/tracing-subscriber/src/fmt/time/datetime.rs index d08ed558..48a6d055 100644 --- a/tracing-subscriber/src/fmt/time/datetime.rs +++ b/tracing-subscriber/src/fmt/time/datetime.rs @@ -192,7 +192,6 @@ // permissive licensing, and of not having licensing issues being an // obstacle to adoption, that text has been removed. - use std::fmt; /// A date/time type which exists primarily to convert `SystemTime` timestamps into an ISO 8601 @@ -333,7 +332,10 @@ impl From for DateTime { #[cfg(test)] mod tests { use i32; - use std::time::{Duration, UNIX_EPOCH}; + use std::{ + format, + time::{Duration, UNIX_EPOCH}, + }; use super::*; diff --git a/tracing-subscriber/src/fmt/writer.rs b/tracing-subscriber/src/fmt/writer.rs index 52a20d69..e7c3e3b4 100644 --- a/tracing-subscriber/src/fmt/writer.rs +++ b/tracing-subscriber/src/fmt/writer.rs @@ -1,10 +1,13 @@ //! Abstractions for creating [`io::Write`] instances. //! //! [`io::Write`]: std::io::Write + +use alloc::{boxed::Box, fmt, string::String, sync::Arc}; use std::{ - fmt, + eprint, io::{self, Write}, - sync::{Arc, Mutex, MutexGuard}, + print, + sync::{Mutex, MutexGuard}, }; use tracing_core::Metadata; @@ -715,9 +718,7 @@ impl TestWriter { /// Returns a new `TestWriter` that writes to `stderr` instead of `stdout`. pub fn with_stderr() -> Self { - Self { - use_stderr: true, - } + Self { use_stderr: true } } } @@ -1224,8 +1225,10 @@ mod test { use crate::fmt::format::Format; use crate::fmt::test::{MockMakeWriter, MockWriter}; use crate::fmt::Subscriber; + use alloc::vec::Vec; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; + use std::{dbg, format, println}; use tracing::{debug, error, info, trace, warn, Level}; use tracing_core::dispatcher::{self, Dispatch}; diff --git a/tracing-subscriber/src/layer/mod.rs b/tracing-subscriber/src/layer/mod.rs index 12fab82c..0bf55efb 100644 --- a/tracing-subscriber/src/layer/mod.rs +++ b/tracing-subscriber/src/layer/mod.rs @@ -1675,7 +1675,6 @@ where feature! { #![any(feature = "std", feature = "alloc")] - #[cfg(not(feature = "std"))] use alloc::vec::Vec; macro_rules! layer_impl_body { @@ -1773,8 +1772,6 @@ feature! { layer_impl_body! {} } - - impl Layer for Vec where L: Layer, diff --git a/tracing-subscriber/src/layer/tests.rs b/tracing-subscriber/src/layer/tests.rs index d7ad6176..02e16bd0 100644 --- a/tracing-subscriber/src/layer/tests.rs +++ b/tracing-subscriber/src/layer/tests.rs @@ -113,6 +113,8 @@ fn downcasts_to_layer() { #[cfg(all(feature = "registry", feature = "std"))] mod registry_tests { + use std::dbg; + use super::*; use crate::registry::LookupSpan; diff --git a/tracing-subscriber/src/lib.rs b/tracing-subscriber/src/lib.rs index a3731448..619fd97b 100644 --- a/tracing-subscriber/src/lib.rs +++ b/tracing-subscriber/src/lib.rs @@ -161,6 +161,8 @@ //! [`time` crate]: https://crates.io/crates/time //! [`liballoc`]: https://doc.rust-lang.org/alloc/index.html //! [`libstd`]: https://doc.rust-lang.org/std/index.html + +#![no_std] #![doc( html_logo_url = "https://raw.githubusercontent.com/tokio-rs/tracing/main/assets/logo-type.png", issue_tracker_base_url = "https://github.com/tokio-rs/tracing/issues/" @@ -201,10 +203,11 @@ // future, reducing diff noise. Allow this even though clippy considers it // "needless". #![allow(clippy::needless_update)] -#![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "alloc")] extern crate alloc; +#[cfg(feature = "std")] +extern crate std; #[macro_use] mod macros; diff --git a/tracing-subscriber/src/registry/extensions.rs b/tracing-subscriber/src/registry/extensions.rs index ff76fb59..afed2f7d 100644 --- a/tracing-subscriber/src/registry/extensions.rs +++ b/tracing-subscriber/src/registry/extensions.rs @@ -1,12 +1,12 @@ // taken from https://github.com/hyperium/http/blob/master/src/extensions.rs. use crate::sync::{RwLockReadGuard, RwLockWriteGuard}; -use std::{ +use alloc::{boxed::Box, fmt}; +use core::{ any::{Any, TypeId}, - collections::HashMap, - fmt, hash::{BuildHasherDefault, Hasher}, }; +use std::collections::HashMap; #[allow(warnings)] type AnyMap = HashMap, BuildHasherDefault>; diff --git a/tracing-subscriber/src/registry/mod.rs b/tracing-subscriber/src/registry/mod.rs index 0fb03ad8..0acc3056 100644 --- a/tracing-subscriber/src/registry/mod.rs +++ b/tracing-subscriber/src/registry/mod.rs @@ -519,7 +519,10 @@ mod tests { prelude::*, registry::LookupSpan, }; - use std::sync::{Arc, Mutex}; + use std::{ + sync::{Arc, Mutex}, + vec::Vec, + }; use tracing::{span, Subscriber}; #[test] diff --git a/tracing-subscriber/src/registry/sharded.rs b/tracing-subscriber/src/registry/sharded.rs index 3004c9c5..64f0cdc5 100644 --- a/tracing-subscriber/src/registry/sharded.rs +++ b/tracing-subscriber/src/registry/sharded.rs @@ -10,10 +10,11 @@ use crate::{ }, sync::RwLock, }; -use std::{ +use core::{ cell::{self, Cell, RefCell}, sync::atomic::{fence, AtomicUsize, Ordering}, }; +use std::thread_local; use tracing_core::{ dispatcher::{self, Dispatch}, span::{self, Current, Id}, @@ -536,7 +537,9 @@ mod tests { use crate::{layer::Context, registry::LookupSpan, Layer}; use std::{ collections::HashMap, + dbg, println, sync::{Arc, Mutex, Weak}, + vec::Vec, }; use tracing::{self, subscriber::with_default}; use tracing_core::{ diff --git a/tracing-subscriber/src/registry/stack.rs b/tracing-subscriber/src/registry/stack.rs index 4a3f7e59..2e682519 100644 --- a/tracing-subscriber/src/registry/stack.rs +++ b/tracing-subscriber/src/registry/stack.rs @@ -1,3 +1,4 @@ +use alloc::vec::Vec; pub(crate) use tracing_core::span::Id; #[derive(Debug)] diff --git a/tracing-subscriber/src/util.rs b/tracing-subscriber/src/util.rs index 1c98aa4d..6a48f255 100644 --- a/tracing-subscriber/src/util.rs +++ b/tracing-subscriber/src/util.rs @@ -1,5 +1,8 @@ //! Extension traits and other utilities to make working with subscribers more //! ergonomic. + +#[cfg(feature = "std")] +use alloc::boxed::Box; use core::fmt; #[cfg(feature = "std")] use std::error::Error;