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
328
329
330
331
332
333
334
335
336
337
338
339
//! Types and implementations to parse the request macro's input.
use proc_macro2::Span;
use syn::{meta::ParseNestedMeta, parse_quote};
use super::{Request, RequestPath, RequestQuery};
use crate::{
api::{Body, Headers},
util::{ParseNestedMetaExt, RumaCommon},
};
impl Request {
/// Validate this request after it is fully parsed.
fn validate(&self) -> syn::Result<()> {
self.path.validate()?;
self.body.validate()?;
Ok(())
}
}
impl TryFrom<syn::ItemStruct> for Request {
type Error = syn::Error;
fn try_from(input: syn::ItemStruct) -> Result<Self, Self::Error> {
// Parse container attributes.
let mut request_attrs = RequestAttrs::default();
for attr in input.attrs {
if !attr.path().is_ident("ruma_api") {
continue;
}
attr.parse_nested_meta(|meta| request_attrs.try_merge(meta))?;
}
let mut request = Request {
ident: input.ident,
generics: input.generics,
headers: Headers::default(),
path: RequestPath::default(),
query: RequestQuery::default(),
body: Body::default(),
error_ty: request_attrs
.error_ty
.ok_or_else(|| syn::Error::new(Span::call_site(), "missing `error` attribute"))?,
};
request.body.set_manual_serde(request_attrs.manual_body_serde);
// Parse struct fields.
for field in input.fields {
let RequestField { inner: field, kind } = field.try_into()?;
match kind {
RequestFieldKind::Body => request.body.push_json_field(field)?,
RequestFieldKind::NewtypeBody => request.body.set_json_all(field)?,
RequestFieldKind::RawBody => request.body.set_raw(field)?,
RequestFieldKind::Path => {
request.path.push(field);
}
RequestFieldKind::Query => request.query.push_field(field)?,
RequestFieldKind::QueryAll => request.query.set_all(field)?,
RequestFieldKind::Header { name } => {
request.headers.insert(name, field)?;
}
}
}
request.validate()?;
Ok(request)
}
}
impl RequestPath {
/// Add the given field to this `RequestPath`.
fn push(&mut self, field: syn::Field) {
self.0.push(field);
}
/// Validate the fields in this `RequestPath`.
fn validate(&self) -> syn::Result<()> {
for field in &self.0 {
if field.attrs.iter().any(|attr| attr.path().is_ident("cfg")) {
return Err(syn::Error::new_spanned(
field,
"`#[cfg]` attribute is not supported on `path` fields",
));
}
}
Ok(())
}
}
impl RequestQuery {
/// Add the given field to the list of [`RequestQuery::Fields`].
///
/// Returns an error if this is not a [`RequestQuery::None`] or [`RequestQuery::Fields`]
/// variant.
fn push_field(&mut self, field: syn::Field) -> syn::Result<()> {
match self {
Self::None => {
*self = Self::Fields(vec![field]);
Ok(())
}
Self::Fields(fields) => {
fields.push(field);
Ok(())
}
Self::All(_) => Err(syn::Error::new(
Span::call_site(),
"cannot have both a `query_all` field and `query` fields",
)),
}
}
/// Set this as a [`RequestQuery::All`] with the given field.
///
/// Returns an error if this is not a [`RequestQuery::None`].
fn set_all(&mut self, field: syn::Field) -> syn::Result<()> {
let error_msg = match self {
Self::None => {
*self = Self::All(field);
return Ok(());
}
Self::Fields(_) => "cannot have both a `query_all` field and `query` fields",
Self::All(_) => "cannot have multiple `query_all` fields",
};
Err(syn::Error::new(Span::call_site(), error_msg))
}
}
/// Attributes on the request struct.
#[derive(Default)]
pub(crate) struct RequestAttrs {
/// The type used for the `EndpointError` associated type on `OutgoingRequest` and
/// `IncomingRequest` implementations.
error_ty: Option<syn::Type>,
/// Whether the request implements `Serialize` and `Deserialize` manually.
manual_body_serde: bool,
}
impl RequestAttrs {
/// Set the error type of this `RequestAttrs`.
///
/// Returns an error if the error type is already set.
fn set_error_ty(&mut self, error_ty: syn::Type) -> syn::Result<()> {
if self.error_ty.is_some() {
return Err(syn::Error::new(
Span::call_site(),
"cannot have multiple values for `error` request attribute",
));
}
self.error_ty = Some(error_ty);
Ok(())
}
/// Set that the request implements `Serialize` and `Deserialize` manually.
///
/// Returns an error if it is already set.
fn set_manual_body_serde(&mut self) -> syn::Result<()> {
if self.manual_body_serde {
return Err(syn::Error::new(
Span::call_site(),
"cannot have multiple `manual_body_serde` request attributes",
));
}
self.manual_body_serde = true;
Ok(())
}
/// Try to parse the given meta item and merge it into this `RequestAttrs`.
///
/// Returns an error if parsing the meta item fails, or if it sets a field that was already set.
pub(crate) fn try_merge(&mut self, meta: ParseNestedMeta<'_>) -> syn::Result<()> {
if meta.path.is_ident("error") {
return self.set_error_ty(meta.value()?.parse()?);
}
if meta.path.is_ident("manual_body_serde") {
return self.set_manual_body_serde();
}
Err(meta.error("unsupported `request` attribute"))
}
/// The error type that was set on the request, or the default value which is `Error`.
pub(super) fn error_ty_or_default(&self, ruma_common: &RumaCommon) -> syn::Type {
self.error_ty.clone().unwrap_or_else(|| parse_quote! { #ruma_common::api::error::Error })
}
}
/// A parsed field of a request struct.
struct RequestField {
/// The field with the `ruma_api` attributes stripped.
inner: syn::Field,
/// The kind of field.
kind: RequestFieldKind,
}
impl RequestField {
/// Set the kind of this `RequestField`.
///
/// Returns an error if the kind was already set.
fn set_kind(&mut self, kind: RequestFieldKind) -> syn::Result<()> {
if !matches!(self.kind, RequestFieldKind::Body) {
return Err(syn::Error::new_spanned(
&self.inner,
"multiple request field kind attributes found, there can only be one",
));
}
self.kind = kind;
Ok(())
}
/// Try to merge the values of the attributes in the given meta in this `RequestField`.
///
/// Returns an error if parsing the meta fails or a value is set twice.
fn try_merge(&mut self, meta: ParseNestedMeta<'_>) -> syn::Result<()> {
if let Some(kind) = RequestFieldKind::try_from_meta(&meta)? {
return self.set_kind(kind);
}
Err(meta.error("unsupported `ruma_api` field attribute"))
}
}
impl TryFrom<syn::Field> for RequestField {
type Error = syn::Error;
fn try_from(inner: syn::Field) -> syn::Result<Self> {
let mut field = RequestField { inner, kind: Default::default() };
let api_attrs = field
.inner
.attrs
.extract_if(.., |attr| attr.path().is_ident("ruma_api"))
.collect::<Vec<_>>();
for attr in api_attrs {
attr.parse_nested_meta(|meta| field.try_merge(meta))?;
}
Ok(field)
}
}
/// The kind of a request field.
#[derive(Default)]
enum RequestFieldKind {
/// Part of the JSON data in the body of the request.
#[default]
Body,
/// The full JSON data in the body of the request.
NewtypeBody,
/// Arbitrary bytes in the body of the request.
RawBody,
/// Data that appears in the URL path.
Path,
/// Data that appears in the query string.
Query,
/// Data that represents all the query string as a single type.
QueryAll,
/// Data in an HTTP header.
Header {
/// The name of the header, as a constant from `http::header`.
name: syn::Ident,
},
}
impl RequestFieldKind {
/// Try to convert the given meta into a `RequestFieldKind`.
///
/// Returns `Ok(Some(kind))` if the meta matches one of the variants and parsing it succeeds,
/// `Ok(None)` if the meta doesn't match one of the variants, and `Err(_)` if the meta matches
/// one of the variants but parsing it fails.
fn try_from_meta(meta: &ParseNestedMeta<'_>) -> syn::Result<Option<Self>> {
let Some(ident) = meta.path.get_ident() else {
return Ok(None);
};
match ident.to_string().as_str() {
"body" => {
if meta.has_value() {
return Err(meta.error("`body` attribute doesn't expect a value"));
}
Ok(Some(Self::NewtypeBody))
}
"raw_body" => {
if meta.has_value() {
return Err(meta.error("`raw_body` attribute doesn't expect a value"));
}
Ok(Some(Self::RawBody))
}
"path" => {
if meta.has_value() {
return Err(meta.error("`path` attribute doesn't expect a value"));
}
Ok(Some(Self::Path))
}
"query" => {
if meta.has_value() {
return Err(meta.error("`query` attribute doesn't expect a value"));
}
Ok(Some(Self::Query))
}
"query_all" => {
if meta.has_value() {
return Err(meta.error("`query_all` attribute doesn't expect a value"));
}
Ok(Some(Self::QueryAll))
}
"header" => {
let name = meta.value()?.parse()?;
Ok(Some(Self::Header { name }))
}
_ => Ok(None),
}
}
}