| 1 | // Copyright 2019 The Fuchsia Authors |
| 2 | // |
| 3 | // Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 |
| 4 | // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT |
| 5 | // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. |
| 6 | // This file may not be copied, modified, or distributed except according to |
| 7 | // those terms. |
| 8 | |
| 9 | use syn::{Data, DataEnum, DataStruct, DataUnion, Type}; |
| 10 | |
| 11 | pub trait DataExt { |
| 12 | /// Extract the types of all fields. For enums, extract the types of fields |
| 13 | /// from each variant. |
| 14 | fn field_types(&self) -> Vec<&Type>; |
| 15 | } |
| 16 | |
| 17 | impl DataExt for Data { |
| 18 | fn field_types(&self) -> Vec<&Type> { |
| 19 | match self { |
| 20 | Data::Struct(strc: &DataStruct) => strc.field_types(), |
| 21 | Data::Enum(enm: &DataEnum) => enm.field_types(), |
| 22 | Data::Union(un: &DataUnion) => un.field_types(), |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | impl DataExt for DataStruct { |
| 28 | fn field_types(&self) -> Vec<&Type> { |
| 29 | self.fields.iter().map(|f: &Field| &f.ty).collect() |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | impl DataExt for DataEnum { |
| 34 | fn field_types(&self) -> Vec<&Type> { |
| 35 | self.variants.iter().flat_map(|var: &Variant| &var.fields).map(|f: &Field| &f.ty).collect() |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | impl DataExt for DataUnion { |
| 40 | fn field_types(&self) -> Vec<&Type> { |
| 41 | self.fields.named.iter().map(|f: &Field| &f.ty).collect() |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | pub trait EnumExt { |
| 46 | fn is_c_like(&self) -> bool; |
| 47 | } |
| 48 | |
| 49 | impl EnumExt for DataEnum { |
| 50 | fn is_c_like(&self) -> bool { |
| 51 | self.field_types().is_empty() |
| 52 | } |
| 53 | } |
| 54 | |