-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathlib.rs
More file actions
1575 lines (1542 loc) · 52.6 KB
/
lib.rs
File metadata and controls
1575 lines (1542 loc) · 52.6 KB
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![recursion_limit="128"]
#![doc(html_root_url = "https://api.rocket.rs/master")]
#![doc(html_favicon_url = "https://rocket.rs/images/favicon.ico")]
#![doc(html_logo_url = "https://rocket.rs/images/logo-boxed.png")]
#![warn(rust_2018_idioms, missing_docs)]
//! # Rocket - Code Generation
//!
//! This crate implements the code generation portions of Rocket. This includes
//! custom derives, custom attributes, and procedural macros. The documentation
//! here is purely technical. The code generation facilities are documented
//! thoroughly in the [Rocket programming guide](https://rocket.rs/master/guide).
//!
//! # Usage
//!
//! You **_should not_** directly depend on this library. To use the macros,
//! attributes, and derives in this crate, it suffices to depend on `rocket` in
//! `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! rocket = "0.6.0-dev"
//! ```
//!
//! And to import all macros, attributes, and derives via `#[macro_use]` in the
//! crate root:
//!
//! ```rust
//! #[macro_use] extern crate rocket;
//! # #[get("/")] fn hello() { }
//! # fn main() { rocket::build().mount("/", routes![hello]); }
//! ```
//!
//! Or, alternatively, selectively import from the top-level scope:
//!
//! ```rust
//! # extern crate rocket;
//!
//! use rocket::{get, routes};
//! # #[get("/")] fn hello() { }
//! # fn main() { rocket::build().mount("/", routes![hello]); }
//! ```
//!
//! # Debugging Codegen
//!
//! When the `ROCKET_CODEGEN_DEBUG` environment variable is set, this crate
//! logs, at compile-time and to the console, the items it generates. For
//! example, you might run the following to build a Rocket application with
//! codegen debug logging enabled:
//!
//! ```sh
//! ROCKET_CODEGEN_DEBUG=1 cargo build
//! ```
#[macro_use] extern crate quote;
use rocket_http as http;
#[macro_use]
mod exports;
mod proc_macro_ext;
mod derive;
mod attribute;
mod bang;
mod http_codegen;
mod syn_ext;
mod name;
use crate::http::Method;
use proc_macro::TokenStream;
static URI_MACRO_PREFIX: &str = "rocket_uri_macro_";
static ROCKET_IDENT_PREFIX: &str = "__rocket_";
macro_rules! emit {
($tokens:expr) => ({
use devise::ext::SpanDiagnosticExt;
let mut tokens = $tokens;
if std::env::var_os("ROCKET_CODEGEN_DEBUG").is_some() {
let debug_tokens = proc_macro2::Span::call_site()
.note("emitting Rocket code generation debug output")
.note(tokens.to_string())
.emit_as_item_tokens();
tokens.extend(debug_tokens);
}
tokens.into()
})
}
macro_rules! route_attribute {
($name:ident => $method:expr) => (
/// Attribute to generate a [`Route`] and associated metadata.
///
/// This and all other route attributes can only be applied to free
/// functions:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// #
/// #[get("/")]
/// fn index() -> &'static str {
/// "Hello, world!"
/// }
/// ```
///
/// There are 7 method-specific route attributes:
///
/// * [`get`] - `GET` specific route
/// * [`put`] - `PUT` specific route
/// * [`post`] - `POST` specific route
/// * [`delete`] - `DELETE` specific route
/// * [`head`] - `HEAD` specific route
/// * [`options`] - `OPTIONS` specific route
/// * [`patch`] - `PATCH` specific route
///
/// Additionally, [`route`] allows the method and uri to be explicitly
/// specified:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// #
/// #[route(GET, uri = "/")]
/// fn index() -> &'static str {
/// "Hello, world!"
/// }
/// ```
///
/// [`get`]: attr.get.html
/// [`put`]: attr.put.html
/// [`post`]: attr.post.html
/// [`delete`]: attr.delete.html
/// [`head`]: attr.head.html
/// [`options`]: attr.options.html
/// [`patch`]: attr.patch.html
/// [`route`]: attr.route.html
///
/// # Grammar
///
/// The grammar for all method-specific route attributes is defined as:
///
/// ```text
/// route := '"' uri ('?' query)? '"' (',' parameter)*
///
/// uri := ('/' segment)*
///
/// query := segment ('&' segment)*
///
/// segment := URI_SEG
/// | SINGLE_PARAM
/// | TRAILING_PARAM
///
/// parameter := 'rank' '=' INTEGER
/// | 'format' '=' '"' MEDIA_TYPE '"'
/// | 'data' '=' '"' SINGLE_PARAM '"'
///
/// SINGLE_PARAM := '<' IDENT '>'
/// TRAILING_PARAM := '<' IDENT '..>'
///
/// URI_SEG := valid, non-percent-encoded HTTP URI segment
/// MEDIA_TYPE := valid HTTP media type or known shorthand
///
/// INTEGER := unsigned integer, as defined by Rust
/// IDENT := valid identifier, as defined by Rust
/// ```
///
/// The generic route attribute is defined as:
///
/// ```text
/// generic-route := METHOD ',' 'uri' '=' route
/// ```
///
/// # Typing Requirements
///
/// Every identifier, except for `_`, that appears in a dynamic
/// parameter (`SINGLE_PARAM` or `TRAILING_PARAM`) must appear as an
/// argument to the function. For example, the following route requires
/// the decorated function to have the arguments `foo`, `baz`, `msg`,
/// `rest`, and `form`:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// # use rocket::form::Form;
/// # use std::path::PathBuf;
/// # #[derive(FromForm)] struct F { a: usize }
/// #[get("/<foo>/bar/<baz..>?<msg>&closed&<rest..>", data = "<form>")]
/// # fn f(foo: usize, baz: PathBuf, msg: String, rest: F, form: Form<F>) { }
/// ```
///
/// The type of each function argument corresponding to a dynamic
/// parameter is required to implement one of Rocket's guard traits. The
/// exact trait that is required to be implemented depends on the kind
/// of dynamic parameter (`SINGLE` or `TRAILING`) and where in the route
/// attribute the parameter appears. The table below summarizes trait
/// requirements:
///
/// | position | kind | trait |
/// |----------|-------------|-------------------|
/// | path | `<ident>` | [`FromParam`] |
/// | path | `<ident..>` | [`FromSegments`] |
/// | query | `<ident>` | [`FromForm`] |
/// | query | `<ident..>` | [`FromForm`] |
/// | data | `<ident>` | [`FromData`] |
///
/// The type of each function argument that _does not_ have a
/// corresponding dynamic parameter is required to implement the
/// [`FromRequest`] trait.
///
/// A route argument declared a `_` must _not_ appear in the function
/// argument list and has no typing requirements.
///
/// The return type of the decorated function must implement the
/// [`Responder`] trait.
///
/// [`FromParam`]: ../rocket/request/trait.FromParam.html
/// [`FromSegments`]: ../rocket/request/trait.FromSegments.html
/// [`FromFormField`]: ../rocket/request/trait.FromFormField.html
/// [`FromForm`]: ../rocket/form/trait.FromForm.html
/// [`FromData`]: ../rocket/data/trait.FromData.html
/// [`FromRequest`]: ../rocket/request/trait.FromRequest.html
/// [`Route`]: ../rocket/struct.Route.html
/// [`Responder`]: ../rocket/response/trait.Responder.html
///
/// # Semantics
///
/// The attribute generates three items:
///
/// 1. A route [`Handler`].
///
/// The generated handler validates and generates all arguments for
/// the generated function according to the trait that their type
/// must implement. The order in which arguments are processed is:
///
/// 1. Request guards from left to right.
///
/// If a request guard fails, the request is forwarded if the
/// [`Outcome`] is `Forward` or failed if the [`Outcome`] is
/// `Error`. See [`FromRequest` Outcomes] for further detail.
///
/// 2. Path and query guards in an unspecified order. If a path
/// or query guard fails, the request is forwarded.
///
/// 3. Data guard, if any.
///
/// If a data guard fails, the request is forwarded if the
/// [`Outcome`] is `Forward` or failed if the [`Outcome`] is
/// `Error`. See [`FromData`] for further detail.
///
/// If all validation succeeds, the decorated function is called.
/// The returned value is used to generate a [`Response`] via the
/// type's [`Responder`] implementation.
///
/// 2. A static structure used by [`routes!`] to generate a [`Route`].
///
/// The static structure (and resulting [`Route`]) is populated
/// with the name (the function's name), path, query, rank, and
/// format from the route attribute. The handler is set to the
/// generated handler.
///
/// 3. A macro used by [`uri!`] to type-check and generate an
/// [`Origin`].
///
/// [`Handler`]: ../rocket/route/trait.Handler.html
/// [`routes!`]: macro.routes.html
/// [`uri!`]: macro.uri.html
/// [`Origin`]: ../rocket/http/uri/struct.Origin.html
/// [`Outcome`]: ../rocket/outcome/enum.Outcome.html
/// [`Response`]: ../rocket/struct.Response.html
/// [`FromRequest` Outcomes]: ../rocket/request/trait.FromRequest.html#outcomes
#[proc_macro_attribute]
pub fn $name(args: TokenStream, input: TokenStream) -> TokenStream {
emit!(attribute::route::route_attribute($method, args, input))
}
)
}
route_attribute!(route => None);
route_attribute!(get => Method::Get);
route_attribute!(put => Method::Put);
route_attribute!(post => Method::Post);
route_attribute!(delete => Method::Delete);
route_attribute!(head => Method::Head);
route_attribute!(patch => Method::Patch);
route_attribute!(options => Method::Options);
/// Attribute to generate a [`Catcher`] and associated metadata.
///
/// This attribute can only be applied to free functions:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// #
/// use rocket::Request;
/// use rocket::http::Status;
///
/// #[catch(404)]
/// fn not_found(req: &Request) -> String {
/// format!("Sorry, {} does not exist.", req.uri())
/// }
///
/// #[catch(default)]
/// fn default(status: Status, req: &Request) -> String {
/// format!("{} ({})", status, req.uri())
/// }
/// ```
///
/// # Grammar
///
/// The grammar for the `#[catch]` attributes is defined as:
///
/// ```text
/// catch := STATUS | 'default'
///
/// STATUS := valid HTTP status code (integer in [200, 599])
/// ```
///
/// # Typing Requirements
///
/// The decorated function may take zero, one, or two arguments. It's type
/// signature must be one of the following, where `R:`[`Responder`]:
///
/// * `fn() -> R`
/// * `fn(`[`&Request`]`) -> R`
/// * `fn(`[`Status`]`, `[`&Request`]`) -> R`
///
/// # Semantics
///
/// The attribute generates two items:
///
/// 1. An error [`Handler`].
///
/// The generated handler calls the decorated function, passing in the
/// [`Status`] and [`&Request`] values if requested. The returned value is
/// used to generate a [`Response`] via the type's [`Responder`]
/// implementation.
///
/// 2. A static structure used by [`catchers!`] to generate a [`Catcher`].
///
/// The static structure (and resulting [`Catcher`]) is populated with the
/// name (the function's name) and status code from the route attribute or
/// `None` if `default`. The handler is set to the generated handler.
///
/// [`&Request`]: ../rocket/struct.Request.html
/// [`Status`]: ../rocket/http/struct.Status.html
/// [`Handler`]: ../rocket/catcher/trait.Handler.html
/// [`catchers!`]: macro.catchers.html
/// [`Catcher`]: ../rocket/struct.Catcher.html
/// [`Response`]: ../rocket/struct.Response.html
/// [`Responder`]: ../rocket/response/trait.Responder.html
#[proc_macro_attribute]
pub fn catch(args: TokenStream, input: TokenStream) -> TokenStream {
emit!(attribute::catch::catch_attribute(args, input))
}
/// Suppress a warning generated by a Rocket lint.
///
/// Lints:
/// * `unknown_format`
/// * `dubious_payload`
/// * `segment_chars`
/// * `arbitrary_main`
/// * `sync_spawn`
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate rocket;
///
/// #[suppress(dubious_payload)]
/// #[get("/", data = "<_a>")]
/// fn _f(_a: String) { }
///
/// #[get("/", data = "<_a>", format = "foo/bar")]
/// #[suppress(dubious_payload, unknown_format)]
/// fn _g(_a: String) { }
/// ```
#[proc_macro_attribute]
pub fn suppress(args: TokenStream, input: TokenStream) -> TokenStream {
emit!(attribute::suppress::suppress_attribute(args, input))
}
/// Retrofits supports for `async fn` in unit tests.
///
/// Simply decorate a test `async fn` with `#[async_test]` instead of `#[test]`:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// #[cfg(test)]
/// mod tests {
/// #[async_test]
/// async fn test() {
/// /* .. */
/// }
/// }
/// ```
///
/// The attribute rewrites the function to execute inside of a Rocket-compatible
/// async runtime.
#[proc_macro_attribute]
pub fn async_test(args: TokenStream, input: TokenStream) -> TokenStream {
emit!(attribute::entry::async_test_attribute(args, input))
}
/// Retrofits `async fn` support in `main` functions.
///
/// A `main` `async fn` function decorated with `#[rocket::main]` is transformed
/// into a regular `main` function that internally initializes a Rocket-specific
/// tokio runtime and runs the attributed `async fn` inside of it:
///
/// ```rust,no_run
/// #[rocket::main]
/// async fn main() -> Result<(), rocket::Error> {
/// let _rocket = rocket::build()
/// .ignite().await?
/// .launch().await?;
///
/// Ok(())
/// }
/// ```
///
/// It should be used only when the return values of `ignite()` or `launch()`
/// are to be inspected:
///
/// ```rust,no_run
/// #[rocket::main]
/// async fn main() -> Result<(), rocket::Error> {
/// let rocket = rocket::build().ignite().await?;
/// println!("Hello, Rocket: {:?}", rocket);
///
/// let rocket = rocket.launch().await?;
/// println!("Welcome back, Rocket: {:?}", rocket);
///
/// Ok(())
/// }
/// ```
///
/// For all other cases, use [`#[launch]`](launch) instead.
///
/// The function attributed with `#[rocket::main]` _must_ be `async` and _must_
/// be called `main`. Violation of either results in a compile-time error.
#[proc_macro_attribute]
pub fn main(args: TokenStream, input: TokenStream) -> TokenStream {
emit!(attribute::entry::main_attribute(args, input))
}
/// Generates a `main` function that launches a returned `Rocket<Build>`.
///
/// When applied to a function that returns a `Rocket<Build>` instance,
/// `#[launch]` automatically initializes an `async` runtime and
/// launches the function's returned instance:
///
/// ```rust,no_run
/// # use rocket::launch;
/// use rocket::{Rocket, Build};
///
/// #[launch]
/// fn rocket() -> Rocket<Build> {
/// rocket::build()
/// }
/// ```
///
/// This generates code equivalent to the following:
///
/// ```rust,no_run
/// # use rocket::{Rocket, Build};
/// # fn rocket() -> Rocket<Build> {
/// # rocket::build()
/// # }
/// #
/// #[rocket::main]
/// async fn main() {
/// // Recall that an uninspected `Error` will cause a pretty-printed panic,
/// // so rest assured errors do not go undetected when using `#[launch]`.
/// let _ = rocket().launch().await;
/// }
/// ```
///
/// To avoid needing to import _any_ items in the common case, the `launch`
/// attribute will infer a return type written as `_` as `Rocket<Build>`:
///
/// ```rust,no_run
/// # use rocket::launch;
/// #[launch]
/// fn rocket() -> _ {
/// rocket::build()
/// }
/// ```
///
/// The attributed function may be `async`:
///
/// ```rust,no_run
/// # use rocket::launch;
/// # async fn some_async_work() {}
/// #[launch]
/// async fn rocket() -> _ {
/// some_async_work().await;
/// rocket::build()
/// }
/// ```
#[proc_macro_attribute]
pub fn launch(args: TokenStream, input: TokenStream) -> TokenStream {
emit!(attribute::entry::launch_attribute(args, input))
}
/// Derive for the [`FromFormField`] trait.
///
/// The [`FromFormField`] derive can be applied to enums with nullary
/// (zero-length) fields:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// #
/// #[derive(FromFormField)]
/// enum MyValue {
/// First,
/// Second,
/// Third,
/// }
/// ```
///
/// The derive generates an implementation of the [`FromFormField`] trait for
/// the decorated `enum`. The implementation returns successfully when the form
/// value matches, case insensitively, the stringified version of a variant's
/// name, returning an instance of said variant. If there is no match, an error
/// recording all of the available options is returned.
///
/// As an example, for the `enum` above, the form values `"first"`, `"FIRST"`,
/// `"fiRSt"`, and so on would parse as `MyValue::First`, while `"second"` and
/// `"third"` (in any casing) would parse as `MyValue::Second` and
/// `MyValue::Third`, respectively.
///
/// The `field` field attribute can be used to change the string value that is
/// compared against for a given variant:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// #
/// #[derive(FromFormField)]
/// enum MyValue {
/// First,
/// Second,
/// #[field(value = "fourth")]
/// #[field(value = "fifth")]
/// Third,
/// }
/// ```
///
/// When more than one `value` is specified, matching _any_ value will result in
/// parsing the decorated variant. Declaring any two values that are
/// case-insensitively equal to any other value or variant name is a
/// compile-time error.
///
/// The `#[field]` attribute's grammar is:
///
/// ```text
/// field := 'value' '=' STRING_LIT
///
/// STRING_LIT := any valid string literal, as defined by Rust
/// ```
///
/// The attribute accepts a single string parameter of name `value`
/// corresponding to the string to use to match against for the decorated
/// variant. In the example above, the the strings `"fourth"`, `"FOUrth"`,
/// `"fiFTH"` and so on would parse as `MyValue::Third`.
///
/// [`FromFormField`]: ../rocket/form/trait.FromFormField.html
#[proc_macro_derive(FromFormField, attributes(field))]
pub fn derive_from_form_field(input: TokenStream) -> TokenStream {
emit!(derive::from_form_field::derive_from_form_field(input))
}
/// Derive for the [`FromForm`] trait.
///
/// The [`FromForm`] derive can be applied to structures with named or unnamed
/// fields:
///
/// ```rust
/// use rocket::form::FromForm;
///
/// #[derive(FromForm)]
/// struct MyStruct<'r> {
/// field: usize,
/// #[field(name = "renamed_field")]
/// #[field(name = uncased("RenamedField"))]
/// other: &'r str,
/// #[field(validate = range(1..), default = 3)]
/// r#type: usize,
/// #[field(default = None)]
/// is_nice: bool,
/// }
///
/// #[derive(FromForm)]
/// #[field(validate = len(6..))]
/// #[field(validate = neq("password"))]
/// struct Password<'r>(&'r str);
/// ```
///
/// Each field type is required to implement [`FromForm`].
///
/// The derive generates an implementation of the [`FromForm`] trait.
///
/// **Named Fields**
///
/// If the structure has named fields, the implementation parses a form whose
/// field names match the field names of the structure on which the derive was
/// applied. Each field's value is parsed with the [`FromForm`] implementation
/// of the field's type. The `FromForm` implementation succeeds only when all
/// fields parse successfully or return a default. Errors are collected into a
/// [`form::Errors`] and returned if non-empty after parsing all fields.
///
/// **Unnamed Fields**
///
/// If the structure is a tuple struct, it must have exactly one field. The
/// implementation parses a form exactly when the internal field parses a form
/// _and_ any `#[field]` validations succeed.
///
/// ## Syntax
///
/// The derive accepts one field attribute: `field`, and one container
/// attribute, `form`, with the following syntax:
///
/// ```text
/// field := name? default? validate*
///
/// name := 'name' '=' name_val ','?
/// name_val := '"' FIELD_NAME '"'
/// | 'uncased(' '"' FIELD_NAME '"' ')
///
/// default := 'default' '=' EXPR ','?
/// | 'default_with' '=' EXPR ','?
///
/// validate := 'validate' '=' EXPR ','?
///
/// FIELD_NAME := valid field name, according to the HTML5 spec
/// EXPR := valid expression, as defined by Rust
/// ```
///
/// `#[field]` can be applied any number of times on a field. `default` and
/// `default_with` are mutually exclusive: at most _one_ of `default` or
/// `default_with` can be present per field.
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// #[derive(FromForm)]
/// struct MyStruct {
/// #[field(name = uncased("number"))]
/// #[field(default = 42)]
/// field: usize,
/// #[field(name = "renamed_field")]
/// #[field(name = uncased("anotherName"))]
/// #[field(validate = eq("banana"))]
/// #[field(validate = neq("orange"))]
/// other: String
/// }
/// ```
///
/// For tuples structs, the `field` attribute can be applied to the structure
/// itself:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// #[derive(FromForm)]
/// #[field(default = 42, validate = eq(42))]
/// struct Meaning(usize);
/// ```
///
/// ## Field Attribute Parameters
///
/// * **`name`**
///
/// A `name` attribute changes the name to match against when parsing the
/// form field. The value is either an exact string to match against
/// (`"foo"`), or `uncased("foo")`, which causes the match to be
/// case-insensitive but case-preserving. When more than one `name`
/// attribute is applied, the field will match against _any_ of the names.
///
/// * **`validate = expr`**
///
/// The validation `expr` is run if the field type parses successfully. The
/// expression must return a value of type `Result<(), form::Errors>`. On
/// `Err`, the errors are added to the thus-far collected errors. If more
/// than one `validate` attribute is applied, _all_ validations are run.
///
/// * **`default = expr`**
///
/// If `expr` is not literally `None`, the parameter sets the default value
/// of the field to be `expr.into()`. If `expr` _is_ `None`, the parameter
/// _unsets_ the default value of the field, if any. The expression is only
/// evaluated if the attributed field is missing in the incoming form.
///
/// Except when `expr` is `None`, `expr` must be of type `T: Into<F>` where
/// `F` is the field's type.
///
/// * **`default_with = expr`**
///
/// The parameter sets the default value of the field to be exactly `expr`
/// which must be of type `Option<F>` where `F` is the field's type. If the
/// expression evaluates to `None`, there is no default. Otherwise the value
/// wrapped in `Some` is used. The expression is only evaluated if the
/// attributed field is missing in the incoming form.
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// use std::num::NonZeroUsize;
///
/// #[derive(FromForm)]
/// struct MyForm {
/// // `NonZeroUsize::new()` return an `Option<NonZeroUsize>`.
/// #[field(default_with = NonZeroUsize::new(42))]
/// num: NonZeroUsize,
/// }
/// ```
///
/// [`FromForm`]: ../rocket/form/trait.FromForm.html
/// [`form::Errors`]: ../rocket/form/struct.Errors.html
///
/// # Generics
///
/// The derive accepts any number of type generics and at most one lifetime
/// generic. If a type generic is present, the generated implementation will
/// require a bound of `FromForm<'r>` for the field type containing the generic.
/// For example, for a struct `struct Foo<T>(Json<T>)`, the bound `Json<T>:
/// FromForm<'r>` will be added to the generated implementation.
///
/// ```rust
/// use rocket::form::FromForm;
/// use rocket::serde::json::Json;
///
/// // The bounds `A: FromForm<'r>`, `B: FromForm<'r>` will be required.
/// #[derive(FromForm)]
/// struct FancyForm<A, B> {
/// first: A,
/// second: B,
/// };
///
/// // The bound `Json<T>: FromForm<'r>` will be required.
/// #[derive(FromForm)]
/// struct JsonToken<T> {
/// token: Json<T>,
/// id: usize,
/// }
/// ```
///
/// If a lifetime generic is present, it is replaced with `'r` in the
/// generated implementation `impl FromForm<'r>`:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// // Generates `impl<'r> FromForm<'r> for MyWrapper<'r>`.
/// #[derive(FromForm)]
/// struct MyWrapper<'a>(&'a str);
/// ```
///
/// Both type generics and one lifetime generic may be used:
///
/// ```rust
/// use rocket::form::{self, FromForm};
///
/// // The bound `form::Result<'r, T>: FromForm<'r>` will be required.
/// #[derive(FromForm)]
/// struct SomeResult<'o, T>(form::Result<'o, T>);
/// ```
///
/// The special bounds on `Json` and `Result` are required due to incomplete and
/// incorrect support for lifetime generics in `async` blocks in Rust. See
/// [rust-lang/#64552](https://github.com/rust-lang/rust/issues/64552) for
/// further details.
#[proc_macro_derive(FromForm, attributes(form, field))]
pub fn derive_from_form(input: TokenStream) -> TokenStream {
emit!(derive::from_form::derive_from_form(input))
}
/// Derive for the [`FromParam`] trait.
///
/// This [`FromParam`] derive can be applied to C-like enums whose variants have
/// no fields. The generated implementation case-sensitively matches each
/// variant to its stringified field name. If there is no match, an error
/// of type [`InvalidOption`] is returned.
///
/// [`FromParam`]: ../rocket/request/trait.FromParam.html
/// [`InvalidOption`]: ../rocket/error/struct.InvalidOption.html
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// use rocket::request::FromParam;
///
/// #[derive(FromParam, Debug, PartialEq)]
/// enum MyParam {
/// A,
/// Bob,
/// }
///
/// assert_eq!(MyParam::from_param("A").unwrap(), MyParam::A);
/// assert_eq!(MyParam::from_param("Bob").unwrap(), MyParam::Bob);
/// assert!(MyParam::from_param("a").is_err());
/// assert!(MyParam::from_param("bob").is_err());
/// assert!(MyParam::from_param("c").is_err());
/// assert!(MyParam::from_param("C").is_err());
///
/// // Now `MyParam` can be used in an route to accept either `A` or `B`.
/// #[get("/<param>")]
/// fn index(param: MyParam) -> &'static str {
/// match param {
/// MyParam::A => "A",
/// MyParam::Bob => "Bob",
/// }
/// }
#[proc_macro_derive(FromParam)]
pub fn derive_from_param(input: TokenStream) -> TokenStream {
emit!(derive::from_param::derive_from_param(input))
}
/// Derive for the [`Responder`] trait.
///
/// The [`Responder`] derive can be applied to enums and structs with named
/// fields. When applied to enums, variants must have at least one field. When
/// applied to structs, the struct must have at least one field.
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// # use std::fs::File;
/// # use rocket::http::ContentType;
/// # type OtherResponder = MyResponderA;
/// #
/// #[derive(Responder)]
/// enum MyResponderA {
/// A(String),
/// B(File, ContentType),
/// }
///
/// #[derive(Responder)]
/// struct MyResponderB {
/// inner: OtherResponder,
/// header: ContentType,
/// }
/// ```
///
/// # Semantics
///
/// The derive generates an implementation of the [`Responder`] trait for the
/// decorated enum or structure. The derive uses the _first_ field of a variant
/// or structure to generate a [`Response`]. As such, the type of the first
/// field must implement [`Responder`]. The remaining fields of a variant or
/// structure are set as headers in the produced [`Response`] using
/// [`Response::set_header()`]. As such, every other field (unless explicitly
/// ignored, explained next) must implement `Into<Header>`.
///
/// Except for the first field, fields decorated with `#[response(ignore)]` are
/// ignored by the derive:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// # use std::fs::File;
/// # use rocket::http::ContentType;
/// # use rocket::fs::NamedFile;
/// # type Other = usize;
/// #
/// #[derive(Responder)]
/// enum MyResponder {
/// A(String),
/// B(File, ContentType, #[response(ignore)] Other),
/// }
///
/// #[derive(Responder)]
/// struct MyOtherResponder {
/// inner: NamedFile,
/// header: ContentType,
/// #[response(ignore)]
/// other: Other,
/// }
/// ```
///
/// Decorating the first field with `#[response(ignore)]` has no effect.
///
/// # Field Attribute
///
/// Additionally, the `response` attribute can be used on named structures and
/// enum variants to override the status and/or content-type of the [`Response`]
/// produced by the generated implementation. The `response` attribute used in
/// these positions has the following grammar:
///
/// ```text
/// response := parameter (',' parameter)?
///
/// parameter := 'status' '=' STATUS
/// | 'content_type' '=' CONTENT_TYPE
///
/// STATUS := unsigned integer >= 100 and < 600
/// CONTENT_TYPE := string literal, as defined by Rust, identifying a valid
/// Content-Type, as defined by Rocket
/// ```
///
/// It can be used as follows:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// # use rocket::http::ContentType;
/// # use rocket::fs::NamedFile;
/// # type Other = usize;
/// # type InnerResponder = String;
/// #
/// #[derive(Responder)]
/// enum Error {
/// #[response(status = 500, content_type = "json")]
/// A(String),
/// #[response(status = 404)]
/// B(NamedFile, ContentType),
/// }
///
/// #[derive(Responder)]
/// #[response(status = 400)]
/// struct MyResponder {
/// inner: InnerResponder,
/// header: ContentType,
/// #[response(ignore)]
/// other: Other,
/// }
/// ```
///
/// The attribute accepts two key/value pairs: `status` and `content_type`. The
/// value of `status` must be an unsigned integer representing a valid status
/// code. The [`Response`] produced from the generated implementation will have
/// its status overridden to this value.
///
/// The value of `content_type` must be a valid media-type in `top/sub` form or
/// `shorthand` form. Examples include:
///
/// * `"text/html"`
/// * `"application/x-custom"`
/// * `"html"`
/// * `"json"`
/// * `"plain"`
/// * `"binary"`
///
/// See [`ContentType::parse_flexible()`] for a full list of available
/// shorthands. The [`Response`] produced from the generated implementation will
/// have its content-type overridden to this value.
///
/// [`Responder`]: ../rocket/response/trait.Responder.html
/// [`Response`]: ../rocket/struct.Response.html
/// [`Response::set_header()`]: ../rocket/response/struct.Response.html#method.set_header
/// [`ContentType::parse_flexible()`]: ../rocket/http/struct.ContentType.html#method.parse_flexible
///
/// # Generics
///
/// The derive accepts any number of type generics and at most one lifetime
/// generic. If a type generic is present and the generic is used in the first
/// field of a structure, the generated implementation will require a bound of
/// `Responder<'r, 'o>` for the field type containing the generic. In all other
/// fields, unless ignores, a bound of `Into<Header<'o>` is added.
///
/// For example, for a struct `struct Foo<T, H>(Json<T>, H)`, the derive adds:
///
/// * `Json<T>: Responder<'r, 'o>`
/// * `H: Into<Header<'o>>`
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// use rocket::serde::Serialize;
/// use rocket::serde::json::Json;
/// use rocket::http::ContentType;
/// use rocket::response::Responder;
///
/// // The bound `T: Responder` will be added.
/// #[derive(Responder)]
/// #[response(status = 404, content_type = "html")]
/// struct NotFoundHtml<T>(T);
///
/// // The bound `Json<T>: Responder` will be added.
/// #[derive(Responder)]
/// struct NotFoundJson<T>(Json<T>);
///
/// // The bounds `Json<T>: Responder, E: Responder` will be added.
/// #[derive(Responder)]
/// enum MyResult<T, E> {
/// Ok(Json<T>),
/// #[response(status = 404)]
/// Err(E, ContentType)
/// }
/// ```
///
/// If a lifetime generic is present, it will be replaced with `'o` in the
/// generated implementation `impl Responder<'r, 'o>`:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// // Generates `impl<'r, 'o> Responder<'r, 'o> for NotFoundHtmlString<'o>`.
/// #[derive(Responder)]
/// #[response(status = 404, content_type = "html")]
/// struct NotFoundHtmlString<'a>(&'a str);
/// ```
///
/// Both type generics and lifetime generic may be used:
///