]> git.proxmox.com Git - rustc.git/blob - vendor/clap_derive/src/derives/parser.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / vendor / clap_derive / src / derives / parser.rs
1 // Copyright 2018 Guillaume Pinot (@TeXitoi) <texitoi@texitoi.eu>,
2 // Kevin Knapp (@kbknapp) <kbknapp@gmail.com>, and
3 // Ana Hobden (@hoverbear) <operator@hoverbear.org>
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 //
11 // This work was derived from Structopt (https://github.com/TeXitoi/structopt)
12 // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the
13 // MIT/Apache 2.0 license.
14
15 use crate::{
16 derives::{args, into_app, subcommand},
17 dummies,
18 };
19
20 use proc_macro2::TokenStream;
21 use proc_macro_error::abort_call_site;
22 use quote::quote;
23 use syn::{
24 self, punctuated::Punctuated, token::Comma, Attribute, Data, DataEnum, DataStruct, DeriveInput,
25 Field, Fields, Generics, Ident,
26 };
27
28 pub fn derive_parser(input: &DeriveInput) -> TokenStream {
29 let ident = &input.ident;
30
31 match input.data {
32 Data::Struct(DataStruct {
33 fields: Fields::Named(ref fields),
34 ..
35 }) => {
36 dummies::parser_struct(ident);
37 gen_for_struct(ident, &input.generics, &fields.named, &input.attrs)
38 }
39 Data::Struct(DataStruct {
40 fields: Fields::Unit,
41 ..
42 }) => {
43 dummies::parser_struct(ident);
44 gen_for_struct(
45 ident,
46 &input.generics,
47 &Punctuated::<Field, Comma>::new(),
48 &input.attrs,
49 )
50 }
51 Data::Enum(ref e) => {
52 dummies::parser_enum(ident);
53 gen_for_enum(ident, &input.generics, &input.attrs, e)
54 }
55 _ => abort_call_site!("`#[derive(Parser)]` only supports non-tuple structs and enums"),
56 }
57 }
58
59 fn gen_for_struct(
60 name: &Ident,
61 generics: &Generics,
62 fields: &Punctuated<Field, Comma>,
63 attrs: &[Attribute],
64 ) -> TokenStream {
65 let into_app = into_app::gen_for_struct(name, generics, attrs);
66 let args = args::gen_for_struct(name, generics, fields, attrs);
67
68 let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
69
70 quote! {
71 impl #impl_generics clap::Parser for #name #ty_generics #where_clause {}
72
73 #into_app
74 #args
75 }
76 }
77
78 fn gen_for_enum(
79 name: &Ident,
80 generics: &Generics,
81 attrs: &[Attribute],
82 e: &DataEnum,
83 ) -> TokenStream {
84 let into_app = into_app::gen_for_enum(name, generics, attrs);
85 let subcommand = subcommand::gen_for_enum(name, generics, attrs, e);
86
87 let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
88
89 quote! {
90 impl #impl_generics clap::Parser for #name #ty_generics #where_clause {}
91
92 #into_app
93 #subcommand
94 }
95 }