Skip to main content

teksilo_telemetry_codegen/
lib.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! `teksilo-telemetry-codegen` — compile-time codegen for Teksilo telemetry.
5//!
6//! Consumes a YAML event manifest at build time and expands to:
7//!
8//! - A `SCHEMA_VERSION: u32` constant.
9//! - For each event with `enum`-typed props: a dedicated enum type with
10//!   an `as_str()` method.
11//! - For each event: a typed `emit_<event_name>(reporter, install_id,
12//!   session_id, …props…)` free function that assembles an
13//!   `teksilo_telemetry::Event` and hands it to the reporter.
14//!
15//! # Usage
16//!
17//! ```rust,ignore
18//! // In your app's lib.rs or main.rs:
19//! teksilo_telemetry_codegen::include_telemetry_schema!("telemetry/events.yaml");
20//! ```
21//!
22//! The path is resolved relative to `CARGO_MANIFEST_DIR` (the crate
23//! containing the macro invocation).
24//!
25//! # YAML format
26//!
27//! ```yaml
28//! schema_version: 1
29//! events:
30//!   - name: intent.dispatched
31//!     category: intent
32//!     expires: "2027-06-01"
33//!     bug: "https://github.com/your-org/your-app/issues/42"
34//!     description: "Fired whenever an intent passes through dispatch."
35//!     props:
36//!       - name: name
37//!         type: dev_static
38//!       - name: source
39//!         type: enum
40//!         values: [shortcut, menu, handler, programmatic, accessibility]
41//! ```
42//!
43//! # Property types
44//!
45//! | YAML type     | Rust type                       | `PropValue` variant         |
46//! |---------------|---------------------------------|-----------------------------|
47//! | `dev_static`  | `&'static str`                  | `StaticStr`                 |
48//! | `bounded_str` | `&str`                          | `BoundedStr`                |
49//! | `u32`         | `u32`                           | `U32`                       |
50//! | `i64`         | `i64`                           | `I64`                       |
51//! | `bool`        | `bool`                          | `Bool`                      |
52//! | `f64_bucket`  | `teksilo_telemetry::F64Bucket`     | `F64Bucket`                 |
53//! | `enum`        | generated enum (see above)      | `Enum { variant: &'static str }` |
54
55use proc_macro::TokenStream;
56use proc_macro2::Span;
57use quote::quote;
58use syn::{LitStr, parse_macro_input};
59
60mod codegen;
61mod manifest;
62mod validation;
63
64/// Expand a YAML telemetry manifest into typed `emit_*` functions.
65///
66/// See the [crate-level documentation](self) for the full reference.
67#[proc_macro]
68pub fn include_telemetry_schema(input: TokenStream) -> TokenStream {
69    let path_lit = parse_macro_input!(input as LitStr);
70    let relative_path = path_lit.value();
71
72    // Resolve against the invoking crate's manifest directory.
73    let manifest_dir = match std::env::var("CARGO_MANIFEST_DIR") {
74        Ok(d) => d,
75        Err(_) => {
76            return error(Span::call_site(), "CARGO_MANIFEST_DIR is not set").into();
77        }
78    };
79    let full_path = std::path::PathBuf::from(&manifest_dir).join(&relative_path);
80
81    // Read the file.
82    let content = match std::fs::read_to_string(&full_path) {
83        Ok(s) => s,
84        Err(e) => {
85            return error(
86                Span::call_site(),
87                &format!("cannot read `{}`: {e}", full_path.display()),
88            )
89            .into();
90        }
91    };
92
93    // Parse YAML.
94    let schema = match manifest::parse_schema(&content) {
95        Ok(s) => s,
96        Err(e) => return error(Span::call_site(), &e).into(),
97    };
98
99    // Validate.
100    let warnings = match validation::validate(&schema) {
101        Ok(w) => w,
102        Err(e) => return error(Span::call_site(), &e).into(),
103    };
104
105    // Generate typed emit_* functions.
106    let generated = codegen::generate(&schema, &warnings);
107
108    // Emit an include_str! reference so Cargo reruns when the YAML
109    // file changes.
110    let abs_path = full_path.to_string_lossy().to_string();
111    let abs_path_lit = LitStr::new(&abs_path, Span::call_site());
112    let file_tracker = quote! {
113        const _TELEMETRY_SCHEMA_TRACKED: &str = ::std::include_str!(#abs_path_lit);
114    };
115
116    let out = quote! {
117        #file_tracker
118        #generated
119    };
120    out.into()
121}
122
123fn error(span: Span, message: &str) -> proc_macro2::TokenStream {
124    syn::Error::new(span, message).to_compile_error()
125}