obs-build 0.2.1

Build-time codegen helpers for the obs SDK; reads .proto via buffa-build + buffa-reflect.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
//! Codegen passes that turn an [`EventDecl`] into the four output
//! fragments per spec 12 § 3.1: `schemas.rs`, `builders.rs`,
//! `lints.rs`, `arrow_schema.rs` (Parquet schema assembly waits for
//! Phase 4).
//!
//! All bytes are written deterministically — same input → byte-identical
//! output across machines and runs (spec 12 § 1.2).

// `format!` builds the codegen output fragments on a `String` via
// `push_str(&format!(...))`. Switching to `write!` saves one
// allocation per line but loses the ergonomic format-args ordering
// the codegen relies on; the readability win in this file
// substantially outweighs the alloc cost (codegen runs at build time).
#![allow(
    clippy::format_push_string,
    clippy::uninlined_format_args,
    clippy::format_in_format_args
)]

use heck::ToShoutySnakeCase;
use obs_proto::obs::v1::{Cardinality, Classification, FieldKind, Severity, Tier};

use crate::{
    lints::{self, LintField, LintInput, LintProtoType},
    options::{EventOptions, FieldOptions},
};

/// One event's worth of decoded annotations, ready to be rendered into
/// the four output files.
#[derive(Debug)]
pub(crate) struct EventDecl {
    pub full_name: String,
    pub event: EventOptions,
    pub fields: Vec<FieldDecl>,
}

#[derive(Debug)]
pub(crate) struct FieldDecl {
    pub name: String,
    pub number: u32,
    pub options: FieldOptions,
    /// Proto type as inferred from the descriptor's `Kind`, when known.
    /// Drives L014's proto-type validation (spec 95 § 2.2).
    pub proto_type: Option<LintProtoType>,
    /// Precise Rust type emitted by buffa for this wire field (e.g.
    /// `"u32"`, `"i64"`, `"f64"`). `None` when the proto Kind doesn't
    /// map to a fixed scalar (string/bytes/message/enum). Used by the
    /// builder setter to emit width-correct parameters — without this
    /// a `uint32` field would get a `u64` setter and refuse to assign.
    pub wire_rust_type: Option<&'static str>,
    /// Fully-qualified Rust path of the enum type when the field's
    /// kind is `Kind::Enum(_)`. Nested-enum parents are already
    /// snake_case'd so a field like `GatewayUpstreamFailed.category`
    /// whose proto enum is nested under `GatewayUpstreamFailed` gets
    /// `tok::v1::events::…::gateway::gateway_upstream_failed::ErrorCategory`
    /// rather than the raw proto path. `None` when the field is not
    /// enum-typed.
    pub enum_rust_path: Option<String>,
}

impl EventDecl {
    pub(crate) fn rust_name(&self) -> &str {
        self.full_name.rsplit('.').next().unwrap_or(&self.full_name)
    }

    /// Path to the buffa-generated message type, written so it
    /// resolves at the include-site of `obs::include_schemas!`. The
    /// buffa codegen produces `pub mod {pkg_seg} { pub mod ... { pub
    /// struct ObsXxx; } }` for each proto package, and we include the
    /// resulting `obs_buffa.rs` into the same scope as the obs codegen
    /// files. `myapp.v1.ObsXxx` therefore lives at `myapp::v1::ObsXxx`.
    pub(crate) fn rust_path(&self) -> String {
        self.full_name.replace('.', "::")
    }

    pub(crate) fn schema_static_ident(&self) -> String {
        format!("__OBS_SCHEMA_{}", self.rust_name().to_shouty_snake_case())
    }

    pub(crate) fn erased_struct_ident(&self) -> String {
        format!("{}Schema", self.rust_name())
    }

    pub(crate) fn builder_struct_ident(&self) -> String {
        format!("{}Builder", self.rust_name())
    }

    pub(crate) fn schema_hash(&self) -> u64 {
        // Same algorithm as `obs-macros::derive(Event)`.
        let mut s = String::new();
        s.push_str(&self.full_name);
        s.push('|');
        s.push_str(self.event.tier.unwrap_or(Tier::Log).as_str());
        s.push('|');
        s.push_str(self.event.default_sev.unwrap_or(Severity::Info).as_str());
        s.push('|');
        for f in &self.fields {
            s.push_str(&f.name);
            s.push(':');
            s.push_str(f.options.kind.unwrap_or(FieldKind::Attribute).as_str());
            s.push(':');
            s.push_str(
                f.options
                    .cardinality
                    .unwrap_or(Cardinality::Unspecified)
                    .as_str(),
            );
            s.push(':');
            s.push_str(
                f.options
                    .classification
                    .unwrap_or(Classification::Internal)
                    .as_str(),
            );
            s.push(',');
        }
        let h = blake3::hash(s.as_bytes());
        let bytes = h.as_bytes();
        let arr = <[u8; 8]>::try_from(&bytes[..8]).expect("blake3 always produces 32 bytes");
        u64::from_le_bytes(arr)
    }
}

// ─── schemas.rs ────────────────────────────────────────────────────────

pub(crate) fn render_schemas(events: &[EventDecl]) -> String {
    let mut out = String::new();
    out.push_str("// @generated by obs-build. DO NOT EDIT.\n");
    out.push_str("// File: schemas.rs — EventSchemaErased impls + linkme registrations.\n\n");
    for evt in events {
        out.push_str(&render_one_schema(evt));
        out.push('\n');
    }
    out
}

fn render_one_schema(decl: &EventDecl) -> String {
    let erased_struct = decl.erased_struct_ident();
    let static_ident = decl.schema_static_ident();
    let rust_path = decl.rust_path();
    let tier = decl.event.tier.unwrap_or(Tier::Log);
    let sev = decl.event.default_sev.unwrap_or(Severity::Info);
    let schema_hash = decl.schema_hash();

    let mut fields_lit = String::from("&[");
    for f in &decl.fields {
        let role_str = field_role_path(f.options.kind.unwrap_or(FieldKind::Attribute));
        let card = cardinality_path(f.options.cardinality.unwrap_or(Cardinality::Unspecified));
        let classn =
            classification_path(f.options.classification.unwrap_or(Classification::Internal));
        fields_lit.push_str(&format!(
            "::obs_core::FieldMeta::new(\"{name}\", {num}, {role}, {card}, {classn}),",
            name = f.name,
            num = f.number,
            role = role_str,
            card = card,
            classn = classn,
        ));
    }
    fields_lit.push(']');

    let project_body = render_project_body(&decl.fields);
    let project_metrics_body = render_project_metrics_body(&decl.full_name, &decl.fields);
    let paired_with_lit = match decl.event.paired_with.as_deref() {
        Some(s) if !s.is_empty() => format!("::std::option::Option::Some({})", rust_str_lit(s)),
        _ => "::std::option::Option::None".to_string(),
    };

    format!(
        r#"impl ::obs_core::EventSchema for {rust_path} {{
    const FULL_NAME: &'static str = "{full_name}";
    const TIER: ::obs_core::__private::Tier = {tier_path};
    const DEFAULT_SEV: ::obs_core::__private::Severity = {sev_path};
    const FIELDS: &'static [::obs_core::FieldMeta] = {fields};
    const SCHEMA_HASH: u64 = {hash}u64;
    const SPANS_PAIRED_WITH: ::std::option::Option<&'static str> = {paired_with};

    fn encode_payload(&self, buf: &mut ::obs_core::__private::BytesMut) {{
        // Delegate to buffa's `Message::write_to`. The size cache is
        // a per-call scratch; we accept the small allocation cost
        // here in exchange for keeping `EventSchema` infallible.
        let mut __cache = ::buffa::SizeCache::default();
        let _ = <Self as ::buffa::Message>::compute_size(self, &mut __cache);
        <Self as ::buffa::Message>::write_to(self, &mut __cache, buf);
    }}

    fn project(&self, env: &mut ::obs_core::ObsEnvelope) {{
{project_body}    }}

    fn project_metrics(&self, sink: &mut dyn ::obs_core::MetricEmitter) {{
{project_metrics_body}    }}
}}

#[doc(hidden)]
#[derive(Debug)]
#[allow(non_camel_case_types)]
pub struct {erased_struct};

impl ::obs_core::__private::Sealed for {erased_struct} {{}}

impl ::obs_core::__private::EventSchemaErased for {erased_struct} {{
    fn full_name(&self) -> &'static str {{ <{rust_path} as ::obs_core::EventSchema>::FULL_NAME }}
    fn schema_hash(&self) -> u64 {{ <{rust_path} as ::obs_core::EventSchema>::SCHEMA_HASH }}
    fn tier(&self) -> ::obs_core::__private::Tier {{ <{rust_path} as ::obs_core::EventSchema>::TIER }}
    fn default_sev(&self) -> ::obs_core::__private::Severity {{ <{rust_path} as ::obs_core::EventSchema>::DEFAULT_SEV }}
    fn fields(&self) -> &'static [::obs_core::FieldMeta] {{ <{rust_path} as ::obs_core::EventSchema>::FIELDS }}
    fn spans_paired_with(&self) -> ::std::option::Option<&'static str> {{
        <{rust_path} as ::obs_core::EventSchema>::SPANS_PAIRED_WITH
    }}
}}

#[::obs_core::__private::linkme::distributed_slice(::obs_core::__private::EVENT_SCHEMAS)]
#[linkme(crate = ::obs_core::__private::linkme)]
#[doc(hidden)]
static {static_ident}: &'static dyn ::obs_core::__private::EventSchemaErased = &{erased_struct};
"#,
        erased_struct = erased_struct,
        full_name = decl.full_name,
        rust_path = rust_path,
        hash = schema_hash,
        tier_path = tier_path(tier),
        sev_path = sev_path(sev),
        fields = fields_lit,
        static_ident = static_ident,
        project_body = project_body,
        project_metrics_body = project_metrics_body,
        paired_with = paired_with_lit,
    )
}

/// Generate the `project_metrics` body. For each `MEASUREMENT`-kind
/// field with a `MetricSpec`, emit one call to the matching
/// `MetricEmitter::record_*` method. Instruments are field-relative;
/// metric sinks prefix the owning event name.
/// Fields without a MetricSpec default to a counter with unit `1`.
/// Spec 12 § 3.6 / spec 93 P1-6.
fn render_project_metrics_body(full_name: &str, fields: &[FieldDecl]) -> String {
    use obs_proto::obs::v1::MetricKind;
    let mut out = String::new();
    let mut had_any = false;
    for f in fields {
        if !matches!(
            f.options.kind.unwrap_or(FieldKind::Attribute),
            FieldKind::Measurement
        ) {
            continue;
        }
        had_any = true;
        let instrument_lit = f.name.clone();
        let (kind, unit, bounds) = match &f.options.metric {
            Some(spec) => (
                spec.kind.unwrap_or(MetricKind::Counter),
                spec.unit.clone(),
                spec.bounds.clone(),
            ),
            None => (MetricKind::Counter, None, Vec::new()),
        };
        let unit_expr = match unit.as_deref() {
            Some(u) if !u.is_empty() => {
                format!("::std::option::Option::Some({})", rust_str_lit(u))
            }
            _ => "::std::option::Option::None".to_string(),
        };
        match kind {
            MetricKind::Counter => {
                out.push_str(&format!(
                    "        sink.record_counter({inst}, self.{name} as u64, {unit});\n",
                    inst = rust_str_lit(&instrument_lit),
                    name = f.name,
                    unit = unit_expr,
                ));
            }
            MetricKind::Gauge => {
                out.push_str(&format!(
                    "        sink.record_gauge_u64({inst}, self.{name} as u64, {unit});\n",
                    inst = rust_str_lit(&instrument_lit),
                    name = f.name,
                    unit = unit_expr,
                ));
            }
            MetricKind::Histogram => {
                let bounds_lit = if bounds.is_empty() {
                    "&[] as &[f64]".to_string()
                } else {
                    let parts: Vec<String> = bounds.iter().map(|b| format!("{b:?}")).collect();
                    format!("&[{}] as &[f64]", parts.join(", "))
                };
                let static_ident = format!(
                    "__OBS_HIST_BOUNDS_{}_{}",
                    full_name.replace('.', "_").to_uppercase(),
                    f.name.to_uppercase()
                );
                out.push_str(&format!(
                    "        static {ident}: &[f64] = {bounds};\n        \
                     sink.record_histogram({inst}, self.{name} as f64, {unit}, {ident});\n",
                    ident = static_ident,
                    bounds = bounds_lit,
                    inst = rust_str_lit(&instrument_lit),
                    name = f.name,
                    unit = unit_expr,
                ));
            }
            _ => {
                // Treat Unspecified as Counter for forward-compat.
                out.push_str(&format!(
                    "        sink.record_counter({inst}, self.{name} as u64, {unit});\n",
                    inst = rust_str_lit(&instrument_lit),
                    name = f.name,
                    unit = unit_expr,
                ));
            }
        }
    }
    if !had_any {
        out.push_str("        let _ = sink;\n");
    }
    out
}

fn render_project_body(fields: &[FieldDecl]) -> String {
    let mut out = String::new();
    for f in fields {
        let kind = f.options.kind.unwrap_or(FieldKind::Attribute);
        match kind {
            FieldKind::Label => {
                out.push_str(&format!(
                    "        env.labels.insert(\"{name}\".to_string(), \
                     ::std::string::ToString::to_string(&self.{name}));\n",
                    name = f.name
                ));
            }
            FieldKind::TraceId => {
                out.push_str(&format!(
                    "        env.trace_id = ::std::string::ToString::to_string(&self.{name});\n",
                    name = f.name
                ));
            }
            FieldKind::SpanId => {
                out.push_str(&format!(
                    "        env.span_id = ::std::string::ToString::to_string(&self.{name});\n",
                    name = f.name
                ));
            }
            FieldKind::ParentSpanId => {
                out.push_str(&format!(
                    "        env.parent_span_id = \
                     ::std::string::ToString::to_string(&self.{name});\n",
                    name = f.name
                ));
            }
            _ => {}
        }
    }
    if out.is_empty() {
        // EventSchema::project must be a `fn`, not an empty body.
        // Insert a no-op statement so rustfmt doesn't complain about
        // empty fn bodies if the user inspects the output.
        out.push_str("        let _ = env;\n");
    }
    out
}

// ─── builders.rs ───────────────────────────────────────────────────────
//
// Phase-2 emits a manual builder rather than a typed_builder derive.
// The buffa-generated message types do not implement `TypedBuilder`
// directly; rather than introduce a parallel `Args` struct that copies
// every field, we emit one builder struct that mutates the buffa
// message in place (default-constructed) and exposes `.emit()` /
// `.emit_at()`. This is the minimum viable typed-builder per spec 12
// § 3.3 — required-field enforcement at the typed-builder level lands
// in Phase 4 once the Args-struct contract is finalised.

pub(crate) fn render_builders(events: &[EventDecl]) -> String {
    let mut out = String::new();
    out.push_str("// @generated by obs-build. DO NOT EDIT.\n");
    out.push_str("// File: builders.rs — fluent builder + .emit() / .emit_at() per event.\n\n");
    for evt in events {
        out.push_str(&render_one_builder(evt));
        out.push('\n');
    }
    out
}

fn render_one_builder(decl: &EventDecl) -> String {
    let rust_path = decl.rust_path();
    let builder = decl.builder_struct_ident();
    let setters: String = decl
        .fields
        .iter()
        .map(|f| render_setter(f, &rust_path))
        .collect();
    format!(
        r#"/// Builder generated by `obs-build` for `{full}`.
#[derive(Debug)]
pub struct {builder} {{
    inner: {rust_path},
}}

impl {builder} {{
{setters}
    /// Finalise the builder.
    pub fn build(self) -> {rust_path} {{ self.inner }}

    /// Build and emit at the schema-declared default severity.
    pub fn emit(self) {{
        let evt = self.build();
        static __CALLSITE: ::obs_core::__private::ObsCallsite =
            ::obs_core::__private::ObsCallsite::new(
                <{rust_path} as ::obs_core::EventSchema>::FULL_NAME,
                <{rust_path} as ::obs_core::EventSchema>::DEFAULT_SEV,
                module_path!(),
                file!(),
                line!(),
            );
        ::obs_core::emit::emit_with_callsite::<{rust_path}>(
            &__CALLSITE,
            &evt,
            <{rust_path} as ::obs_core::EventSchema>::DEFAULT_SEV,
        );
    }}

    /// Build and emit at a specific severity.
    pub fn emit_at(self, sev: ::obs_core::__private::Severity) {{
        let evt = self.build();
        static __CALLSITE: ::obs_core::__private::ObsCallsite =
            ::obs_core::__private::ObsCallsite::new(
                <{rust_path} as ::obs_core::EventSchema>::FULL_NAME,
                <{rust_path} as ::obs_core::EventSchema>::DEFAULT_SEV,
                module_path!(),
                file!(),
                line!(),
            );
        ::obs_core::emit::emit_with_callsite::<{rust_path}>(&__CALLSITE, &evt, sev);
    }}
}}

impl {rust_path} {{
    /// Begin building a `{full}` event.
    pub fn builder() -> {builder} {{
        {builder} {{ inner: <{rust_path} as ::std::default::Default>::default() }}
    }}
}}
"#,
        full = decl.full_name,
        rust_path = rust_path,
        builder = builder,
        setters = setters,
    )
}

fn render_setter(field: &FieldDecl, rust_path: &str) -> String {
    let kind = field.options.kind.unwrap_or(FieldKind::Attribute);
    // Setter shape is driven primarily by `FieldKind`, then refined by
    // the inferred proto wire type so non-string ATTRIBUTE / LABEL
    // fields (e.g. `bool`, `uint64`) get a typed setter instead of the
    // String-coerced one. Without that refinement, a proto field like
    // `bool was_completed = 3 [(obs.v1.field) = { kind: ATTRIBUTE }]`
    // would compile-fail because `bool` does not implement
    // `Into<String>`.
    let proto_type = field.proto_type.as_ref();

    // Enum-typed fields: the struct field is `EnumValue<EnumTy>`, so
    // the setter accepts anything convertible into that. Emit an
    // `Into<EnumValue<…>>` bound — buffa ships `From<EnumTy>` and
    // `From<i32>` impls that cover the common cases. The Rust path
    // has been pre-built in config.rs with parent-message segments
    // already snake_case'd per buffa's nested-type convention.
    if let Some(enum_path) = field.enum_rust_path.as_deref() {
        let setter_param = format!(
            "impl ::std::convert::Into<::buffa::EnumValue<{}>>",
            enum_path
        );
        let assign = format!("self.inner.{} = value.into();", field.name);
        return format!(
            "    /// Setter for `{name}` (proto field {num}); generated for `{rust_path}`.\n    \
             #[allow(clippy::needless_pass_by_value, clippy::missing_const_for_fn)]\n    pub fn \
             {name}(mut self, value: {param}) -> Self {{ {assign} self }}\n",
            name = field.name,
            num = field.number,
            rust_path = rust_path,
            param = setter_param,
            assign = assign,
        );
    }

    // Prefer the precise wire Rust type when buffa exposed one — that
    // way `uint32` gets a `u32` setter, `int64` gets `i64`, `double`
    // gets `f64`, etc. Falling back to the coarse LintProtoType keeps
    // older callers working when the precise type wasn't recorded.
    //
    // MEASUREMENT / TIMESTAMP_NS / DURATION_NS semantics *usually*
    // map to `u64`, but the proto author gets to pick (`uint32 delta`
    // is a common cardinality-bounded counter). Respect the precise
    // wire type so the setter signature matches the struct field
    // rather than always widening to u64.
    let typed_setter = match (kind, proto_type, field.wire_rust_type) {
        (
            FieldKind::Measurement | FieldKind::TimestampNs | FieldKind::DurationNs,
            _,
            Some(rust_ty),
        ) => Some(rust_ty),
        (FieldKind::Measurement | FieldKind::TimestampNs | FieldKind::DurationNs, _, None) => {
            Some("u64")
        }
        (
            FieldKind::Label | FieldKind::Attribute | FieldKind::Forensic,
            Some(LintProtoType::Bool),
            _,
        ) => Some("bool"),
        (
            FieldKind::Label | FieldKind::Attribute | FieldKind::Forensic,
            Some(proto_type),
            Some(rust_ty),
        ) if proto_type.is_numeric() => Some(rust_ty),
        (FieldKind::Label | FieldKind::Attribute | FieldKind::Forensic, Some(proto_type), None)
            if proto_type.is_numeric() =>
        {
            Some("u64")
        }
        (
            FieldKind::Label | FieldKind::Attribute | FieldKind::Forensic,
            Some(LintProtoType::Bytes),
            _,
        ) => Some("::std::vec::Vec<u8>"),
        _ => None,
    };
    let (setter_param, assign) = match typed_setter {
        Some(ty) => (
            ty.to_string(),
            format!("self.inner.{} = value;", field.name),
        ),
        None => (
            "impl ::std::convert::Into<::std::string::String>".to_string(),
            format!("self.inner.{} = value.into();", field.name),
        ),
    };
    let setter_param = setter_param.as_str();
    let assign = assign.as_str();
    format!(
        "    /// Setter for `{name}` (proto field {num}); generated for `{rust_path}`.\n    \
         #[allow(clippy::needless_pass_by_value, clippy::missing_const_for_fn)]\n    pub fn \
         {name}(mut self, value: {param}) -> Self {{ {assign} self }}\n",
        name = field.name,
        num = field.number,
        rust_path = rust_path,
        param = setter_param,
        assign = assign,
    )
}

// ─── lints.rs ──────────────────────────────────────────────────────────
//
// Codegen-side lint emission. Both authoring paths (proto-first +
// `#[derive(Event)]`) consume the shared `obs-build::lints` module
// so the catalogue cannot drift; this fn just renders each
// `LintError` as a const-eval `panic!` in the generated Rust source.
// Decision D8-1 / spec 95 § 2.1.

pub(crate) fn render_lints(events: &[EventDecl], event_prefix: &str) -> String {
    let mut out = String::new();
    out.push_str("// @generated by obs-build. DO NOT EDIT.\n");
    out.push_str(
        "// File: lints.rs — const-eval lint asserts (spec 12 § 3.4 / spec 95 § 2.1 D8-1).\n// A \
         failure here is a hard compile error.\n\n",
    );
    for evt in events {
        out.push_str(&render_one_lint(evt, event_prefix));
        out.push('\n');
    }
    out.push_str(&render_l013(events));
    out
}

fn render_one_lint(decl: &EventDecl, event_prefix: &str) -> String {
    let input = build_lint_input(decl, event_prefix);
    let mut s = String::new();
    for err in lints::emit_lints(&input) {
        s.push_str(&format!(
            "const _: () = ::std::panic!({});\n",
            rust_str_lit(&err.message)
        ));
    }
    s
}

fn build_lint_input(decl: &EventDecl, event_prefix: &str) -> LintInput {
    LintInput {
        event_name: decl.rust_name().to_string(),
        tier: decl.event.tier.unwrap_or(Tier::Log),
        event_prefix: event_prefix.to_string(),
        fields: decl
            .fields
            .iter()
            .map(|f| LintField {
                name: f.name.clone(),
                kind: f.options.kind.unwrap_or(FieldKind::Attribute),
                cardinality: f.options.cardinality.unwrap_or(Cardinality::Unspecified),
                classification: f.options.classification.unwrap_or(Classification::Internal),
                has_metric: f.options.metric.is_some(),
                proto_type: f.proto_type.clone(),
            })
            .collect(),
    }
}

fn render_l013(events: &[EventDecl]) -> String {
    if events.len() < 2 {
        return String::new();
    }
    let pairs: Vec<(String, u64)> = events
        .iter()
        .map(|e| (e.full_name.clone(), e.schema_hash()))
        .collect();
    let errs = lints::emit_cross_event_lints(&pairs);
    if errs.is_empty() {
        return String::new();
    }
    let mut s = String::new();
    s.push_str("\n// L013: schema_hash uniqueness across this codegen unit. Spec 95 § 2.1.\n");
    for err in errs {
        s.push_str(&format!(
            "const _: () = ::std::panic!({});\n",
            rust_str_lit(&err.message)
        ));
    }
    s
}

/// Render a Rust string literal, escaping backslashes, quotes, and
/// newlines so the rendered text round-trips through `rustc`'s lexer.
fn rust_str_lit(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for ch in s.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{{{:x}}}", c as u32)),
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

// ─── arrow_schema.rs ───────────────────────────────────────────────────

pub(crate) fn render_arrow_schema(events: &[EventDecl]) -> String {
    let mut out = String::new();
    out.push_str("// @generated by obs-build. DO NOT EDIT.\n");
    out.push_str(
        "// File: arrow_schema.rs — per-event Arrow Field fragment table.\n//\n// Phase-2 ships \
         the dispatch table only; the real Arrow Field\n// construction lands in Phase 4A \
         (obs-parquet). The table is\n// referenced by ParquetSink::new at startup; until that \
         lands,\n// the per-event stubs always return `None` (sparse-NULL behaviour).\n\n",
    );
    out.push_str(
        "/// Returns the Arrow `Field` fragment for `full_name`, when the schema is known to this \
         codegen unit.\n",
    );
    out.push_str(
        "/// Phase-2 stub: every entry returns `None`. Phase 4A populates the static fragments.\n",
    );
    out.push_str("#[must_use]\n");
    out.push_str(
        "pub fn payload_struct_for(full_name: &str) -> ::std::option::Option<&'static str> {\n",
    );
    out.push_str("    match full_name {\n");
    for evt in events {
        out.push_str(&format!(
            "        \"{}\" => ::std::option::Option::Some(\"{}\"),\n",
            evt.full_name, evt.full_name
        ));
    }
    out.push_str("        _ => ::std::option::Option::None,\n");
    out.push_str("    }\n}\n\n");

    out.push_str(
        "/// Iterate every `full_name` this codegen unit declares an Arrow fragment for.\n",
    );
    out.push_str("/// Used by `obs migrate parquet` and `obs migrate clickhouse` (Phase 4A).\n");
    out.push_str("pub fn all_payload_full_names() -> &'static [&'static str] {\n");
    out.push_str("    &[\n");
    for evt in events {
        out.push_str(&format!("        \"{}\",\n", evt.full_name));
    }
    out.push_str("    ]\n}\n");
    out
}

// ─── shared helpers ───────────────────────────────────────────────────

pub(crate) fn tier_path(t: Tier) -> &'static str {
    match t {
        Tier::Log => "::obs_core::__private::Tier::Log",
        Tier::Metric => "::obs_core::__private::Tier::Metric",
        Tier::Trace => "::obs_core::__private::Tier::Trace",
        Tier::Audit => "::obs_core::__private::Tier::Audit",
        _ => "::obs_core::__private::Tier::Unspecified",
    }
}
pub(crate) fn sev_path(s: Severity) -> &'static str {
    match s {
        Severity::Trace => "::obs_core::__private::Severity::Trace",
        Severity::Debug => "::obs_core::__private::Severity::Debug",
        Severity::Info => "::obs_core::__private::Severity::Info",
        Severity::Warn => "::obs_core::__private::Severity::Warn",
        Severity::Error => "::obs_core::__private::Severity::Error",
        Severity::Fatal => "::obs_core::__private::Severity::Fatal",
        _ => "::obs_core::__private::Severity::Unspecified",
    }
}
pub(crate) fn field_role_path(k: FieldKind) -> &'static str {
    match k {
        FieldKind::Label => "::obs_core::FieldRole::Label",
        FieldKind::Attribute => "::obs_core::FieldRole::Attribute",
        FieldKind::Measurement => "::obs_core::FieldRole::Measurement",
        FieldKind::TraceId => "::obs_core::FieldRole::TraceId",
        FieldKind::SpanId => "::obs_core::FieldRole::SpanId",
        FieldKind::ParentSpanId => "::obs_core::FieldRole::ParentSpanId",
        FieldKind::TimestampNs => "::obs_core::FieldRole::TimestampNs",
        FieldKind::DurationNs => "::obs_core::FieldRole::DurationNs",
        FieldKind::Forensic => "::obs_core::FieldRole::Forensic",
        _ => "::obs_core::FieldRole::Attribute",
    }
}
pub(crate) fn cardinality_path(c: Cardinality) -> &'static str {
    match c {
        Cardinality::Low => "::obs_core::__private::Cardinality::Low",
        Cardinality::Medium => "::obs_core::__private::Cardinality::Medium",
        Cardinality::High => "::obs_core::__private::Cardinality::High",
        Cardinality::Unbounded => "::obs_core::__private::Cardinality::Unbounded",
        _ => "::obs_core::__private::Cardinality::Unspecified",
    }
}
pub(crate) fn classification_path(c: Classification) -> &'static str {
    match c {
        Classification::Pii => "::obs_core::__private::Classification::Pii",
        Classification::Secret => "::obs_core::__private::Classification::Secret",
        Classification::Internal => "::obs_core::__private::Classification::Internal",
        _ => "::obs_core::__private::Classification::Unspecified",
    }
}