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
#![doc = include_str!("../README.md")]

//! ## About
//! Custom derive support for the [`der`] crate.
//!
//! This crate contains custom derive macros intended to be used in the
//! following way:
//!
//! - [`Choice`][`derive@Choice`]: map ASN.1 `CHOICE` to a Rust enum.
//! - [`Enumerated`][`derive@Enumerated`]: map ASN.1 `ENUMERATED` to a C-like Rust enum.
//! - [`Sequence`][`derive@Sequence`]: map ASN.1 `SEQUENCE` to a Rust struct.
//! - [`ValueOrd`][`derive@ValueOrd`]: determine DER ordering for ASN.1 `SET OF`.
//!
//! Note that this crate shouldn't be used directly, but instead accessed
//! by using the `derive` feature of the `der` crate, which re-exports the
//! above macros from the toplevel.
//!
//! ## Why not `serde`?
//! The `der` crate is designed to be easily usable in embedded environments,
//! including ones where code size comes at a premium.
//!
//! This crate (i.e. `der_derive`) is able to generate code which is
//! significantly smaller than `serde_derive`. This is because the `der`
//! crate has been designed with high-level abstractions which reduce
//! code size, including trait object-based encoders which allow encoding
//! logic which is duplicated in `serde` serializers to be implemented in
//! a single place in the `der` crate.
//!
//! This is a deliberate tradeoff in terms of performance, flexibility, and
//! code size. At least for now, the `der` crate is optimizing for leveraging
//! as many abstractions as it can to minimize code size.
//!
//! ## Toplevel attributes
//!
//! The following attributes can be added to an `enum` or `struct` when
//! deriving either [`Choice`] or [`Sequence`] respectively:
//!
//! ### `#[asn1(tag_mode = "...")]` attribute: `EXPLICIT` vs `IMPLICIT`
//!
//! This attribute can be used to declare the tagging mode used by a particular
//! ASN.1 module.
//!
//! It's used when parsing `CONTEXT-SENSITIVE` fields.
//!
//! The default is `EXPLICIT`, so the attribute only needs to be added when
//! a particular module is declared `IMPLICIT`.
//!
//! ## Field-level attributes
//!
//! The following attributes can be added to either the fields of a particular
//! `struct` or the variants of a particular `enum`:
//!
//! ### `#[asn1(context_specific = "...")]` attribute: `CONTEXT-SPECIFIC` support
//!
//! This attribute can be added to associate a particular `CONTEXT-SPECIFIC`
//! tag number with a given enum variant or struct field.
//!
//! The value must be quoted and contain a number, e.g. `#[asn1(context_specific = "42"]`.
//!
//! ### `#[asn1(default = "...")]` attribute: `DEFAULT` support
//!
//! This behaves like `serde_derive`'s `default` attribute, allowing you to
//! specify the path to a function which returns a default value.
//!
//! ### `#[asn1(extensible = "true")]` attribute: support for `...` extensibility operator
//!
//! This attribute can be applied to the fields of `struct` types, and will
//! skip over unrecognized lower-numbered `CONTEXT-SPECIFIC` fields when
//! looking for a particular field of a struct.
//!
//! ### `#[asn1(optional = "true")]` attribute: support for `OPTIONAL` fields
//!
//! This attribute explicitly annotates a field as `OPTIONAL`.
//!
//! ### `#[asn1(type = "...")]` attribute: ASN.1 type declaration
//!
//! This attribute can be used to specify the ASN.1 type for a particular
//! `enum` variant or `struct` field.
//!
//! It's presently mandatory for all `enum` variants, even when using one of
//! the ASN.1 types defined by this crate.
//!
//! For structs, placing this attribute on a field makes it possible to
//! decode/encode types which don't directly implement the `Decode`/`Encode`
//! traits but do impl `From` and `TryInto` and `From` for one of the ASN.1 types
//! listed below (use the ASN.1 type keywords as the `type`):
//!
//! - `BIT STRING`: performs an intermediate conversion to [`der::asn1::BitString`]
//! - `IA5String`: performs an intermediate conversion to [`der::asn1::IA5String`]
//! - `GeneralizedTime`: performs an intermediate conversion to [`der::asn1::GeneralizedTime`]
//! - `OCTET STRING`: performs an intermediate conversion to [`der::asn1::OctetString`]
//! - `PrintableString`: performs an intermediate conversion to [`der::asn1::PrintableString`]
//! - `UTCTime`: performs an intermediate conversion to [`der::asn1::UtcTime`]
//! - `UTF8String`: performs an intermediate conversion to [`der::asn1::Utf8String`]
//!
//! ### `#[asn1(constructed = "...")]` attribute: support for constructed inner types
//!
//! This attribute can be used to specify that an "inner" type is constructed. It is most
//! commonly used when a `CHOICE` has a constructed inner type.
//!
//! Note: please open a GitHub Issue if you would like to request support
//! for additional ASN.1 types.
//!
//! [`der`]: https://docs.rs/der/
//! [`Choice`]: derive@Choice
//! [`Sequence`]: derive@Sequence
//! [`der::asn1::BitString`]: https://docs.rs/der/latest/der/asn1/struct.BitString.html
//! [`der::asn1::Ia5String`]: https://docs.rs/der/latest/der/asn1/struct.Ia5String.html
//! [`der::asn1::GeneralizedTime`]: https://docs.rs/der/latest/der/asn1/struct.GeneralizedTime.html
//! [`der::asn1::OctetString`]: https://docs.rs/der/latest/der/asn1/struct.OctetString.html
//! [`der::asn1::PrintableString`]: https://docs.rs/der/latest/der/asn1/struct.PrintableString.html
//! [`der::asn1::UtcTime`]: https://docs.rs/der/latest/der/asn1/struct.UtcTime.html
//! [`der::asn1::Utf8String`]: https://docs.rs/der/latest/der/asn1/struct.Utf8String.html

#![crate_type = "proc-macro"]
#![forbid(unsafe_code, clippy::unwrap_used)]
#![warn(rust_2018_idioms, trivial_casts, unused_qualifications)]

mod asn1_type;
mod attributes;
mod choice;
mod enumerated;
mod newtype;
mod sequence;
mod tag;
mod value_ord;

use crate::{
    asn1_type::Asn1Type,
    attributes::{FieldAttrs, TypeAttrs, ATTR_NAME},
    choice::DeriveChoice,
    enumerated::DeriveEnumerated,
    newtype::DeriveNewtype,
    sequence::DeriveSequence,
    tag::{Tag, TagMode, TagNumber},
    value_ord::DeriveValueOrd,
};
use proc_macro::TokenStream;
use proc_macro_error::proc_macro_error;
use syn::{parse_macro_input, DeriveInput};

/// Derive the [`Choice`][1] trait on an `enum`.
///
/// This custom derive macro can be used to automatically impl the
/// [`Decodable`][2] and [`Encodable`][3] traits along with the
/// [`Choice`][1] supertrait for any enum representing an ASN.1 `CHOICE`.
///
/// The enum must consist entirely of 1-tuple variants wrapping inner
/// types which must also impl the [`Decodable`][2] and [`Encodable`][3]
/// traits. It will will also generate [`From`] impls for each of the
/// inner types of the variants into the enum that wraps them.
///
/// # Usage
///
/// ```ignore
/// // NOTE: requires the `derive` feature of `der`
/// use der::Choice;
///
/// /// `Time` as defined in RFC 5280
/// #[derive(Choice)]
/// pub enum Time {
///     #[asn1(type = "UTCTime")]
///     UtcTime(UtcTime),
///
///     #[asn1(type = "GeneralizedTime")]
///     GeneralTime(GeneralizedTime),
/// }
/// ```
///
/// # `#[asn1(type = "...")]` attribute
///
/// See [toplevel documentation for the `der_derive` crate][4] for more
/// information about the `#[asn1]` attribute.
///
/// [1]: https://docs.rs/der/latest/der/trait.Choice.html
/// [2]: https://docs.rs/der/latest/der/trait.Decodable.html
/// [3]: https://docs.rs/der/latest/der/trait.Encodable.html
/// [4]: https://docs.rs/der_derive/
#[proc_macro_derive(Choice, attributes(asn1))]
#[proc_macro_error]
pub fn derive_choice(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    DeriveChoice::new(input).to_tokens().into()
}

/// Derive decoders and encoders for ASN.1 [`Enumerated`] types on a
/// C-like `enum` type.
///
/// # Usage
///
/// The `Enumerated` proc macro requires a C-like enum which impls `Copy`
/// and has a `#[repr]` of `u8`, `u16`, or `u32`:
///
/// ```ignore
/// use der::Enumerated;
///
/// #[derive(Enumerated, Copy, Clone, Debug, Eq, PartialEq)]
/// #[repr(u32)]
/// pub enum CrlReason {
///     Unspecified = 0,
///     KeyCompromise = 1,
///     CaCompromise = 2,
///     AffiliationChanged = 3,
///     Superseded = 4,
///     CessationOfOperation = 5,
///     CertificateHold = 6,
///     RemoveFromCrl = 8,
///     PrivilegeWithdrawn = 9,
///     AaCompromised = 10
/// }
/// ```
///
/// Note that the derive macro will write a `TryFrom<...>` impl for the
/// provided `#[repr]`, which is used by the decoder.
#[proc_macro_derive(Enumerated, attributes(asn1))]
#[proc_macro_error]
pub fn derive_enumerated(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    DeriveEnumerated::new(input).to_tokens().into()
}

/// Derive the [`Sequence`][1] trait on a `struct`.
///
/// This custom derive macro can be used to automatically impl the
/// `Sequence` trait for any struct which can be decoded/encoded as an
/// ASN.1 `SEQUENCE`.
///
/// # Usage
///
/// ```ignore
/// use der::{
///     asn1::{Any, ObjectIdentifier},
///     Sequence
/// };
///
/// /// X.509 `AlgorithmIdentifier`
/// #[derive(Sequence)]
/// pub struct AlgorithmIdentifier<'a> {
///     /// This field contains an ASN.1 `OBJECT IDENTIFIER`, a.k.a. OID.
///     pub algorithm: ObjectIdentifier,
///
///     /// This field is `OPTIONAL` and contains the ASN.1 `ANY` type, which
///     /// in this example allows arbitrary algorithm-defined parameters.
///     pub parameters: Option<Any<'a>>
/// }
/// ```
///
/// # `#[asn1(type = "...")]` attribute
///
/// See [toplevel documentation for the `der_derive` crate][2] for more
/// information about the `#[asn1]` attribute.
///
/// [1]: https://docs.rs/der/latest/der/trait.Sequence.html
/// [2]: https://docs.rs/der_derive/
#[proc_macro_derive(Sequence, attributes(asn1))]
#[proc_macro_error]
pub fn derive_sequence(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    DeriveSequence::new(input).to_tokens().into()
}

/// Derive the [`ValueOrd`][1] trait on a `struct`.
///
/// This trait is used in conjunction with ASN.1 `SET OF` types to determine
/// the lexicographical order of their DER encodings.
///
/// [1]: https://docs.rs/der/latest/der/trait.ValueOrd.html
#[proc_macro_derive(ValueOrd, attributes(asn1))]
#[proc_macro_error]
pub fn derive_value_ord(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    DeriveValueOrd::new(input).to_tokens().into()
}

/// Wraps a der type in a newtype.
///
/// The newtype receives implementations of `der::FixedTag`,
/// `der::DecodeValue`, `der::EncodeValue`, `Deref`, `DerefMut`, and
/// bi-directional `From`.
#[proc_macro_derive(Newtype)]
#[proc_macro_error]
pub fn derive_newtype(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    DeriveNewtype::new(input).to_tokens().into()
}