typestate_builder_macro/lib.rs
1// Copyright (c) 2024 Andy Allison
2//
3// Licensed under either of
4//
5// * MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
6// * Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
7//
8// at your option.
9//
10// Unless you explicitly state otherwise, any contribution intentionally submitted
11// for inclusion in the work by you, as defined in the Apache-2.0 license, shall
12// be dual licensed as above, without any additional terms or conditions.
13
14//! This crate provides the `TypestateBuilder` derive macro for generating a
15//! typestate-pattern builder for structs.
16//!
17//! This is the helper crate of [typestate-builder](https://docs.rs/typestate-builder/latest/typestate_builder/).
18
19#![warn(missing_docs)]
20
21mod analyze;
22mod analyze2;
23mod graph;
24mod helper;
25mod parse;
26mod produce;
27
28use graph::{StructElement, StructRelation};
29use proc_macro::TokenStream;
30use proc_macro_error::proc_macro_error;
31use quote::quote;
32use syn::{parse_macro_input, DeriveInput};
33
34/// The `TypestateBuilder` derive macro generates builder pattern code based on the
35/// typestate pattern. It provides compile-time guarantees that all necessary fields
36/// are initialized before building the final struct.
37///
38/// For more information, read [the document of the consumer crate](https://docs.rs/typestate-builder/latest/typestate_builder/).
39///
40/// # Panics
41/// This macro will panic if applied to a non-struct type (such as an enum or union).
42#[proc_macro_derive(TypestateBuilder)]
43#[proc_macro_error]
44pub fn typestate_builder_derive(input: TokenStream) -> TokenStream {
45 // Parse the input token stream into a `DeriveInput` structure.
46 let input = parse_macro_input!(input as DeriveInput);
47
48 let (mut graph, mut map) = parse::run(input);
49 analyze::run(&mut graph, &map);
50 analyze2::run(&mut graph, &mut map);
51 let res = produce::run(&graph, &map);
52
53 // Combine the generated code into a final token stream.
54 let output = quote! {
55 #(#res)*
56 };
57
58 // #[cfg(debug_assertions)]
59 // {
60 // helper::write_graph_to_file(&graph, "example.dot").unwrap();
61 // }
62 output.into()
63}