diff options
Diffstat (limited to 'third_party/rust/tracing-core')
26 files changed, 5365 insertions, 0 deletions
diff --git a/third_party/rust/tracing-core/.cargo-checksum.json b/third_party/rust/tracing-core/.cargo-checksum.json new file mode 100644 index 0000000000..d86c97be07 --- /dev/null +++ b/third_party/rust/tracing-core/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"c0e17b9a0e4f134b8507ba8f6ac2d4800eb1a4024c42f8888c24525cfbf0c1ae","Cargo.toml":"5d803dae41ee1b5f564ee9321d14bd7f5b25b8b237c9f2e9e9a4a0d6bc24238b","LICENSE":"898b1ae9821e98daf8964c8d6c7f61641f5f5aa78ad500020771c0939ee0dea1","README.md":"cefe3a66d7cdf9d71089d5104a4997a93ed231232f1024799b240bb436721288","src/callsite.rs":"2c0ef84a22d2c93aa6c70220c38f40ac1416de427b0d2d3169541e05eac901bf","src/dispatcher.rs":"386fb35ec3a2ebd37c96b50a52eca8232e8c55756681815963d8050ecbc3a417","src/event.rs":"afac8c061d1c450799fdab8512df6792b64ea11456703a4b3589bc4e696f099e","src/field.rs":"560179f2399d52ed37bda79939ce1b29a60da03baa7068d5613a7ecac5814e50","src/lazy_static/LICENSE":"1e2391052f82d7b0111f512680dcbecf01b06842f5295833e7bd435be2b09a9b","src/lazy_static/core_lazy.rs":"b4c1aaec440177f0de3148fd7b5b60f052890267035966069e9d6a167a72af6a","src/lazy_static/mod.rs":"31abed65708c02b36ec4c72d0788b3fc18c684274ba943dc80fc9f2347f5fb2f","src/lib.rs":"c5ec7961ecb51ad0f30e077edd310d69be09446692c81cf19edf04d03a87e97e","src/metadata.rs":"ef18a9de74a7e8891e33585269d58b2f62613f80d450195cb50c44cde7805d9c","src/parent.rs":"5d5ad733343280a64a1feb6a008e186c39305ec554f14279012b8d7915821471","src/span.rs":"18d9000b35469ea91c56d3e0023e18a982ef625232c617c2827a417793b02c4a","src/spin/LICENSE":"58545fed1565e42d687aecec6897d35c6d37ccb71479a137c0deb2203e125c79","src/spin/mod.rs":"c458ce5e875acb7fbfb279f23254f4924d7c6d6fee419b740800d2e8087d1524","src/spin/mutex.rs":"eaf592b586a5ed73735d6442009b16b0350cb1f71013dafcc95a512c1a49f187","src/spin/once.rs":"c611328c4287adf5c63ae768e2923f34228cad6e019263c98dd33f96a3357edf","src/stdlib.rs":"491c9e37321798c86124c0690f7c5f29054bc444cc51406c36b6fdb106392303","src/subscriber.rs":"66edfcad19821e4d8d92c9ad44b4717c97a89ea5e5172a4c6d6301bdd5a76025","tests/common/mod.rs":"0bbb217baa17df0f96cc1ff57dfa74ccc5a959e7f66b15bb7d25d5f43358a278","tests/dispatch.rs":"c99a9ee042b2a9185d090ffc1a042e1bced0626ce95608c610dd8f7867022f3d","tests/global_dispatch.rs":"cdc05d77e448ee8b50bfb930abafa3f19b4c6f922b7bebc7797fa1dbdaa1d398","tests/macros.rs":"b1603d888b349c8d103794deceec3b1ae4538b8d3eba805f3f561899e8ad0dd2"},"package":"f50de3927f93d202783f4513cda820ab47ef17f624b03c096e86ef00c67e6b5f"}
\ No newline at end of file diff --git a/third_party/rust/tracing-core/CHANGELOG.md b/third_party/rust/tracing-core/CHANGELOG.md new file mode 100644 index 0000000000..4d04e65229 --- /dev/null +++ b/third_party/rust/tracing-core/CHANGELOG.md @@ -0,0 +1,216 @@ +# 0.1.17 (September 28, 2020) + +### Fixed + +- Incorrect inlining of `Event::dispatch` and `Event::child_of`, which could + result in `dispatcher::get_default` being inlined at the callsite ([#994]) + +### Added + +- `Copy` implementations for `Level` and `LevelFilter` ([#992]) + +Thanks to new contributors @jyn514 and @TaKO8Ki for contributing to this +release! + +[#994]: https://github.com/tokio-rs/tracing/pull/994 +[#992]: https://github.com/tokio-rs/tracing/pull/992 + +# 0.1.16 (September 8, 2020) + +### Fixed + +- Added a conversion from `Option<Level>` to `LevelFilter`. This resolves a + previously unreported regression where `Option<Level>` was no longer + a valid LevelFilter. ([#966](https://github.com/tokio-rs/tracing/pull/966)) + +# 0.1.15 (August 22, 2020) + +### Fixed + +- When combining `Interest` from multiple subscribers, if the interests differ, + the current subscriber is now always asked if a callsite should be enabled + (#927) + +## Added + +- Internal API changes to support optimizations in the `tracing` crate (#943) +- **docs**: Multiple fixes and improvements (#913, #941) + +# 0.1.14 (August 10, 2020) + +### Fixed + +- Incorrect calculation of global max level filter which could result in fast + filtering paths not being taken (#908) + +# 0.1.13 (August 4, 2020) + +### Fixed + +- Missing `fmt::Display` impl for `field::DisplayValue` causing a compilation + failure when the "log" feature is enabled (#887) + +Thanks to @d-e-s-o for contributing to this release! + +# 0.1.12 (July 31, 2020) + +### Added + +- `LevelFilter` type and `LevelFilter::current()` for returning the highest level + that any subscriber will enable (#853) +- `Subscriber::max_level_hint` optional trait method, for setting the value + returned by `LevelFilter::current()` (#853) + +### Fixed + +- **docs**: Removed outdated reference to a Tokio API that no longer exists + (#857) + +Thanks to new contributor @dignati for contributing to this release! + +# 0.1.11 (June 8, 2020) + +### Changed + +- Replaced use of `inner_local_macros` with `$crate::` (#729) + +### Added + +- `must_use` warning to guards returned by `dispatcher::set_default` (#686) +- `fmt::Debug` impl to `dyn Value`s (#696) +- Functions to convert between `span::Id` and `NonZeroU64` (#770) +- More obvious warnings in documentation (#769) + +### Fixed + +- Compiler error when `tracing-core/std` feature is enabled but `tracing/std` is + not (#760) +- Clippy warning on vtable address comparison in `callsite::Identifier` (#749) +- Documentation formatting issues (#715, #771) + +Thanks to @bkchr, @majecty, @taiki-e, @nagisa, and @nvzqz for contributing to +this release! + +# 0.1.10 (January 24, 2020) + +### Added + +- `field::Empty` type for declaring empty fields whose values will be recorded + later (#548) +- `field::Value` implementations for `Wrapping` and `NonZero*` numbers (#538) + +### Fixed + +- Broken and unresolvable links in RustDoc (#595) + +Thanks to @oli-cosmian for contributing to this release! + +# 0.1.9 (January 10, 2020) + +### Added + +- API docs now show what feature flags are required to enable each item (#523) + +### Fixed + +- A panic when the current default subscriber subscriber calls + `dispatcher::with_default` as it is being dropped (#522) +- Incorrect documentation for `Subscriber::drop_span` (#524) + +# 0.1.8 (December 20, 2019) + +### Added + +- `Default` impl for `Dispatch` (#411) + +### Fixed + +- Removed duplicate `lazy_static` dependencies (#424) +- Fixed no-std dependencies being enabled even when `std` feature flag is set + (#424) +- Broken link to `Metadata` in `Event` docs (#461) + +# 0.1.7 (October 18, 2019) + +### Added + +- Added `dispatcher::set_default` API which returns a drop guard (#388) + +### Fixed + +- Added missing `Value` impl for `u8` (#392) +- Broken links in docs. + +# 0.1.7 (October 18, 2019) + +### Added + +- Added `dispatcher::set_default` API which returns a drop guard (#388) + +### Fixed + +- Added missing `Value` impl for `u8` (#392) +- Broken links in docs. + +# 0.1.6 (September 12, 2019) + +### Added + +- Internal APIs to support performance optimizations (#326) + +### Fixed + +- Clarified wording in `field::display` documentation (#340) + +# 0.1.6 (August 16, 2019) + +### Added + +- `std::error::Error` as a new primitive `Value` type (#277) +- `Event::new` and `Event::new_child_of` to manually construct `Event`s (#281) + +# 0.1.4 (August 9, 2019) + +### Added + +- Support for `no-std` + `liballoc` (#256) + +### Fixed + +- Broken links in RustDoc (#259) + +# 0.1.3 (August 8, 2019) + +### Added + +- `std::fmt::Display` implementation for `Level` (#194) +- `std::str::FromStr` implementation for `Level` (#195) + +# 0.1.2 (July 10, 2019) + +### Deprecated + +- `Subscriber::drop_span` in favor of new `Subscriber::try_close` (#168) + +### Added + +- `Into<Option<&Id>>`, `Into<Option<Id>>`, and + `Into<Option<&'static Metadata<'static>>>` impls for `span::Current` (#170) +- `Subscriber::try_close` method (#153) +- Improved documentation for `dispatcher` (#171) + +# 0.1.1 (July 6, 2019) + +### Added + +- `Subscriber::current_span` API to return the current span (#148). +- `span::Current` type, representing the `Subscriber`'s view of the current + span (#148). + +### Fixed + +- Typos and broken links in documentation (#123, #124, #128, #154) + +# 0.1.0 (June 27, 2019) + +- Initial release diff --git a/third_party/rust/tracing-core/Cargo.toml b/third_party/rust/tracing-core/Cargo.toml new file mode 100644 index 0000000000..f305004bbf --- /dev/null +++ b/third_party/rust/tracing-core/Cargo.toml @@ -0,0 +1,36 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +edition = "2018" +name = "tracing-core" +version = "0.1.17" +authors = ["Tokio Contributors <team@tokio.rs>"] +description = "Core primitives for application-level tracing.\n" +homepage = "https://tokio.rs" +readme = "README.md" +keywords = ["logging", "tracing", "profiling"] +categories = ["development-tools::debugging", "development-tools::profiling", "asynchronous"] +license = "MIT" +repository = "https://github.com/tokio-rs/tracing" +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "docsrs"] +[dependencies.lazy_static] +version = "1" +optional = true + +[features] +default = ["std"] +std = ["lazy_static"] +[badges.maintenance] +status = "actively-developed" diff --git a/third_party/rust/tracing-core/LICENSE b/third_party/rust/tracing-core/LICENSE new file mode 100644 index 0000000000..cdb28b4b56 --- /dev/null +++ b/third_party/rust/tracing-core/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2019 Tokio Contributors + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/third_party/rust/tracing-core/README.md b/third_party/rust/tracing-core/README.md new file mode 100644 index 0000000000..5b33f8ca81 --- /dev/null +++ b/third_party/rust/tracing-core/README.md @@ -0,0 +1,121 @@ +![Tracing — Structured, application-level diagnostics][splash] + +[splash]: https://raw.githubusercontent.com/tokio-rs/tracing/master/assets/splash.svg + +# tracing-core + +Core primitives for application-level tracing. + +[![Crates.io][crates-badge]][crates-url] +[![Documentation][docs-badge]][docs-url] +[![Documentation (master)][docs-master-badge]][docs-master-url] +[![MIT licensed][mit-badge]][mit-url] +[![Build Status][actions-badge]][actions-url] +[![Discord chat][discord-badge]][discord-url] + +[Documentation][docs-url] | [Chat][discord-url] + +[crates-badge]: https://img.shields.io/crates/v/tracing-core.svg +[crates-url]: https://crates.io/crates/tracing-core/0.1.17 +[docs-badge]: https://docs.rs/tracing-core/badge.svg +[docs-url]: https://docs.rs/tracing-core/0.1.17 +[docs-master-badge]: https://img.shields.io/badge/docs-master-blue +[docs-master-url]: https://tracing-rs.netlify.com/tracing_core +[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg +[mit-url]: LICENSE +[actions-badge]: https://github.com/tokio-rs/tracing/workflows/CI/badge.svg +[actions-url]:https://github.com/tokio-rs/tracing/actions?query=workflow%3ACI +[discord-badge]: https://img.shields.io/discord/500028886025895936?logo=discord&label=discord&logoColor=white +[discord-url]: https://discord.gg/EeF3cQw + +## Overview + +[`tracing`] is a framework for instrumenting Rust programs to collect +structured, event-based diagnostic information. This crate defines the core +primitives of `tracing`. + +The crate provides: + +* [`span::Id`] identifies a span within the execution of a program. + +* [`Event`] represents a single event within a trace. + +* [`Subscriber`], the trait implemented to collect trace data. + +* [`Metadata`] and [`Callsite`] provide information describing spans and + events. + +* [`Field`], [`FieldSet`], [`Value`], and [`ValueSet`] represent the + structured data attached to spans and events. + +* [`Dispatch`] allows spans and events to be dispatched to `Subscriber`s. + +In addition, it defines the global callsite registry and per-thread current +dispatcher which other components of the tracing system rely on. + +*Compiler support: [requires `rustc` 1.40+][msrv]* + +[msrv]: #supported-rust-versions + +## Usage + +Application authors will typically not use this crate directly. Instead, they +will use the [`tracing`] crate, which provides a much more fully-featured +API. However, this crate's API will change very infrequently, so it may be used +when dependencies must be very stable. + +`Subscriber` implementations may depend on `tracing-core` rather than `tracing`, +as the additional APIs provided by `tracing` are primarily useful for +instrumenting libraries and applications, and are generally not necessary for +`Subscriber` implementations. + +### Crate Feature Flags + +The following crate feature flags are available: + +* `std`: Depend on the Rust standard library (enabled by default). + + `no_std` users may disable this feature with `default-features = false`: + + ```toml + [dependencies] + tracing-core = { version = "0.1.17", default-features = false } + ``` + + **Note**:`tracing-core`'s `no_std` support requires `liballoc`. + +[`tracing`]: ../tracing +[`span::Id`]: https://docs.rs/tracing-core/0.1.17/tracing_core/span/struct.Id.html +[`Event`]: https://docs.rs/tracing-core/0.1.17/tracing_core/event/struct.Event.html +[`Subscriber`]: https://docs.rs/tracing-core/0.1.17/tracing_core/subscriber/trait.Subscriber.html +[`Metadata`]: https://docs.rs/tracing-core/0.1.17/tracing_core/metadata/struct.Metadata.html +[`Callsite`]: https://docs.rs/tracing-core/0.1.17/tracing_core/callsite/trait.Callsite.html +[`Field`]: https://docs.rs/tracing-core/0.1.17/tracing_core/field/struct.Field.html +[`FieldSet`]: https://docs.rs/tracing-core/0.1.17/tracing_core/field/struct.FieldSet.html +[`Value`]: https://docs.rs/tracing-core/0.1.17/tracing_core/field/trait.Value.html +[`ValueSet`]: https://docs.rs/tracing-core/0.1.17/tracing_core/field/struct.ValueSet.html +[`Dispatch`]: https://docs.rs/tracing-core/0.1.17/tracing_core/dispatcher/struct.Dispatch.html + +## Supported Rust Versions + +Tracing is built against the latest stable release. The minimum supported +version is 1.40. The current Tracing version is not guaranteed to build on Rust +versions earlier than the minimum supported version. + +Tracing follows the same compiler support policies as the rest of the Tokio +project. The current stable Rust compiler and the three most recent minor +versions before it will always be supported. For example, if the current stable +compiler version is 1.45, the minimum supported version will not be increased +past 1.42, three minor versions prior. Increasing the minimum supported compiler +version is not considered a semver breaking change as long as doing so complies +with this policy. + +## License + +This project is licensed under the [MIT license](LICENSE). + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in Tokio by you, shall be licensed as MIT, without any additional +terms or conditions. diff --git a/third_party/rust/tracing-core/src/callsite.rs b/third_party/rust/tracing-core/src/callsite.rs new file mode 100644 index 0000000000..5e48473e15 --- /dev/null +++ b/third_party/rust/tracing-core/src/callsite.rs @@ -0,0 +1,171 @@ +//! Callsites represent the source locations from which spans or events +//! originate. +use crate::stdlib::{ + fmt, + hash::{Hash, Hasher}, + sync::Mutex, + vec::Vec, +}; +use crate::{ + dispatcher::{self, Dispatch}, + metadata::{LevelFilter, Metadata}, + subscriber::Interest, +}; + +lazy_static! { + static ref REGISTRY: Mutex<Registry> = Mutex::new(Registry { + callsites: Vec::new(), + dispatchers: Vec::new(), + }); +} + +struct Registry { + callsites: Vec<&'static dyn Callsite>, + dispatchers: Vec<dispatcher::Registrar>, +} + +impl Registry { + fn rebuild_callsite_interest(&self, callsite: &'static dyn Callsite) { + let meta = callsite.metadata(); + + // Iterate over the subscribers in the registry, and — if they are + // active — register the callsite with them. + let mut interests = self + .dispatchers + .iter() + .filter_map(|registrar| registrar.try_register(meta)); + + // Use the first subscriber's `Interest` as the base value. + let interest = if let Some(interest) = interests.next() { + // Combine all remaining `Interest`s. + interests.fold(interest, Interest::and) + } else { + // If nobody was interested in this thing, just return `never`. + Interest::never() + }; + + callsite.set_interest(interest) + } + + fn rebuild_interest(&mut self) { + let mut max_level = LevelFilter::OFF; + self.dispatchers.retain(|registrar| { + if let Some(dispatch) = registrar.upgrade() { + // If the subscriber did not provide a max level hint, assume + // that it may enable every level. + let level_hint = dispatch.max_level_hint().unwrap_or(LevelFilter::TRACE); + if level_hint > max_level { + max_level = level_hint; + } + true + } else { + false + } + }); + + self.callsites.iter().for_each(|&callsite| { + self.rebuild_callsite_interest(callsite); + }); + LevelFilter::set_max(max_level); + } +} + +/// Trait implemented by callsites. +/// +/// These functions are only intended to be called by the callsite registry, which +/// correctly handles determining the common interest between all subscribers. +pub trait Callsite: Sync { + /// Sets the [`Interest`] for this callsite. + /// + /// [`Interest`]: ../subscriber/struct.Interest.html + fn set_interest(&self, interest: Interest); + + /// Returns the [metadata] associated with the callsite. + /// + /// [metadata]: ../metadata/struct.Metadata.html + fn metadata(&self) -> &Metadata<'_>; +} + +/// Uniquely identifies a [`Callsite`] +/// +/// Two `Identifier`s are equal if they both refer to the same callsite. +/// +/// [`Callsite`]: ../callsite/trait.Callsite.html +#[derive(Clone)] +pub struct Identifier( + /// **Warning**: The fields on this type are currently `pub` because it must + /// be able to be constructed statically by macros. However, when `const + /// fn`s are available on stable Rust, this will no longer be necessary. + /// Thus, these fields are *not* considered stable public API, and they may + /// change warning. Do not rely on any fields on `Identifier`. When + /// constructing new `Identifier`s, use the `identify_callsite!` macro or + /// the `Callsite::id` function instead. + // TODO: When `Callsite::id` is a const fn, this need no longer be `pub`. + #[doc(hidden)] + pub &'static dyn Callsite, +); + +/// Clear and reregister interest on every [`Callsite`] +/// +/// This function is intended for runtime reconfiguration of filters on traces +/// when the filter recalculation is much less frequent than trace events are. +/// The alternative is to have the [`Subscriber`] that supports runtime +/// reconfiguration of filters always return [`Interest::sometimes()`] so that +/// [`enabled`] is evaluated for every event. +/// +/// This function will also re-compute the global maximum level as determined by +/// the [`max_level_hint`] method. If a [`Subscriber`] +/// implementation changes the value returned by its `max_level_hint` +/// implementation at runtime, then it **must** call this function after that +/// value changes, in order for the change to be reflected. +/// +/// [`max_level_hint`]: ../subscriber/trait.Subscriber.html#method.max_level_hint +/// [`Callsite`]: ../callsite/trait.Callsite.html +/// [`enabled`]: ../subscriber/trait.Subscriber.html#tymethod.enabled +/// [`Interest::sometimes()`]: ../subscriber/struct.Interest.html#method.sometimes +/// [`Subscriber`]: ../subscriber/trait.Subscriber.html +pub fn rebuild_interest_cache() { + let mut registry = REGISTRY.lock().unwrap(); + registry.rebuild_interest(); +} + +/// Register a new `Callsite` with the global registry. +/// +/// This should be called once per callsite after the callsite has been +/// constructed. +pub fn register(callsite: &'static dyn Callsite) { + let mut registry = REGISTRY.lock().unwrap(); + registry.rebuild_callsite_interest(callsite); + registry.callsites.push(callsite); +} + +pub(crate) fn register_dispatch(dispatch: &Dispatch) { + let mut registry = REGISTRY.lock().unwrap(); + registry.dispatchers.push(dispatch.registrar()); + registry.rebuild_interest(); +} + +// ===== impl Identifier ===== + +impl PartialEq for Identifier { + fn eq(&self, other: &Identifier) -> bool { + self.0 as *const _ as *const () == other.0 as *const _ as *const () + } +} + +impl Eq for Identifier {} + +impl fmt::Debug for Identifier { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Identifier({:p})", self.0) + } +} + +impl Hash for Identifier { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + (self.0 as *const dyn Callsite).hash(state) + } +} diff --git a/third_party/rust/tracing-core/src/dispatcher.rs b/third_party/rust/tracing-core/src/dispatcher.rs new file mode 100644 index 0000000000..658463584e --- /dev/null +++ b/third_party/rust/tracing-core/src/dispatcher.rs @@ -0,0 +1,947 @@ +//! Dispatches trace events to [`Subscriber`]s. +//! +//! The _dispatcher_ is the component of the tracing system which is responsible +//! for forwarding trace data from the instrumentation points that generate it +//! to the subscriber that collects it. +//! +//! # Using the Trace Dispatcher +//! +//! Every thread in a program using `tracing` has a _default subscriber_. When +//! events occur, or spans are created, they are dispatched to the thread's +//! current subscriber. +//! +//! ## Setting the Default Subscriber +//! +//! By default, the current subscriber is an empty implementation that does +//! nothing. To use a subscriber implementation, it must be set as the default. +//! There are two methods for doing so: [`with_default`] and +//! [`set_global_default`]. `with_default` sets the default subscriber for the +//! duration of a scope, while `set_global_default` sets a default subscriber +//! for the entire process. +//! +//! To use either of these functions, we must first wrap our subscriber in a +//! [`Dispatch`], a cloneable, type-erased reference to a subscriber. For +//! example: +//! ```rust +//! # pub struct FooSubscriber; +//! # use tracing_core::{ +//! # dispatcher, Event, Metadata, +//! # span::{Attributes, Id, Record} +//! # }; +//! # impl tracing_core::Subscriber for FooSubscriber { +//! # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) } +//! # fn record(&self, _: &Id, _: &Record) {} +//! # fn event(&self, _: &Event) {} +//! # fn record_follows_from(&self, _: &Id, _: &Id) {} +//! # fn enabled(&self, _: &Metadata) -> bool { false } +//! # fn enter(&self, _: &Id) {} +//! # fn exit(&self, _: &Id) {} +//! # } +//! # impl FooSubscriber { fn new() -> Self { FooSubscriber } } +//! use dispatcher::Dispatch; +//! +//! let my_subscriber = FooSubscriber::new(); +//! let my_dispatch = Dispatch::new(my_subscriber); +//! ``` +//! Then, we can use [`with_default`] to set our `Dispatch` as the default for +//! the duration of a block: +//! ```rust +//! # pub struct FooSubscriber; +//! # use tracing_core::{ +//! # dispatcher, Event, Metadata, +//! # span::{Attributes, Id, Record} +//! # }; +//! # impl tracing_core::Subscriber for FooSubscriber { +//! # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) } +//! # fn record(&self, _: &Id, _: &Record) {} +//! # fn event(&self, _: &Event) {} +//! # fn record_follows_from(&self, _: &Id, _: &Id) {} +//! # fn enabled(&self, _: &Metadata) -> bool { false } +//! # fn enter(&self, _: &Id) {} +//! # fn exit(&self, _: &Id) {} +//! # } +//! # impl FooSubscriber { fn new() -> Self { FooSubscriber } } +//! # let my_subscriber = FooSubscriber::new(); +//! # let my_dispatch = dispatcher::Dispatch::new(my_subscriber); +//! // no default subscriber +//! +//! # #[cfg(feature = "std")] +//! dispatcher::with_default(&my_dispatch, || { +//! // my_subscriber is the default +//! }); +//! +//! // no default subscriber again +//! ``` +//! It's important to note that `with_default` will not propagate the current +//! thread's default subscriber to any threads spawned within the `with_default` +//! block. To propagate the default subscriber to new threads, either use +//! `with_default` from the new thread, or use `set_global_default`. +//! +//! As an alternative to `with_default`, we can use [`set_global_default`] to +//! set a `Dispatch` as the default for all threads, for the lifetime of the +//! program. For example: +//! ```rust +//! # pub struct FooSubscriber; +//! # use tracing_core::{ +//! # dispatcher, Event, Metadata, +//! # span::{Attributes, Id, Record} +//! # }; +//! # impl tracing_core::Subscriber for FooSubscriber { +//! # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) } +//! # fn record(&self, _: &Id, _: &Record) {} +//! # fn event(&self, _: &Event) {} +//! # fn record_follows_from(&self, _: &Id, _: &Id) {} +//! # fn enabled(&self, _: &Metadata) -> bool { false } +//! # fn enter(&self, _: &Id) {} +//! # fn exit(&self, _: &Id) {} +//! # } +//! # impl FooSubscriber { fn new() -> Self { FooSubscriber } } +//! # let my_subscriber = FooSubscriber::new(); +//! # let my_dispatch = dispatcher::Dispatch::new(my_subscriber); +//! // no default subscriber +//! +//! dispatcher::set_global_default(my_dispatch) +//! // `set_global_default` will return an error if the global default +//! // subscriber has already been set. +//! .expect("global default was already set!"); +//! +//! // `my_subscriber` is now the default +//! ``` +//! +//! <div class="information"> +//! <div class="tooltip ignore" style="">ⓘ<span class="tooltiptext">Note</span></div> +//! </div> +//! <div class="example-wrap" style="display:inline-block"> +//! <pre class="ignore" style="white-space:normal;font:inherit;"> +//! <strong>Note</strong>:the thread-local scoped dispatcher +//! (<a href="#fn.with_default"><code>with_default</code></a>) requires the +//! Rust standard library. <code>no_std</code> users should use +//! <a href="#fn.set_global_default"><code>set_global_default</code></a> +//! instead. +//! </pre></div> +//! +//! ## Accessing the Default Subscriber +//! +//! A thread's current default subscriber can be accessed using the +//! [`get_default`] function, which executes a closure with a reference to the +//! currently default `Dispatch`. This is used primarily by `tracing` +//! instrumentation. +//! +//! [`Subscriber`]: struct.Subscriber.html +//! [`with_default`]: fn.with_default.html +//! [`set_global_default`]: fn.set_global_default.html +//! [`get_default`]: fn.get_default.html +//! [`Dispatch`]: struct.Dispatch.html +use crate::{ + callsite, span, + subscriber::{self, Subscriber}, + Event, LevelFilter, Metadata, +}; + +use crate::stdlib::{ + any::Any, + fmt, + sync::{ + atomic::{AtomicBool, AtomicUsize, Ordering}, + Arc, Weak, + }, +}; + +#[cfg(feature = "std")] +use crate::stdlib::{ + cell::{Cell, RefCell, RefMut}, + error, +}; + +/// `Dispatch` trace data to a [`Subscriber`]. +/// +/// [`Subscriber`]: trait.Subscriber.html +#[derive(Clone)] +pub struct Dispatch { + subscriber: Arc<dyn Subscriber + Send + Sync>, +} + +#[cfg(feature = "std")] +thread_local! { + static CURRENT_STATE: State = State { + default: RefCell::new(Dispatch::none()), + can_enter: Cell::new(true), + }; +} + +static EXISTS: AtomicBool = AtomicBool::new(false); +static GLOBAL_INIT: AtomicUsize = AtomicUsize::new(UNINITIALIZED); + +const UNINITIALIZED: usize = 0; +const INITIALIZING: usize = 1; +const INITIALIZED: usize = 2; + +static mut GLOBAL_DISPATCH: Option<Dispatch> = None; + +/// The dispatch state of a thread. +#[cfg(feature = "std")] +struct State { + /// This thread's current default dispatcher. + default: RefCell<Dispatch>, + /// Whether or not we can currently begin dispatching a trace event. + /// + /// This is set to `false` when functions such as `enter`, `exit`, `event`, + /// and `new_span` are called on this thread's default dispatcher, to + /// prevent further trace events triggered inside those functions from + /// creating an infinite recursion. When we finish handling a dispatch, this + /// is set back to `true`. + can_enter: Cell<bool>, +} + +/// While this guard is active, additional calls to subscriber functions on +/// the default dispatcher will not be able to access the dispatch context. +/// Dropping the guard will allow the dispatch context to be re-entered. +#[cfg(feature = "std")] +struct Entered<'a>(&'a State); + +/// A guard that resets the current default dispatcher to the prior +/// default dispatcher when dropped. +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +#[derive(Debug)] +pub struct DefaultGuard(Option<Dispatch>); + +/// Sets this dispatch as the default for the duration of a closure. +/// +/// The default dispatcher is used when creating a new [span] or +/// [`Event`]. +/// +/// <div class="information"> +/// <div class="tooltip ignore" style="">ⓘ<span class="tooltiptext">Note</span></div> +/// </div> +/// <div class="example-wrap" style="display:inline-block"> +/// <pre class="ignore" style="white-space:normal;font:inherit;"> +/// <strong>Note</strong>: This function required the Rust standard library. +/// <code>no_std</code> users should use <a href="../fn.set_global_default.html"> +/// <code>set_global_default</code></a> instead. +/// </pre></div> +/// +/// [span]: ../span/index.html +/// [`Subscriber`]: ../subscriber/trait.Subscriber.html +/// [`Event`]: ../event/struct.Event.html +/// [`set_global_default`]: ../fn.set_global_default.html +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +pub fn with_default<T>(dispatcher: &Dispatch, f: impl FnOnce() -> T) -> T { + // When this guard is dropped, the default dispatcher will be reset to the + // prior default. Using this (rather than simply resetting after calling + // `f`) ensures that we always reset to the prior dispatcher even if `f` + // panics. + let _guard = set_default(dispatcher); + f() +} + +/// Sets the dispatch as the default dispatch for the duration of the lifetime +/// of the returned DefaultGuard +/// +/// <div class="information"> +/// <div class="tooltip ignore" style="">ⓘ<span class="tooltiptext">Note</span></div> +/// </div> +/// <div class="example-wrap" style="display:inline-block"> +/// <pre class="ignore" style="white-space:normal;font:inherit;"> +/// <strong>Note</strong>: This function required the Rust standard library. +/// <code>no_std</code> users should use <a href="../fn.set_global_default.html"> +/// <code>set_global_default</code></a> instead. +/// </pre></div> +/// +/// [`set_global_default`]: ../fn.set_global_default.html +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +#[must_use = "Dropping the guard unregisters the dispatcher."] +pub fn set_default(dispatcher: &Dispatch) -> DefaultGuard { + // When this guard is dropped, the default dispatcher will be reset to the + // prior default. Using this ensures that we always reset to the prior + // dispatcher even if the thread calling this function panics. + State::set_default(dispatcher.clone()) +} + +/// Sets this dispatch as the global default for the duration of the entire program. +/// Will be used as a fallback if no thread-local dispatch has been set in a thread +/// (using `with_default`.) +/// +/// Can only be set once; subsequent attempts to set the global default will fail. +/// Returns `Err` if the global default has already been set. +/// +/// +/// <div class="information"> +/// <div class="tooltip compile_fail" style="">⚠ ️<span class="tooltiptext">Warning</span></div> +/// </div><div class="example-wrap" style="display:inline-block"><pre class="compile_fail" style="white-space:normal;font:inherit;"> +/// <strong>Warning</strong>: In general, libraries should <em>not</em> call +/// <code>set_global_default()</code>! Doing so will cause conflicts when +/// executables that depend on the library try to set the default later. +/// </pre></div> +/// +/// [span]: ../span/index.html +/// [`Subscriber`]: ../subscriber/trait.Subscriber.html +/// [`Event`]: ../event/struct.Event.html +pub fn set_global_default(dispatcher: Dispatch) -> Result<(), SetGlobalDefaultError> { + if GLOBAL_INIT.compare_and_swap(UNINITIALIZED, INITIALIZING, Ordering::SeqCst) == UNINITIALIZED + { + unsafe { + GLOBAL_DISPATCH = Some(dispatcher); + } + GLOBAL_INIT.store(INITIALIZED, Ordering::SeqCst); + EXISTS.store(true, Ordering::Release); + Ok(()) + } else { + Err(SetGlobalDefaultError { _no_construct: () }) + } +} + +/// Returns true if a `tracing` dispatcher has ever been set. +/// +/// This may be used to completely elide trace points if tracing is not in use +/// at all or has yet to be initialized. +#[doc(hidden)] +#[inline(always)] +pub fn has_been_set() -> bool { + EXISTS.load(Ordering::Relaxed) +} + +/// Returned if setting the global dispatcher fails. +#[derive(Debug)] +pub struct SetGlobalDefaultError { + _no_construct: (), +} + +impl fmt::Display for SetGlobalDefaultError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.pad("a global default trace dispatcher has already been set") + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl error::Error for SetGlobalDefaultError {} + +/// Executes a closure with a reference to this thread's current [dispatcher]. +/// +/// Note that calls to `get_default` should not be nested; if this function is +/// called while inside of another `get_default`, that closure will be provided +/// with `Dispatch::none` rather than the previously set dispatcher. +/// +/// [dispatcher]: ../dispatcher/struct.Dispatch.html +#[cfg(feature = "std")] +pub fn get_default<T, F>(mut f: F) -> T +where + F: FnMut(&Dispatch) -> T, +{ + CURRENT_STATE + .try_with(|state| { + if let Some(entered) = state.enter() { + return f(&*entered.current()); + } + + f(&Dispatch::none()) + }) + .unwrap_or_else(|_| f(&Dispatch::none())) +} + +/// Executes a closure with a reference to this thread's current [dispatcher]. +/// +/// Note that calls to `get_default` should not be nested; if this function is +/// called while inside of another `get_default`, that closure will be provided +/// with `Dispatch::none` rather than the previously set dispatcher. +/// +/// [dispatcher]: ../dispatcher/struct.Dispatch.html +#[cfg(feature = "std")] +#[doc(hidden)] +#[inline(never)] +pub fn get_current<T>(f: impl FnOnce(&Dispatch) -> T) -> Option<T> { + CURRENT_STATE + .try_with(|state| { + let entered = state.enter()?; + Some(f(&*entered.current())) + }) + .ok()? +} + +/// Executes a closure with a reference to the current [dispatcher]. +/// +/// [dispatcher]: ../dispatcher/struct.Dispatch.html +#[cfg(not(feature = "std"))] +#[doc(hidden)] +pub fn get_current<T>(f: impl FnOnce(&Dispatch) -> T) -> Option<T> { + let dispatch = get_global()?; + Some(f(&dispatch)) +} + +/// Executes a closure with a reference to the current [dispatcher]. +/// +/// [dispatcher]: ../dispatcher/struct.Dispatch.html +#[cfg(not(feature = "std"))] +pub fn get_default<T, F>(mut f: F) -> T +where + F: FnMut(&Dispatch) -> T, +{ + if let Some(d) = get_global() { + f(d) + } else { + f(&Dispatch::none()) + } +} + +fn get_global() -> Option<&'static Dispatch> { + if GLOBAL_INIT.load(Ordering::SeqCst) != INITIALIZED { + return None; + } + unsafe { + // This is safe given the invariant that setting the global dispatcher + // also sets `GLOBAL_INIT` to `INITIALIZED`. + Some(GLOBAL_DISPATCH.as_ref().expect( + "invariant violated: GLOBAL_DISPATCH must be initialized before GLOBAL_INIT is set", + )) + } +} + +pub(crate) struct Registrar(Weak<dyn Subscriber + Send + Sync>); + +impl Dispatch { + /// Returns a new `Dispatch` that discards events and spans. + #[inline] + pub fn none() -> Self { + Dispatch { + subscriber: Arc::new(NoSubscriber), + } + } + + /// Returns a `Dispatch` that forwards to the given [`Subscriber`]. + /// + /// [`Subscriber`]: ../subscriber/trait.Subscriber.html + pub fn new<S>(subscriber: S) -> Self + where + S: Subscriber + Send + Sync + 'static, + { + let me = Dispatch { + subscriber: Arc::new(subscriber), + }; + callsite::register_dispatch(&me); + me + } + + pub(crate) fn registrar(&self) -> Registrar { + Registrar(Arc::downgrade(&self.subscriber)) + } + + /// Registers a new callsite with this subscriber, returning whether or not + /// the subscriber is interested in being notified about the callsite. + /// + /// This calls the [`register_callsite`] function on the [`Subscriber`] + /// that this `Dispatch` forwards to. + /// + /// [`Subscriber`]: ../subscriber/trait.Subscriber.html + /// [`register_callsite`]: ../subscriber/trait.Subscriber.html#method.register_callsite + #[inline] + pub fn register_callsite(&self, metadata: &'static Metadata<'static>) -> subscriber::Interest { + self.subscriber.register_callsite(metadata) + } + + /// Returns the highest [verbosity level][level] that this [`Subscriber`] will + /// enable, or `None`, if the subscriber does not implement level-based + /// filtering or chooses not to implement this method. + /// + /// This calls the [`max_level_hint`] function on the [`Subscriber`] + /// that this `Dispatch` forwards to. + /// + /// [level]: ../struct.Level.html + /// [`Subscriber`]: ../subscriber/trait.Subscriber.html + /// [`register_callsite`]: ../subscriber/trait.Subscriber.html#method.max_level_hint + // TODO(eliza): consider making this a public API? + #[inline] + pub(crate) fn max_level_hint(&self) -> Option<LevelFilter> { + self.subscriber.max_level_hint() + } + + /// Record the construction of a new span, returning a new [ID] for the + /// span being constructed. + /// + /// This calls the [`new_span`] function on the [`Subscriber`] that this + /// `Dispatch` forwards to. + /// + /// [ID]: ../span/struct.Id.html + /// [`Subscriber`]: ../subscriber/trait.Subscriber.html + /// [`new_span`]: ../subscriber/trait.Subscriber.html#method.new_span + #[inline] + pub fn new_span(&self, span: &span::Attributes<'_>) -> span::Id { + self.subscriber.new_span(span) + } + + /// Record a set of values on a span. + /// + /// This calls the [`record`] function on the [`Subscriber`] that this + /// `Dispatch` forwards to. + /// + /// [`Subscriber`]: ../subscriber/trait.Subscriber.html + /// [`record`]: ../subscriber/trait.Subscriber.html#method.record + #[inline] + pub fn record(&self, span: &span::Id, values: &span::Record<'_>) { + self.subscriber.record(span, values) + } + + /// Adds an indication that `span` follows from the span with the id + /// `follows`. + /// + /// This calls the [`record_follows_from`] function on the [`Subscriber`] + /// that this `Dispatch` forwards to. + /// + /// [`Subscriber`]: ../subscriber/trait.Subscriber.html + /// [`record_follows_from`]: ../subscriber/trait.Subscriber.html#method.record_follows_from + #[inline] + pub fn record_follows_from(&self, span: &span::Id, follows: &span::Id) { + self.subscriber.record_follows_from(span, follows) + } + + /// Returns true if a span with the specified [metadata] would be + /// recorded. + /// + /// This calls the [`enabled`] function on the [`Subscriber`] that this + /// `Dispatch` forwards to. + /// + /// [metadata]: ../metadata/struct.Metadata.html + /// [`Subscriber`]: ../subscriber/trait.Subscriber.html + /// [`enabled`]: ../subscriber/trait.Subscriber.html#method.enabled + #[inline] + pub fn enabled(&self, metadata: &Metadata<'_>) -> bool { + self.subscriber.enabled(metadata) + } + + /// Records that an [`Event`] has occurred. + /// + /// This calls the [`event`] function on the [`Subscriber`] that this + /// `Dispatch` forwards to. + /// + /// [`Event`]: ../event/struct.Event.html + /// [`Subscriber`]: ../subscriber/trait.Subscriber.html + /// [`event`]: ../subscriber/trait.Subscriber.html#method.event + #[inline] + pub fn event(&self, event: &Event<'_>) { + self.subscriber.event(event) + } + + /// Records that a span has been can_enter. + /// + /// This calls the [`enter`] function on the [`Subscriber`] that this + /// `Dispatch` forwards to. + /// + /// [`Subscriber`]: ../subscriber/trait.Subscriber.html + /// [`enter`]: ../subscriber/trait.Subscriber.html#method.enter + #[inline] + pub fn enter(&self, span: &span::Id) { + self.subscriber.enter(span); + } + + /// Records that a span has been exited. + /// + /// This calls the [`exit`] function on the [`Subscriber`] that this + /// `Dispatch` forwards to. + /// + /// [`Subscriber`]: ../subscriber/trait.Subscriber.html + /// [`exit`]: ../subscriber/trait.Subscriber.html#method.exit + #[inline] + pub fn exit(&self, span: &span::Id) { + self.subscriber.exit(span); + } + + /// Notifies the subscriber that a [span ID] has been cloned. + /// + /// This function must only be called with span IDs that were returned by + /// this `Dispatch`'s [`new_span`] function. The `tracing` crate upholds + /// this guarantee and any other libraries implementing instrumentation APIs + /// must as well. + /// + /// This calls the [`clone_span`] function on the `Subscriber` that this + /// `Dispatch` forwards to. + /// + /// [span ID]: ../span/struct.Id.html + /// [`Subscriber`]: ../subscriber/trait.Subscriber.html + /// [`clone_span`]: ../subscriber/trait.Subscriber.html#method.clone_span + /// [`new_span`]: ../subscriber/trait.Subscriber.html#method.new_span + #[inline] + pub fn clone_span(&self, id: &span::Id) -> span::Id { + self.subscriber.clone_span(&id) + } + + /// Notifies the subscriber that a [span ID] has been dropped. + /// + /// This function must only be called with span IDs that were returned by + /// this `Dispatch`'s [`new_span`] function. The `tracing` crate upholds + /// this guarantee and any other libraries implementing instrumentation APIs + /// must as well. + /// + /// This calls the [`drop_span`] function on the [`Subscriber`] that this + /// `Dispatch` forwards to. + /// + /// <div class="information"> + /// <div class="tooltip compile_fail" style="">⚠ ️<span class="tooltiptext">Warning</span></div> + /// </div> + /// <div class="example-wrap" style="display:inline-block"><pre class="compile_fail" style="white-space:normal;font:inherit;"> + /// <strong>Deprecated</strong>: The <a href="#method.try_close"><code>try_close</code></a> + /// method is functionally identical, but returns <code>true</code> if the span is now closed. + /// It should be used instead of this method. + /// </pre></div> + /// + /// [span ID]: ../span/struct.Id.html + /// [`Subscriber`]: ../subscriber/trait.Subscriber.html + /// [`drop_span`]: ../subscriber/trait.Subscriber.html#method.drop_span + /// [`new_span`]: ../subscriber/trait.Subscriber.html#method.new_span + /// [`try_close`]: #method.try_close + #[inline] + #[deprecated(since = "0.1.2", note = "use `Dispatch::try_close` instead")] + pub fn drop_span(&self, id: span::Id) { + #[allow(deprecated)] + self.subscriber.drop_span(id); + } + + /// Notifies the subscriber that a [span ID] has been dropped, and returns + /// `true` if there are now 0 IDs referring to that span. + /// + /// This function must only be called with span IDs that were returned by + /// this `Dispatch`'s [`new_span`] function. The `tracing` crate upholds + /// this guarantee and any other libraries implementing instrumentation APIs + /// must as well. + /// + /// This calls the [`try_close`] function on the [`Subscriber`] that this + /// `Dispatch` forwards to. + /// + /// [span ID]: ../span/struct.Id.html + /// [`Subscriber`]: ../subscriber/trait.Subscriber.html + /// [`try_close`]: ../subscriber/trait.Subscriber.html#method.try_close + /// [`new_span`]: ../subscriber/trait.Subscriber.html#method.new_span + #[inline] + pub fn try_close(&self, id: span::Id) -> bool { + self.subscriber.try_close(id) + } + + /// Returns a type representing this subscriber's view of the current span. + /// + /// This calls the [`current`] function on the `Subscriber` that this + /// `Dispatch` forwards to. + /// + /// [`current`]: ../subscriber/trait.Subscriber.html#method.current + #[inline] + pub fn current_span(&self) -> span::Current { + self.subscriber.current_span() + } + + /// Returns `true` if this `Dispatch` forwards to a `Subscriber` of type + /// `T`. + #[inline] + pub fn is<T: Any>(&self) -> bool { + Subscriber::is::<T>(&*self.subscriber) + } + + /// Returns some reference to the `Subscriber` this `Dispatch` forwards to + /// if it is of type `T`, or `None` if it isn't. + #[inline] + pub fn downcast_ref<T: Any>(&self) -> Option<&T> { + Subscriber::downcast_ref(&*self.subscriber) + } +} + +impl Default for Dispatch { + /// Returns the current default dispatcher + fn default() -> Self { + get_default(|default| default.clone()) + } +} + +impl fmt::Debug for Dispatch { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.pad("Dispatch(...)") + } +} + +impl<S> From<S> for Dispatch +where + S: Subscriber + Send + Sync + 'static, +{ + #[inline] + fn from(subscriber: S) -> Self { + Dispatch::new(subscriber) + } +} + +struct NoSubscriber; +impl Subscriber for NoSubscriber { + #[inline] + fn register_callsite(&self, _: &'static Metadata<'static>) -> subscriber::Interest { + subscriber::Interest::never() + } + + fn new_span(&self, _: &span::Attributes<'_>) -> span::Id { + span::Id::from_u64(0xDEAD) + } + + fn event(&self, _event: &Event<'_>) {} + + fn record(&self, _span: &span::Id, _values: &span::Record<'_>) {} + + fn record_follows_from(&self, _span: &span::Id, _follows: &span::Id) {} + + #[inline] + fn enabled(&self, _metadata: &Metadata<'_>) -> bool { + false + } + + fn enter(&self, _span: &span::Id) {} + fn exit(&self, _span: &span::Id) {} +} + +impl Registrar { + pub(crate) fn try_register( + &self, + metadata: &'static Metadata<'static>, + ) -> Option<subscriber::Interest> { + self.0.upgrade().map(|s| s.register_callsite(metadata)) + } + + pub(crate) fn upgrade(&self) -> Option<Dispatch> { + self.0.upgrade().map(|subscriber| Dispatch { subscriber }) + } +} + +// ===== impl State ===== + +#[cfg(feature = "std")] +impl State { + /// Replaces the current default dispatcher on this thread with the provided + /// dispatcher.Any + /// + /// Dropping the returned `ResetGuard` will reset the default dispatcher to + /// the previous value. + #[inline] + fn set_default(new_dispatch: Dispatch) -> DefaultGuard { + let prior = CURRENT_STATE + .try_with(|state| { + state.can_enter.set(true); + state.default.replace(new_dispatch) + }) + .ok(); + EXISTS.store(true, Ordering::Release); + DefaultGuard(prior) + } + + #[inline] + fn enter(&self) -> Option<Entered<'_>> { + if self.can_enter.replace(false) { + Some(Entered(&self)) + } else { + None + } + } +} + +// ===== impl Entered ===== + +#[cfg(feature = "std")] +impl<'a> Entered<'a> { + #[inline] + fn current(&self) -> RefMut<'a, Dispatch> { + let mut default = self.0.default.borrow_mut(); + + if default.is::<NoSubscriber>() { + if let Some(global) = get_global() { + // don't redo this call on the next check + *default = global.clone(); + } + } + + default + } +} + +#[cfg(feature = "std")] +impl<'a> Drop for Entered<'a> { + #[inline] + fn drop(&mut self) { + self.0.can_enter.set(true); + } +} + +// ===== impl DefaultGuard ===== + +#[cfg(feature = "std")] +impl Drop for DefaultGuard { + #[inline] + fn drop(&mut self) { + if let Some(dispatch) = self.0.take() { + // Replace the dispatcher and then drop the old one outside + // of the thread-local context. Dropping the dispatch may + // lead to the drop of a subscriber which, in the process, + // could then also attempt to access the same thread local + // state -- causing a clash. + let prev = CURRENT_STATE.try_with(|state| state.default.replace(dispatch)); + drop(prev) + } + } +} + +#[cfg(test)] +mod test { + use super::*; + #[cfg(feature = "std")] + use crate::stdlib::sync::atomic::{AtomicUsize, Ordering}; + use crate::{ + callsite::Callsite, + metadata::{Kind, Level, Metadata}, + subscriber::Interest, + }; + + #[test] + fn dispatch_is() { + let dispatcher = Dispatch::new(NoSubscriber); + assert!(dispatcher.is::<NoSubscriber>()); + } + + #[test] + fn dispatch_downcasts() { + let dispatcher = Dispatch::new(NoSubscriber); + assert!(dispatcher.downcast_ref::<NoSubscriber>().is_some()); + } + + struct TestCallsite; + static TEST_CALLSITE: TestCallsite = TestCallsite; + static TEST_META: Metadata<'static> = metadata! { + name: "test", + target: module_path!(), + level: Level::DEBUG, + fields: &[], + callsite: &TEST_CALLSITE, + kind: Kind::EVENT + }; + + impl Callsite for TestCallsite { + fn set_interest(&self, _: Interest) {} + fn metadata(&self) -> &Metadata<'_> { + &TEST_META + } + } + + #[test] + #[cfg(feature = "std")] + fn events_dont_infinite_loop() { + // This test ensures that an event triggered within a subscriber + // won't cause an infinite loop of events. + struct TestSubscriber; + impl Subscriber for TestSubscriber { + fn enabled(&self, _: &Metadata<'_>) -> bool { + true + } + + fn new_span(&self, _: &span::Attributes<'_>) -> span::Id { + span::Id::from_u64(0xAAAA) + } + + fn record(&self, _: &span::Id, _: &span::Record<'_>) {} + + fn record_follows_from(&self, _: &span::Id, _: &span::Id) {} + + fn event(&self, _: &Event<'_>) { + static EVENTS: AtomicUsize = AtomicUsize::new(0); + assert_eq!( + EVENTS.fetch_add(1, Ordering::Relaxed), + 0, + "event method called twice!" + ); + Event::dispatch(&TEST_META, &TEST_META.fields().value_set(&[])) + } + + fn enter(&self, _: &span::Id) {} + + fn exit(&self, _: &span::Id) {} + } + + with_default(&Dispatch::new(TestSubscriber), || { + Event::dispatch(&TEST_META, &TEST_META.fields().value_set(&[])) + }) + } + + #[test] + #[cfg(feature = "std")] + fn spans_dont_infinite_loop() { + // This test ensures that a span created within a subscriber + // won't cause an infinite loop of new spans. + + fn mk_span() { + get_default(|current| { + current.new_span(&span::Attributes::new( + &TEST_META, + &TEST_META.fields().value_set(&[]), + )) + }); + } + + struct TestSubscriber; + impl Subscriber for TestSubscriber { + fn enabled(&self, _: &Metadata<'_>) -> bool { + true + } + + fn new_span(&self, _: &span::Attributes<'_>) -> span::Id { + static NEW_SPANS: AtomicUsize = AtomicUsize::new(0); + assert_eq!( + NEW_SPANS.fetch_add(1, Ordering::Relaxed), + 0, + "new_span method called twice!" + ); + mk_span(); + span::Id::from_u64(0xAAAA) + } + + fn record(&self, _: &span::Id, _: &span::Record<'_>) {} + + fn record_follows_from(&self, _: &span::Id, _: &span::Id) {} + + fn event(&self, _: &Event<'_>) {} + + fn enter(&self, _: &span::Id) {} + + fn exit(&self, _: &span::Id) {} + } + + with_default(&Dispatch::new(TestSubscriber), mk_span) + } + + #[test] + fn default_no_subscriber() { + let default_dispatcher = Dispatch::default(); + assert!(default_dispatcher.is::<NoSubscriber>()); + } + + #[cfg(feature = "std")] + #[test] + fn default_dispatch() { + struct TestSubscriber; + impl Subscriber for TestSubscriber { + fn enabled(&self, _: &Metadata<'_>) -> bool { + true + } + + fn new_span(&self, _: &span::Attributes<'_>) -> span::Id { + span::Id::from_u64(0xAAAA) + } + + fn record(&self, _: &span::Id, _: &span::Record<'_>) {} + + fn record_follows_from(&self, _: &span::Id, _: &span::Id) {} + + fn event(&self, _: &Event<'_>) {} + + fn enter(&self, _: &span::Id) {} + + fn exit(&self, _: &span::Id) {} + } + let guard = set_default(&Dispatch::new(TestSubscriber)); + let default_dispatcher = Dispatch::default(); + assert!(default_dispatcher.is::<TestSubscriber>()); + + drop(guard); + let default_dispatcher = Dispatch::default(); + assert!(default_dispatcher.is::<NoSubscriber>()); + } +} diff --git a/third_party/rust/tracing-core/src/event.rs b/third_party/rust/tracing-core/src/event.rs new file mode 100644 index 0000000000..2c886ced47 --- /dev/null +++ b/third_party/rust/tracing-core/src/event.rs @@ -0,0 +1,134 @@ +//! Events represent single points in time during the execution of a program. +use crate::parent::Parent; +use crate::span::Id; +use crate::{field, Metadata}; + +/// `Event`s represent single points in time where something occurred during the +/// execution of a program. +/// +/// An `Event` can be compared to a log record in unstructured logging, but with +/// two key differences: +/// - `Event`s exist _within the context of a [span]_. Unlike log lines, they +/// may be located within the trace tree, allowing visibility into the +/// _temporal_ context in which the event occurred, as well as the source +/// code location. +/// - Like spans, `Event`s have structured key-value data known as _[fields]_, +/// which may include textual message. In general, a majority of the data +/// associated with an event should be in the event's fields rather than in +/// the textual message, as the fields are more structured. +/// +/// [span]: ../span +/// [fields]: ../field +#[derive(Debug)] +pub struct Event<'a> { + fields: &'a field::ValueSet<'a>, + metadata: &'static Metadata<'static>, + parent: Parent, +} + +impl<'a> Event<'a> { + /// Constructs a new `Event` with the specified metadata and set of values, + /// and observes it with the current subscriber. + pub fn dispatch(metadata: &'static Metadata<'static>, fields: &'a field::ValueSet<'_>) { + let event = Event::new(metadata, fields); + crate::dispatcher::get_default(|current| { + current.event(&event); + }); + } + + /// Returns a new `Event` in the current span, with the specified metadata + /// and set of values. + #[inline] + pub fn new(metadata: &'static Metadata<'static>, fields: &'a field::ValueSet<'a>) -> Self { + Event { + metadata, + fields, + parent: Parent::Current, + } + } + + /// Returns a new `Event` as a child of the specified span, with the + /// provided metadata and set of values. + #[inline] + pub fn new_child_of( + parent: impl Into<Option<Id>>, + metadata: &'static Metadata<'static>, + fields: &'a field::ValueSet<'a>, + ) -> Self { + let parent = match parent.into() { + Some(p) => Parent::Explicit(p), + None => Parent::Root, + }; + Event { + metadata, + fields, + parent, + } + } + + /// Constructs a new `Event` with the specified metadata and set of values, + /// and observes it with the current subscriber and an explicit parent. + pub fn child_of( + parent: impl Into<Option<Id>>, + metadata: &'static Metadata<'static>, + fields: &'a field::ValueSet<'_>, + ) { + let event = Self::new_child_of(parent, metadata, fields); + crate::dispatcher::get_default(|current| { + current.event(&event); + }); + } + + /// Visits all the fields on this `Event` with the specified [visitor]. + /// + /// [visitor]: ../field/trait.Visit.html + #[inline] + pub fn record(&self, visitor: &mut dyn field::Visit) { + self.fields.record(visitor); + } + + /// Returns an iterator over the set of values on this `Event`. + pub fn fields(&self) -> field::Iter { + self.fields.field_set().iter() + } + + /// Returns [metadata] describing this `Event`. + /// + /// [metadata]: ../struct.Metadata.html + pub fn metadata(&self) -> &'static Metadata<'static> { + self.metadata + } + + /// Returns true if the new event should be a root. + pub fn is_root(&self) -> bool { + match self.parent { + Parent::Root => true, + _ => false, + } + } + + /// Returns true if the new event's parent should be determined based on the + /// current context. + /// + /// If this is true and the current thread is currently inside a span, then + /// that span should be the new event's parent. Otherwise, if the current + /// thread is _not_ inside a span, then the new event will be the root of its + /// own trace tree. + pub fn is_contextual(&self) -> bool { + match self.parent { + Parent::Current => true, + _ => false, + } + } + + /// Returns the new event's explicitly-specified parent, if there is one. + /// + /// Otherwise (if the new event is a root or is a child of the current span), + /// returns false. + pub fn parent(&self) -> Option<&Id> { + match self.parent { + Parent::Explicit(ref p) => Some(p), + _ => None, + } + } +} diff --git a/third_party/rust/tracing-core/src/field.rs b/third_party/rust/tracing-core/src/field.rs new file mode 100644 index 0000000000..1cda8d9cb8 --- /dev/null +++ b/third_party/rust/tracing-core/src/field.rs @@ -0,0 +1,980 @@ +//! Span and `Event` key-value data. +//! +//! Spans and events may be annotated with key-value data, referred to as known +//! as _fields_. These fields consist of a mapping from a key (corresponding to +//! a `&str` but represented internally as an array index) to a [`Value`]. +//! +//! # `Value`s and `Subscriber`s +//! +//! `Subscriber`s consume `Value`s as fields attached to [span]s or [`Event`]s. +//! The set of field keys on a given span or is defined on its [`Metadata`]. +//! When a span is created, it provides [`Attributes`] to the `Subscriber`'s +//! [`new_span`] method, containing any fields whose values were provided when +//! the span was created; and may call the `Subscriber`'s [`record`] method +//! with additional [`Record`]s if values are added for more of its fields. +//! Similarly, the [`Event`] type passed to the subscriber's [`event`] method +//! will contain any fields attached to each event. +//! +//! `tracing` represents values as either one of a set of Rust primitives +//! (`i64`, `u64`, `bool`, and `&str`) or using a `fmt::Display` or `fmt::Debug` +//! implementation. `Subscriber`s are provided these primitive value types as +//! `dyn Value` trait objects. +//! +//! These trait objects can be formatted using `fmt::Debug`, but may also be +//! recorded as typed data by calling the [`Value::record`] method on these +//! trait objects with a _visitor_ implementing the [`Visit`] trait. This trait +//! represents the behavior used to record values of various types. For example, +//! we might record integers by incrementing counters for their field names, +//! rather than printing them. +//! +//! [`Value`]: trait.Value.html +//! [span]: ../span/ +//! [`Event`]: ../event/struct.Event.html +//! [`Metadata`]: ../metadata/struct.Metadata.html +//! [`Attributes`]: ../span/struct.Attributes.html +//! [`Record`]: ../span/struct.Record.html +//! [`new_span`]: ../subscriber/trait.Subscriber.html#method.new_span +//! [`record`]: ../subscriber/trait.Subscriber.html#method.record +//! [`event`]: ../subscriber/trait.Subscriber.html#method.event +//! [`Value::record`]: trait.Value.html#method.record +//! [`Visit`]: trait.Visit.html +use crate::callsite; +use crate::stdlib::{ + borrow::Borrow, + fmt, + hash::{Hash, Hasher}, + num, + ops::Range, +}; + +use self::private::ValidLen; + +/// An opaque key allowing _O_(1) access to a field in a `Span`'s key-value +/// data. +/// +/// As keys are defined by the _metadata_ of a span, rather than by an +/// individual instance of a span, a key may be used to access the same field +/// across all instances of a given span with the same metadata. Thus, when a +/// subscriber observes a new span, it need only access a field by name _once_, +/// and use the key for that name for all other accesses. +#[derive(Debug)] +pub struct Field { + i: usize, + fields: FieldSet, +} + +/// An empty field. +/// +/// This can be used to indicate that the value of a field is not currently +/// present but will be recorded later. +/// +/// When a field's value is `Empty`. it will not be recorded. +#[derive(Debug, Eq, PartialEq)] +pub struct Empty; + +/// Describes the fields present on a span. +pub struct FieldSet { + /// The names of each field on the described span. + names: &'static [&'static str], + /// The callsite where the described span originates. + callsite: callsite::Identifier, +} + +/// A set of fields and values for a span. +pub struct ValueSet<'a> { + values: &'a [(&'a Field, Option<&'a (dyn Value + 'a)>)], + fields: &'a FieldSet, +} + +/// An iterator over a set of fields. +#[derive(Debug)] +pub struct Iter { + idxs: Range<usize>, + fields: FieldSet, +} + +/// Visits typed values. +/// +/// An instance of `Visit` ("a visitor") represents the logic necessary to +/// record field values of various types. When an implementor of [`Value`] is +/// [recorded], it calls the appropriate method on the provided visitor to +/// indicate the type that value should be recorded as. +/// +/// When a [`Subscriber`] implementation [records an `Event`] or a +/// [set of `Value`s added to a `Span`], it can pass an `&mut Visit` to the +/// `record` method on the provided [`ValueSet`] or [`Event`]. This visitor +/// will then be used to record all the field-value pairs present on that +/// `Event` or `ValueSet`. +/// +/// # Examples +/// +/// A simple visitor that writes to a string might be implemented like so: +/// ``` +/// # extern crate tracing_core as tracing; +/// use std::fmt::{self, Write}; +/// use tracing::field::{Value, Visit, Field}; +/// pub struct StringVisitor<'a> { +/// string: &'a mut String, +/// } +/// +/// impl<'a> Visit for StringVisitor<'a> { +/// fn record_debug(&mut self, field: &Field, value: &fmt::Debug) { +/// write!(self.string, "{} = {:?}; ", field.name(), value).unwrap(); +/// } +/// } +/// ``` +/// This visitor will format each recorded value using `fmt::Debug`, and +/// append the field name and formatted value to the provided string, +/// regardless of the type of the recorded value. When all the values have +/// been recorded, the `StringVisitor` may be dropped, allowing the string +/// to be printed or stored in some other data structure. +/// +/// The `Visit` trait provides default implementations for `record_i64`, +/// `record_u64`, `record_bool`, `record_str`, and `record_error`, which simply +/// forward the recorded value to `record_debug`. Thus, `record_debug` is the +/// only method which a `Visit` implementation *must* implement. However, +/// visitors may override the default implementations of these functions in +/// order to implement type-specific behavior. +/// +/// Additionally, when a visitor receives a value of a type it does not care +/// about, it is free to ignore those values completely. For example, a +/// visitor which only records numeric data might look like this: +/// +/// ``` +/// # extern crate tracing_core as tracing; +/// # use std::fmt::{self, Write}; +/// # use tracing::field::{Value, Visit, Field}; +/// pub struct SumVisitor { +/// sum: i64, +/// } +/// +/// impl Visit for SumVisitor { +/// fn record_i64(&mut self, _field: &Field, value: i64) { +/// self.sum += value; +/// } +/// +/// fn record_u64(&mut self, _field: &Field, value: u64) { +/// self.sum += value as i64; +/// } +/// +/// fn record_debug(&mut self, _field: &Field, _value: &fmt::Debug) { +/// // Do nothing +/// } +/// } +/// ``` +/// +/// This visitor (which is probably not particularly useful) keeps a running +/// sum of all the numeric values it records, and ignores all other values. A +/// more practical example of recording typed values is presented in +/// `examples/counters.rs`, which demonstrates a very simple metrics system +/// implemented using `tracing`. +/// +/// <div class="information"> +/// <div class="tooltip ignore" style="">ⓘ<span class="tooltiptext">Note</span></div> +/// </div> +/// <div class="example-wrap" style="display:inline-block"> +/// <pre class="ignore" style="white-space:normal;font:inherit;"> +/// <strong>Note</strong>: The <code>record_error</code> trait method is only +/// available when the Rust standard library is present, as it requires the +/// <code>std::error::Error</code> trait. +/// </pre></div> +/// +/// [`Value`]: trait.Value.html +/// [recorded]: trait.Value.html#method.record +/// [`Subscriber`]: ../subscriber/trait.Subscriber.html +/// [records an `Event`]: ../subscriber/trait.Subscriber.html#method.event +/// [set of `Value`s added to a `Span`]: ../subscriber/trait.Subscriber.html#method.record +/// [`Event`]: ../event/struct.Event.html +/// [`ValueSet`]: struct.ValueSet.html +pub trait Visit { + /// Visit a signed 64-bit integer value. + fn record_i64(&mut self, field: &Field, value: i64) { + self.record_debug(field, &value) + } + + /// Visit an unsigned 64-bit integer value. + fn record_u64(&mut self, field: &Field, value: u64) { + self.record_debug(field, &value) + } + + /// Visit a boolean value. + fn record_bool(&mut self, field: &Field, value: bool) { + self.record_debug(field, &value) + } + + /// Visit a string value. + fn record_str(&mut self, field: &Field, value: &str) { + self.record_debug(field, &value) + } + + /// Records a type implementing `Error`. + /// + /// <div class="information"> + /// <div class="tooltip ignore" style="">ⓘ<span class="tooltiptext">Note</span></div> + /// </div> + /// <div class="example-wrap" style="display:inline-block"> + /// <pre class="ignore" style="white-space:normal;font:inherit;"> + /// <strong>Note</strong>: This is only enabled when the Rust standard library is + /// present. + /// </pre> + #[cfg(feature = "std")] + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] + fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) { + self.record_debug(field, &format_args!("{}", value)) + } + + /// Visit a value implementing `fmt::Debug`. + fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug); +} + +/// A field value of an erased type. +/// +/// Implementors of `Value` may call the appropriate typed recording methods on +/// the [visitor] passed to their `record` method in order to indicate how +/// their data should be recorded. +/// +/// [visitor]: trait.Visit.html +pub trait Value: crate::sealed::Sealed { + /// Visits this value with the given `Visitor`. + fn record(&self, key: &Field, visitor: &mut dyn Visit); +} + +/// A `Value` which serializes using `fmt::Display`. +/// +/// Uses `record_debug` in the `Value` implementation to +/// avoid an unnecessary evaluation. +#[derive(Clone)] +pub struct DisplayValue<T: fmt::Display>(T); + +/// A `Value` which serializes as a string using `fmt::Debug`. +#[derive(Clone)] +pub struct DebugValue<T: fmt::Debug>(T); + +/// Wraps a type implementing `fmt::Display` as a `Value` that can be +/// recorded using its `Display` implementation. +pub fn display<T>(t: T) -> DisplayValue<T> +where + T: fmt::Display, +{ + DisplayValue(t) +} + +/// Wraps a type implementing `fmt::Debug` as a `Value` that can be +/// recorded using its `Debug` implementation. +pub fn debug<T>(t: T) -> DebugValue<T> +where + T: fmt::Debug, +{ + DebugValue(t) +} + +// ===== impl Visit ===== + +impl<'a, 'b> Visit for fmt::DebugStruct<'a, 'b> { + fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) { + self.field(field.name(), value); + } +} + +impl<'a, 'b> Visit for fmt::DebugMap<'a, 'b> { + fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) { + self.entry(&format_args!("{}", field), value); + } +} + +impl<F> Visit for F +where + F: FnMut(&Field, &dyn fmt::Debug), +{ + fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) { + (self)(field, value) + } +} + +// ===== impl Value ===== + +macro_rules! impl_values { + ( $( $record:ident( $( $whatever:tt)+ ) ),+ ) => { + $( + impl_value!{ $record( $( $whatever )+ ) } + )+ + } +} + +macro_rules! ty_to_nonzero { + (u8) => { + NonZeroU8 + }; + (u16) => { + NonZeroU16 + }; + (u32) => { + NonZeroU32 + }; + (u64) => { + NonZeroU64 + }; + (u128) => { + NonZeroU128 + }; + (usize) => { + NonZeroUsize + }; + (i8) => { + NonZeroI8 + }; + (i16) => { + NonZeroI16 + }; + (i32) => { + NonZeroI32 + }; + (i64) => { + NonZeroI64 + }; + (i128) => { + NonZeroI128 + }; + (isize) => { + NonZeroIsize + }; +} + +macro_rules! impl_one_value { + (bool, $op:expr, $record:ident) => { + impl_one_value!(normal, bool, $op, $record); + }; + ($value_ty:tt, $op:expr, $record:ident) => { + impl_one_value!(normal, $value_ty, $op, $record); + impl_one_value!(nonzero, $value_ty, $op, $record); + }; + (normal, $value_ty:tt, $op:expr, $record:ident) => { + impl $crate::sealed::Sealed for $value_ty {} + impl $crate::field::Value for $value_ty { + fn record(&self, key: &$crate::field::Field, visitor: &mut dyn $crate::field::Visit) { + visitor.$record(key, $op(*self)) + } + } + }; + (nonzero, $value_ty:tt, $op:expr, $record:ident) => { + // This `use num::*;` is reported as unused because it gets emitted + // for every single invocation of this macro, so there are multiple `use`s. + // All but the first are useless indeed. + // We need this import because we can't write a path where one part is + // the `ty_to_nonzero!($value_ty)` invocation. + #[allow(clippy::useless_attribute, unused)] + use num::*; + impl $crate::sealed::Sealed for ty_to_nonzero!($value_ty) {} + impl $crate::field::Value for ty_to_nonzero!($value_ty) { + fn record(&self, key: &$crate::field::Field, visitor: &mut dyn $crate::field::Visit) { + visitor.$record(key, $op(self.get())) + } + } + }; +} + +macro_rules! impl_value { + ( $record:ident( $( $value_ty:tt ),+ ) ) => { + $( + impl_one_value!($value_ty, |this: $value_ty| this, $record); + )+ + }; + ( $record:ident( $( $value_ty:tt ),+ as $as_ty:ty) ) => { + $( + impl_one_value!($value_ty, |this: $value_ty| this as $as_ty, $record); + )+ + }; +} + +// ===== impl Value ===== + +impl_values! { + record_u64(u64), + record_u64(usize, u32, u16, u8 as u64), + record_i64(i64), + record_i64(isize, i32, i16, i8 as i64), + record_bool(bool) +} + +impl<T: crate::sealed::Sealed> crate::sealed::Sealed for Wrapping<T> {} +impl<T: crate::field::Value> crate::field::Value for Wrapping<T> { + fn record(&self, key: &crate::field::Field, visitor: &mut dyn crate::field::Visit) { + self.0.record(key, visitor) + } +} + +impl crate::sealed::Sealed for str {} + +impl Value for str { + fn record(&self, key: &Field, visitor: &mut dyn Visit) { + visitor.record_str(key, &self) + } +} + +#[cfg(feature = "std")] +impl crate::sealed::Sealed for dyn std::error::Error + 'static {} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl Value for dyn std::error::Error + 'static { + fn record(&self, key: &Field, visitor: &mut dyn Visit) { + visitor.record_error(key, self) + } +} + +impl<'a, T: ?Sized> crate::sealed::Sealed for &'a T where T: Value + crate::sealed::Sealed + 'a {} + +impl<'a, T: ?Sized> Value for &'a T +where + T: Value + 'a, +{ + fn record(&self, key: &Field, visitor: &mut dyn Visit) { + (*self).record(key, visitor) + } +} + +impl<'a> crate::sealed::Sealed for fmt::Arguments<'a> {} + +impl<'a> Value for fmt::Arguments<'a> { + fn record(&self, key: &Field, visitor: &mut dyn Visit) { + visitor.record_debug(key, self) + } +} + +impl fmt::Debug for dyn Value { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // We are only going to be recording the field value, so we don't + // actually care about the field name here. + struct NullCallsite; + static NULL_CALLSITE: NullCallsite = NullCallsite; + impl crate::callsite::Callsite for NullCallsite { + fn set_interest(&self, _: crate::subscriber::Interest) { + unreachable!("you somehow managed to register the null callsite?") + } + + fn metadata(&self) -> &crate::Metadata<'_> { + unreachable!("you somehow managed to access the null callsite?") + } + } + + static FIELD: Field = Field { + i: 0, + fields: FieldSet::new(&[], crate::identify_callsite!(&NULL_CALLSITE)), + }; + + let mut res = Ok(()); + self.record(&FIELD, &mut |_: &Field, val: &dyn fmt::Debug| { + res = write!(f, "{:?}", val); + }); + res + } +} + +impl fmt::Display for dyn Value { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(self, f) + } +} + +// ===== impl DisplayValue ===== + +impl<T: fmt::Display> crate::sealed::Sealed for DisplayValue<T> {} + +impl<T> Value for DisplayValue<T> +where + T: fmt::Display, +{ + fn record(&self, key: &Field, visitor: &mut dyn Visit) { + visitor.record_debug(key, &format_args!("{}", self.0)) + } +} + +impl<T: fmt::Display> fmt::Debug for DisplayValue<T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0) + } +} + +impl<T: fmt::Display> fmt::Display for DisplayValue<T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&self.0, f) + } +} + +// ===== impl DebugValue ===== + +impl<T: fmt::Debug> crate::sealed::Sealed for DebugValue<T> {} + +impl<T: fmt::Debug> Value for DebugValue<T> +where + T: fmt::Debug, +{ + fn record(&self, key: &Field, visitor: &mut dyn Visit) { + visitor.record_debug(key, &self.0) + } +} + +impl<T: fmt::Debug> fmt::Debug for DebugValue<T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}", self.0) + } +} + +impl crate::sealed::Sealed for Empty {} +impl Value for Empty { + #[inline] + fn record(&self, _: &Field, _: &mut dyn Visit) {} +} + +// ===== impl Field ===== + +impl Field { + /// Returns an [`Identifier`] that uniquely identifies the [`Callsite`] + /// which defines this field. + /// + /// [`Identifier`]: ../callsite/struct.Identifier.html + /// [`Callsite`]: ../callsite/trait.Callsite.html + #[inline] + pub fn callsite(&self) -> callsite::Identifier { + self.fields.callsite() + } + + /// Returns a string representing the name of the field. + pub fn name(&self) -> &'static str { + self.fields.names[self.i] + } +} + +impl fmt::Display for Field { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.pad(self.name()) + } +} + +impl AsRef<str> for Field { + fn as_ref(&self) -> &str { + self.name() + } +} + +impl PartialEq for Field { + fn eq(&self, other: &Self) -> bool { + self.callsite() == other.callsite() && self.i == other.i + } +} + +impl Eq for Field {} + +impl Hash for Field { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.callsite().hash(state); + self.i.hash(state); + } +} + +impl Clone for Field { + fn clone(&self) -> Self { + Field { + i: self.i, + fields: FieldSet { + names: self.fields.names, + callsite: self.fields.callsite(), + }, + } + } +} + +// ===== impl FieldSet ===== + +impl FieldSet { + /// Constructs a new `FieldSet` with the given array of field names and callsite. + pub const fn new(names: &'static [&'static str], callsite: callsite::Identifier) -> Self { + Self { names, callsite } + } + + /// Returns an [`Identifier`] that uniquely identifies the [`Callsite`] + /// which defines this set of fields.. + /// + /// [`Identifier`]: ../callsite/struct.Identifier.html + /// [`Callsite`]: ../callsite/trait.Callsite.html + pub(crate) fn callsite(&self) -> callsite::Identifier { + callsite::Identifier(self.callsite.0) + } + + /// Returns the [`Field`] named `name`, or `None` if no such field exists. + /// + /// [`Field`]: ../struct.Field.html + pub fn field<Q: ?Sized>(&self, name: &Q) -> Option<Field> + where + Q: Borrow<str>, + { + let name = &name.borrow(); + self.names.iter().position(|f| f == name).map(|i| Field { + i, + fields: FieldSet { + names: self.names, + callsite: self.callsite(), + }, + }) + } + + /// Returns `true` if `self` contains the given `field`. + /// + /// <div class="information"> + /// <div class="tooltip ignore" style="">ⓘ<span class="tooltiptext">Note</span></div> + /// </div> + /// <div class="example-wrap" style="display:inline-block"> + /// <pre class="ignore" style="white-space:normal;font:inherit;"> + /// <strong>Note</strong>: If <code>field</code> shares a name with a field + /// in this <code>FieldSet</code>, but was created by a <code>FieldSet</code> + /// with a different callsite, this <code>FieldSet</code> does <em>not</em> + /// contain it. This is so that if two separate span callsites define a field + /// named "foo", the <code>Field</code> corresponding to "foo" for each + /// of those callsites are not equivalent. + /// </pre></div> + pub fn contains(&self, field: &Field) -> bool { + field.callsite() == self.callsite() && field.i <= self.len() + } + + /// Returns an iterator over the `Field`s in this `FieldSet`. + pub fn iter(&self) -> Iter { + let idxs = 0..self.len(); + Iter { + idxs, + fields: FieldSet { + names: self.names, + callsite: self.callsite(), + }, + } + } + + /// Returns a new `ValueSet` with entries for this `FieldSet`'s values. + /// + /// Note that a `ValueSet` may not be constructed with arrays of over 32 + /// elements. + #[doc(hidden)] + pub fn value_set<'v, V>(&'v self, values: &'v V) -> ValueSet<'v> + where + V: ValidLen<'v>, + { + ValueSet { + fields: self, + values: &values.borrow()[..], + } + } + + /// Returns the number of fields in this `FieldSet`. + #[inline] + pub fn len(&self) -> usize { + self.names.len() + } + + /// Returns whether or not this `FieldSet` has fields. + #[inline] + pub fn is_empty(&self) -> bool { + self.names.is_empty() + } +} + +impl<'a> IntoIterator for &'a FieldSet { + type IntoIter = Iter; + type Item = Field; + #[inline] + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl fmt::Debug for FieldSet { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("FieldSet") + .field("names", &self.names) + .field("callsite", &self.callsite) + .finish() + } +} + +impl fmt::Display for FieldSet { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_set() + .entries(self.names.iter().map(display)) + .finish() + } +} + +// ===== impl Iter ===== + +impl Iterator for Iter { + type Item = Field; + fn next(&mut self) -> Option<Field> { + let i = self.idxs.next()?; + Some(Field { + i, + fields: FieldSet { + names: self.fields.names, + callsite: self.fields.callsite(), + }, + }) + } +} + +// ===== impl ValueSet ===== + +impl<'a> ValueSet<'a> { + /// Returns an [`Identifier`] that uniquely identifies the [`Callsite`] + /// defining the fields this `ValueSet` refers to. + /// + /// [`Identifier`]: ../callsite/struct.Identifier.html + /// [`Callsite`]: ../callsite/trait.Callsite.html + #[inline] + pub fn callsite(&self) -> callsite::Identifier { + self.fields.callsite() + } + + /// Visits all the fields in this `ValueSet` with the provided [visitor]. + /// + /// [visitor]: ../trait.Visit.html + pub(crate) fn record(&self, visitor: &mut dyn Visit) { + let my_callsite = self.callsite(); + for (field, value) in self.values { + if field.callsite() != my_callsite { + continue; + } + if let Some(value) = value { + value.record(field, visitor); + } + } + } + + /// Returns `true` if this `ValueSet` contains a value for the given `Field`. + pub(crate) fn contains(&self, field: &Field) -> bool { + field.callsite() == self.callsite() + && self + .values + .iter() + .any(|(key, val)| *key == field && val.is_some()) + } + + /// Returns true if this `ValueSet` contains _no_ values. + pub(crate) fn is_empty(&self) -> bool { + let my_callsite = self.callsite(); + self.values + .iter() + .all(|(key, val)| val.is_none() || key.callsite() != my_callsite) + } + + pub(crate) fn field_set(&self) -> &FieldSet { + self.fields + } +} + +impl<'a> fmt::Debug for ValueSet<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.values + .iter() + .fold(&mut f.debug_struct("ValueSet"), |dbg, (key, v)| { + if let Some(val) = v { + val.record(key, dbg); + } + dbg + }) + .field("callsite", &self.callsite()) + .finish() + } +} + +impl<'a> fmt::Display for ValueSet<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.values + .iter() + .fold(&mut f.debug_map(), |dbg, (key, v)| { + if let Some(val) = v { + val.record(key, dbg); + } + dbg + }) + .finish() + } +} + +// ===== impl ValidLen ===== + +mod private { + use super::*; + + /// Marker trait implemented by arrays which are of valid length to + /// construct a `ValueSet`. + /// + /// `ValueSet`s may only be constructed from arrays containing 32 or fewer + /// elements, to ensure the array is small enough to always be allocated on the + /// stack. This trait is only implemented by arrays of an appropriate length, + /// ensuring that the correct size arrays are used at compile-time. + pub trait ValidLen<'a>: Borrow<[(&'a Field, Option<&'a (dyn Value + 'a)>)]> {} +} + +macro_rules! impl_valid_len { + ( $( $len:tt ),+ ) => { + $( + impl<'a> private::ValidLen<'a> for + [(&'a Field, Option<&'a (dyn Value + 'a)>); $len] {} + )+ + } +} + +impl_valid_len! { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 +} + +#[cfg(test)] +mod test { + use super::*; + use crate::metadata::{Kind, Level, Metadata}; + use crate::stdlib::{borrow::ToOwned, string::String}; + + struct TestCallsite1; + static TEST_CALLSITE_1: TestCallsite1 = TestCallsite1; + static TEST_META_1: Metadata<'static> = metadata! { + name: "field_test1", + target: module_path!(), + level: Level::INFO, + fields: &["foo", "bar", "baz"], + callsite: &TEST_CALLSITE_1, + kind: Kind::SPAN, + }; + + impl crate::callsite::Callsite for TestCallsite1 { + fn set_interest(&self, _: crate::subscriber::Interest) { + unimplemented!() + } + + fn metadata(&self) -> &Metadata<'_> { + &TEST_META_1 + } + } + + struct TestCallsite2; + static TEST_CALLSITE_2: TestCallsite2 = TestCallsite2; + static TEST_META_2: Metadata<'static> = metadata! { + name: "field_test2", + target: module_path!(), + level: Level::INFO, + fields: &["foo", "bar", "baz"], + callsite: &TEST_CALLSITE_2, + kind: Kind::SPAN, + }; + + impl crate::callsite::Callsite for TestCallsite2 { + fn set_interest(&self, _: crate::subscriber::Interest) { + unimplemented!() + } + + fn metadata(&self) -> &Metadata<'_> { + &TEST_META_2 + } + } + + #[test] + fn value_set_with_no_values_is_empty() { + let fields = TEST_META_1.fields(); + let values = &[ + (&fields.field("foo").unwrap(), None), + (&fields.field("bar").unwrap(), None), + (&fields.field("baz").unwrap(), None), + ]; + let valueset = fields.value_set(values); + assert!(valueset.is_empty()); + } + + #[test] + fn empty_value_set_is_empty() { + let fields = TEST_META_1.fields(); + let valueset = fields.value_set(&[]); + assert!(valueset.is_empty()); + } + + #[test] + fn value_sets_with_fields_from_other_callsites_are_empty() { + let fields = TEST_META_1.fields(); + let values = &[ + (&fields.field("foo").unwrap(), Some(&1 as &dyn Value)), + (&fields.field("bar").unwrap(), Some(&2 as &dyn Value)), + (&fields.field("baz").unwrap(), Some(&3 as &dyn Value)), + ]; + let valueset = TEST_META_2.fields().value_set(values); + assert!(valueset.is_empty()) + } + + #[test] + fn sparse_value_sets_are_not_empty() { + let fields = TEST_META_1.fields(); + let values = &[ + (&fields.field("foo").unwrap(), None), + (&fields.field("bar").unwrap(), Some(&57 as &dyn Value)), + (&fields.field("baz").unwrap(), None), + ]; + let valueset = fields.value_set(values); + assert!(!valueset.is_empty()); + } + + #[test] + fn fields_from_other_callsets_are_skipped() { + let fields = TEST_META_1.fields(); + let values = &[ + (&fields.field("foo").unwrap(), None), + ( + &TEST_META_2.fields().field("bar").unwrap(), + Some(&57 as &dyn Value), + ), + (&fields.field("baz").unwrap(), None), + ]; + + struct MyVisitor; + impl Visit for MyVisitor { + fn record_debug(&mut self, field: &Field, _: &dyn (crate::stdlib::fmt::Debug)) { + assert_eq!(field.callsite(), TEST_META_1.callsite()) + } + } + let valueset = fields.value_set(values); + valueset.record(&mut MyVisitor); + } + + #[test] + fn empty_fields_are_skipped() { + let fields = TEST_META_1.fields(); + let values = &[ + (&fields.field("foo").unwrap(), Some(&Empty as &dyn Value)), + (&fields.field("bar").unwrap(), Some(&57 as &dyn Value)), + (&fields.field("baz").unwrap(), Some(&Empty as &dyn Value)), + ]; + + struct MyVisitor; + impl Visit for MyVisitor { + fn record_debug(&mut self, field: &Field, _: &dyn (crate::stdlib::fmt::Debug)) { + assert_eq!(field.name(), "bar") + } + } + let valueset = fields.value_set(values); + valueset.record(&mut MyVisitor); + } + + #[test] + fn record_debug_fn() { + let fields = TEST_META_1.fields(); + let values = &[ + (&fields.field("foo").unwrap(), Some(&1 as &dyn Value)), + (&fields.field("bar").unwrap(), Some(&2 as &dyn Value)), + (&fields.field("baz").unwrap(), Some(&3 as &dyn Value)), + ]; + let valueset = fields.value_set(values); + let mut result = String::new(); + valueset.record(&mut |_: &Field, value: &dyn fmt::Debug| { + use crate::stdlib::fmt::Write; + write!(&mut result, "{:?}", value).unwrap(); + }); + assert_eq!(result, "123".to_owned()); + } +} diff --git a/third_party/rust/tracing-core/src/lazy_static/LICENSE b/third_party/rust/tracing-core/src/lazy_static/LICENSE new file mode 100644 index 0000000000..28e478827c --- /dev/null +++ b/third_party/rust/tracing-core/src/lazy_static/LICENSE @@ -0,0 +1,26 @@ + +Copyright (c) 2010 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/third_party/rust/tracing-core/src/lazy_static/core_lazy.rs b/third_party/rust/tracing-core/src/lazy_static/core_lazy.rs new file mode 100644 index 0000000000..c61d36202d --- /dev/null +++ b/third_party/rust/tracing-core/src/lazy_static/core_lazy.rs @@ -0,0 +1,30 @@ +// Copyright 2016 lazy-static.rs Developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use crate::spin::Once; + +pub(crate) struct Lazy<T: Sync>(Once<T>); + +impl<T: Sync> Lazy<T> { + pub(crate) const INIT: Self = Lazy(Once::INIT); + + #[inline(always)] + pub(crate) fn get<F>(&'static self, builder: F) -> &T + where + F: FnOnce() -> T, + { + self.0.call_once(builder) + } +} + +#[macro_export] +#[doc(hidden)] +macro_rules! __lazy_static_create { + ($NAME:ident, $T:ty) => { + static $NAME: $crate::lazy_static::lazy::Lazy<$T> = $crate::lazy_static::lazy::Lazy::INIT; + }; +} diff --git a/third_party/rust/tracing-core/src/lazy_static/mod.rs b/third_party/rust/tracing-core/src/lazy_static/mod.rs new file mode 100644 index 0000000000..78f0ae722b --- /dev/null +++ b/third_party/rust/tracing-core/src/lazy_static/mod.rs @@ -0,0 +1,89 @@ +// Copyright 2016 lazy-static.rs Developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +/*! +A macro for declaring lazily evaluated statics. +Using this macro, it is possible to have `static`s that require code to be +executed at runtime in order to be initialized. +This includes anything requiring heap allocations, like vectors or hash maps, +as well as anything that requires function calls to be computed. +*/ + +#[path = "core_lazy.rs"] +pub(crate) mod lazy; + +#[doc(hidden)] +pub(crate) use core::ops::Deref as __Deref; + +#[macro_export] +#[doc(hidden)] +macro_rules! __lazy_static_internal { + // optional visibility restrictions are wrapped in `()` to allow for + // explicitly passing otherwise implicit information about private items + ($(#[$attr:meta])* ($($vis:tt)*) static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => { + $crate::__lazy_static_internal!(@MAKE TY, $(#[$attr])*, ($($vis)*), $N); + $crate::__lazy_static_internal!(@TAIL, $N : $T = $e); + $crate::lazy_static!($($t)*); + }; + (@TAIL, $N:ident : $T:ty = $e:expr) => { + impl $crate::lazy_static::__Deref for $N { + type Target = $T; + fn deref(&self) -> &$T { + #[inline(always)] + fn __static_ref_initialize() -> $T { $e } + + #[inline(always)] + fn __stability() -> &'static $T { + $crate::__lazy_static_create!(LAZY, $T); + LAZY.get(__static_ref_initialize) + } + __stability() + } + } + impl $crate::lazy_static::LazyStatic for $N { + fn initialize(lazy: &Self) { + let _ = &**lazy; + } + } + }; + // `vis` is wrapped in `()` to prevent parsing ambiguity + (@MAKE TY, $(#[$attr:meta])*, ($($vis:tt)*), $N:ident) => { + #[allow(missing_copy_implementations)] + #[allow(non_camel_case_types)] + #[allow(dead_code)] + $(#[$attr])* + $($vis)* struct $N {__private_field: ()} + #[doc(hidden)] + $($vis)* static $N: $N = $N {__private_field: ()}; + }; + () => () +} + +#[macro_export] +#[doc(hidden)] +macro_rules! lazy_static { + ($(#[$attr:meta])* static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => { + // use `()` to explicitly forward the information about private items + $crate::__lazy_static_internal!($(#[$attr])* () static ref $N : $T = $e; $($t)*); + }; + ($(#[$attr:meta])* pub static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => { + $crate::__lazy_static_internal!($(#[$attr])* (pub) static ref $N : $T = $e; $($t)*); + }; + ($(#[$attr:meta])* pub ($($vis:tt)+) static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => { + $crate::__lazy_static_internal!($(#[$attr])* (pub ($($vis)+)) static ref $N : $T = $e; $($t)*); + }; + () => () +} + +/// Support trait for enabling a few common operation on lazy static values. +/// +/// This is implemented by each defined lazy static, and +/// used by the free functions in this crate. +pub(crate) trait LazyStatic { + #[doc(hidden)] + fn initialize(lazy: &Self); +} diff --git a/third_party/rust/tracing-core/src/lib.rs b/third_party/rust/tracing-core/src/lib.rs new file mode 100644 index 0000000000..0d266b8e9c --- /dev/null +++ b/third_party/rust/tracing-core/src/lib.rs @@ -0,0 +1,279 @@ +//! Core primitives for `tracing`. +//! +//! [`tracing`] is a framework for instrumenting Rust programs to collect +//! structured, event-based diagnostic information. This crate defines the core +//! primitives of `tracing`. +//! +//! This crate provides: +//! +//! * [`span::Id`] identifies a span within the execution of a program. +//! +//! * [`Event`] represents a single event within a trace. +//! +//! * [`Subscriber`], the trait implemented to collect trace data. +//! +//! * [`Metadata`] and [`Callsite`] provide information describing spans and +//! `Event`s. +//! +//! * [`Field`], [`FieldSet`], [`Value`], and [`ValueSet`] represent the +//! structured data attached to a span. +//! +//! * [`Dispatch`] allows spans and events to be dispatched to `Subscriber`s. +//! +//! In addition, it defines the global callsite registry and per-thread current +//! dispatcher which other components of the tracing system rely on. +//! +//! *Compiler support: [requires `rustc` 1.40+][msrv]* +//! +//! [msrv]: #supported-rust-versions +//! +//! ## Usage +//! +//! Application authors will typically not use this crate directly. Instead, +//! they will use the [`tracing`] crate, which provides a much more +//! fully-featured API. However, this crate's API will change very infrequently, +//! so it may be used when dependencies must be very stable. +//! +//! `Subscriber` implementations may depend on `tracing-core` rather than +//! `tracing`, as the additional APIs provided by `tracing` are primarily useful +//! for instrumenting libraries and applications, and are generally not +//! necessary for `Subscriber` implementations. +//! +//! The [`tokio-rs/tracing`] repository contains less stable crates designed to +//! be used with the `tracing` ecosystem. It includes a collection of +//! `Subscriber` implementations, as well as utility and adapter crates. +//! +//! ### Crate Feature Flags +//! +//! The following crate feature flags are available: +//! +//! * `std`: Depend on the Rust standard library (enabled by default). +//! +//! `no_std` users may disable this feature with `default-features = false`: +//! +//! ```toml +//! [dependencies] +//! tracing-core = { version = "0.1.17", default-features = false } +//! ``` +//! +//! **Note**:`tracing-core`'s `no_std` support requires `liballoc`. +//! +//! ## Supported Rust Versions +//! +//! Tracing is built against the latest stable release. The minimum supported +//! version is 1.40. The current Tracing version is not guaranteed to build on +//! Rust versions earlier than the minimum supported version. +//! +//! Tracing follows the same compiler support policies as the rest of the Tokio +//! project. The current stable Rust compiler and the three most recent minor +//! versions before it will always be supported. For example, if the current +//! stable compiler version is 1.45, the minimum supported version will not be +//! increased past 1.42, three minor versions prior. Increasing the minimum +//! supported compiler version is not considered a semver breaking change as +//! long as doing so complies with this policy. +//! +//! +//! [`span::Id`]: span/struct.Id.html +//! [`Event`]: event/struct.Event.html +//! [`Subscriber`]: subscriber/trait.Subscriber.html +//! [`Metadata`]: metadata/struct.Metadata.html +//! [`Callsite`]: callsite/trait.Callsite.html +//! [`Field`]: field/struct.Field.html +//! [`FieldSet`]: field/struct.FieldSet.html +//! [`Value`]: field/trait.Value.html +//! [`ValueSet`]: field/struct.ValueSet.html +//! [`Dispatch`]: dispatcher/struct.Dispatch.html +//! [`tokio-rs/tracing`]: https://github.com/tokio-rs/tracing +//! [`tracing`]: https://crates.io/crates/tracing +#![doc(html_root_url = "https://docs.rs/tracing-core/0.1.17")] +#![doc( + html_logo_url = "https://raw.githubusercontent.com/tokio-rs/tracing/master/assets/logo-type.png", + issue_tracker_base_url = "https://github.com/tokio-rs/tracing/issues/" +)] +#![cfg_attr(not(feature = "std"), no_std)] +#![cfg_attr(docsrs, feature(doc_cfg), deny(broken_intra_doc_links))] +#![warn( + missing_debug_implementations, + missing_docs, + rust_2018_idioms, + unreachable_pub, + bad_style, + const_err, + dead_code, + improper_ctypes, + non_shorthand_field_patterns, + no_mangle_generic_items, + overflowing_literals, + path_statements, + patterns_in_fns_without_body, + private_in_public, + unconditional_recursion, + unused, + unused_allocation, + unused_comparisons, + unused_parens, + while_true +)] +#[cfg(not(feature = "std"))] +extern crate alloc; + +/// Statically constructs an [`Identifier`] for the provided [`Callsite`]. +/// +/// This may be used in contexts, such as static initializers, where the +/// [`Callsite::id`] function is not currently usable. +/// +/// For example: +/// ```rust +/// # #[macro_use] +/// # extern crate tracing_core; +/// use tracing_core::callsite; +/// # use tracing_core::{Metadata, subscriber::Interest}; +/// # fn main() { +/// pub struct MyCallsite { +/// // ... +/// } +/// impl callsite::Callsite for MyCallsite { +/// # fn set_interest(&self, _: Interest) { unimplemented!() } +/// # fn metadata(&self) -> &Metadata { unimplemented!() } +/// // ... +/// } +/// +/// static CALLSITE: MyCallsite = MyCallsite { +/// // ... +/// }; +/// +/// static CALLSITE_ID: callsite::Identifier = identify_callsite!(&CALLSITE); +/// # } +/// ``` +/// +/// [`Identifier`]: callsite/struct.Identifier.html +/// [`Callsite`]: callsite/trait.Callsite.html +/// [`Callsite::id`]: callsite/trait.Callsite.html#method.id +#[macro_export] +macro_rules! identify_callsite { + ($callsite:expr) => { + $crate::callsite::Identifier($callsite) + }; +} + +/// Statically constructs new span [metadata]. +/// +/// /// For example: +/// ```rust +/// # #[macro_use] +/// # extern crate tracing_core; +/// # use tracing_core::{callsite::Callsite, subscriber::Interest}; +/// use tracing_core::metadata::{Kind, Level, Metadata}; +/// # fn main() { +/// # pub struct MyCallsite { } +/// # impl Callsite for MyCallsite { +/// # fn set_interest(&self, _: Interest) { unimplemented!() } +/// # fn metadata(&self) -> &Metadata { unimplemented!() } +/// # } +/// # +/// static FOO_CALLSITE: MyCallsite = MyCallsite { +/// // ... +/// }; +/// +/// static FOO_METADATA: Metadata = metadata!{ +/// name: "foo", +/// target: module_path!(), +/// level: Level::DEBUG, +/// fields: &["bar", "baz"], +/// callsite: &FOO_CALLSITE, +/// kind: Kind::SPAN, +/// }; +/// # } +/// ``` +/// +/// [metadata]: metadata/struct.Metadata.html +/// [`Metadata::new`]: metadata/struct.Metadata.html#method.new +#[macro_export] +macro_rules! metadata { + ( + name: $name:expr, + target: $target:expr, + level: $level:expr, + fields: $fields:expr, + callsite: $callsite:expr, + kind: $kind:expr + ) => { + $crate::metadata! { + name: $name, + target: $target, + level: $level, + fields: $fields, + callsite: $callsite, + kind: $kind, + } + }; + ( + name: $name:expr, + target: $target:expr, + level: $level:expr, + fields: $fields:expr, + callsite: $callsite:expr, + kind: $kind:expr, + ) => { + $crate::metadata::Metadata::new( + $name, + $target, + $level, + Some(file!()), + Some(line!()), + Some(module_path!()), + $crate::field::FieldSet::new($fields, $crate::identify_callsite!($callsite)), + $kind, + ) + }; +} + +// std uses lazy_static from crates.io +#[cfg(feature = "std")] +#[macro_use] +extern crate lazy_static; + +// no_std uses vendored version of lazy_static 1.4.0 (4216696) with spin +// This can conflict when included in a project already using std lazy_static +// Remove this module when cargo enables specifying dependencies for no_std +#[cfg(not(feature = "std"))] +#[macro_use] +mod lazy_static; + +// Trimmed-down vendored version of spin 0.5.2 (0387621) +// Dependency of no_std lazy_static, not required in a std build +#[cfg(not(feature = "std"))] +pub(crate) mod spin; + +#[cfg(not(feature = "std"))] +#[doc(hidden)] +pub type Once = self::spin::Once<()>; + +#[cfg(feature = "std")] +pub use stdlib::sync::Once; + +pub mod callsite; +pub mod dispatcher; +pub mod event; +pub mod field; +pub mod metadata; +mod parent; +pub mod span; +pub(crate) mod stdlib; +pub mod subscriber; + +#[doc(inline)] +pub use self::{ + callsite::Callsite, + dispatcher::Dispatch, + event::Event, + field::Field, + metadata::{Level, LevelFilter, Metadata}, + subscriber::Subscriber, +}; + +pub use self::{metadata::Kind, subscriber::Interest}; + +mod sealed { + pub trait Sealed {} +} diff --git a/third_party/rust/tracing-core/src/metadata.rs b/third_party/rust/tracing-core/src/metadata.rs new file mode 100644 index 0000000000..fe67bcfcd8 --- /dev/null +++ b/third_party/rust/tracing-core/src/metadata.rs @@ -0,0 +1,872 @@ +//! Metadata describing trace data. +use super::{callsite, field}; +use crate::stdlib::{ + cmp, fmt, + str::FromStr, + sync::atomic::{AtomicUsize, Ordering}, +}; + +/// Metadata describing a [span] or [event]. +/// +/// All spans and events have the following metadata: +/// - A [name], represented as a static string. +/// - A [target], a string that categorizes part of the system where the span +/// or event occurred. The `tracing` macros default to using the module +/// path where the span or event originated as the target, but it may be +/// overridden. +/// - A [verbosity level]. +/// - The names of the [fields] defined by the span or event. +/// - Whether the metadata corresponds to a span or event. +/// +/// In addition, the following optional metadata describing the source code +/// location where the span or event originated _may_ be provided: +/// - The [file name] +/// - The [line number] +/// - The [module path] +/// +/// Metadata is used by [`Subscriber`]s when filtering spans and events, and it +/// may also be used as part of their data payload. +/// +/// When created by the `event!` or `span!` macro, the metadata describing a +/// particular event or span is constructed statically and exists as a single +/// static instance. Thus, the overhead of creating the metadata is +/// _significantly_ lower than that of creating the actual span. Therefore, +/// filtering is based on metadata, rather than on the constructed span. +/// +/// <div class="information"> +/// <div class="tooltip ignore" style="">ⓘ<span class="tooltiptext">Note</span></div> +/// </div> +/// <div class="example-wrap" style="display:inline-block"> +/// <pre class="ignore" style="white-space:normal;font:inherit;"> +/// <strong>Note</strong>: Although instances of <code>Metadata</code> cannot +/// be compared directly, they provide a method <a href="struct.Metadata.html#method.id"> +/// <code>id</code></a>, returning an opaque <a href="../callsite/struct.Identifier.html"> +/// callsite identifier</a> which uniquely identifies the callsite where the metadata +/// originated. This can be used to determine if two <code>Metadata</code> correspond to +/// the same callsite. +/// </pre></div> +/// +/// [span]: ../span/index.html +/// [event]: ../event/index.html +/// [name]: #method.name +/// [target]: #method.target +/// [fields]: #method.fields +/// [verbosity level]: #method.level +/// [file name]: #method.file +/// [line number]: #method.line +/// [module path]: #method.module +/// [`Subscriber`]: ../subscriber/trait.Subscriber.html +/// [`id`]: struct.Metadata.html#method.id +/// [callsite identifier]: ../callsite/struct.Identifier.html +pub struct Metadata<'a> { + /// The name of the span described by this metadata. + name: &'static str, + + /// The part of the system that the span that this metadata describes + /// occurred in. + target: &'a str, + + /// The level of verbosity of the described span. + level: Level, + + /// The name of the Rust module where the span occurred, or `None` if this + /// could not be determined. + module_path: Option<&'a str>, + + /// The name of the source code file where the span occurred, or `None` if + /// this could not be determined. + file: Option<&'a str>, + + /// The line number in the source code file where the span occurred, or + /// `None` if this could not be determined. + line: Option<u32>, + + /// The names of the key-value fields attached to the described span or + /// event. + fields: field::FieldSet, + + /// The kind of the callsite. + kind: Kind, +} + +/// Indicates whether the callsite is a span or event. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Kind(KindInner); + +/// Describes the level of verbosity of a span or event. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct Level(LevelInner); + +/// A filter comparable to a verbosity `Level`. +/// +/// If a `Level` is considered less than a `LevelFilter`, it should be +/// considered disabled; if greater than or equal to the `LevelFilter`, that +/// level is enabled. +/// +/// Note that this is essentially identical to the `Level` type, but with the +/// addition of an `OFF` level that completely disables all trace +/// instrumentation. +#[repr(transparent)] +#[derive(Copy, Clone, Eq, PartialEq)] +pub struct LevelFilter(Option<Level>); + +/// Indicates that a string could not be parsed to a valid level. +#[derive(Clone, Debug)] +pub struct ParseLevelFilterError(()); + +static MAX_LEVEL: AtomicUsize = AtomicUsize::new(LevelFilter::OFF_USIZE); + +// ===== impl Metadata ===== + +impl<'a> Metadata<'a> { + /// Construct new metadata for a span or event, with a name, target, level, field + /// names, and optional source code location. + pub const fn new( + name: &'static str, + target: &'a str, + level: Level, + file: Option<&'a str>, + line: Option<u32>, + module_path: Option<&'a str>, + fields: field::FieldSet, + kind: Kind, + ) -> Self { + Metadata { + name, + target, + level, + module_path, + file, + line, + fields, + kind, + } + } + + /// Returns the names of the fields on the described span or event. + pub fn fields(&self) -> &field::FieldSet { + &self.fields + } + + /// Returns the level of verbosity of the described span or event. + pub fn level(&self) -> &Level { + &self.level + } + + /// Returns the name of the span. + pub fn name(&self) -> &'static str { + self.name + } + + /// Returns a string describing the part of the system where the span or + /// event that this metadata describes occurred. + /// + /// Typically, this is the module path, but alternate targets may be set + /// when spans or events are constructed. + pub fn target(&self) -> &'a str { + self.target + } + + /// Returns the path to the Rust module where the span occurred, or + /// `None` if the module path is unknown. + pub fn module_path(&self) -> Option<&'a str> { + self.module_path + } + + /// Returns the name of the source code file where the span + /// occurred, or `None` if the file is unknown + pub fn file(&self) -> Option<&'a str> { + self.file + } + + /// Returns the line number in the source code file where the span + /// occurred, or `None` if the line number is unknown. + pub fn line(&self) -> Option<u32> { + self.line + } + + /// Returns an opaque `Identifier` that uniquely identifies the callsite + /// this `Metadata` originated from. + #[inline] + pub fn callsite(&self) -> callsite::Identifier { + self.fields.callsite() + } + + /// Returns true if the callsite kind is `Event`. + pub fn is_event(&self) -> bool { + self.kind.is_event() + } + + /// Return true if the callsite kind is `Span`. + pub fn is_span(&self) -> bool { + self.kind.is_span() + } +} + +impl<'a> fmt::Debug for Metadata<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut meta = f.debug_struct("Metadata"); + meta.field("name", &self.name) + .field("target", &self.target) + .field("level", &self.level); + + if let Some(path) = self.module_path() { + meta.field("module_path", &path); + } + + match (self.file(), self.line()) { + (Some(file), Some(line)) => { + meta.field("location", &format_args!("{}:{}", file, line)); + } + (Some(file), None) => { + meta.field("file", &format_args!("{}", file)); + } + + // Note: a line num with no file is a kind of weird case that _probably_ never occurs... + (None, Some(line)) => { + meta.field("line", &line); + } + (None, None) => {} + }; + + meta.field("fields", &format_args!("{}", self.fields)) + .field("callsite", &self.callsite()) + .field("kind", &self.kind) + .finish() + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +enum KindInner { + Event, + Span, +} + +impl Kind { + /// `Event` callsite + pub const EVENT: Kind = Kind(KindInner::Event); + + /// `Span` callsite + pub const SPAN: Kind = Kind(KindInner::Span); + + /// Return true if the callsite kind is `Span` + pub fn is_span(&self) -> bool { + match self { + Kind(KindInner::Span) => true, + _ => false, + } + } + + /// Return true if the callsite kind is `Event` + pub fn is_event(&self) -> bool { + match self { + Kind(KindInner::Event) => true, + _ => false, + } + } +} + +// ===== impl Level ===== + +impl Level { + /// The "error" level. + /// + /// Designates very serious errors. + pub const ERROR: Level = Level(LevelInner::Error); + /// The "warn" level. + /// + /// Designates hazardous situations. + pub const WARN: Level = Level(LevelInner::Warn); + /// The "info" level. + /// + /// Designates useful information. + pub const INFO: Level = Level(LevelInner::Info); + /// The "debug" level. + /// + /// Designates lower priority information. + pub const DEBUG: Level = Level(LevelInner::Debug); + /// The "trace" level. + /// + /// Designates very low priority, often extremely verbose, information. + pub const TRACE: Level = Level(LevelInner::Trace); +} + +impl fmt::Display for Level { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Level::TRACE => f.pad("TRACE"), + Level::DEBUG => f.pad("DEBUG"), + Level::INFO => f.pad("INFO"), + Level::WARN => f.pad("WARN"), + Level::ERROR => f.pad("ERROR"), + } + } +} + +#[cfg(feature = "std")] +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +impl crate::stdlib::error::Error for ParseLevelError {} + +impl FromStr for Level { + type Err = ParseLevelError; + fn from_str(s: &str) -> Result<Self, ParseLevelError> { + s.parse::<usize>() + .map_err(|_| ParseLevelError { _p: () }) + .and_then(|num| match num { + 1 => Ok(Level::ERROR), + 2 => Ok(Level::WARN), + 3 => Ok(Level::INFO), + 4 => Ok(Level::DEBUG), + 5 => Ok(Level::TRACE), + _ => Err(ParseLevelError { _p: () }), + }) + .or_else(|_| match s { + s if s.eq_ignore_ascii_case("error") => Ok(Level::ERROR), + s if s.eq_ignore_ascii_case("warn") => Ok(Level::WARN), + s if s.eq_ignore_ascii_case("info") => Ok(Level::INFO), + s if s.eq_ignore_ascii_case("debug") => Ok(Level::DEBUG), + s if s.eq_ignore_ascii_case("trace") => Ok(Level::TRACE), + _ => Err(ParseLevelError { _p: () }), + }) + } +} + +#[repr(usize)] +#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] +enum LevelInner { + /// The "trace" level. + /// + /// Designates very low priority, often extremely verbose, information. + Trace = 0, + /// The "debug" level. + /// + /// Designates lower priority information. + Debug = 1, + /// The "info" level. + /// + /// Designates useful information. + Info = 2, + /// The "warn" level. + /// + /// Designates hazardous situations. + Warn = 3, + /// The "error" level. + /// + /// Designates very serious errors. + Error = 4, +} + +// === impl LevelFilter === + +impl From<Level> for LevelFilter { + #[inline] + fn from(level: Level) -> Self { + Self::from_level(level) + } +} + +impl From<Option<Level>> for LevelFilter { + #[inline] + fn from(level: Option<Level>) -> Self { + Self(level) + } +} + +impl Into<Option<Level>> for LevelFilter { + #[inline] + fn into(self) -> Option<Level> { + self.into_level() + } +} + +impl LevelFilter { + /// The "off" level. + /// + /// Designates that trace instrumentation should be completely disabled. + pub const OFF: LevelFilter = LevelFilter(None); + /// The "error" level. + /// + /// Designates very serious errors. + pub const ERROR: LevelFilter = LevelFilter::from_level(Level::ERROR); + /// The "warn" level. + /// + /// Designates hazardous situations. + pub const WARN: LevelFilter = LevelFilter::from_level(Level::WARN); + /// The "info" level. + /// + /// Designates useful information. + pub const INFO: LevelFilter = LevelFilter::from_level(Level::INFO); + /// The "debug" level. + /// + /// Designates lower priority information. + pub const DEBUG: LevelFilter = LevelFilter::from_level(Level::DEBUG); + /// The "trace" level. + /// + /// Designates very low priority, often extremely verbose, information. + pub const TRACE: LevelFilter = LevelFilter(Some(Level::TRACE)); + + /// Returns a `LevelFilter` that enables spans and events with verbosity up + /// to and including `level`. + pub const fn from_level(level: Level) -> Self { + Self(Some(level)) + } + + /// Returns the most verbose [`Level`] that this filter accepts, or `None` + /// if it is [`OFF`]. + /// + /// [`Level`]: ../struct.Level.html + /// [`OFF`]: #associatedconstant.OFF + pub const fn into_level(self) -> Option<Level> { + self.0 + } + + // These consts are necessary because `as` casts are not allowed as + // match patterns. + const ERROR_USIZE: usize = LevelInner::Error as usize; + const WARN_USIZE: usize = LevelInner::Warn as usize; + const INFO_USIZE: usize = LevelInner::Info as usize; + const DEBUG_USIZE: usize = LevelInner::Debug as usize; + const TRACE_USIZE: usize = LevelInner::Trace as usize; + // Using the value of the last variant + 1 ensures that we match the value + // for `Option::None` as selected by the niche optimization for + // `LevelFilter`. If this is the case, converting a `usize` value into a + // `LevelFilter` (in `LevelFilter::current`) will be an identity conversion, + // rather than generating a lookup table. + const OFF_USIZE: usize = LevelInner::Error as usize + 1; + + /// Returns a `LevelFilter` that matches the most verbose [`Level`] that any + /// currently active [`Subscriber`] will enable. + /// + /// User code should treat this as a *hint*. If a given span or event has a + /// level *higher* than the returned `LevelFilter`, it will not be enabled. + /// However, if the level is less than or equal to this value, the span or + /// event is *not* guaranteed to be enabled; the subscriber will still + /// filter each callsite individually. + /// + /// Therefore, comparing a given span or event's level to the returned + /// `LevelFilter` **can** be used for determining if something is + /// *disabled*, but **should not** be used for determining if something is + /// *enabled*.` + /// + /// [`Level`]: ../struct.Level.html + /// [`Subscriber`]: ../../trait.Subscriber.html + #[inline(always)] + pub fn current() -> Self { + match MAX_LEVEL.load(Ordering::Relaxed) { + Self::ERROR_USIZE => Self::ERROR, + Self::WARN_USIZE => Self::WARN, + Self::INFO_USIZE => Self::INFO, + Self::DEBUG_USIZE => Self::DEBUG, + Self::TRACE_USIZE => Self::TRACE, + Self::OFF_USIZE => Self::OFF, + #[cfg(debug_assertions)] + unknown => unreachable!( + "/!\\ `LevelFilter` representation seems to have changed! /!\\ \n\ + This is a bug (and it's pretty bad). Please contact the `tracing` \ + maintainers. Thank you and I'm sorry.\n \ + The offending repr was: {:?}", + unknown, + ), + #[cfg(not(debug_assertions))] + _ => unsafe { + // Using `unreachable_unchecked` here (rather than + // `unreachable!()`) is necessary to ensure that rustc generates + // an identity conversion from integer -> discriminant, rather + // than generating a lookup table. We want to ensure this + // function is a single `mov` instruction (on x86) if at all + // possible, because it is called *every* time a span/event + // callsite is hit; and it is (potentially) the only code in the + // hottest path for skipping a majority of callsites when level + // filtering is in use. + // + // safety: This branch is only truly unreachable if we guarantee + // that no values other than the possible enum discriminants + // will *ever* be present. The `AtomicUsize` is initialized to + // the `OFF` value. It is only set by the `set_max` function, + // which takes a `LevelFilter` as a parameter. This restricts + // the inputs to `set_max` to the set of valid discriminants. + // Therefore, **as long as `MAX_VALUE` is only ever set by + // `set_max`**, this is safe. + crate::stdlib::hint::unreachable_unchecked() + }, + } + } + + pub(crate) fn set_max(LevelFilter(level): LevelFilter) { + let val = match level { + Some(Level(level)) => level as usize, + None => Self::OFF_USIZE, + }; + + // using an AcqRel swap ensures an ordered relationship of writes to the + // max level. + MAX_LEVEL.swap(val, Ordering::AcqRel); + } +} + +impl fmt::Display for LevelFilter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + LevelFilter::OFF => f.pad("off"), + LevelFilter::ERROR => f.pad("error"), + LevelFilter::WARN => f.pad("warn"), + LevelFilter::INFO => f.pad("info"), + LevelFilter::DEBUG => f.pad("debug"), + LevelFilter::TRACE => f.pad("trace"), + } + } +} + +impl fmt::Debug for LevelFilter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + LevelFilter::OFF => f.pad("LevelFilter::OFF"), + LevelFilter::ERROR => f.pad("LevelFilter::ERROR"), + LevelFilter::WARN => f.pad("LevelFilter::WARN"), + LevelFilter::INFO => f.pad("LevelFilter::INFO"), + LevelFilter::DEBUG => f.pad("LevelFilter::DEBUG"), + LevelFilter::TRACE => f.pad("LevelFilter::TRACE"), + } + } +} + +impl FromStr for LevelFilter { + type Err = ParseLevelFilterError; + fn from_str(from: &str) -> Result<Self, Self::Err> { + from.parse::<usize>() + .ok() + .and_then(|num| match num { + 0 => Some(LevelFilter::OFF), + 1 => Some(LevelFilter::ERROR), + 2 => Some(LevelFilter::WARN), + 3 => Some(LevelFilter::INFO), + 4 => Some(LevelFilter::DEBUG), + 5 => Some(LevelFilter::TRACE), + _ => None, + }) + .or_else(|| match from { + "" => Some(LevelFilter::ERROR), + s if s.eq_ignore_ascii_case("error") => Some(LevelFilter::ERROR), + s if s.eq_ignore_ascii_case("warn") => Some(LevelFilter::WARN), + s if s.eq_ignore_ascii_case("info") => Some(LevelFilter::INFO), + s if s.eq_ignore_ascii_case("debug") => Some(LevelFilter::DEBUG), + s if s.eq_ignore_ascii_case("trace") => Some(LevelFilter::TRACE), + s if s.eq_ignore_ascii_case("off") => Some(LevelFilter::OFF), + _ => None, + }) + .ok_or_else(|| ParseLevelFilterError(())) + } +} + +/// Returned if parsing a `Level` fails. +#[derive(Debug)] +pub struct ParseLevelError { + _p: (), +} + +impl fmt::Display for ParseLevelError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.pad( + "error parsing level: expected one of \"error\", \"warn\", \ + \"info\", \"debug\", \"trace\", or a number 1-5", + ) + } +} + +impl fmt::Display for ParseLevelFilterError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.pad( + "error parsing level filter: expected one of \"off\", \"error\", \ + \"warn\", \"info\", \"debug\", \"trace\", or a number 0-5", + ) + } +} + +#[cfg(feature = "std")] +impl std::error::Error for ParseLevelFilterError {} + +// ==== Level and LevelFilter comparisons ==== + +// /!\ BIG, IMPORTANT WARNING /!\ +// Do NOT mess with these implementations! They are hand-written for a reason! +// +// Since comparing `Level`s and `LevelFilter`s happens in a *very* hot path +// (potentially, every time a span or event macro is hit, regardless of whether +// or not is enabled), we *need* to ensure that these comparisons are as fast as +// possible. Therefore, we have some requirements: +// +// 1. We want to do our best to ensure that rustc will generate integer-integer +// comparisons wherever possible. +// +// The derived `Ord`/`PartialOrd` impls for `LevelFilter` will not do this, +// because `LevelFilter`s are represented by `Option<Level>`, rather than as +// a separate `#[repr(usize)]` enum. This was (unfortunately) necessary for +// backwards-compatibility reasons, as the `tracing` crate's original +// version of `LevelFilter` defined `const fn` conversions between `Level`s +// and `LevelFilter`, so we're stuck with the `Option<Level>` repr. +// Therefore, we need hand-written `PartialOrd` impls that cast both sides of +// the comparison to `usize`s, to force the compiler to generate integer +// compares. +// +// 2. The hottest `Level`/`LevelFilter` comparison, the one that happens every +// time a callsite is hit, occurs *within the `tracing` crate's macros*. +// This means that the comparison is happening *inside* a crate that +// *depends* on `tracing-core`, not in `tracing-core` itself. The compiler +// will only inline function calls across crate boundaries if the called +// function is annotated with an `#[inline]` attribute, and we *definitely* +// want the comparison functions to be inlined: as previously mentioned, they +// should compile down to a single integer comparison on release builds, and +// it seems really sad to push an entire stack frame to call a function +// consisting of one `cmp` instruction! +// +// Therefore, we need to ensure that all the comparison methods have +// `#[inline]` or `#[inline(always)]` attributes. It's not sufficient to just +// add the attribute to `partial_cmp` in a manual implementation of the +// trait, since it's the comparison operators (`lt`, `le`, `gt`, and `ge`) +// that will actually be *used*, and the default implementation of *those* +// methods, which calls `partial_cmp`, does not have an inline annotation. +// +// 3. We need the comparisons to be inverted. The discriminants for the +// `LevelInner` enum are assigned in "backwards" order, with `TRACE` having +// the *lowest* value. However, we want `TRACE` to compare greater-than all +// other levels. +// +// Why are the numeric values inverted? In order to ensure that `LevelFilter` +// (which, as previously mentioned, *has* to be internally represented by an +// `Option<Level>`) compiles down to a single integer value. This is +// necessary for storing the global max in an `AtomicUsize`, and for ensuring +// that we use fast integer-integer comparisons, as mentioned previously. In +// order to ensure this, we exploit the niche optimization. The niche +// optimization for `Option<{enum with a numeric repr}>` will choose +// `(HIGHEST_DISCRIMINANT_VALUE + 1)` as the representation for `None`. +// Therefore, the integer representation of `LevelFilter::OFF` (which is +// `None`) will be the number 5. `OFF` must compare higher than every other +// level in order for it to filter as expected. Since we want to use a single +// `cmp` instruction, we can't special-case the integer value of `OFF` to +// compare higher, as that will generate more code. Instead, we need it to be +// on one end of the enum, with `ERROR` on the opposite end, so we assign the +// value 0 to `ERROR`. +// +// This *does* mean that when parsing `LevelFilter`s or `Level`s from +// `String`s, the integer values are inverted, but that doesn't happen in a +// hot path. +// +// Note that we manually invert the comparisons by swapping the left-hand and +// right-hand side. Using `Ordering::reverse` generates significantly worse +// code (per Matt Godbolt's Compiler Explorer). +// +// Anyway, that's a brief history of why this code is the way it is. Don't +// change it unless you know what you're doing. + +impl PartialEq<LevelFilter> for Level { + #[inline(always)] + fn eq(&self, other: &LevelFilter) -> bool { + self.0 as usize == filter_as_usize(&other.0) + } +} + +impl PartialOrd for Level { + #[inline(always)] + fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> { + Some(self.cmp(other)) + } + + #[inline(always)] + fn lt(&self, other: &Level) -> bool { + (other.0 as usize) < (self.0 as usize) + } + + #[inline(always)] + fn le(&self, other: &Level) -> bool { + (other.0 as usize) <= (self.0 as usize) + } + + #[inline(always)] + fn gt(&self, other: &Level) -> bool { + (other.0 as usize) > (self.0 as usize) + } + + #[inline(always)] + fn ge(&self, other: &Level) -> bool { + (other.0 as usize) >= (self.0 as usize) + } +} + +impl Ord for Level { + #[inline(always)] + fn cmp(&self, other: &Self) -> cmp::Ordering { + (other.0 as usize).cmp(&(self.0 as usize)) + } +} + +impl PartialOrd<LevelFilter> for Level { + #[inline(always)] + fn partial_cmp(&self, other: &LevelFilter) -> Option<cmp::Ordering> { + Some(filter_as_usize(&other.0).cmp(&(self.0 as usize))) + } + + #[inline(always)] + fn lt(&self, other: &LevelFilter) -> bool { + filter_as_usize(&other.0) < (self.0 as usize) + } + + #[inline(always)] + fn le(&self, other: &LevelFilter) -> bool { + filter_as_usize(&other.0) <= (self.0 as usize) + } + + #[inline(always)] + fn gt(&self, other: &LevelFilter) -> bool { + filter_as_usize(&other.0) > (self.0 as usize) + } + + #[inline(always)] + fn ge(&self, other: &LevelFilter) -> bool { + filter_as_usize(&other.0) >= (self.0 as usize) + } +} + +#[inline(always)] +fn filter_as_usize(x: &Option<Level>) -> usize { + match x { + Some(Level(f)) => *f as usize, + None => LevelFilter::OFF_USIZE, + } +} + +impl PartialEq<Level> for LevelFilter { + #[inline(always)] + fn eq(&self, other: &Level) -> bool { + filter_as_usize(&self.0) == other.0 as usize + } +} + +impl PartialOrd for LevelFilter { + #[inline(always)] + fn partial_cmp(&self, other: &LevelFilter) -> Option<cmp::Ordering> { + Some(self.cmp(other)) + } + + #[inline(always)] + fn lt(&self, other: &LevelFilter) -> bool { + filter_as_usize(&other.0) < filter_as_usize(&self.0) + } + + #[inline(always)] + fn le(&self, other: &LevelFilter) -> bool { + filter_as_usize(&other.0) <= filter_as_usize(&self.0) + } + + #[inline(always)] + fn gt(&self, other: &LevelFilter) -> bool { + filter_as_usize(&other.0) > filter_as_usize(&self.0) + } + + #[inline(always)] + fn ge(&self, other: &LevelFilter) -> bool { + filter_as_usize(&other.0) >= filter_as_usize(&self.0) + } +} + +impl Ord for LevelFilter { + #[inline(always)] + fn cmp(&self, other: &Self) -> cmp::Ordering { + filter_as_usize(&other.0).cmp(&filter_as_usize(&self.0)) + } +} + +impl PartialOrd<Level> for LevelFilter { + #[inline(always)] + fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> { + Some((other.0 as usize).cmp(&filter_as_usize(&self.0))) + } + + #[inline(always)] + fn lt(&self, other: &Level) -> bool { + (other.0 as usize) < filter_as_usize(&self.0) + } + + #[inline(always)] + fn le(&self, other: &Level) -> bool { + (other.0 as usize) <= filter_as_usize(&self.0) + } + + #[inline(always)] + fn gt(&self, other: &Level) -> bool { + (other.0 as usize) > filter_as_usize(&self.0) + } + + #[inline(always)] + fn ge(&self, other: &Level) -> bool { + (other.0 as usize) >= filter_as_usize(&self.0) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::stdlib::mem; + + #[test] + fn level_from_str() { + assert_eq!("error".parse::<Level>().unwrap(), Level::ERROR); + assert_eq!("4".parse::<Level>().unwrap(), Level::DEBUG); + assert!("0".parse::<Level>().is_err()) + } + + #[test] + fn filter_level_conversion() { + let mapping = [ + (LevelFilter::OFF, None), + (LevelFilter::ERROR, Some(Level::ERROR)), + (LevelFilter::WARN, Some(Level::WARN)), + (LevelFilter::INFO, Some(Level::INFO)), + (LevelFilter::DEBUG, Some(Level::DEBUG)), + (LevelFilter::TRACE, Some(Level::TRACE)), + ]; + for (filter, level) in mapping.iter() { + assert_eq!(filter.clone().into_level(), *level); + match level { + Some(level) => { + let actual: LevelFilter = level.clone().into(); + assert_eq!(actual, *filter); + } + None => { + let actual: LevelFilter = None.into(); + assert_eq!(actual, *filter); + } + } + } + } + + #[test] + fn level_filter_is_usize_sized() { + assert_eq!( + mem::size_of::<LevelFilter>(), + mem::size_of::<usize>(), + "`LevelFilter` is no longer `usize`-sized! global MAX_LEVEL may now be invalid!" + ) + } + + #[test] + fn level_filter_reprs() { + let mapping = [ + (LevelFilter::OFF, LevelInner::Error as usize + 1), + (LevelFilter::ERROR, LevelInner::Error as usize), + (LevelFilter::WARN, LevelInner::Warn as usize), + (LevelFilter::INFO, LevelInner::Info as usize), + (LevelFilter::DEBUG, LevelInner::Debug as usize), + (LevelFilter::TRACE, LevelInner::Trace as usize), + ]; + for &(filter, expected) in &mapping { + let repr = unsafe { + // safety: The entire purpose of this test is to assert that the + // actual repr matches what we expect it to be --- we're testing + // that *other* unsafe code is sound using the transmuted value. + // We're not going to do anything with it that might be unsound. + mem::transmute::<LevelFilter, usize>(filter) + }; + assert_eq!(expected, repr, "repr changed for {:?}", filter) + } + } +} diff --git a/third_party/rust/tracing-core/src/parent.rs b/third_party/rust/tracing-core/src/parent.rs new file mode 100644 index 0000000000..cb34b376cc --- /dev/null +++ b/third_party/rust/tracing-core/src/parent.rs @@ -0,0 +1,11 @@ +use crate::span::Id; + +#[derive(Debug)] +pub(crate) enum Parent { + /// The new span will be a root span. + Root, + /// The new span will be rooted in the current span. + Current, + /// The new span has an explicitly-specified parent. + Explicit(Id), +} diff --git a/third_party/rust/tracing-core/src/span.rs b/third_party/rust/tracing-core/src/span.rs new file mode 100644 index 0000000000..6dfc41dca6 --- /dev/null +++ b/third_party/rust/tracing-core/src/span.rs @@ -0,0 +1,327 @@ +//! Spans represent periods of time in the execution of a program. +use crate::parent::Parent; +use crate::stdlib::num::NonZeroU64; +use crate::{field, Metadata}; + +/// Identifies a span within the context of a subscriber. +/// +/// They are generated by [`Subscriber`]s for each span as it is created, by +/// the [`new_span`] trait method. See the documentation for that method for +/// more information on span ID generation. +/// +/// [`Subscriber`]: ../subscriber/trait.Subscriber.html +/// [`new_span`]: ../subscriber/trait.Subscriber.html#method.new_span +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Id(NonZeroU64); + +/// Attributes provided to a `Subscriber` describing a new span when it is +/// created. +#[derive(Debug)] +pub struct Attributes<'a> { + metadata: &'static Metadata<'static>, + values: &'a field::ValueSet<'a>, + parent: Parent, +} + +/// A set of fields recorded by a span. +#[derive(Debug)] +pub struct Record<'a> { + values: &'a field::ValueSet<'a>, +} + +/// Indicates what [the `Subscriber` considers] the "current" span. +/// +/// As subscribers may not track a notion of a current span, this has three +/// possible states: +/// - "unknown", indicating that the subscriber does not track a current span, +/// - "none", indicating that the current context is known to not be in a span, +/// - "some", with the current span's [`Id`] and [`Metadata`]. +/// +/// [the `Subscriber` considers]: ../subscriber/trait.Subscriber.html#method.current_span +/// [`Id`]: struct.Id.html +/// [`Metadata`]: ../metadata/struct.Metadata.html +#[derive(Debug)] +pub struct Current { + inner: CurrentInner, +} + +#[derive(Debug)] +enum CurrentInner { + Current { + id: Id, + metadata: &'static Metadata<'static>, + }, + None, + Unknown, +} + +// ===== impl Span ===== + +impl Id { + /// Constructs a new span ID from the given `u64`. + /// + /// <div class="information"> + /// <div class="tooltip ignore" style="">ⓘ<span class="tooltiptext">Note</span></div> + /// </div> + /// <div class="example-wrap" style="display:inline-block"> + /// <pre class="ignore" style="white-space:normal;font:inherit;"> + /// <strong>Note</strong>: Span IDs must be greater than zero.</pre></div> + /// + /// # Panics + /// - If the provided `u64` is 0 + pub fn from_u64(u: u64) -> Self { + Id(NonZeroU64::new(u).expect("span IDs must be > 0")) + } + + /// Constructs a new span ID from the given `NonZeroU64`. + /// + /// Unlike [`Id::from_u64`](#method.from_u64), this will never panic. + #[inline] + pub const fn from_non_zero_u64(id: NonZeroU64) -> Self { + Id(id) + } + + // 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() + } + + // 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 `NonZeroU64`. + #[inline] + pub const fn into_non_zero_u64(&self) -> NonZeroU64 { + self.0 + } +} + +impl<'a> Into<Option<Id>> for &'a Id { + fn into(self) -> Option<Id> { + Some(self.clone()) + } +} + +// ===== impl Attributes ===== + +impl<'a> Attributes<'a> { + /// Returns `Attributes` describing a new child span of the current span, + /// with the provided metadata and values. + pub fn new(metadata: &'static Metadata<'static>, values: &'a field::ValueSet<'a>) -> Self { + Attributes { + metadata, + values, + parent: Parent::Current, + } + } + + /// Returns `Attributes` describing a new span at the root of its own trace + /// tree, with the provided metadata and values. + pub fn new_root(metadata: &'static Metadata<'static>, values: &'a field::ValueSet<'a>) -> Self { + Attributes { + metadata, + values, + parent: Parent::Root, + } + } + + /// Returns `Attributes` describing a new child span of the specified + /// parent span, with the provided metadata and values. + pub fn child_of( + parent: Id, + metadata: &'static Metadata<'static>, + values: &'a field::ValueSet<'a>, + ) -> Self { + Attributes { + metadata, + values, + parent: Parent::Explicit(parent), + } + } + + /// Returns a reference to the new span's metadata. + pub fn metadata(&self) -> &'static Metadata<'static> { + self.metadata + } + + /// Returns a reference to a `ValueSet` containing any values the new span + /// was created with. + pub fn values(&self) -> &field::ValueSet<'a> { + self.values + } + + /// Returns true if the new span should be a root. + pub fn is_root(&self) -> bool { + match self.parent { + Parent::Root => true, + _ => false, + } + } + + /// Returns true if the new span's parent should be determined based on the + /// current context. + /// + /// If this is true and the current thread is currently inside a span, then + /// that span should be the new span's parent. Otherwise, if the current + /// thread is _not_ inside a span, then the new span will be the root of its + /// own trace tree. + pub fn is_contextual(&self) -> bool { + match self.parent { + Parent::Current => true, + _ => false, + } + } + + /// Returns the new span's explicitly-specified parent, if there is one. + /// + /// Otherwise (if the new span is a root or is a child of the current span), + /// returns false. + pub fn parent(&self) -> Option<&Id> { + match self.parent { + Parent::Explicit(ref p) => Some(p), + _ => None, + } + } + + /// Records all the fields in this set of `Attributes` with the provided + /// [Visitor]. + /// + /// [visitor]: ../field/trait.Visit.html + pub fn record(&self, visitor: &mut dyn field::Visit) { + self.values.record(visitor) + } + + /// Returns `true` if this set of `Attributes` contains a value for the + /// given `Field`. + pub fn contains(&self, field: &field::Field) -> bool { + self.values.contains(field) + } + + /// Returns true if this set of `Attributes` contains _no_ values. + pub fn is_empty(&self) -> bool { + self.values.is_empty() + } +} + +// ===== impl Record ===== + +impl<'a> Record<'a> { + /// Constructs a new `Record` from a `ValueSet`. + pub fn new(values: &'a field::ValueSet<'a>) -> Self { + Self { values } + } + + /// Records all the fields in this `Record` with the provided [Visitor]. + /// + /// [visitor]: ../field/trait.Visit.html + pub fn record(&self, visitor: &mut dyn field::Visit) { + self.values.record(visitor) + } + + /// Returns `true` if this `Record` contains a value for the given `Field`. + pub fn contains(&self, field: &field::Field) -> bool { + self.values.contains(field) + } + + /// Returns true if this `Record` contains _no_ values. + pub fn is_empty(&self) -> bool { + self.values.is_empty() + } +} + +// ===== impl Current ===== + +impl Current { + /// Constructs a new `Current` that indicates the current context is a span + /// with the given `metadata` and `metadata`. + pub fn new(id: Id, metadata: &'static Metadata<'static>) -> Self { + Self { + inner: CurrentInner::Current { id, metadata }, + } + } + + /// Constructs a new `Current` that indicates the current context is *not* + /// in a span. + pub fn none() -> Self { + Self { + inner: CurrentInner::None, + } + } + + /// Constructs a new `Current` that indicates the `Subscriber` does not + /// track a current span. + pub(crate) fn unknown() -> Self { + Self { + inner: CurrentInner::Unknown, + } + } + + /// Returns `true` if the `Subscriber` that constructed this `Current` tracks a + /// current span. + /// + /// If this returns `true` and [`id`], [`metadata`], or [`into_inner`] + /// return `None`, that indicates that we are currently known to *not* be + /// inside a span. If this returns `false`, those methods will also return + /// `None`, but in this case, that is because the subscriber does not keep + /// track of the currently-entered span. + /// + /// [`id`]: #method.id + /// [`metadata`]: #method.metadata + /// [`into_inner`]: #method.into_inner + pub fn is_known(&self) -> bool { + match self.inner { + CurrentInner::Unknown => false, + _ => true, + } + } + + /// Consumes `self` and returns the span `Id` and `Metadata` of the current + /// span, if one exists and is known. + pub fn into_inner(self) -> Option<(Id, &'static Metadata<'static>)> { + match self.inner { + CurrentInner::Current { id, metadata } => Some((id, metadata)), + _ => None, + } + } + + /// Borrows the `Id` of the current span, if one exists and is known. + pub fn id(&self) -> Option<&Id> { + match self.inner { + CurrentInner::Current { ref id, .. } => Some(id), + _ => None, + } + } + + /// Borrows the `Metadata` of the current span, if one exists and is known. + pub fn metadata(&self) -> Option<&'static Metadata<'static>> { + match self.inner { + CurrentInner::Current { ref metadata, .. } => Some(*metadata), + _ => None, + } + } +} + +impl<'a> Into<Option<&'a Id>> for &'a Current { + fn into(self) -> Option<&'a Id> { + self.id() + } +} + +impl<'a> Into<Option<Id>> for &'a Current { + fn into(self) -> Option<Id> { + self.id().cloned() + } +} + +impl Into<Option<Id>> for Current { + fn into(self) -> Option<Id> { + self.id().cloned() + } +} + +impl<'a> Into<Option<&'static Metadata<'static>>> for &'a Current { + fn into(self) -> Option<&'static Metadata<'static>> { + self.metadata() + } +} diff --git a/third_party/rust/tracing-core/src/spin/LICENSE b/third_party/rust/tracing-core/src/spin/LICENSE new file mode 100644 index 0000000000..84d5f4d7af --- /dev/null +++ b/third_party/rust/tracing-core/src/spin/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Mathijs van de Nes + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third_party/rust/tracing-core/src/spin/mod.rs b/third_party/rust/tracing-core/src/spin/mod.rs new file mode 100644 index 0000000000..148b192b34 --- /dev/null +++ b/third_party/rust/tracing-core/src/spin/mod.rs @@ -0,0 +1,7 @@ +//! Synchronization primitives based on spinning + +pub(crate) use mutex::*; +pub(crate) use once::Once; + +mod mutex; +mod once; diff --git a/third_party/rust/tracing-core/src/spin/mutex.rs b/third_party/rust/tracing-core/src/spin/mutex.rs new file mode 100644 index 0000000000..383a2cd839 --- /dev/null +++ b/third_party/rust/tracing-core/src/spin/mutex.rs @@ -0,0 +1,109 @@ +use core::cell::UnsafeCell; +use core::default::Default; +use core::fmt; +use core::marker::Sync; +use core::ops::{Deref, DerefMut, Drop}; +use core::option::Option::{self, None, Some}; +use core::sync::atomic::{spin_loop_hint as cpu_relax, AtomicBool, Ordering}; + +/// This type provides MUTual EXclusion based on spinning. +pub(crate) struct Mutex<T: ?Sized> { + lock: AtomicBool, + data: UnsafeCell<T>, +} + +/// A guard to which the protected data can be accessed +/// +/// When the guard falls out of scope it will release the lock. +#[derive(Debug)] +pub(crate) struct MutexGuard<'a, T: ?Sized> { + lock: &'a AtomicBool, + data: &'a mut T, +} + +// Same unsafe impls as `std::sync::Mutex` +unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {} +unsafe impl<T: ?Sized + Send> Send for Mutex<T> {} + +impl<T> Mutex<T> { + /// Creates a new spinlock wrapping the supplied data. + pub(crate) const fn new(user_data: T) -> Mutex<T> { + Mutex { + lock: AtomicBool::new(false), + data: UnsafeCell::new(user_data), + } + } +} + +impl<T: ?Sized> Mutex<T> { + fn obtain_lock(&self) { + while self.lock.compare_and_swap(false, true, Ordering::Acquire) != false { + // Wait until the lock looks unlocked before retrying + while self.lock.load(Ordering::Relaxed) { + cpu_relax(); + } + } + } + + /// Locks the spinlock and returns a guard. + /// + /// The returned value may be dereferenced for data access + /// and the lock will be dropped when the guard falls out of scope. + pub(crate) fn lock(&self) -> MutexGuard<'_, T> { + self.obtain_lock(); + MutexGuard { + lock: &self.lock, + data: unsafe { &mut *self.data.get() }, + } + } + + /// Tries to lock the mutex. If it is already locked, it will return None. Otherwise it returns + /// a guard within Some. + pub(crate) fn try_lock(&self) -> Option<MutexGuard<'_, T>> { + if self.lock.compare_and_swap(false, true, Ordering::Acquire) == false { + Some(MutexGuard { + lock: &self.lock, + data: unsafe { &mut *self.data.get() }, + }) + } else { + None + } + } +} + +impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.try_lock() { + Some(guard) => write!(f, "Mutex {{ data: ") + .and_then(|()| (&*guard).fmt(f)) + .and_then(|()| write!(f, "}}")), + None => write!(f, "Mutex {{ <locked> }}"), + } + } +} + +impl<T: ?Sized + Default> Default for Mutex<T> { + fn default() -> Mutex<T> { + Mutex::new(Default::default()) + } +} + +impl<'a, T: ?Sized> Deref for MutexGuard<'a, T> { + type Target = T; + fn deref<'b>(&'b self) -> &'b T { + &*self.data + } +} + +impl<'a, T: ?Sized> DerefMut for MutexGuard<'a, T> { + fn deref_mut<'b>(&'b mut self) -> &'b mut T { + &mut *self.data + } +} + +impl<'a, T: ?Sized> Drop for MutexGuard<'a, T> { + /// The dropping of the MutexGuard will release the lock it was created from. + fn drop(&mut self) { + self.lock.store(false, Ordering::Release); + } +} diff --git a/third_party/rust/tracing-core/src/spin/once.rs b/third_party/rust/tracing-core/src/spin/once.rs new file mode 100644 index 0000000000..0bc47b566a --- /dev/null +++ b/third_party/rust/tracing-core/src/spin/once.rs @@ -0,0 +1,146 @@ +use core::cell::UnsafeCell; +use core::fmt; +use core::sync::atomic::{spin_loop_hint as cpu_relax, AtomicUsize, Ordering}; + +/// A synchronization primitive which can be used to run a one-time global +/// initialization. Unlike its std equivalent, this is generalized so that the +/// closure returns a value and it is stored. Once therefore acts something like +/// a future, too. +pub struct Once<T> { + state: AtomicUsize, + data: UnsafeCell<Option<T>>, // TODO remove option and use mem::uninitialized +} + +impl<T: fmt::Debug> fmt::Debug for Once<T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.r#try() { + Some(s) => write!(f, "Once {{ data: ") + .and_then(|()| s.fmt(f)) + .and_then(|()| write!(f, "}}")), + None => write!(f, "Once {{ <uninitialized> }}"), + } + } +} + +// Same unsafe impls as `std::sync::RwLock`, because this also allows for +// concurrent reads. +unsafe impl<T: Send + Sync> Sync for Once<T> {} +unsafe impl<T: Send> Send for Once<T> {} + +// Four states that a Once can be in, encoded into the lower bits of `state` in +// the Once structure. +const INCOMPLETE: usize = 0x0; +const RUNNING: usize = 0x1; +const COMPLETE: usize = 0x2; +const PANICKED: usize = 0x3; + +use core::hint::unreachable_unchecked as unreachable; + +impl<T> Once<T> { + /// Initialization constant of `Once`. + pub const INIT: Self = Once { + state: AtomicUsize::new(INCOMPLETE), + data: UnsafeCell::new(None), + }; + + /// Creates a new `Once` value. + pub const fn new() -> Once<T> { + Self::INIT + } + + fn force_get<'a>(&'a self) -> &'a T { + match unsafe { &*self.data.get() }.as_ref() { + None => unsafe { unreachable() }, + Some(p) => p, + } + } + + /// Performs an initialization routine once and only once. The given closure + /// will be executed if this is the first time `call_once` has been called, + /// and otherwise the routine will *not* be invoked. + /// + /// This method will block the calling thread if another initialization + /// routine is currently running. + /// + /// When this function returns, it is guaranteed that some initialization + /// has run and completed (it may not be the closure specified). The + /// returned pointer will point to the result from the closure that was + /// run. + pub fn call_once<'a, F>(&'a self, builder: F) -> &'a T + where + F: FnOnce() -> T, + { + let mut status = self.state.load(Ordering::SeqCst); + + if status == INCOMPLETE { + status = self + .state + .compare_and_swap(INCOMPLETE, RUNNING, Ordering::SeqCst); + if status == INCOMPLETE { + // We init + // We use a guard (Finish) to catch panics caused by builder + let mut finish = Finish { + state: &self.state, + panicked: true, + }; + unsafe { *self.data.get() = Some(builder()) }; + finish.panicked = false; + + status = COMPLETE; + self.state.store(status, Ordering::SeqCst); + + // This next line is strictly an optimization + return self.force_get(); + } + } + + loop { + match status { + INCOMPLETE => unreachable!(), + RUNNING => { + // We spin + cpu_relax(); + status = self.state.load(Ordering::SeqCst) + } + PANICKED => panic!("Once has panicked"), + COMPLETE => return self.force_get(), + _ => unsafe { unreachable() }, + } + } + } + + /// Returns a pointer iff the `Once` was previously initialized + pub fn r#try<'a>(&'a self) -> Option<&'a T> { + match self.state.load(Ordering::SeqCst) { + COMPLETE => Some(self.force_get()), + _ => None, + } + } + + /// Like try, but will spin if the `Once` is in the process of being + /// initialized + pub fn wait<'a>(&'a self) -> Option<&'a T> { + loop { + match self.state.load(Ordering::SeqCst) { + INCOMPLETE => return None, + RUNNING => cpu_relax(), // We spin + COMPLETE => return Some(self.force_get()), + PANICKED => panic!("Once has panicked"), + _ => unsafe { unreachable() }, + } + } + } +} + +struct Finish<'a> { + state: &'a AtomicUsize, + panicked: bool, +} + +impl<'a> Drop for Finish<'a> { + fn drop(&mut self) { + if self.panicked { + self.state.store(PANICKED, Ordering::SeqCst); + } + } +} diff --git a/third_party/rust/tracing-core/src/stdlib.rs b/third_party/rust/tracing-core/src/stdlib.rs new file mode 100644 index 0000000000..4a1c17c2b8 --- /dev/null +++ b/third_party/rust/tracing-core/src/stdlib.rs @@ -0,0 +1,78 @@ +//! Re-exports either the Rust `std` library or `core` and `alloc` when `std` is +//! disabled. +//! +//! `crate::stdlib::...` should be used rather than `std::` when adding code that +//! will be available with the standard library disabled. +//! +//! Note that this module is called `stdlib` rather than `std`, as Rust 1.34.0 +//! does not permit redefining the name `stdlib` (although this works on the +//! latest stable Rust). +#[cfg(feature = "std")] +pub(crate) use std::*; + +#[cfg(not(feature = "std"))] +pub(crate) use self::no_std::*; + +#[cfg(not(feature = "std"))] +mod no_std { + // We pre-emptively export everything from libcore/liballoc, (even modules + // we aren't using currently) to make adding new code easier. Therefore, + // some of these imports will be unused. + #![allow(unused_imports)] + + pub(crate) use core::{ + any, array, ascii, cell, char, clone, cmp, convert, default, f32, f64, ffi, future, hash, + hint, i128, i16, i8, isize, iter, marker, mem, num, ops, option, pin, ptr, result, task, + time, u128, u16, u32, u8, usize, + }; + + pub(crate) use alloc::{boxed, collections, rc, string, vec}; + + pub(crate) mod borrow { + pub(crate) use alloc::borrow::*; + pub(crate) use core::borrow::*; + } + + pub(crate) mod fmt { + pub(crate) use alloc::fmt::*; + pub(crate) use core::fmt::*; + } + + pub(crate) mod slice { + pub(crate) use alloc::slice::*; + pub(crate) use core::slice::*; + } + + pub(crate) mod str { + pub(crate) use alloc::str::*; + pub(crate) use core::str::*; + } + + pub(crate) mod sync { + pub(crate) use crate::spin::MutexGuard; + pub(crate) use alloc::sync::*; + pub(crate) use core::sync::*; + + /// This wraps `spin::Mutex` to return a `Result`, so that it can be + /// used with code written against `std::sync::Mutex`. + /// + /// Since `spin::Mutex` doesn't support poisoning, the `Result` returned + /// by `lock` will always be `Ok`. + #[derive(Debug, Default)] + pub(crate) struct Mutex<T> { + inner: crate::spin::Mutex<T>, + } + + impl<T> Mutex<T> { + pub(crate) fn new(data: T) -> Self { + Self { + inner: crate::spin::Mutex::new(data), + } + } + + pub(crate) fn lock(&self) -> Result<MutexGuard<'_, T>, ()> { + Ok(self.inner.lock()) + } + } + } +} diff --git a/third_party/rust/tracing-core/src/subscriber.rs b/third_party/rust/tracing-core/src/subscriber.rs new file mode 100644 index 0000000000..2b56f8d483 --- /dev/null +++ b/third_party/rust/tracing-core/src/subscriber.rs @@ -0,0 +1,570 @@ +//! Subscribers collect and record trace data. +use crate::{span, Event, LevelFilter, Metadata}; + +use crate::stdlib::any::{Any, TypeId}; + +/// Trait representing the functions required to collect trace data. +/// +/// Crates that provide implementations of methods for collecting or recording +/// trace data should implement the `Subscriber` interface. This trait is +/// intended to represent fundamental primitives for collecting trace events and +/// spans — other libraries may offer utility functions and types to make +/// subscriber implementations more modular or improve the ergonomics of writing +/// subscribers. +/// +/// A subscriber is responsible for the following: +/// - Registering new spans as they are created, and providing them with span +/// IDs. Implicitly, this means the subscriber may determine the strategy for +/// determining span equality. +/// - Recording the attachment of field values and follows-from annotations to +/// spans. +/// - Filtering spans and events, and determining when those filters must be +/// invalidated. +/// - Observing spans as they are entered, exited, and closed, and events as +/// they occur. +/// +/// When a span is entered or exited, the subscriber is provided only with the +/// [ID] with which it tagged that span when it was created. This means +/// that it is up to the subscriber to determine whether and how span _data_ — +/// the fields and metadata describing the span — should be stored. The +/// [`new_span`] function is called when a new span is created, and at that +/// point, the subscriber _may_ choose to store the associated data if it will +/// be referenced again. However, if the data has already been recorded and will +/// not be needed by the implementations of `enter` and `exit`, the subscriber +/// may freely discard that data without allocating space to store it. +/// +/// ## Overriding default impls +/// +/// Some trait methods on `Subscriber` have default implementations, either in +/// order to reduce the surface area of implementing `Subscriber`, or for +/// backward-compatibility reasons. However, many subscribers will likely want +/// to override these default implementations. +/// +/// The following methods are likely of interest: +/// +/// - [`register_callsite`] is called once for each callsite from which a span +/// event may originate, and returns an [`Interest`] value describing whether or +/// not the subscriber wishes to see events or spans from that callsite. By +/// default, it calls [`enabled`], and returns `Interest::always()` if +/// `enabled` returns true, or `Interest::never()` if enabled returns false. +/// However, if the subscriber's interest can change dynamically at runtime, +/// it may want to override this function to return `Interest::sometimes()`. +/// Additionally, subscribers which wish to perform a behaviour once for each +/// callsite, such as allocating storage for data related to that callsite, +/// can perform it in `register_callsite`. +/// - [`clone_span`] is called every time a span ID is cloned, and [`try_close`] +/// is called when a span ID is dropped. By default, these functions do +/// nothing. However, they can be used to implement reference counting for +/// spans, allowing subscribers to free storage for span data and to determine +/// when a span has _closed_ permanently (rather than being exited). +/// Subscribers which store per-span data or which need to track span closures +/// should override these functions together. +/// +/// [ID]: ../span/struct.Id.html +/// [`new_span`]: trait.Subscriber.html#method.new_span +/// [`register_callsite`]: trait.Subscriber.html#method.register_callsite +/// [`Interest`]: struct.Interest.html +/// [`enabled`]: trait.Subscriber.html#method.enabled +/// [`clone_span`]: trait.Subscriber.html#method.clone_span +/// [`try_close`]: trait.Subscriber.html#method.try_close +pub trait Subscriber: 'static { + // === Span registry methods ============================================== + + /// Registers a new callsite with this subscriber, returning whether or not + /// the subscriber is interested in being notified about the callsite. + /// + /// By default, this function assumes that the subscriber's [filter] + /// represents an unchanging view of its interest in the callsite. However, + /// if this is not the case, subscribers may override this function to + /// indicate different interests, or to implement behaviour that should run + /// once for every callsite. + /// + /// This function is guaranteed to be called at least once per callsite on + /// every active subscriber. The subscriber may store the keys to fields it + /// cares about in order to reduce the cost of accessing fields by name, + /// preallocate storage for that callsite, or perform any other actions it + /// wishes to perform once for each callsite. + /// + /// The subscriber should then return an [`Interest`], indicating + /// whether it is interested in being notified about that callsite in the + /// future. This may be `Always` indicating that the subscriber always + /// wishes to be notified about the callsite, and its filter need not be + /// re-evaluated; `Sometimes`, indicating that the subscriber may sometimes + /// care about the callsite but not always (such as when sampling), or + /// `Never`, indicating that the subscriber never wishes to be notified about + /// that callsite. If all active subscribers return `Never`, a callsite will + /// never be enabled unless a new subscriber expresses interest in it. + /// + /// `Subscriber`s which require their filters to be run every time an event + /// occurs or a span is entered/exited should return `Interest::sometimes`. + /// If a subscriber returns `Interest::sometimes`, then its' [`enabled`] method + /// will be called every time an event or span is created from that callsite. + /// + /// For example, suppose a sampling subscriber is implemented by + /// incrementing a counter every time `enabled` is called and only returning + /// `true` when the counter is divisible by a specified sampling rate. If + /// that subscriber returns `Interest::always` from `register_callsite`, then + /// the filter will not be re-evaluated once it has been applied to a given + /// set of metadata. Thus, the counter will not be incremented, and the span + /// or event that corresponds to the metadata will never be `enabled`. + /// + /// `Subscriber`s that need to change their filters occasionally should call + /// [`rebuild_interest_cache`] to re-evaluate `register_callsite` for all + /// callsites. + /// + /// Similarly, if a `Subscriber` has a filtering strategy that can be + /// changed dynamically at runtime, it would need to re-evaluate that filter + /// if the cached results have changed. + /// + /// A subscriber which manages fanout to multiple other subscribers + /// should proxy this decision to all of its child subscribers, + /// returning `Interest::never` only if _all_ such children return + /// `Interest::never`. If the set of subscribers to which spans are + /// broadcast may change dynamically, the subscriber should also never + /// return `Interest::Never`, as a new subscriber may be added that _is_ + /// interested. + /// + /// # Notes + /// This function may be called again when a new subscriber is created or + /// when the registry is invalidated. + /// + /// If a subscriber returns `Interest::never` for a particular callsite, it + /// _may_ still see spans and events originating from that callsite, if + /// another subscriber expressed interest in it. + /// + /// [filter]: #method.enabled + /// [metadata]: ../metadata/struct.Metadata.html + /// [`Interest`]: struct.Interest.html + /// [`enabled`]: #method.enabled + /// [`rebuild_interest_cache`]: ../callsite/fn.rebuild_interest_cache.html + fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest { + if self.enabled(metadata) { + Interest::always() + } else { + Interest::never() + } + } + + /// Returns true if a span or event with the specified [metadata] would be + /// recorded. + /// + /// By default, it is assumed that this filter needs only be evaluated once + /// for each callsite, so it is called by [`register_callsite`] when each + /// callsite is registered. The result is used to determine if the subscriber + /// is always [interested] or never interested in that callsite. This is intended + /// primarily as an optimization, so that expensive filters (such as those + /// involving string search, et cetera) need not be re-evaluated. + /// + /// However, if the subscriber's interest in a particular span or event may + /// change, or depends on contexts only determined dynamically at runtime, + /// then the `register_callsite` method should be overridden to return + /// [`Interest::sometimes`]. In that case, this function will be called every + /// time that span or event occurs. + /// + /// [metadata]: ../metadata/struct.Metadata.html + /// [interested]: struct.Interest.html + /// [`Interest::sometimes`]: struct.Interest.html#method.sometimes + /// [`register_callsite`]: #method.register_callsite + fn enabled(&self, metadata: &Metadata<'_>) -> bool; + + /// Returns the highest [verbosity level][level] that this `Subscriber` will + /// enable, or `None`, if the subscriber does not implement level-based + /// filtering or chooses not to implement this method. + /// + /// If this method returns a [`Level`][level], it will be used as a hint to + /// determine the most verbose level that will be enabled. This will allow + /// spans and events which are more verbose than that level to be skipped + /// more efficiently. Subscribers which perform filtering are strongly + /// encouraged to provide an implementation of this method. + /// + /// If the maximum level the subscriber will enable can change over the + /// course of its lifetime, it is free to return a different value from + /// multiple invocations of this method. However, note that changes in the + /// maximum level will **only** be reflected after the callsite [`Interest`] + /// cache is rebuilt, by calling the [`callsite::rebuild_interest_cache`][rebuild] + /// function. Therefore, if the subscriber will change the value returned by + /// this method, it is responsible for ensuring that + /// [`rebuild_interest_cache`][rebuild] is called after the value of the max + /// level changes. + /// + /// [level]: ../struct.Level.html + /// [`Interest`]: struct.Interest.html + /// [rebuild]: ../callsite/fn.rebuild_interest_cache.html + fn max_level_hint(&self) -> Option<LevelFilter> { + None + } + + /// Visit the construction of a new span, returning a new [span ID] for the + /// span being constructed. + /// + /// The provided [`Attributes`] contains any field values that were provided + /// when the span was created. The subscriber may pass a [visitor] to the + /// `Attributes`' [`record` method] to record these values. + /// + /// IDs are used to uniquely identify spans and events within the context of a + /// subscriber, so span equality will be based on the returned ID. Thus, if + /// the subscriber wishes for all spans with the same metadata to be + /// considered equal, it should return the same ID every time it is given a + /// particular set of metadata. Similarly, if it wishes for two separate + /// instances of a span with the same metadata to *not* be equal, it should + /// return a distinct ID every time this function is called, regardless of + /// the metadata. + /// + /// Note that the subscriber is free to assign span IDs based on whatever + /// scheme it sees fit. Any guarantees about uniqueness, ordering, or ID + /// reuse are left up to the subscriber implementation to determine. + /// + /// [span ID]: ../span/struct.Id.html + /// [`Attributes`]: ../span/struct.Attributes.html + /// [visitor]: ../field/trait.Visit.html + /// [`record` method]: ../span/struct.Attributes.html#method.record + fn new_span(&self, span: &span::Attributes<'_>) -> span::Id; + + // === Notification methods =============================================== + + /// Record a set of values on a span. + /// + /// This method will be invoked when value is recorded on a span. + /// Recording multiple values for the same field is possible, + /// but the actual behaviour is defined by the subscriber implementation. + /// + /// Keep in mind that a span might not provide a value + /// for each field it declares. + /// + /// The subscriber is expected to provide a [visitor] to the `Record`'s + /// [`record` method] in order to record the added values. + /// + /// # Example + /// "foo = 3" will be recorded when [`record`] is called on the + /// `Attributes` passed to `new_span`. + /// Since values are not provided for the `bar` and `baz` fields, + /// the span's `Metadata` will indicate that it _has_ those fields, + /// but values for them won't be recorded at this time. + /// + /// ```rust,ignore + /// #[macro_use] + /// extern crate tracing; + /// + /// let mut span = span!("my_span", foo = 3, bar, baz); + /// + /// // `Subscriber::record` will be called with a `Record` + /// // containing "bar = false" + /// span.record("bar", &false); + /// + /// // `Subscriber::record` will be called with a `Record` + /// // containing "baz = "a string"" + /// span.record("baz", &"a string"); + /// ``` + /// + /// [visitor]: ../field/trait.Visit.html + /// [`record`]: ../span/struct.Attributes.html#method.record + /// [`record` method]: ../span/struct.Record.html#method.record + fn record(&self, span: &span::Id, values: &span::Record<'_>); + + /// Adds an indication that `span` follows from the span with the id + /// `follows`. + /// + /// This relationship differs somewhat from the parent-child relationship: a + /// span may have any number of prior spans, rather than a single one; and + /// spans are not considered to be executing _inside_ of the spans they + /// follow from. This means that a span may close even if subsequent spans + /// that follow from it are still open, and time spent inside of a + /// subsequent span should not be included in the time its precedents were + /// executing. This is used to model causal relationships such as when a + /// single future spawns several related background tasks, et cetera. + /// + /// If the subscriber has spans corresponding to the given IDs, it should + /// record this relationship in whatever way it deems necessary. Otherwise, + /// if one or both of the given span IDs do not correspond to spans that the + /// subscriber knows about, or if a cyclical relationship would be created + /// (i.e., some span _a_ which proceeds some other span _b_ may not also + /// follow from _b_), it may silently do nothing. + fn record_follows_from(&self, span: &span::Id, follows: &span::Id); + + /// Records that an [`Event`] has occurred. + /// + /// This method will be invoked when an Event is constructed by + /// the `Event`'s [`dispatch` method]. For example, this happens internally + /// when an event macro from `tracing` is called. + /// + /// The key difference between this method and `record` is that `record` is + /// called when a value is recorded for a field defined by a span, + /// while `event` is called when a new event occurs. + /// + /// The provided `Event` struct contains any field values attached to the + /// event. The subscriber may pass a [visitor] to the `Event`'s + /// [`record` method] to record these values. + /// + /// [`Event`]: ../event/struct.Event.html + /// [visitor]: ../field/trait.Visit.html + /// [`record` method]: ../event/struct.Event.html#method.record + /// [`dispatch` method]: ../event/struct.Event.html#method.dispatch + fn event(&self, event: &Event<'_>); + + /// Records that a span has been entered. + /// + /// When entering a span, this method is called to notify the subscriber + /// that the span has been entered. The subscriber is provided with the + /// [span ID] of the entered span, and should update any internal state + /// tracking the current span accordingly. + /// + /// [span ID]: ../span/struct.Id.html + fn enter(&self, span: &span::Id); + + /// Records that a span has been exited. + /// + /// When exiting a span, this method is called to notify the subscriber + /// that the span has been exited. The subscriber is provided with the + /// [span ID] of the exited span, and should update any internal state + /// tracking the current span accordingly. + /// + /// Exiting a span does not imply that the span will not be re-entered. + /// + /// [span ID]: ../span/struct.Id.html + fn exit(&self, span: &span::Id); + + /// Notifies the subscriber that a [span ID] has been cloned. + /// + /// This function is guaranteed to only be called with span IDs that were + /// returned by this subscriber's `new_span` function. + /// + /// Note that the default implementation of this function this is just the + /// identity function, passing through the identifier. However, it can be + /// used in conjunction with [`try_close`] to track the number of handles + /// capable of `enter`ing a span. When all the handles have been dropped + /// (i.e., `try_close` has been called one more time than `clone_span` for a + /// given ID), the subscriber may assume that the span will not be entered + /// again. It is then free to deallocate storage for data associated with + /// that span, write data from that span to IO, and so on. + /// + /// For more unsafe situations, however, if `id` is itself a pointer of some + /// kind this can be used as a hook to "clone" the pointer, depending on + /// what that means for the specified pointer. + /// + /// [span ID]: ../span/struct.Id.html + /// [`try_close`]: trait.Subscriber.html#method.try_close + fn clone_span(&self, id: &span::Id) -> span::Id { + id.clone() + } + + /// **This method is deprecated.** + /// + /// Using `drop_span` may result in subscribers composed using + /// `tracing-subscriber` crate's `Layer` trait from observing close events. + /// Use [`try_close`] instead. + /// + /// The default implementation of this function does nothing. + /// + /// [`try_close`]: trait.Subscriber.html#method.try_close + #[deprecated(since = "0.1.2", note = "use `Subscriber::try_close` instead")] + fn drop_span(&self, _id: span::Id) {} + + /// Notifies the subscriber that a [`span ID`] has been dropped, and returns + /// `true` if there are now 0 IDs that refer to that span. + /// + /// Higher-level libraries providing functionality for composing multiple + /// subscriber implementations may use this return value to notify any + /// "layered" subscribers that this subscriber considers the span closed. + /// + /// The default implementation of this method calls the subscriber's + /// [`drop_span`] method and returns `false`. This means that, unless the + /// subscriber overrides the default implementation, close notifications + /// will never be sent to any layered subscribers. In general, if the + /// subscriber tracks reference counts, this method should be implemented, + /// rather than `drop_span`. + /// + /// This function is guaranteed to only be called with span IDs that were + /// returned by this subscriber's `new_span` function. + /// + /// It's guaranteed that if this function has been called once more than the + /// number of times `clone_span` was called with the same `id`, then no more + /// handles that can enter the span with that `id` exist. This means that it + /// can be used in conjunction with [`clone_span`] to track the number of + /// handles capable of `enter`ing a span. When all the handles have been + /// dropped (i.e., `try_close` has been called one more time than + /// `clone_span` for a given ID), the subscriber may assume that the span + /// will not be entered again, and should return `true`. It is then free to + /// deallocate storage for data associated with that span, write data from + /// that span to IO, and so on. + /// + /// **Note**: since this function is called when spans are dropped, + /// implementations should ensure that they are unwind-safe. Panicking from + /// inside of a `try_close` function may cause a double panic, if the span + /// was dropped due to a thread unwinding. + /// + /// [span ID]: ../span/struct.Id.html + /// [`clone_span`]: trait.Subscriber.html#method.clone_span + /// [`drop_span`]: trait.Subscriber.html#method.drop_span + fn try_close(&self, id: span::Id) -> bool { + #[allow(deprecated)] + self.drop_span(id); + false + } + + /// Returns a type representing this subscriber's view of the current span. + /// + /// If subscribers track a current span, they should override this function + /// to return [`Current::new`] if the thread from which this method is + /// called is inside a span, or [`Current::none`] if the thread is not + /// inside a span. + /// + /// By default, this returns a value indicating that the subscriber + /// does **not** track what span is current. If the subscriber does not + /// implement a current span, it should not override this method. + /// + /// [`Current::new`]: ../span/struct.Current.html#tymethod.new + /// [`Current::none`]: ../span/struct.Current.html#tymethod.none + fn current_span(&self) -> span::Current { + span::Current::unknown() + } + + // === Downcasting methods ================================================ + + /// If `self` is the same type as the provided `TypeId`, returns an untyped + /// `*const` pointer to that type. Otherwise, returns `None`. + /// + /// If you wish to downcast a `Subscriber`, it is strongly advised to use + /// the safe API provided by [`downcast_ref`] instead. + /// + /// This API is required for `downcast_raw` to be a trait method; a method + /// signature like [`downcast_ref`] (with a generic type parameter) is not + /// object-safe, and thus cannot be a trait method for `Subscriber`. This + /// means that if we only exposed `downcast_ref`, `Subscriber` + /// implementations could not override the downcasting behavior + /// + /// This method may be overridden by "fan out" or "chained" subscriber + /// implementations which consist of multiple composed types. Such + /// subscribers might allow `downcast_raw` by returning references to those + /// component if they contain components with the given `TypeId`. + /// + /// # Safety + /// + /// The [`downcast_ref`] method expects that the pointer returned by + /// `downcast_raw` is non-null and points to a valid instance of the type + /// with the provided `TypeId`. Failure to ensure this will result in + /// undefined behaviour, so implementing `downcast_raw` is unsafe. + /// + /// [`downcast_ref`]: #method.downcast_ref + unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> { + if id == TypeId::of::<Self>() { + Some(self as *const Self as *const ()) + } else { + None + } + } +} + +impl dyn Subscriber { + /// Returns `true` if this `Subscriber` is the same type as `T`. + pub fn is<T: Any>(&self) -> bool { + self.downcast_ref::<T>().is_some() + } + + /// Returns some reference to this `Subscriber` value if it is of type `T`, + /// or `None` if it isn't. + pub fn downcast_ref<T: Any>(&self) -> Option<&T> { + unsafe { + let raw = self.downcast_raw(TypeId::of::<T>())?; + if raw.is_null() { + None + } else { + Some(&*(raw as *const _)) + } + } + } +} + +/// Indicates a [`Subscriber`]'s interest in a particular callsite. +/// +/// `Subscriber`s return an `Interest` from their [`register_callsite`] methods +/// in order to determine whether that span should be enabled or disabled. +/// +/// [`Subscriber`]: ../trait.Subscriber.html +/// [`register_callsite`]: ../trait.Subscriber.html#method.register_callsite +#[derive(Clone, Debug)] +pub struct Interest(InterestKind); + +#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] +enum InterestKind { + Never = 0, + Sometimes = 1, + Always = 2, +} + +impl Interest { + /// Returns an `Interest` indicating that the subscriber is never interested + /// in being notified about a callsite. + /// + /// If all active subscribers are `never()` interested in a callsite, it will + /// be completely disabled unless a new subscriber becomes active. + #[inline] + pub fn never() -> Self { + Interest(InterestKind::Never) + } + + /// Returns an `Interest` indicating the subscriber is sometimes interested + /// in being notified about a callsite. + /// + /// If all active subscribers are `sometimes` or `never` interested in a + /// callsite, the currently active subscriber will be asked to filter that + /// callsite every time it creates a span. This will be the case until a new + /// subscriber expresses that it is `always` interested in the callsite. + #[inline] + pub fn sometimes() -> Self { + Interest(InterestKind::Sometimes) + } + + /// Returns an `Interest` indicating the subscriber is always interested in + /// being notified about a callsite. + /// + /// If any subscriber expresses that it is `always()` interested in a given + /// callsite, then the callsite will always be enabled. + #[inline] + pub fn always() -> Self { + Interest(InterestKind::Always) + } + + /// Returns `true` if the subscriber is never interested in being notified + /// about this callsite. + #[inline] + pub fn is_never(&self) -> bool { + match self.0 { + InterestKind::Never => true, + _ => false, + } + } + + /// Returns `true` if the subscriber is sometimes interested in being notified + /// about this callsite. + #[inline] + pub fn is_sometimes(&self) -> bool { + match self.0 { + InterestKind::Sometimes => true, + _ => false, + } + } + + /// Returns `true` if the subscriber is always interested in being notified + /// about this callsite. + #[inline] + pub fn is_always(&self) -> bool { + match self.0 { + InterestKind::Always => true, + _ => false, + } + } + + /// Returns the common interest between these two Interests. + /// + /// If both interests are the same, this propagates that interest. + /// Otherwise, if they differ, the result must always be + /// `Interest::sometimes` --- if the two subscribers differ in opinion, we + /// will have to ask the current subscriber what it thinks, no matter what. + pub(crate) fn and(self, rhs: Interest) -> Self { + if self.0 == rhs.0 { + self + } else { + Interest::sometimes() + } + } +} diff --git a/third_party/rust/tracing-core/tests/common/mod.rs b/third_party/rust/tracing-core/tests/common/mod.rs new file mode 100644 index 0000000000..3420f0b899 --- /dev/null +++ b/third_party/rust/tracing-core/tests/common/mod.rs @@ -0,0 +1,30 @@ +use tracing_core::{metadata::Metadata, span, subscriber::Subscriber, Event}; + +pub struct TestSubscriberA; +impl Subscriber for TestSubscriberA { + fn enabled(&self, _: &Metadata<'_>) -> bool { + true + } + fn new_span(&self, _: &span::Attributes<'_>) -> span::Id { + span::Id::from_u64(1) + } + fn record(&self, _: &span::Id, _: &span::Record<'_>) {} + fn record_follows_from(&self, _: &span::Id, _: &span::Id) {} + fn event(&self, _: &Event<'_>) {} + fn enter(&self, _: &span::Id) {} + fn exit(&self, _: &span::Id) {} +} +pub struct TestSubscriberB; +impl Subscriber for TestSubscriberB { + fn enabled(&self, _: &Metadata<'_>) -> bool { + true + } + fn new_span(&self, _: &span::Attributes<'_>) -> span::Id { + span::Id::from_u64(1) + } + fn record(&self, _: &span::Id, _: &span::Record<'_>) {} + fn record_follows_from(&self, _: &span::Id, _: &span::Id) {} + fn event(&self, _: &Event<'_>) {} + fn enter(&self, _: &span::Id) {} + fn exit(&self, _: &span::Id) {} +} diff --git a/third_party/rust/tracing-core/tests/dispatch.rs b/third_party/rust/tracing-core/tests/dispatch.rs new file mode 100644 index 0000000000..7184fc9f33 --- /dev/null +++ b/third_party/rust/tracing-core/tests/dispatch.rs @@ -0,0 +1,57 @@ +mod common; + +use common::*; +use tracing_core::dispatcher::*; + +#[cfg(feature = "std")] +#[test] +fn set_default_dispatch() { + set_global_default(Dispatch::new(TestSubscriberA)).expect("global dispatch set failed"); + get_default(|current| { + assert!( + current.is::<TestSubscriberA>(), + "global dispatch get failed" + ) + }); + + let guard = set_default(&Dispatch::new(TestSubscriberB)); + get_default(|current| assert!(current.is::<TestSubscriberB>(), "set_default get failed")); + + // Drop the guard, setting the dispatch back to the global dispatch + drop(guard); + + get_default(|current| { + assert!( + current.is::<TestSubscriberA>(), + "global dispatch get failed" + ) + }); +} + +#[cfg(feature = "std")] +#[test] +fn nested_set_default() { + let _guard = set_default(&Dispatch::new(TestSubscriberA)); + get_default(|current| { + assert!( + current.is::<TestSubscriberA>(), + "set_default for outer subscriber failed" + ) + }); + + let inner_guard = set_default(&Dispatch::new(TestSubscriberB)); + get_default(|current| { + assert!( + current.is::<TestSubscriberB>(), + "set_default inner subscriber failed" + ) + }); + + drop(inner_guard); + get_default(|current| { + assert!( + current.is::<TestSubscriberA>(), + "set_default outer subscriber failed" + ) + }); +} diff --git a/third_party/rust/tracing-core/tests/global_dispatch.rs b/third_party/rust/tracing-core/tests/global_dispatch.rs new file mode 100644 index 0000000000..d430ac6182 --- /dev/null +++ b/third_party/rust/tracing-core/tests/global_dispatch.rs @@ -0,0 +1,34 @@ +mod common; + +use common::*; +use tracing_core::dispatcher::*; +#[test] +fn global_dispatch() { + set_global_default(Dispatch::new(TestSubscriberA)).expect("global dispatch set failed"); + get_default(|current| { + assert!( + current.is::<TestSubscriberA>(), + "global dispatch get failed" + ) + }); + + #[cfg(feature = "std")] + with_default(&Dispatch::new(TestSubscriberB), || { + get_default(|current| { + assert!( + current.is::<TestSubscriberB>(), + "thread-local override of global dispatch failed" + ) + }); + }); + + get_default(|current| { + assert!( + current.is::<TestSubscriberA>(), + "reset to global override failed" + ) + }); + + set_global_default(Dispatch::new(TestSubscriberA)) + .expect_err("double global dispatch set succeeded"); +} diff --git a/third_party/rust/tracing-core/tests/macros.rs b/third_party/rust/tracing-core/tests/macros.rs new file mode 100644 index 0000000000..ee9007eeeb --- /dev/null +++ b/third_party/rust/tracing-core/tests/macros.rs @@ -0,0 +1,48 @@ +use tracing_core::{ + callsite::Callsite, + metadata, + metadata::{Kind, Level, Metadata}, + subscriber::Interest, +}; + +#[test] +fn metadata_macro_api() { + // This test should catch any inadvertent breaking changes + // caused by changes to the macro. + struct TestCallsite; + + impl Callsite for TestCallsite { + fn set_interest(&self, _: Interest) { + unimplemented!("test") + } + fn metadata(&self) -> &Metadata<'_> { + unimplemented!("test") + } + } + + static CALLSITE: TestCallsite = TestCallsite; + let _metadata = metadata! { + name: "test_metadata", + target: "test_target", + level: Level::DEBUG, + fields: &["foo", "bar", "baz"], + callsite: &CALLSITE, + kind: Kind::SPAN, + }; + let _metadata = metadata! { + name: "test_metadata", + target: "test_target", + level: Level::TRACE, + fields: &[], + callsite: &CALLSITE, + kind: Kind::EVENT, + }; + let _metadata = metadata! { + name: "test_metadata", + target: "test_target", + level: Level::INFO, + fields: &[], + callsite: &CALLSITE, + kind: Kind::EVENT + }; +} |