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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{DeriveInput, Expr, Lit, Meta};
/// Attributes parsed from `#[frame(...)]`.
#[derive(Default)]
pub(crate) struct FrameAttributes {
/// Custom frame name (defaults to struct name).
pub name: Option<String>,
/// Polar angle name for SphericalNaming (e.g., "dec", "lat", "alt").
pub polar: Option<String>,
/// Azimuthal angle name for SphericalNaming (e.g., "ra", "lon", "az").
pub azimuth: Option<String>,
/// Distance name for SphericalNaming (defaults to "distance").
pub distance: Option<String>,
/// Whether to generate inherent impls on Direction<F> and Position<C,F,U>.
/// Only valid when the frame is defined in the same crate as Direction/Position.
pub inherent: bool,
/// Ellipsoid type name for HasEllipsoid impl (e.g., "Wgs84").
pub ellipsoid: Option<syn::Ident>,
}
pub(crate) fn derive_reference_frame_impl(input: DeriveInput) -> syn::Result<TokenStream2> {
let name = &input.ident;
let attrs = parse_frame_attributes(&input)?;
let name_expr = match &attrs.name {
Some(custom_name) => quote! { #custom_name },
None => {
let name_str = name.to_string();
quote! { #name_str }
}
};
// Generate SphericalNaming impl (always) + inherent methods (when `inherent` flag set)
let spherical_impl = match (&attrs.polar, &attrs.azimuth) {
(Some(polar), Some(azimuth)) => {
let distance = attrs.distance.as_deref().unwrap_or("distance");
let polar_ident = syn::Ident::new(polar, proc_macro2::Span::call_site());
let azimuth_ident = syn::Ident::new(azimuth, proc_macro2::Span::call_site());
// SphericalNaming is always generated (trait impl, not inherent)
let naming_impl = quote! {
impl ::affn::frames::SphericalNaming for #name {
fn polar_name() -> &'static str {
#polar
}
fn azimuth_name() -> &'static str {
#azimuth
}
fn distance_name() -> &'static str {
#distance
}
}
};
// Inherent impls: only generated when `inherent` flag is set.
// These require Direction/Position to be in the same crate as the frame.
let inherent_impl = if attrs.inherent {
// Determine constructor parameter order:
// IAU convention: polar first for alt/az, azimuth first for everything else
let polar_first = polar == "alt";
let (first_param, second_param) = if polar_first {
(&polar_ident, &azimuth_ident)
} else {
(&azimuth_ident, &polar_ident)
};
// The core spherical constructors always take (polar, azimuth).
let (polar_arg, azimuth_arg) = (&polar_ident, &azimuth_ident);
let polar_doc = format!("Returns the {} angle in degrees.", polar);
let azimuth_doc = format!("Returns the {} angle in degrees.", azimuth);
let dir_new_doc = format!(
"Creates a new direction from {} and {} (canonicalized).",
first_param, second_param
);
let pos_new_doc = format!(
"Creates a new position from {}, {}, and distance (canonicalized).",
first_param, second_param
);
// Ellipsoidal getters: only for frames with an associated
// ellipsoid. We do NOT generate a constructor —
// `ellipsoidal::Position` already has its own `new()`.
let ellipsoidal_getters = if attrs.ellipsoid.is_some() {
let distance_ident = syn::Ident::new(distance, proc_macro2::Span::call_site());
let distance_doc = format!(
"Returns the {} (height above the reference ellipsoid).",
distance
);
quote! {
// ── EllipsoidalPosition<C, F, U>: inherent named getters ──
impl<C, U> ::affn::ellipsoidal::Position<C, #name, U>
where
C: ::affn::centers::ReferenceCenter,
U: ::qtty::length::LengthUnit,
{
#[doc = #polar_doc]
#[inline]
pub fn #polar_ident(&self) -> ::qtty::angular::Degrees {
self.lat
}
#[doc = #azimuth_doc]
#[inline]
pub fn #azimuth_ident(&self) -> ::qtty::angular::Degrees {
self.lon
}
#[doc = #distance_doc]
#[inline]
pub fn #distance_ident(&self) -> ::qtty::Quantity<U> {
self.height
}
}
}
} else {
quote! {}
};
quote! {
// ── Direction<F>: inherent named constructor + getters ──
impl ::affn::spherical::Direction<#name> {
#[doc = #dir_new_doc]
#[inline]
pub fn new(
#first_param: ::qtty::angular::Degrees,
#second_param: ::qtty::angular::Degrees,
) -> Self {
let (polar, azimuth) =
::affn::spherical::canonicalize_polar_azimuth(#polar_arg, #azimuth_arg);
Self::new_unchecked(polar, azimuth)
}
#[doc = #polar_doc]
#[inline]
pub fn #polar_ident(&self) -> ::qtty::angular::Degrees {
self.polar
}
#[doc = #azimuth_doc]
#[inline]
pub fn #azimuth_ident(&self) -> ::qtty::angular::Degrees {
self.azimuth
}
}
// ── Position<C, F, U>: inherent named getters (any center) ──
impl<C, U> ::affn::spherical::Position<C, #name, U>
where
C: ::affn::centers::ReferenceCenter,
U: ::qtty::length::LengthUnit,
{
#[doc = #polar_doc]
#[inline]
pub fn #polar_ident(&self) -> ::qtty::angular::Degrees {
self.polar
}
#[doc = #azimuth_doc]
#[inline]
pub fn #azimuth_ident(&self) -> ::qtty::angular::Degrees {
self.azimuth
}
}
// ── Position<C, F, U>: named constructor (only Params = ()) ──
impl<C, U> ::affn::spherical::Position<C, #name, U>
where
C: ::affn::centers::ReferenceCenter<Params = ()>,
U: ::qtty::length::LengthUnit,
{
#[doc = #pos_new_doc]
#[inline]
pub fn new<T: Into<::qtty::Quantity<U>>>(
#first_param: ::qtty::angular::Degrees,
#second_param: ::qtty::angular::Degrees,
distance: T,
) -> Self {
Self::new_with_params((), #polar_arg, #azimuth_arg, distance.into())
}
}
#ellipsoidal_getters
}
} else {
quote! {}
};
quote! {
#naming_impl
#inherent_impl
}
}
(Some(_), None) => {
return Err(syn::Error::new_spanned(
&input.ident,
"`polar` attribute requires `azimuth` to also be specified",
));
}
(None, Some(_)) => {
return Err(syn::Error::new_spanned(
&input.ident,
"`azimuth` attribute requires `polar` to also be specified",
));
}
(None, None) => quote! {},
};
// Generate HasEllipsoid impl when `ellipsoid = "..."` is specified
let ellipsoid_impl = match &attrs.ellipsoid {
Some(ellipsoid_ident) => quote! {
impl ::affn::ellipsoid::HasEllipsoid for #name {
type Ellipsoid = ::affn::ellipsoid::#ellipsoid_ident;
}
},
None => quote! {},
};
// When SphericalNaming names are available, also override ReferenceFrame::spherical_names()
// so that Display impls on spherical types can use domain names without requiring
// a SphericalNaming bound.
let spherical_names_method = match (&attrs.polar, &attrs.azimuth) {
(Some(polar), Some(azimuth)) => {
let distance = attrs.distance.as_deref().unwrap_or("distance");
quote! {
fn spherical_names() -> ::core::option::Option<(&'static str, &'static str, &'static str)> {
::core::option::Option::Some((#polar, #azimuth, #distance))
}
}
}
_ => quote! {},
};
let expanded = quote! {
impl ::affn::frames::ReferenceFrame for #name {
fn frame_name() -> &'static str {
#name_expr
}
#spherical_names_method
}
#spherical_impl
#ellipsoid_impl
};
Ok(expanded)
}
pub(crate) fn parse_frame_attributes(input: &DeriveInput) -> syn::Result<FrameAttributes> {
let mut attrs = FrameAttributes::default();
for attr in &input.attrs {
if attr.path().is_ident("frame") {
let nested = attr.parse_args_with(
syn::punctuated::Punctuated::<Meta, syn::Token![,]>::parse_terminated,
)?;
for meta in nested {
match &meta {
Meta::Path(path) if path.is_ident("inherent") => {
attrs.inherent = true;
}
Meta::NameValue(nv) => {
let value_str = extract_string_literal(&nv.value)?;
if nv.path.is_ident("name") {
attrs.name = Some(value_str);
} else if nv.path.is_ident("polar") {
attrs.polar = Some(value_str);
} else if nv.path.is_ident("azimuth") {
attrs.azimuth = Some(value_str);
} else if nv.path.is_ident("distance") {
attrs.distance = Some(value_str);
} else if nv.path.is_ident("ellipsoid") {
attrs.ellipsoid =
Some(syn::Ident::new(&value_str, proc_macro2::Span::call_site()));
} else {
return Err(syn::Error::new_spanned(
&nv.path,
format!(
"unknown `frame` attribute `{}`; \
known attributes are: name, polar, azimuth, \
distance, ellipsoid, inherent",
nv.path
.get_ident()
.map(|id| id.to_string())
.unwrap_or_else(|| "<unknown>".into())
),
));
}
}
_ => {
return Err(syn::Error::new_spanned(
&meta,
"unknown `frame` attribute; expected a name=value attribute \
such as `name = \"...\"`, `polar = \"...\"`, \
`azimuth = \"...\"`, `distance = \"...\"`, \
`ellipsoid = \"...\"`, or the bare flag `inherent`",
));
}
}
}
}
}
Ok(attrs)
}
/// Extract a string literal from an expression, or return an error.
fn extract_string_literal(expr: &Expr) -> syn::Result<String> {
if let Expr::Lit(expr_lit) = expr {
if let Lit::Str(lit_str) = &expr_lit.lit {
return Ok(lit_str.value());
}
}
Err(syn::Error::new_spanned(expr, "expected string literal"))
}