Skip to content
This repository has been archived by the owner on Jun 8, 2024. It is now read-only.

Commit

Permalink
support emit attributes on stable
Browse files Browse the repository at this point in the history
  • Loading branch information
KodrAus committed Mar 24, 2024
1 parent f202a6d commit 666358f
Show file tree
Hide file tree
Showing 15 changed files with 254 additions and 135 deletions.
1 change: 0 additions & 1 deletion core/src/ctxt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,6 @@ mod internal {

#[cfg(feature = "alloc")]
mod alloc_support {
use alloc::boxed::Box;
use core::any::Any;

use crate::props::ErasedProps;
Expand Down
10 changes: 9 additions & 1 deletion core/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,14 @@ impl<'a> Path<'a> {
}
}

impl<'a> Eq for Path<'a> {}

impl<'a, 'b> PartialEq<Path<'b>> for Path<'a> {
fn eq(&self, other: &Path<'b>) -> bool {
self.0 == other.0
}
}

impl<'a> fmt::Debug for Path<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
Expand Down Expand Up @@ -106,7 +114,7 @@ impl<'a> serde::Serialize for Path<'a> {

#[cfg(feature = "alloc")]
mod alloc_support {
use alloc::{borrow::Cow, boxed::Box};
use alloc::borrow::Cow;

use super::*;

Expand Down
5 changes: 1 addition & 4 deletions core/src/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,10 +247,7 @@ impl<'k> serde::Serialize for Str<'k> {

#[cfg(feature = "alloc")]
mod alloc_support {
use alloc::{
borrow::{Cow, ToOwned},
string::String,
};
use alloc::borrow::Cow;

use super::*;

Expand Down
2 changes: 0 additions & 2 deletions core/src/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -513,8 +513,6 @@ enum PartKind<'a> {
mod alloc_support {
use super::*;

use alloc::vec::Vec;

impl Template<'static> {
pub fn new_owned(parts: impl Into<Box<[Part<'static>]>>) -> Self {
let parts = parts.into();
Expand Down
6 changes: 6 additions & 0 deletions core/src/timestamp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ impl Timestamp {
}

pub fn from_parts(parts: Parts) -> Option<Self> {
/*
Original implementation: https://github.com/tokio-rs/prost/blob/master/prost-types/src/datetime.rs
Licensed under Apache 2.0
*/

let is_leap;
let start_of_year;
let year = (parts.years as i64) - 1900;
Expand Down
2 changes: 1 addition & 1 deletion core/src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ impl<'v, const N: usize> From<&'v [i64; N]> for Value<'v> {
mod alloc_support {
use super::*;

use alloc::{borrow::Cow, vec::Vec};
use alloc::borrow::Cow;

impl<'v> Value<'v> {
pub fn as_f64_sequence(&self) -> Vec<f64> {
Expand Down
4 changes: 2 additions & 2 deletions core/src/well_known.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub const KEY_TS_START: &'static str = "ts_start";
pub const KEY_TPL: &'static str = "tpl";
pub const KEY_MSG: &'static str = "msg";

// Level
// Log
pub const KEY_LVL: &'static str = "lvl";

pub const LVL_DEBUG: &'static str = "debug";
Expand All @@ -21,7 +21,7 @@ pub const KEY_TRACE_ID: &'static str = "trace_id";
pub const KEY_SPAN_ID: &'static str = "span_id";
pub const KEY_SPAN_PARENT: &'static str = "span_parent";

// Metrics
// Metric
pub const KEY_METRIC_NAME: &'static str = "metric_name";
pub const KEY_METRIC_AGG: &'static str = "metric_agg";
pub const KEY_METRIC_VALUE: &'static str = "metric_value";
Expand Down
9 changes: 5 additions & 4 deletions macros/src/capture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pub fn key_value_with_hook(
fv: &FieldValue,
interpolated: bool,
captured: bool,
) -> TokenStream {
) -> syn::Result<TokenStream> {
let fn_name = match &*fv.key_name() {
emit_core::well_known::KEY_LVL => quote_spanned!(fv.span()=> __private_capture_as_level),
emit_core::well_known::KEY_ERR => quote_spanned!(fv.span()=> __private_capture_as_error),
Expand Down Expand Up @@ -73,11 +73,12 @@ pub fn key_value_with_hook(
(#expr).__private_optional_capture_some().__private_optional_map_some(|v| v.#fn_name()) #interpolated_expr #captured_expr
});

quote_spanned!(fv.span()=>
#(#attrs)*
hook::eval_hooks(
&attrs,
syn::parse_quote_spanned!(fv.span()=>
{
(#key_tokens, #value_tokens)
}
}),
)
}

Expand Down
18 changes: 10 additions & 8 deletions macros/src/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub fn template_hole_with_hook(
hole: &ExprLit,
interpolated: bool,
captured: bool,
) -> TokenStream {
) -> syn::Result<TokenStream> {
let interpolated_expr = if interpolated {
quote!(.__private_interpolated())
} else {
Expand All @@ -27,13 +27,15 @@ pub fn template_hole_with_hook(
quote!(.__private_uncaptured())
};

quote_spanned!(hole.span()=>
#(#attrs)*
#[allow(unused_imports)]
{
use emit::__private::{__PrivateFmtHook as _, __PrivateInterpolatedHook as _};
emit::template::Part::hole(#hole).__private_fmt_as_default()#interpolated_expr #captured_expr
}
hook::eval_hooks(
&attrs,
syn::parse_quote_spanned!(hole.span()=>
#[allow(unused_imports)]
{
use emit::__private::{__PrivateFmtHook as _, __PrivateInterpolatedHook as _};
emit::template::Part::hole(#hole).__private_fmt_as_default()#interpolated_expr #captured_expr
}
),
)
}

Expand Down
42 changes: 40 additions & 2 deletions macros/src/hook.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::fmt::Write;
use std::{collections::HashMap, fmt::Write, sync::OnceLock};

use proc_macro2::TokenStream;
use quote::ToTokens;
Expand All @@ -8,11 +8,21 @@ use syn::{
spanned::Spanned,
token::Comma,
visit_mut::{self, VisitMut},
Expr, ExprMethodCall, Ident,
Attribute, Expr, ExprMethodCall, Ident, Meta, MetaList,
};

use crate::util::parse_comma_separated2;

static HOOKS: OnceLock<
HashMap<&'static str, fn(TokenStream, TokenStream) -> syn::Result<TokenStream>>,
> = OnceLock::new();

pub(crate) fn get(
name: &str,
) -> Option<impl Fn(TokenStream, TokenStream) -> syn::Result<TokenStream>> {
HOOKS.get_or_init(crate::hooks).get(name)
}

pub struct RenameHookTokens<P, T> {
pub args: TokenStream,
pub expr: TokenStream,
Expand Down Expand Up @@ -120,3 +130,31 @@ impl ToTokens for Hook {
tokens.extend(quote!(#expr));
}
}

pub(crate) fn eval_hooks(attrs: &[Attribute], expr: Expr) -> syn::Result<TokenStream> {
let mut unapplied = Vec::new();
let mut expr = quote!(#expr);

for attr in attrs {
if attr.path().segments.len() == 2 {
let root = attr.path().segments.first().unwrap();
let name = attr.path().segments.last().unwrap();

if root.ident == "emit" {
let args = match &attr.meta {
Meta::List(MetaList { ref tokens, .. }) => Some(tokens),
_ => None,
};

if let Some(eval) = get(&name.ident.to_string()) {
expr = eval(quote!(#args), expr)?;
continue;
}
}
}

unapplied.push(attr.clone());
}

Ok(quote_spanned!(expr.span()=> #(#unapplied)* #expr))
}
Loading

0 comments on commit 666358f

Please sign in to comment.