1use proc_macro2::Span;
2use std::ops::{Deref, DerefMut};
3use syn::spanned::Spanned;
4
5use crate::{
6 FromDeriveInput, FromField, FromGenericParam, FromGenerics, FromMeta, FromTypeParam,
7 FromVariant, Result,
8};
9
10/// 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}
27
28impl<T> SpannedValue<T> {
29 pub fn new(value: T, span: Span) -> Self {
30 SpannedValue { value, span }
31 }
32
33 /// Get the source code location referenced by this struct.
34 pub fn span(&self) -> Span {
35 self.span
36 }
37
38 /// Apply a mapping function to a reference to the spanned value.
39 pub fn map_ref<U>(&self, map_fn: impl FnOnce(&T) -> U) -> SpannedValue<U> {
40 SpannedValue::new(value:map_fn(&self.value), self.span)
41 }
42}
43
44impl<T: Default> Default for SpannedValue<T> {
45 fn default() -> Self {
46 SpannedValue::new(value:Default::default(), Span::call_site())
47 }
48}
49
50impl<T> Deref for SpannedValue<T> {
51 type Target = T;
52
53 fn deref(&self) -> &T {
54 &self.value
55 }
56}
57
58impl<T> DerefMut for SpannedValue<T> {
59 fn deref_mut(&mut self) -> &mut T {
60 &mut self.value
61 }
62}
63
64impl<T> AsRef<T> for SpannedValue<T> {
65 fn as_ref(&self) -> &T {
66 &self.value
67 }
68}
69
70macro_rules! spanned {
71 ($trayt:ident, $method:ident, $syn:path) => {
72 impl<T: $trayt> $trayt for SpannedValue<T> {
73 fn $method(value: &$syn) -> Result<Self> {
74 Ok(SpannedValue::new(
75 $trayt::$method(value).map_err(|e| e.with_span(value))?,
76 value.span(),
77 ))
78 }
79 }
80 };
81}
82
83impl<T: FromMeta> FromMeta for SpannedValue<T> {
84 fn from_meta(item: &syn::Meta) -> Result<Self> {
85 let value = T::from_meta(item).map_err(|e| e.with_span(item))?;
86 let span = match item {
87 // Example: `#[darling(skip)]` as SpannedValue<bool>
88 // should have the span pointing to the word `skip`.
89 syn::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.
92 syn::Meta::List(list) => list.tokens.span(),
93 // Example: `#[darling(skip = true)]` as SpannedValue<bool>
94 // should have the span pointing to the word `true`.
95 syn::Meta::NameValue(nv) => nv.value.span(),
96 };
97
98 Ok(Self::new(value, span))
99 }
100
101 fn 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 }
106
107 fn 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 }
112
113 fn 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}
119
120spanned!(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);
126
127impl<T: Spanned> From<T> for SpannedValue<T> {
128 fn from(value: T) -> Self {
129 let span: Span = value.span();
130 SpannedValue::new(value, span)
131 }
132}
133
134#[cfg(test)]
135mod tests {
136 use super::*;
137 use proc_macro2::Span;
138
139 /// Make sure that `SpannedValue` can be seamlessly used as its underlying type.
140 #[test]
141 fn deref() {
142 let test = SpannedValue::new("hello", Span::call_site());
143 assert_eq!("hello", test.trim());
144 }
145}
146