facet_macro_parse/
lib.rs

1//! # Facet Macro Parse
2//!
3//! Parsed type representations for the facet macro ecosystem.
4//!
5//! This crate provides the parsed types (`PStruct`, `PEnum`, `PContainer`, `PAttrs`, etc.)
6//! that represent the result of parsing Rust type definitions for code generation.
7//!
8//! It depends on `facet-macro-types` for the underlying unsynn grammar.
9
10#![allow(uncommon_codepoints)]
11
12// Re-export everything from facet-macro-types for convenience
13pub use facet_macro_types::*;
14
15mod parsed;
16pub use parsed::*;
17
18mod generic_params;
19pub use generic_params::*;
20
21mod unescaping;
22pub use unescaping::*;
23
24// ============================================================================
25// CONVENIENCE PARSING FUNCTIONS
26// ============================================================================
27
28/// Represents a parsed type (either a struct or an enum)
29pub enum PType {
30    /// A parsed struct
31    Struct(PStruct),
32    /// A parsed enum
33    Enum(PEnum),
34}
35
36impl PType {
37    /// Get the name identifier of the type
38    pub fn name(&self) -> &Ident {
39        match self {
40            PType::Struct(s) => &s.container.name,
41            PType::Enum(e) => &e.container.name,
42        }
43    }
44}
45
46/// Parse a TokenStream into a `PType` (either struct or enum).
47///
48/// This is a convenience function that tries to parse the token stream
49/// as either a struct or an enum.
50pub fn parse_type(tokens: TokenStream) -> std::result::Result<PType, String> {
51    let mut iter = tokens.to_token_iter();
52
53    // Try to parse as AdtDecl which can be either Struct or Enum
54    match iter.parse::<AdtDecl>() {
55        Ok(AdtDecl::Struct(s)) => Ok(PType::Struct(PStruct::parse(&s))),
56        Ok(AdtDecl::Enum(e)) => Ok(PType::Enum(PEnum::parse(&e))),
57        Err(e) => Err(format!("failed to parse type: {e}")),
58    }
59}