1use proc_macro2::Span;
2use std::ops::{Deref, DerefMut};
3use syn::spanned::Spanned;
45use crate::{
6 FromDeriveInput, FromField, FromGenericParam, FromGenerics, FromMeta, FromTypeParam,
7 FromVariant, Result,
8};
910/// A value and an associated position in source code. The main use case for this is
11/// to preserve position information to emit warnings from proc macros. You can use
12/// a `SpannedValue<T>` as a field in any struct that implements or derives any of
13/// `darling`'s core traits.
14///
15/// To access the underlying value, use the struct's `Deref` implementation.
16///
17/// # Defaulting
18/// This type is meant to be used in conjunction with attribute-extracted options,
19/// but the user may not always explicitly set those options in their source code.
20/// In this case, using `Default::default()` will create an instance which points
21/// to `Span::call_site()`.
22#[derive(Debug, Clone, Copy)]
23pub struct SpannedValue<T> {
24 value: T,
25 span: Span,
26}
2728impl<T> SpannedValue<T> {
29pub fn new(value: T, span: Span) -> Self {
30 SpannedValue { value, span }
31 }
3233/// Get the source code location referenced by this struct.
34pub fn span(&self) -> Span {
35self.span
36 }
3738/// Apply a mapping function to a reference to the spanned value.
39pub fn map_ref<U>(&self, map_fn: impl FnOnce(&T) -> U) -> SpannedValue<U> {
40 SpannedValue::new(map_fn(&self.value), self.span)
41 }
42}
4344impl<T: Default> Default for SpannedValue<T> {
45fn default() -> Self {
46 SpannedValue::new(Default::default(), Span::call_site())
47 }
48}
4950impl<T> Deref for SpannedValue<T> {
51type Target = T;
5253fn deref(&self) -> &T {
54&self.value
55 }
56}
5758impl<T> DerefMut for SpannedValue<T> {
59fn deref_mut(&mut self) -> &mut T {
60&mut self.value
61 }
62}
6364impl<T> AsRef<T> for SpannedValue<T> {
65fn as_ref(&self) -> &T {
66&self.value
67 }
68}
6970macro_rules! spanned {
71 ($trayt:ident, $method:ident, $syn:path) => {
72impl<T: $trayt> $trayt for SpannedValue<T> {
73fn $method(value: &$syn) -> Result<Self> {
74Ok(SpannedValue::new(
75$trayt::$method(value).map_err(|e| e.with_span(value))?,
76 value.span(),
77 ))
78 }
79 }
80 };
81}
8283impl<T: FromMeta> FromMeta for SpannedValue<T> {
84fn from_meta(item: &syn::Meta) -> Result<Self> {
85let value = T::from_meta(item).map_err(|e| e.with_span(item))?;
86let span = match item {
87// Example: `#[darling(skip)]` as SpannedValue<bool>
88 // should have the span pointing to the word `skip`.
89syn::Meta::Path(path) => path.span(),
90// Example: `#[darling(attributes(Value))]` as a SpannedValue<Vec<String>>
91 // should have the span pointing to the list contents.
92syn::Meta::List(list) => list.tokens.span(),
93// Example: `#[darling(skip = true)]` as SpannedValue<bool>
94 // should have the span pointing to the word `true`.
95syn::Meta::NameValue(nv) => nv.value.span(),
96 };
9798Ok(Self::new(value, span))
99 }
100101fn from_nested_meta(item: &crate::ast::NestedMeta) -> Result<Self> {
102 T::from_nested_meta(item)
103 .map(|value| Self::new(value, item.span()))
104 .map_err(|e| e.with_span(item))
105 }
106107fn from_value(literal: &syn::Lit) -> Result<Self> {
108 T::from_value(literal)
109 .map(|value| Self::new(value, literal.span()))
110 .map_err(|e| e.with_span(literal))
111 }
112113fn from_expr(expr: &syn::Expr) -> Result<Self> {
114 T::from_expr(expr)
115 .map(|value| Self::new(value, expr.span()))
116 .map_err(|e| e.with_span(expr))
117 }
118}
119120spanned!(FromGenericParam, from_generic_param, syn::GenericParam);
121spanned!(FromGenerics, from_generics, syn::Generics);
122spanned!(FromTypeParam, from_type_param, syn::TypeParam);
123spanned!(FromDeriveInput, from_derive_input, syn::DeriveInput);
124spanned!(FromField, from_field, syn::Field);
125spanned!(FromVariant, from_variant, syn::Variant);
126127impl<T: Spanned> From<T> for SpannedValue<T> {
128fn from(value: T) -> Self {
129let span = value.span();
130 SpannedValue::new(value, span)
131 }
132}
133134#[cfg(test)]
135mod tests {
136use super::*;
137use proc_macro2::Span;
138139/// Make sure that `SpannedValue` can be seamlessly used as its underlying type.
140#[test]
141fn deref() {
142let test = SpannedValue::new("hello", Span::call_site());
143assert_eq!("hello", test.trim());
144 }
145}