valence_macros/lib.rs
1//! Proc macros for Valence schema and trait DSL compilation.
2//!
3//! # Macros
4//!
5//! - [`valence_schema!`] — declare a table schema (fields, policies, connections, TTL,
6//! optional per-schema `valence::DatabaseEvaluator`, trait mixins).
7//! - [`valence_trait_schema!`] — declare a reusable trait (shared fields / connection names /
8//! policies) that schemas can include via `traits: [TraitName]`.
9//!
10//! # Pipeline
11//!
12//! 1. **Parse** — [`valence_schema_dsl`] turns token trees into parsed schema/trait structures.
13//! 2. **Emit** — `codegen` builds `valence::Schema`, `valence::TraitDefinition`, and
14//! `inventory::submit!` registrations consumed at runtime by Valence registries.
15//!
16//! # Where types like `FieldType` live
17//!
18//! Authoring schemas in app code uses the **`valence`** crate (`valence::prelude::*`), not
19//! this crate. `valence-macros` only parses and emits tokens; it does not re-export DSL types.
20
21use proc_macro::TokenStream;
22
23mod codegen;
24
25/// Defines a Valence model schema at compile time.
26///
27/// Parses the braced DSL, builds a `valence::Schema`, and registers
28/// `valence::SchemaMetadataInit` plus optional `valence::TraitImplementor` entries for
29/// each `traits: [...]` name.
30///
31/// # DSL fields
32///
33/// | Field | Required | Description |
34/// |-------|----------|-------------|
35/// | `table` | yes | Physical / registry table name |
36/// | `version` | yes | Schema version string |
37/// | `fields` | yes | Named field list (`r#type`, `primary_key`, `required`, …). See field-type notes below. |
38/// | `description` | no | Human-readable summary |
39/// | `database` | no | Path to a `const`/`static` `DatabaseEvaluator`; defaults to `DEFAULT_IN_MEMORY` |
40/// | `policies` | no | Read/write/update/delete allow lists |
41/// | `connections` | no | Graph/FK edges (`Cardinality`, `OnDelete`) |
42/// | `ttl` | no | Create-only TTL (`ttl: { seconds }`); native Redis/Mongo; Deferred backends stamp `__valence_expire_at`, ensure an expire-at index, and warn until `valence_platform::ttl_sweep::register_ttl_service`; boot with `Valence::ensure_ttl_for_all` (see `valence::ttl`) |
43/// | `side_effects` | no | Mutation hooks |
44/// | `composite_key` | no | Multi-field primary key |
45/// | `traits` | no | Mix in `valence_trait_schema!` names |
46///
47/// Legacy `privacy: { ... }` blocks are accepted by the parser for compatibility but do not
48/// change emitted runtime metadata (read/write privacy strings are fixed in codegen).
49///
50/// ## Field types (`r#type`)
51///
52/// - `FieldType::Json` — `serde_json::Value`
53/// - `FieldType::JsonAs("path::Type")` — typed JSON; constructors/setters take `T`; optional
54/// `.serde_error(JsonAsSerdeError::Panic|Error)` (default `Error`)
55/// - `FieldType::Record("table")` — `RecordId`; optional `.target("path::Model")` for hops
56/// - `FieldType::Currency` — `valence::Currency` (`CurrencyCode` + `amount_minor`)
57/// - `FieldType::DateTime` — Model API `chrono::DateTime<Utc>`; storage is **UTC unix seconds**
58///
59/// Connections accept `model:` or `target:` (aliases) for an explicit model path.
60///
61/// Backend selection uses a stable evaluator rather than a backend instance:
62///
63/// ```ignore
64/// const COUNTER_DB: valence::DatabaseFromEngine =
65/// valence::Database::from_engine("default", valence::SQLITE_ENGINE_ID);
66///
67/// valence_schema! {
68/// Counter {
69/// table: "counter",
70/// version: "0.1.0",
71/// database: COUNTER_DB,
72/// fields: [],
73/// }
74/// }
75/// ```
76///
77/// The logical name (`"default"`) must match the name passed to
78/// `ValenceBuilder::add_backend`. When `database:` is omitted, the schema evaluator is
79/// `DEFAULT_IN_MEMORY`; the runtime may fall back to its active backend if that key is absent.
80///
81/// # Examples
82///
83/// ```ignore
84/// use valence::prelude::*;
85///
86/// const COUNTER_DB: DatabaseFromEngine =
87/// Database::from_engine("default", valence::MEM_ENGINE_ID);
88///
89/// valence_schema! {
90/// Counter {
91/// table: "counter",
92/// version: "0.1.0",
93/// description: "Simple counter",
94/// database: COUNTER_DB,
95/// fields: [
96/// id: { r#type: FieldType::String, primary_key: true, required: true },
97/// value: { r#type: FieldType::Integer, required: true, default: 0 },
98/// ]
99/// }
100/// }
101/// ```
102///
103/// This registers table `counter` via inventory. Model CRUD requires `valence-codegen`
104/// (`examples/codegen-host`).
105#[proc_macro]
106pub fn valence_schema(input: TokenStream) -> TokenStream {
107 codegen::schema::expand(input)
108}
109
110/// Defines a reusable trait schema (fields, optional connections, optional policies).
111///
112/// Registered as `valence::TraitDefinitionInit` so `valence::TraitRegistry` can merge
113/// trait requirements with concrete `valence_schema!` tables that list `traits: [ThisTrait]`.
114///
115/// # DSL fields
116///
117/// | Field | Required | Description |
118/// |-------|----------|-------------|
119/// | `fields` | no | Reusable named field definitions; uses the same attributes as [`valence_schema!`] |
120/// | `connections` | no | Reusable connection names; concrete schemas provide full edge metadata |
121/// | `policies` | no | Reusable `read`/`create`/`update`/`delete` policy bundles |
122///
123/// At least one of these fields should be supplied for the trait to add behavior.
124///
125/// ## Field attributes
126///
127/// | Attribute | Required | Description |
128/// |-----------|----------|-------------|
129/// | `r#type` (or `type`) | yes | `FieldType` expression. Supported variants include `String`, `Integer`, `Boolean`, `DateTime` (Model API `DateTime<Utc>`; storage is **UTC unix seconds**), `Json` (`serde_json::Value`), `JsonAs("path::Type")` (typed JSON; optional `.serde_error(JsonAsSerdeError::Panic\|Error)`, default `Error`), `Record("table")` (optional `.target("path::Model")` for connection hops), `Currency` (`valence::Currency` / ISO-4217 `CurrencyCode`), `Enum` / `ExternalEnum`. |
130/// | `required` | no | Whether the field must be present (default `false`) |
131/// | `primary_key` | no | Whether the field is a primary key (default `false`) |
132/// | `unique` | no | Whether values must be unique (default `false`) |
133/// | `default` | no | Default value expression |
134/// | `validations` | no | Validator expression list |
135/// | `policies` | no | Field-level policy bundle |
136/// | `encrypted` | no | Whether storage should treat the field as encrypted (default `false`) |
137///
138/// ## Policy fields
139///
140/// A `policies` block accepts `read`, `create`, `update`, and `delete`. Each operation accepts
141/// `always_allow`, `allow`, `block`, and `always_block` rule lists.
142///
143/// ## Connection fields
144///
145/// A `connections` entry has a name and braced expression body. Trait registration preserves
146/// the connection name for attribution; declare full connection metadata (`table`,
147/// `cardinality`, `required`, `on_delete`, and related attributes) on the concrete schema.
148/// Use `model:` or `target:` (aliases) for an explicit cross-crate model path.
149///
150/// # Examples
151///
152/// ```ignore
153/// use valence::prelude::*;
154///
155/// valence_trait_schema! {
156/// Owned {
157/// fields: [
158/// owner: {
159/// r#type: FieldType::Record("user"),
160/// required: true,
161/// policies: { read: { allow: [AUTHENTICATED] } },
162/// },
163/// ],
164/// connections: [
165/// owner: { table: "user", cardinality: HasOne, on_delete: Cascade },
166/// ],
167/// policies: {
168/// read: { allow: [AUTHENTICATED] },
169/// },
170/// }
171/// }
172///
173/// valence_schema! {
174/// Person {
175/// table: "person",
176/// version: "0.1.0",
177/// traits: [Owned],
178/// fields: [
179/// id: { r#type: FieldType::String, primary_key: true, required: true },
180/// ],
181/// }
182/// }
183/// ```
184#[proc_macro]
185pub fn valence_trait_schema(input: TokenStream) -> TokenStream {
186 codegen::trait_schema::expand(input)
187}