Skip to main content

nativeview_abi_macros/
lib.rs

1//! Zero-dependency proc-macro crate implementing `#[derive(NvAbi)]`, `#[derive(ReprEnum)]`,
2//! `abi_consts!`, `abi_aliases!`, `abi_callbacks!`, `#[derive(NvTable)]`, `#[derive(NvCodec)]`,
3//! `#[derive(WordEnum)]`, and `#[derive(EventEnum)]`.
4
5#![cfg_attr(doctest, doc = include_str!("../README.md"))]
6
7extern crate proc_macro;
8
9mod abi;
10mod codec;
11mod emit;
12mod event_enum;
13mod fn_sig;
14mod lit;
15mod parse;
16mod repr;
17mod table;
18mod tok;
19mod word;
20
21use proc_macro::{Group, LexError, Span, TokenStream, TokenTree};
22
23use crate::fn_sig::ParsedFnSig;
24
25pub(crate) enum ParsedItem {
26    Struct(ParsedRecord),
27    Union(ParsedRecord),
28    Enum(ParsedEnum),
29    Vtable(ParsedVtable),
30    Alias(ParsedAlias),
31}
32
33pub(crate) struct ParsedRecord {
34    pub rust_ident: String,
35    pub abi_name: String,
36    pub doc: Option<String>,
37    pub crate_path: String,
38    pub explicit_align: Option<usize>,
39    pub expected_size: Option<usize>,
40    pub expected_size_64: Option<usize>,
41    pub fields: Vec<ParsedField>,
42}
43
44pub(crate) struct ParsedField {
45    pub rust_ident: String,
46    pub abi_name: String,
47    pub ty: String,
48    pub c_type: Option<String>,
49    pub doc: Option<String>,
50    pub expected_offset: Option<usize>,
51    pub expected_offset_64: Option<usize>,
52}
53
54pub(crate) struct ParsedEnum {
55    pub rust_ident: String,
56    pub abi_name: String,
57    pub repr: String,
58    pub doc: Option<String>,
59    pub crate_path: String,
60    pub c_prefix: Option<String>,
61    pub dart_fallback: Option<String>,
62    pub variants: Vec<ParsedVariant>,
63}
64
65pub(crate) struct ParsedVariant {
66    pub rust_ident: String,
67    pub abi_name: String,
68    pub doc: Option<String>,
69}
70
71pub(crate) struct ParsedVtable {
72    pub rust_ident: String,
73    pub abi_name: String,
74    pub module_name: Option<String>,
75    pub interface_id: Option<String>,
76    pub slots_offset: Option<usize>,
77    pub doc: Option<String>,
78    pub crate_path: String,
79    pub header_fields: Vec<ParsedField>,
80    pub methods: Vec<ParsedVtableMethod>,
81}
82
83pub(crate) struct ParsedVtableMethod {
84    pub rust_ident: String,
85    pub abi_name: String,
86    pub doc: Option<String>,
87    pub sig: ParsedFnSig,
88}
89
90pub(crate) struct ParsedAlias {
91    pub rust_ident: String,
92    pub abi_name: String,
93    pub rust_target: String,
94    pub abi_target: String,
95    pub doc: Option<String>,
96    pub crate_path: String,
97}
98
99/// Derives `NvStructSchema` / `NvUnionSchema` / `NvEnumSchema` / `NvVtableSchema` /
100/// `NvAliasSchema` (plus `NvSchema`) and compile-time layout assertions on `#[repr(C)]`
101/// structs/unions/vtables, `#[repr(transparent)]` handle newtypes, and `#[repr(u8|u16|u32|i32)]`
102/// enums.
103#[proc_macro_derive(NvAbi, attributes(nativeview_abi))]
104pub fn derive_nv_abi(input: TokenStream) -> TokenStream {
105    match parse::parse_item(input) {
106        Ok(item) => parse_at_call_site(&emit::emit_item(&item))
107            .unwrap_or_else(|e| compile_error(&format!("nativeview-abi-macros emit error: {e}"))),
108        Err(msg) => compile_error(&msg),
109    }
110}
111
112/// Declares ABI constants verbatim alongside a `const` `&[AbiConstDescriptor]` slice.
113#[proc_macro]
114pub fn abi_consts(input: TokenStream) -> TokenStream {
115    match abi::expand_consts(input) {
116        Ok(code) => parse_at_call_site(&code)
117            .unwrap_or_else(|e| compile_error(&format!("abi_consts! emit error: {e}"))),
118        Err(msg) => compile_error(&msg),
119    }
120}
121
122/// Declares ABI `pub type` aliases verbatim alongside a `const` `&[AbiAliasDescriptor]` slice.
123#[proc_macro]
124pub fn abi_aliases(input: TokenStream) -> TokenStream {
125    match abi::expand_aliases(input) {
126        Ok(code) => parse_at_call_site(&code)
127            .unwrap_or_else(|e| compile_error(&format!("abi_aliases! emit error: {e}"))),
128        Err(msg) => compile_error(&msg),
129    }
130}
131
132/// Declares ABI `extern "C" fn` callback typedefs verbatim alongside a `const`
133/// `&[AbiCallbackDescriptor]` slice.
134#[proc_macro]
135pub fn abi_callbacks(input: TokenStream) -> TokenStream {
136    match abi::expand_callbacks(input) {
137        Ok(code) => parse_at_call_site(&code)
138            .unwrap_or_else(|e| compile_error(&format!("abi_callbacks! emit error: {e}"))),
139        Err(msg) => compile_error(&msg),
140    }
141}
142
143/// Zero-dependency derive for unit-only `#[repr(u8|u16|u32|u64|i8|i16|i32|i64)]` enums emitting
144/// `COUNT`, `ALL`, `as_<repr>`, `try_from_<repr>`, and (only with `#[repr_enum(fallback = V)]`)
145/// `from_<repr>`.
146#[proc_macro_derive(ReprEnum, attributes(repr_enum))]
147pub fn derive_repr_enum(input: TokenStream) -> TokenStream {
148    match repr::derive(input) {
149        Ok(code) => parse_at_call_site(&code)
150            .unwrap_or_else(|e| compile_error(&format!("ReprEnum emit error: {e}"))),
151        Err(msg) => compile_error(&msg),
152    }
153}
154
155fn compile_error(msg: &str) -> TokenStream {
156    parse_at_call_site(&format!("::core::compile_error!({});", emit::quote_str(msg)))
157        .expect("compile_error! must parse as TokenStream")
158}
159
160/// Parses emitted source and pins every token to `Span::call_site()`.
161///
162/// rustc already gives string-parsed tokens the call-site span, but rust-analyzer's proc-macro
163/// server keeps the call-site anchor while replacing each range with the token's byte offset in
164/// `src`. Those ranges point past the derive (often past EOF) and panic IDE features such as the
165/// impls code lens (`line-index: invalid offset`). See docs/UPSTREAM.md.
166fn parse_at_call_site(src: &str) -> Result<TokenStream, LexError> {
167    Ok(respan(src.parse()?, Span::call_site()))
168}
169
170fn respan(stream: TokenStream, span: Span) -> TokenStream {
171    stream
172        .into_iter()
173        .map(|mut tt| {
174            if let TokenTree::Group(g) = &tt {
175                tt = TokenTree::Group(Group::new(g.delimiter(), respan(g.stream(), span)));
176            }
177            tt.set_span(span);
178            tt
179        })
180        .collect()
181}
182
183/// Derives `nativeview_store::NvTable` for a word-table schema struct (see `table.rs` docs).
184#[proc_macro_derive(NvTable, attributes(nv_table, effect, default, bits, no_inherit))]
185pub fn derive_nv_table(input: TokenStream) -> TokenStream {
186    match table::derive(input) {
187        Ok(code) => parse_at_call_site(&code)
188            .unwrap_or_else(|e| compile_error(&format!("NvTable emit error: {e}"))),
189        Err(msg) => compile_error(&msg),
190    }
191}
192
193/// Derives `nativeview_codec::{NvEncode, NvDecode}` for Tier-2 little-endian binary structs and enums.
194#[proc_macro_derive(NvCodec, attributes(nativeview_codec))]
195pub fn derive_nv_codec(input: TokenStream) -> TokenStream {
196    match codec::derive(input) {
197        Ok(code) => parse_at_call_site(&code)
198            .unwrap_or_else(|e| compile_error(&format!("NvCodec emit error: {e}"))),
199        Err(msg) => compile_error(&msg),
200    }
201}
202
203/// Derives `nativeview_store::{WordValue, OptWord}` + `COUNT`/`BITS`/`ALL`/`to_word`/`from_word`
204/// for fieldless `#[repr(u8)]` contiguous `0..N` enums.
205#[proc_macro_derive(WordEnum, attributes(word_enum))]
206pub fn derive_word_enum(input: TokenStream) -> TokenStream {
207    match word::derive(input) {
208        Ok(code) => parse_at_call_site(&code)
209            .unwrap_or_else(|e| compile_error(&format!("WordEnum emit error: {e}"))),
210        Err(msg) => compile_error(&msg),
211    }
212}
213
214/// Derives `nativeview_abi::EventEnum` + `COUNT`/`ALL`/`event_id`/`bit`/`set`/`from_event_id`/`BitOr`
215/// for table-scoped `#[repr(u8)]` contiguous `0..N` (`1 <= N <= 32`) event enums.
216#[proc_macro_derive(EventEnum, attributes(event_enum))]
217pub fn derive_event_enum(input: TokenStream) -> TokenStream {
218    match event_enum::derive(input) {
219        Ok(code) => parse_at_call_site(&code)
220            .unwrap_or_else(|e| compile_error(&format!("EventEnum emit error: {e}"))),
221        Err(msg) => compile_error(&msg),
222    }
223}