Skip to main content

etw_wrapper_macro/
lib.rs

1//! Procedural macro implementation for `etw-wrapper`.
2//!
3//! See [`gen_etw_wrapper!`] for the supported syntax and generated API.
4
5mod eventman;
6mod model;
7
8use std::collections::HashMap;
9use std::path::PathBuf;
10
11use crate::model::{AnsiEncoding, Count, Event, Length, Provider, WinType};
12use convert_case::ccase;
13use proc_macro::TokenStream;
14use proc_macro_crate::{FoundCrate, crate_name};
15use proc_macro2::{Span, TokenStream as TokenStream2};
16use quote::{format_ident, quote};
17use syn::parse::{Parse, ParseStream};
18use syn::{Ident, LitBool, LitStr, Meta, Token, parenthesized};
19use unicode_ident::{is_xid_continue, is_xid_start};
20
21/// The parsed macro input, including the manifest path, event error behavior, and optional
22/// wrapper name overrides.
23struct WrapperArgs {
24    path: LitStr,
25    event_errors: EventErrors,
26    input_panics: PanicConfig,
27    write_panics: PanicConfig,
28    overrides: Vec<NameOverride>,
29}
30
31/// How generated event methods expose errors to their callers.
32#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
33enum EventErrors {
34    /// Return the error to the caller as a `Result`.
35    #[default]
36    Propagate,
37    /// Deliberately discard errors from event preparation and writing.
38    Ignore,
39}
40
41#[derive(Default)]
42struct PanicConfig {
43    enabled: bool,
44    when: Option<Meta>,
45}
46
47#[derive(Clone, Copy)]
48struct PanicPolicy<'a> {
49    enabled: bool,
50    when: Option<&'a Meta>,
51}
52
53#[derive(Clone, Copy)]
54struct EventPolicy<'a> {
55    errors: EventErrors,
56    input_panics: PanicPolicy<'a>,
57    write_panics: PanicPolicy<'a>,
58}
59
60/// A `SYMBOL -> NewName` override. `key` is matched against a provider's
61/// manifest `symbol`, `name` is the struct name to generate instead of the default.
62struct NameOverride {
63    key: String,
64    /// Span of the key token, so an unmatched override can be reported against the symbol
65    /// the caller wrote rather than the whole macro invocation.
66    key_span: Span,
67    name: Ident,
68}
69
70/// Paths used by generated code.
71struct CodegenContext {
72    runtime: TokenStream2,
73}
74
75impl CodegenContext {
76    fn resolve() -> anyhow::Result<Self> {
77        let runtime = match crate_name("etw-wrapper")? {
78            // Use the stable self-alias exported by etw-wrapper. Unlike `crate`, this also works
79            // when expansion occurs in one of that package's integration tests or doctests.
80            FoundCrate::Itself => quote!(::etw_wrapper),
81            FoundCrate::Name(name) => {
82                let name = Ident::new(&name, Span::call_site());
83                quote!(::#name)
84            }
85        };
86        Ok(Self { runtime })
87    }
88
89    #[cfg(test)]
90    fn canonical() -> Self {
91        Self {
92            runtime: quote!(::etw_wrapper),
93        }
94    }
95}
96
97fn parse_cfg_predicate(input: ParseStream, option: &str) -> syn::Result<Meta> {
98    let cfg: Ident = input.parse()?;
99    if cfg != "cfg" {
100        return Err(syn::Error::new(
101            cfg.span(),
102            format!("`{option}` must be a `cfg(...)` predicate"),
103        ));
104    }
105    let content;
106    parenthesized!(content in input);
107    content.parse()
108}
109
110fn parse_panic_config(input: ParseStream, option: &str) -> syn::Result<PanicConfig> {
111    if input.peek(LitBool) {
112        let enabled = input.parse::<LitBool>()?.value;
113        return Ok(PanicConfig {
114            enabled,
115            when: None,
116        });
117    }
118
119    let when = parse_cfg_predicate(input, option).map_err(|_| {
120        syn::Error::new(
121            input.span(),
122            format!("`{option}` must be `true`, `false`, or a `cfg(...)` predicate"),
123        )
124    })?;
125    Ok(PanicConfig {
126        enabled: true,
127        when: Some(when),
128    })
129}
130
131impl Parse for WrapperArgs {
132    fn parse(input: ParseStream) -> syn::Result<Self> {
133        let path: LitStr = input.parse()?;
134        let mut event_errors = EventErrors::default();
135        let mut event_errors_set = false;
136        let mut input_panics = PanicConfig::default();
137        let mut input_panics_set = false;
138        let mut write_panics = PanicConfig::default();
139        let mut write_panics_set = false;
140        let mut overrides = Vec::new();
141
142        while input.peek(Token![,]) {
143            input.parse::<Token![,]>()?;
144            // Tolerate a trailing comma
145            if input.is_empty() {
146                break;
147            }
148
149            let (key, key_span) = if input.peek(LitStr) {
150                let lit: LitStr = input.parse()?;
151                (lit.value(), lit.span())
152            } else {
153                let ident: Ident = input.parse()?;
154                let key = ident.to_string();
155                let key_span = ident.span();
156
157                if input.peek(Token![=]) {
158                    input.parse::<Token![=]>()?;
159                    match key.as_str() {
160                        "event_methods_return_unit" => {
161                            if event_errors_set {
162                                return Err(syn::Error::new(
163                                    key_span,
164                                    "duplicate `event_methods_return_unit` option",
165                                ));
166                            }
167
168                            event_errors = if input.parse::<LitBool>()?.value {
169                                EventErrors::Ignore
170                            } else {
171                                EventErrors::Propagate
172                            };
173                            event_errors_set = true;
174                        }
175                        "panic_on_input" => {
176                            if input_panics_set {
177                                return Err(syn::Error::new(
178                                    key_span,
179                                    "duplicate `panic_on_input` option",
180                                ));
181                            }
182
183                            input_panics = parse_panic_config(input, "panic_on_input")?;
184                            input_panics_set = true;
185                        }
186                        "panic_on_write" => {
187                            if write_panics_set {
188                                return Err(syn::Error::new(
189                                    key_span,
190                                    "duplicate `panic_on_write` option",
191                                ));
192                            }
193
194                            write_panics = parse_panic_config(input, "panic_on_write")?;
195                            write_panics_set = true;
196                        }
197                        _ => {
198                            return Err(syn::Error::new(
199                                key_span,
200                                format!("unknown gen_etw_wrapper option `{key}`"),
201                            ));
202                        }
203                    }
204                    continue;
205                }
206
207                (key, key_span)
208            };
209            input.parse::<Token![->]>()?;
210            let name: Ident = input.parse()?;
211            if overrides.iter().any(|o: &NameOverride| o.key == key) {
212                return Err(syn::Error::new(
213                    key_span,
214                    format!("duplicate name override for provider symbol `{key}`"),
215                ));
216            }
217
218            overrides.push(NameOverride {
219                key,
220                key_span,
221                name,
222            });
223        }
224
225        Ok(WrapperArgs {
226            path,
227            event_errors,
228            input_panics,
229            write_panics,
230            overrides,
231        })
232    }
233}
234
235/// Generates strongly typed ETW providers from an instrumentation manifest.
236///
237/// Invoke this macro in item position with a path to an ETW manifest:
238///
239/// ```ignore
240/// use etw_wrapper::gen_etw_wrapper;
241///
242/// gen_etw_wrapper!("manifests/widgetservice.man");
243/// ```
244///
245/// The path is resolved relative to the invoking crate's `CARGO_MANIFEST_DIR`. Changes to the
246/// manifest are tracked by Cargo and cause the crate to be rebuilt.
247///
248/// # Generated API
249///
250/// The macro generates one public provider struct for each provider in the manifest. By default,
251/// its name is the provider's `symbol` converted to PascalCase with `Logger` appended. For example,
252/// `PROVIDER_WIDGETSERVICE` produces `ProviderWidgetserviceLogger`.
253///
254/// Each provider struct has:
255///
256/// - a `register()` associated function that registers the provider with ETW;
257/// - one snake_case method per manifest event, with parameters derived from the event template;
258/// - automatic provider unregistration when the value is dropped.
259///
260/// Event methods return [`etw_wrapper::Result<()>`](https://docs.rs/etw-wrapper/latest/etw_wrapper/type.Result.html).
261/// Manifest fields used as a `count` reference, or as the `length` of a `win:Binary` field, are
262/// derived from the corresponding slice and omitted from the Rust method signature. The `length`
263/// reference of a string field sets the width of the encoded string, so it stays a parameter.
264///
265/// # Event errors
266///
267/// By default, event methods return `etw_wrapper::Result<()>`. Applications that treat logging as
268/// best-effort can generate event methods that return `()` and discard errors:
269///
270/// ```ignore
271/// # use etw_wrapper::gen_etw_wrapper;
272/// gen_etw_wrapper!(
273///     "manifests/widgetservice.man",
274///     event_methods_return_unit = true,
275///     panic_on_input = cfg(debug_assertions),
276/// );
277/// ```
278///
279/// `panic_on_input` covers errors detected while validating or preparing caller-provided values.
280/// `panic_on_write` covers errors returned by the Windows event-write call. Each accepts `true`,
281/// `false` (the default), or a Rust `cfg(...)` predicate. When a panic behavior is disabled, event
282/// errors are returned unless `event_methods_return_unit = true`. Only
283/// `event_methods_return_unit` affects the generated method's return type.
284///
285/// This setting affects only event methods. Provider registration remains fallible.
286///
287/// See the repository's
288/// [type mapping](https://github.com/austinwagner/etw-wrapper-rs#type-mapping) for the complete
289/// mapping from manifest `inType`, `length`, and `count` attributes to Rust parameter types.
290///
291/// # Naming providers
292///
293/// Map a provider symbol to a Rust identifier to override the generated struct name:
294///
295/// ```ignore
296/// # use etw_wrapper::gen_etw_wrapper;
297/// gen_etw_wrapper!(
298///     "manifests/widgetservice.man",
299///     PROVIDER_WIDGETSERVICE -> WidgetLogger,
300/// );
301/// ```
302///
303/// Quote a provider symbol when it is not a valid Rust identifier. A manifest with multiple
304/// providers may contain multiple comma-separated overrides:
305///
306/// ```ignore
307/// # use etw_wrapper::gen_etw_wrapper;
308/// gen_etw_wrapper!(
309///     "manifests/providers.man",
310///     "Contoso.WidgetService" -> WidgetLogger,
311///     PROVIDER_DATABASE -> DatabaseLogger,
312/// );
313/// ```
314///
315/// An override that does not match a provider symbol is a compile error.
316///
317/// # Example
318///
319/// Given a manifest that declares `PROVIDER_WIDGETSERVICE` with a `SERVICE_STARTED` event, an
320/// invocation can be used as follows:
321///
322/// ```ignore
323/// use etw_wrapper::{FileTime, gen_etw_wrapper};
324///
325/// gen_etw_wrapper!(
326///     "manifests/widgetservice.man",
327///     PROVIDER_WIDGETSERVICE -> WidgetLogger,
328/// );
329///
330/// fn emit() -> etw_wrapper::Result<()> {
331///     let logger = WidgetLogger::register()?;
332///     logger.service_started("1.0.0", 8, FileTime::default())
333/// }
334/// ```
335///
336/// # Provider resources
337///
338/// This macro emits events but does not compile or register the provider's message and metadata
339/// resource tables. Applications that need decoded event names, fields, and messages must compile
340/// and register those resources separately, for example with `mc.exe` and `wevtutil.exe`.
341#[proc_macro]
342pub fn gen_etw_wrapper(input: TokenStream) -> TokenStream {
343    let args = syn::parse_macro_input!(input as WrapperArgs);
344    match impl_gen_etw_wrapper(&args) {
345        Ok(ts) => ts.into(),
346        // A syn::Error carries a span, so let it point at the offending tokens. Everything else
347        // originates in the manifest file and can only be reported against the whole invocation,
348        // with "{:#}" flattening anyhow's context chain into the message.
349        Err(e) => match e.downcast::<syn::Error>() {
350            Ok(e) => e.to_compile_error().into(),
351            Err(e) => {
352                let msg = format!("{e:#}");
353                quote! { ::core::compile_error!(#msg); }.into()
354            }
355        },
356    }
357}
358
359fn impl_gen_etw_wrapper(args: &WrapperArgs) -> anyhow::Result<TokenStream2> {
360    let path = resolve_path(&args.path.value());
361    let manifest = model::load(&path)?;
362    let codegen = CodegenContext::resolve()?;
363    let event_policy = EventPolicy {
364        errors: args.event_errors,
365        input_panics: PanicPolicy {
366            enabled: args.input_panics.enabled,
367            when: args.input_panics.when.as_ref(),
368        },
369        write_panics: PanicPolicy {
370            enabled: args.write_panics.enabled,
371            when: args.write_panics.when.as_ref(),
372        },
373    };
374
375    // Map each override to its provider symbol
376    let mut overrides: HashMap<&str, &Ident> = HashMap::new();
377    for o in &args.overrides {
378        if !manifest.providers.iter().any(|p| p.symbol == o.key) {
379            return Err(syn::Error::new(
380                o.key_span,
381                format!(
382                    "name override {:?} does not match any provider symbol in the manifest",
383                    o.key
384                ),
385            )
386            .into());
387        }
388        overrides.insert(o.key.as_str(), &o.name);
389    }
390
391    let providers = manifest
392        .providers
393        .iter()
394        .map(|p| {
395            gen_provider(
396                p,
397                overrides.get(p.symbol.as_str()).copied(),
398                event_policy,
399                &codegen,
400            )
401        })
402        .collect::<anyhow::Result<Vec<_>>>()?;
403
404    // Force a rebuild when the manifest file changes by using include_bytes so
405    // Cargo tracks changes to the file
406    let abs = path.to_string_lossy().into_owned();
407
408    Ok(quote! {
409        const _: &[u8] = ::core::include_bytes!(#abs);
410        #(#providers)*
411    })
412}
413
414/// Resolves the manifest path relative to the caller's crate root.
415fn resolve_path(raw: &str) -> PathBuf {
416    let p = PathBuf::from(raw);
417    if p.is_absolute() {
418        return p;
419    }
420    match std::env::var_os("CARGO_MANIFEST_DIR") {
421        Some(dir) => PathBuf::from(dir).join(p),
422        None => p,
423    }
424}
425
426fn gen_provider(
427    p: &Provider,
428    name_override: Option<&Ident>,
429    event_policy: EventPolicy<'_>,
430    codegen: &CodegenContext,
431) -> anyhow::Result<TokenStream2> {
432    // The default name is the PascalCase provider symbol with a Logger suffix, an
433    // explicit override replaces it wholesale
434    let struct_name = match name_override {
435        Some(name) => name.clone(),
436        None => format_ident!("{}Logger", ccase!(pascal, &p.symbol)),
437    };
438    let guid = p.guid;
439    let provider_doc = format!("An ETW logger for the `{}` provider.", p.symbol);
440
441    // Emit one public method per event and one shared backing helper per distinct
442    // WinType parameter signature, keyed by the generated helper name
443    let mut backing: std::collections::BTreeMap<String, TokenStream2> = Default::default();
444    let mut methods: Vec<TokenStream2> = Vec::new();
445    let mut method_idents: HashMap<String, String> = HashMap::new();
446    for ev in &p.events {
447        let specs = ev
448            .params
449            .iter()
450            .map(|t| classify(t, codegen))
451            .collect::<Vec<_>>();
452        let helper = backing_name(&specs);
453        backing
454            .entry(helper.clone())
455            .or_insert_with(|| gen_backing(&helper, &specs, codegen));
456        let (method_ident, method) =
457            gen_event_method(ev, &specs, &helper, p, event_policy, codegen)?;
458        if let Some(prev) = method_idents.insert(method_ident.clone(), ev.symbol.clone()) {
459            anyhow::bail!(
460                "event name {} collides with {} in provider {} (both transform to: {})",
461                ev.symbol,
462                prev,
463                p.symbol,
464                method_ident
465            );
466        }
467        methods.push(method);
468    }
469
470    let helpers = backing.values();
471    let runtime = &codegen.runtime;
472
473    Ok(quote! {
474        #[doc = #provider_doc]
475        pub struct #struct_name {
476            ctx: #runtime::EtwLogger,
477        }
478
479        impl #struct_name {
480            /// Registers the provider with ETW.
481            ///
482            /// The provider is automatically unregistered when dropped.
483            ///
484            /// # Errors
485            ///
486            /// Returns an error if Windows cannot register the provider.
487            pub fn register() -> #runtime::Result<Self> {
488                let guid = #runtime::Guid::from_u128(#guid);
489                let ctx = #runtime::EtwLogger::register(&guid)?;
490                #runtime::Result::Ok(Self { ctx })
491            }
492
493            #(#methods)*
494
495            #(#helpers)*
496        }
497    })
498}
499
500/// One template field lowered for codegen: an optional public parameter, an optional
501/// statement to run before the helper call (length derivation or string truncation),
502/// the identifier handed to the backing helper for this field, and how the field is named
503/// when a message placeholder (`%N`) refers to it.
504struct FieldPlan {
505    param: Option<(Ident, TokenStream2)>,
506    /// Fallible checks that can run before the provider enablement fast path.
507    validation: Option<TokenStream2>,
508    temp: Option<TokenStream2>,
509    call: Ident,
510    doc_ref: String,
511}
512
513/// Whether a manifest field is emitted from a caller-provided value or derived from another field.
514#[derive(Clone)]
515enum FieldRole {
516    Value(ValuePlan),
517    Derived(DerivedPlan),
518}
519
520/// The independent dimensions needed to expose and serialize a caller-provided value.
521#[derive(Clone, Copy)]
522struct ValuePlan {
523    kind: ValueKind,
524    cardinality: Cardinality,
525}
526
527#[derive(Clone, Copy)]
528enum ValueKind {
529    Scalar,
530    Boolean,
531    String {
532        encoding: StringEncoding,
533        length: ElementLength,
534    },
535    Binary {
536        length: ElementLength,
537    },
538    Sid,
539}
540
541#[derive(Clone, Copy)]
542enum StringEncoding {
543    Unicode,
544    ProviderAnsi,
545    Utf8,
546}
547
548#[derive(Clone, Copy)]
549enum ElementLength {
550    Implicit,
551    Fixed(usize),
552    FieldRef(usize),
553}
554
555#[derive(Clone, Copy, Eq, PartialEq)]
556enum Cardinality {
557    Single,
558    Fixed(usize),
559    Dynamic,
560}
561
562impl Cardinality {
563    fn from_count(count: &Count) -> Self {
564        match count {
565            Count::Single => Self::Single,
566            Count::Constant(count) => Self::Fixed(*count as usize),
567            Count::FieldRef(_) => Self::Dynamic,
568        }
569    }
570
571    fn is_array(self) -> bool {
572        self != Self::Single
573    }
574}
575
576#[derive(Clone)]
577enum DerivedPlan {
578    BinaryLength { from: usize },
579    ArrayCount { from: Vec<usize> },
580}
581
582/// Returns whether a `WinType` is an integer type that a `win:Binary length="..."` reference may
583/// target.
584fn is_length_int(w: &WinType) -> bool {
585    matches!(
586        w,
587        WinType::UInt8 | WinType::UInt16 | WinType::UInt32 | WinType::HexInt32
588    )
589}
590
591fn array_param_ty(element: TokenStream2, cardinality: Cardinality) -> anyhow::Result<TokenStream2> {
592    match cardinality {
593        Cardinality::Fixed(count) => {
594            let n = count;
595            Ok(quote!(&[#element; #n]))
596        }
597        Cardinality::Dynamic => Ok(quote!(&[#element])),
598        Cardinality::Single => anyhow::bail!("internal error: array parameter has no count"),
599    }
600}
601
602/// Resolves a `length="..."` or `count="..."` reference (`role`) from the field at `field_index`
603/// (described as `subject` in errors) to the index of a scalar integer field declared before it.
604fn resolve_prior_int_field(
605    index_by_name: &HashMap<&str, usize>,
606    ev: &Event,
607    p: &Provider,
608    field_index: usize,
609    name: &str,
610    subject: &str,
611    role: &str,
612) -> anyhow::Result<usize> {
613    let field = &ev.params[field_index];
614    let index = *index_by_name.get(name).ok_or_else(|| {
615        anyhow::anyhow!(
616            "{subject} {} in event {} of provider {} references unknown {role} field {:?}",
617            field.name,
618            ev.symbol,
619            p.symbol,
620            name
621        )
622    })?;
623    if index >= field_index {
624        anyhow::bail!(
625            "{subject} {} in event {} of provider {} references {role} field {:?}, which must appear before it",
626            field.name,
627            ev.symbol,
628            p.symbol,
629            name
630        );
631    }
632    if !is_length_int(&ev.params[index].win_type) || ev.params[index].count != Count::Single {
633        anyhow::bail!(
634            "{role} field {:?} for {subject} {} in event {} of provider {} must be a scalar win:UInt8, win:UInt16, win:UInt32, or win:HexInt32",
635            name,
636            field.name,
637            ev.symbol,
638            p.symbol
639        );
640    }
641    Ok(index)
642}
643
644fn build_value_plan(
645    index_by_name: &HashMap<&str, usize>,
646    ev: &Event,
647    p: &Provider,
648    field_index: usize,
649) -> anyhow::Result<ValuePlan> {
650    let field = &ev.params[field_index];
651    let cardinality = Cardinality::from_count(&field.count);
652    let string_length = |length: &Length| -> anyhow::Result<ElementLength> {
653        match length {
654            Length::Implicit => Ok(ElementLength::Implicit),
655            // The declared width includes the terminator, so a zero-width string could never be
656            // encoded. Rejecting it here keeps every accepted `Fixed` length usable.
657            Length::Constant(0) => anyhow::bail!(
658                "string field {} in event {} of provider {} declares length=\"0\", which leaves no room for the NUL terminator",
659                field.name,
660                ev.symbol,
661                p.symbol
662            ),
663            Length::Constant(length) => Ok(ElementLength::Fixed(*length as usize)),
664            // A referenced length declares a fixed field width, so every encoded string must have
665            // exactly that length. Decoders read the declared count and never scan for a NUL.
666            Length::FieldRef(name) => Ok(ElementLength::FieldRef(resolve_prior_int_field(
667                index_by_name,
668                ev,
669                p,
670                field_index,
671                name,
672                "string field",
673                "length",
674            )?)),
675        }
676    };
677
678    let kind = match &field.win_type {
679        WinType::Boolean => ValueKind::Boolean,
680        WinType::UnicodeString(length) => ValueKind::String {
681            encoding: StringEncoding::Unicode,
682            length: string_length(length)?,
683        },
684        WinType::AnsiString(length, encoding) => ValueKind::String {
685            encoding: match encoding {
686                AnsiEncoding::ProviderAnsi => StringEncoding::ProviderAnsi,
687                AnsiEncoding::Utf8 => StringEncoding::Utf8,
688            },
689            length: string_length(length)?,
690        },
691        WinType::Binary(length) => ValueKind::Binary {
692            length: match length {
693                Length::Implicit if cardinality.is_array() => {
694                    anyhow::bail!(
695                        "binary array field {} in event {} of provider {} must declare a length",
696                        field.name,
697                        ev.symbol,
698                        p.symbol
699                    )
700                }
701                Length::Implicit => ElementLength::Implicit,
702                Length::Constant(length) => ElementLength::Fixed(*length as usize),
703                Length::FieldRef(name) => ElementLength::FieldRef(resolve_prior_int_field(
704                    index_by_name,
705                    ev,
706                    p,
707                    field_index,
708                    name,
709                    "binary field",
710                    "length",
711                )?),
712            },
713        },
714        WinType::Sid => ValueKind::Sid,
715        // Every remaining WinType is a fixed-size scalar. A future non-scalar type missed here
716        // would still panic during classification via scalar_info.
717        _ => ValueKind::Scalar,
718    };
719
720    Ok(ValuePlan { kind, cardinality })
721}
722
723fn direct_field_plan(id: Ident, ty: TokenStream2) -> FieldPlan {
724    let doc_ref = id.to_string();
725    FieldPlan {
726        param: Some((id.clone(), ty)),
727        validation: None,
728        temp: None,
729        call: id,
730        doc_ref,
731    }
732}
733
734/// A field plan whose parameter is re-encoded into the temporary `tmp` by `temp` before the
735/// backing helper call.
736fn buffered_plan(id: Ident, ty: TokenStream2, tmp: Ident, temp: TokenStream2) -> FieldPlan {
737    let doc_ref = id.to_string();
738    FieldPlan {
739        param: Some((id, ty)),
740        validation: None,
741        temp: Some(temp),
742        call: tmp,
743        doc_ref,
744    }
745}
746
747fn with_validation(mut plan: FieldPlan, validation: TokenStream2) -> FieldPlan {
748    plan.validation = Some(validation);
749    plan
750}
751
752/// Plans an array parameter whose elements are flattened into one contiguous buffer of `elem_ty`.
753/// The statements produced by `per_element` run once per element with `value` bound to the
754/// element reference and the storage `Vec` identifier passed in.
755fn accumulated_plan(
756    field_index: usize,
757    id: Ident,
758    ty: TokenStream2,
759    elem_ty: TokenStream2,
760    per_element: impl FnOnce(&Ident) -> TokenStream2,
761) -> FieldPlan {
762    let storage = format_ident!("__t{}_storage", field_index);
763    let tmp = format_ident!("__t{}", field_index);
764    let body = per_element(&storage);
765    let temp = quote! {
766        let mut #storage = ::std::vec::Vec::<#elem_ty>::new();
767        for value in #id {
768            #body
769        }
770        let #tmp: &[#elem_ty] = &#storage;
771    };
772    buffered_plan(id, ty, tmp, temp)
773}
774
775fn plan_string_value(
776    field_index: usize,
777    value: ValuePlan,
778    id: Ident,
779    idents: &[Ident],
780    specs: &[FieldSpec],
781    codegen: &CodegenContext,
782) -> anyhow::Result<FieldPlan> {
783    let runtime = &codegen.runtime;
784    let ValueKind::String { encoding, length } = value.kind else {
785        unreachable!("string planner requires a string value plan");
786    };
787
788    // A provider-ANSI string is already encoded, so the caller's bytes pass through directly.
789    // The other encodings convert from `&str` with the paired (plain, fixed-length) runtime
790    // functions into a buffer with the given element type.
791    let encode_fns = match encoding {
792        StringEncoding::ProviderAnsi => None,
793        StringEncoding::Unicode => Some(("to_u16cstring", "to_u16cstring_fixed_len", quote!(u16))),
794        StringEncoding::Utf8 => Some(("to_cstring", "to_cstring_fixed_len", quote!(u8))),
795    };
796
797    if value.cardinality == Cardinality::Single {
798        let Some((plain, fixed, elem_ty)) = encode_fns else {
799            let ty = match length {
800                ElementLength::Fixed(length) => quote!(&[u8; #length]),
801                ElementLength::Implicit | ElementLength::FieldRef(_) => {
802                    specs[field_index].rust_ty.clone()
803                }
804            };
805            let plan = direct_field_plan(id, ty);
806            let input = plan.call.clone();
807            // These bytes are already encoded, so a referenced length cannot be applied for the
808            // caller; the buffer they hand over has to match the width the manifest declares.
809            let validate_len = match length {
810                ElementLength::FieldRef(from) => {
811                    let declared = &idents[from];
812                    quote! {
813                        #runtime::field::ensure_len(#input.len(), #declared as usize)?;
814                    }
815                }
816                ElementLength::Implicit | ElementLength::Fixed(_) => TokenStream2::new(),
817            };
818            return Ok(with_validation(
819                plan,
820                quote! {
821                    #validate_len
822                    #runtime::field::ensure_nul_terminated(#input)?;
823                },
824            ));
825        };
826        let plain = format_ident!("{plain}");
827        let fixed = format_ident!("{fixed}");
828        let (validation, encode) = match length {
829            // A constant length is validated during expansion, so only the encoding remains.
830            ElementLength::Fixed(length) => (None, quote!(#runtime::field::#fixed(#id, #length)?)),
831            ElementLength::FieldRef(from) => {
832                let declared = &idents[from];
833                (
834                    Some(quote! {
835                        #runtime::field::ensure_nonzero_length(#declared as usize)?;
836                    }),
837                    quote!(#runtime::field::#fixed(#id, #declared as usize)?),
838                )
839            }
840            ElementLength::Implicit => (None, quote!(#runtime::field::#plain(#id))),
841        };
842        let tmp = format_ident!("__t{}", field_index);
843        let temp = quote! {
844            let #tmp: &[#elem_ty] = &#encode;
845        };
846        let plan = buffered_plan(id, quote!(&str), tmp, temp);
847        return Ok(match validation {
848            Some(validation) => with_validation(plan, validation),
849            None => plan,
850        });
851    }
852
853    match encode_fns {
854        Some((plain, fixed, elem_ty)) => {
855            let plain = format_ident!("{plain}");
856            let fixed = format_ident!("{fixed}");
857            let ty = array_param_ty(quote!(&str), value.cardinality)?;
858            let (validation, encode) = match length {
859                ElementLength::Implicit => (None, quote!(#runtime::field::#plain(value))),
860                ElementLength::Fixed(length) => {
861                    (None, quote!(#runtime::field::#fixed(value, #length)?))
862                }
863                ElementLength::FieldRef(from) => {
864                    let length = &idents[from];
865                    (
866                        Some(quote! {
867                            #runtime::field::ensure_nonzero_length(#length as usize)?;
868                        }),
869                        quote!(#runtime::field::#fixed(value, #length as usize)?),
870                    )
871                }
872            };
873            let plan = accumulated_plan(field_index, id, ty, elem_ty, |storage| {
874                quote! { #storage.extend_from_slice(&#encode); }
875            });
876            Ok(match validation {
877                Some(validation) => with_validation(plan, validation),
878                None => plan,
879            })
880        }
881        None => {
882            let element_ty = match length {
883                ElementLength::Fixed(length) => quote!([u8; #length]),
884                ElementLength::Implicit | ElementLength::FieldRef(_) => quote!(&[u8]),
885            };
886            let ty = array_param_ty(element_ty, value.cardinality)?;
887            let validate_len = match length {
888                ElementLength::FieldRef(from) => {
889                    let length = &idents[from];
890                    quote! {
891                        #runtime::field::ensure_len(value.len(), #length as usize)?;
892                    }
893                }
894                ElementLength::Implicit | ElementLength::Fixed(_) => TokenStream2::new(),
895            };
896            let input = id.clone();
897            let validation = quote! {
898                for value in #input {
899                    #validate_len
900                    #runtime::field::ensure_nul_terminated(value)?;
901                }
902            };
903            let plan = accumulated_plan(field_index, id, ty, quote!(u8), |storage| {
904                quote! {
905                    #storage.extend_from_slice(value);
906                }
907            });
908            Ok(with_validation(plan, validation))
909        }
910    }
911}
912
913fn plan_value_field(
914    field_index: usize,
915    value: ValuePlan,
916    id: Ident,
917    idents: &[Ident],
918    ev: &Event,
919    specs: &[FieldSpec],
920    codegen: &CodegenContext,
921) -> anyhow::Result<FieldPlan> {
922    let runtime = &codegen.runtime;
923
924    match value.kind {
925        ValueKind::Scalar => {
926            if value.cardinality == Cardinality::Single {
927                Ok(direct_field_plan(id, specs[field_index].rust_ty.clone()))
928            } else {
929                let (_, _, element_ty) = scalar_info(&ev.params[field_index].win_type, codegen)
930                    .expect("scalar value plan must have a scalar type");
931                let ty = array_param_ty(element_ty, value.cardinality)?;
932                Ok(direct_field_plan(id, ty))
933            }
934        }
935        ValueKind::Boolean => {
936            if value.cardinality == Cardinality::Single {
937                return Ok(direct_field_plan(id, specs[field_index].rust_ty.clone()));
938            }
939            let ty = array_param_ty(quote!(bool), value.cardinality)?;
940            Ok(accumulated_plan(
941                field_index,
942                id,
943                ty,
944                quote!(i32),
945                |storage| {
946                    quote! { #storage.push(i32::from(*value)); }
947                },
948            ))
949        }
950        ValueKind::String { .. } => {
951            plan_string_value(field_index, value, id, idents, specs, codegen)
952        }
953        ValueKind::Binary { length } => {
954            if value.cardinality == Cardinality::Single {
955                return Ok(match length {
956                    ElementLength::Fixed(length) => direct_field_plan(id, quote!(&[u8; #length])),
957                    ElementLength::Implicit | ElementLength::FieldRef(_) => {
958                        direct_field_plan(id, specs[field_index].rust_ty.clone())
959                    }
960                });
961            }
962
963            match length {
964                ElementLength::Fixed(length) => {
965                    let ty = array_param_ty(quote!([u8; #length]), value.cardinality)?;
966                    let tmp = format_ident!("__t{}", field_index);
967                    let temp = quote! {
968                        let #tmp: &[u8] = #id.as_flattened();
969                    };
970                    Ok(buffered_plan(id, ty, tmp, temp))
971                }
972                ElementLength::FieldRef(_) => {
973                    let ty = array_param_ty(quote!(&[u8]), value.cardinality)?;
974                    Ok(accumulated_plan(
975                        field_index,
976                        id,
977                        ty,
978                        quote!(u8),
979                        |storage| {
980                            quote! { #storage.extend_from_slice(value); }
981                        },
982                    ))
983                }
984                ElementLength::Implicit => {
985                    anyhow::bail!("internal error: binary array has no element length")
986                }
987            }
988        }
989        ValueKind::Sid => {
990            if value.cardinality == Cardinality::Single {
991                return Ok(direct_field_plan(id, specs[field_index].rust_ty.clone()));
992            }
993            let ty = array_param_ty(quote!(&#runtime::field::Sid), value.cardinality)?;
994            Ok(accumulated_plan(
995                field_index,
996                id,
997                ty,
998                quote!(u8),
999                |storage| {
1000                    quote! { #storage.extend_from_slice(value.as_bytes()); }
1001                },
1002            ))
1003        }
1004    }
1005}
1006
1007/// Resolves field dependencies, then produces the public parameter and serialization plan for
1008/// each manifest field.
1009fn plan_event(
1010    ev: &Event,
1011    p: &Provider,
1012    specs: &[FieldSpec],
1013    codegen: &CodegenContext,
1014) -> anyhow::Result<Vec<FieldPlan>> {
1015    let n = ev.params.len();
1016
1017    let mut index_by_name: HashMap<&str, usize> = HashMap::new();
1018    for (index, field) in ev.params.iter().enumerate() {
1019        index_by_name.entry(field.name.as_str()).or_insert(index);
1020    }
1021
1022    let mut roles = (0..n)
1023        .map(|index| build_value_plan(&index_by_name, ev, p, index).map(FieldRole::Value))
1024        .collect::<anyhow::Result<Vec<_>>>()?;
1025
1026    // A referenced binary length is derived from exactly one binary field.
1027    for index in 0..n {
1028        let length_field = match &roles[index] {
1029            FieldRole::Value(ValuePlan {
1030                kind:
1031                    ValueKind::Binary {
1032                        length: ElementLength::FieldRef(length_field),
1033                    },
1034                ..
1035            }) => Some(*length_field),
1036            _ => None,
1037        };
1038        let Some(length_field) = length_field else {
1039            continue;
1040        };
1041
1042        match &roles[length_field] {
1043            FieldRole::Value(_) => {
1044                roles[length_field] = FieldRole::Derived(DerivedPlan::BinaryLength { from: index });
1045            }
1046            FieldRole::Derived(existing) => {
1047                let other = match existing {
1048                    DerivedPlan::BinaryLength { from } => &ev.params[*from].name,
1049                    DerivedPlan::ArrayCount { from } => &ev.params[from[0]].name,
1050                };
1051                anyhow::bail!(
1052                    "field {:?} in event {} of provider {} is referenced by multiple derived values ({} and {})",
1053                    ev.params[length_field].name,
1054                    ev.symbol,
1055                    p.symbol,
1056                    other,
1057                    ev.params[index].name
1058                );
1059            }
1060        }
1061    }
1062
1063    // A count field may describe multiple arrays; generated code checks that their lengths agree.
1064    for (index, field) in ev.params.iter().enumerate() {
1065        let Count::FieldRef(name) = &field.count else {
1066            continue;
1067        };
1068        let count_field =
1069            resolve_prior_int_field(&index_by_name, ev, p, index, name, "array field", "count")?;
1070
1071        roles[count_field] = match roles[count_field].clone() {
1072            FieldRole::Value(_) => {
1073                FieldRole::Derived(DerivedPlan::ArrayCount { from: vec![index] })
1074            }
1075            FieldRole::Derived(DerivedPlan::ArrayCount { mut from }) => {
1076                from.push(index);
1077                FieldRole::Derived(DerivedPlan::ArrayCount { from })
1078            }
1079            FieldRole::Derived(DerivedPlan::BinaryLength { from }) => {
1080                anyhow::bail!(
1081                    "field {:?} in event {} of provider {} is used as both a binary length and an array count ({} and {})",
1082                    name,
1083                    ev.symbol,
1084                    p.symbol,
1085                    ev.params[from].name,
1086                    field.name
1087                )
1088            }
1089        };
1090    }
1091
1092    // Assign identifiers up front so derived fields can name later caller-provided values.
1093    let mut idents: Vec<Ident> = Vec::with_capacity(n);
1094    let mut exposed_names: HashMap<String, String> = HashMap::new();
1095    for (index, (field, role)) in ev.params.iter().zip(&roles).enumerate() {
1096        let ident = match role {
1097            FieldRole::Derived(DerivedPlan::BinaryLength { .. }) => {
1098                format_ident!("__len{}", index)
1099            }
1100            FieldRole::Derived(DerivedPlan::ArrayCount { .. }) => {
1101                format_ident!("__count{}", index)
1102            }
1103            FieldRole::Value(_) => {
1104                let name = safe_ident(&ccase!(snake, &field.name));
1105                if let Some(previous) = exposed_names.insert(name.clone(), field.name.clone()) {
1106                    anyhow::bail!(
1107                        "param name {} collides with {} in event {} of provider {} (both transform to: {})",
1108                        field.name,
1109                        previous,
1110                        ev.symbol,
1111                        p.symbol,
1112                        name
1113                    );
1114                }
1115                format_ident!("{}", name)
1116            }
1117        };
1118        idents.push(ident);
1119    }
1120
1121    let runtime = &codegen.runtime;
1122    let mut plans = Vec::with_capacity(n);
1123    for index in 0..n {
1124        let id = idents[index].clone();
1125        let plan = match &roles[index] {
1126            FieldRole::Value(value) => {
1127                plan_value_field(index, *value, id, &idents, ev, specs, codegen)?
1128            }
1129            FieldRole::Derived(DerivedPlan::BinaryLength { from }) => {
1130                let int_ty = specs[index].rust_ty.clone();
1131                let blob = idents[*from].clone();
1132                let source_is_array = Cardinality::from_count(&ev.params[*from].count).is_array();
1133                let (validation, temp) = if source_is_array {
1134                    (
1135                        quote! {
1136                            let _: #int_ty =
1137                                #runtime::field::checked_len(
1138                                    #runtime::field::uniform_len(#blob)?
1139                                )?;
1140                        },
1141                        quote! {
1142                            let #id: #int_ty =
1143                                #runtime::field::checked_len(
1144                                    #runtime::field::uniform_len(#blob)?
1145                                )?;
1146                        },
1147                    )
1148                } else {
1149                    (
1150                        quote! {
1151                            let _: #int_ty = #runtime::field::checked_len(#blob.len())?;
1152                        },
1153                        quote! {
1154                            let #id: #int_ty = #runtime::field::checked_len(#blob.len())?;
1155                        },
1156                    )
1157                };
1158                let doc_ref = format!("{}.len", blob);
1159                FieldPlan {
1160                    param: None,
1161                    validation: Some(validation),
1162                    temp: Some(temp),
1163                    call: id,
1164                    doc_ref,
1165                }
1166            }
1167            FieldRole::Derived(DerivedPlan::ArrayCount { from }) => {
1168                let first = *from
1169                    .first()
1170                    .ok_or_else(|| anyhow::anyhow!("internal error: array count has no source"))?;
1171                let int_ty = specs[index].rust_ty.clone();
1172                let array = idents[first].clone();
1173                let matching_lengths: Vec<_> = from
1174                    .iter()
1175                    .skip(1)
1176                    .map(|source| {
1177                        let other = &idents[*source];
1178                        quote! {
1179                            #runtime::field::ensure_len(#other.len(), #array.len())?;
1180                        }
1181                    })
1182                    .collect();
1183                let validation = quote! {
1184                    #(#matching_lengths)*
1185                    let _: #int_ty = #runtime::field::checked_len(#array.len())?;
1186                };
1187                let temp = quote! {
1188                    #(#matching_lengths)*
1189                    let #id: #int_ty = #runtime::field::checked_len(#array.len())?;
1190                };
1191                let doc_ref = format!("{}.len", array);
1192                FieldPlan {
1193                    param: None,
1194                    validation: Some(validation),
1195                    temp: Some(temp),
1196                    call: id,
1197                    doc_ref,
1198                }
1199            }
1200        };
1201        plans.push(plan);
1202    }
1203
1204    Ok(plans)
1205}
1206
1207/// Generates doc comments in the following form:
1208/// ```text
1209/// Writes the `EVENT_SYMBOL` event.
1210///
1211/// > The message text with {params} replaced.
1212/// > Inferred length parameters display as {bin_field.len}.
1213/// ```
1214fn event_doc(ev: &Event, field_refs: &[String]) -> TokenStream2 {
1215    let summary = format!("Writes the `{}` event.", ev.symbol);
1216    let message = ev.message.as_ref().map(|m| {
1217        // Render the message as a blockquote, render_message escapes Markdown control characters
1218        let line = format!("> {}", render_message(m, field_refs));
1219        quote! {
1220            #[doc = ""]
1221            #[doc = #line]
1222        }
1223    });
1224    quote! {
1225        #[doc = #summary]
1226        #message
1227    }
1228}
1229
1230/// Rewrites an ETW message's `%N` placeholders into the form `{field_name}`.
1231fn render_message(msg: &str, field_refs: &[String]) -> String {
1232    let bytes = msg.as_bytes();
1233    let mut out = String::with_capacity(msg.len());
1234    let mut i = 0;
1235    while i < bytes.len() {
1236        if bytes[i] != b'%' {
1237            // Copy one whole character so multibyte UTF-8 is not split. Every branch advances by
1238            // whole characters, so `i` is always on a character boundary and this always yields.
1239            let Some(ch) = msg[i..].chars().next() else {
1240                break;
1241            };
1242            push_escaped_markdown(&mut out, ch);
1243            i += ch.len_utf8();
1244            continue;
1245        }
1246
1247        // "%%" represents an escaped percent sign
1248        if bytes.get(i + 1) == Some(&b'%') {
1249            push_escaped_markdown(&mut out, '%');
1250            i += 2;
1251            continue;
1252        }
1253
1254        // "%<digits>" is a field placeholder
1255        let mut j = i + 1;
1256        while j < bytes.len() && bytes[j].is_ascii_digit() {
1257            j += 1;
1258        }
1259        if j == i + 1 {
1260            // Leave a lone "%" or "%<letter>" as literal text
1261            push_escaped_markdown(&mut out, '%');
1262            i += 1;
1263            continue;
1264        }
1265
1266        // The digits are ASCII by construction, but a run too long for usize overflows. Such a
1267        // placeholder can only be out of range, so it falls through to the None arm below.
1268        let n: Option<usize> = msg[i + 1..j].parse().ok();
1269        // Consume an optional "!..!" format specifier immediately following the number
1270        let mut end = j;
1271        if bytes.get(end) == Some(&b'!')
1272            && let Some(rel) = msg[end + 1..].find('!')
1273        {
1274            end = end + 1 + rel + 1;
1275        }
1276        match n
1277            .and_then(|n| n.checked_sub(1))
1278            .and_then(|idx| field_refs.get(idx))
1279        {
1280            Some(r) => {
1281                out.push('{');
1282                out.push_str(r);
1283                out.push('}');
1284            }
1285            // Preserve an out-of-range placeholder as escaped literal text
1286            None => msg[i..end]
1287                .chars()
1288                .for_each(|ch| push_escaped_markdown(&mut out, ch)),
1289        }
1290        i = end;
1291    }
1292    out
1293}
1294
1295fn push_escaped_markdown(out: &mut String, ch: char) {
1296    if matches!(ch, '\\' | '`' | '*' | '_' | '[' | ']' | '<' | '~') {
1297        out.push('\\');
1298    }
1299    out.push(ch);
1300}
1301
1302fn event_error_fallback(event_errors: EventErrors, runtime: &TokenStream2) -> TokenStream2 {
1303    match event_errors {
1304        EventErrors::Propagate => quote! {
1305            #runtime::Result::Err(__error)
1306        },
1307        EventErrors::Ignore => quote! {
1308            ::core::mem::drop(__error);
1309        },
1310    }
1311}
1312
1313fn event_error_handler(
1314    should_panic: bool,
1315    panic_when: Option<&Meta>,
1316    panic_message: &str,
1317    fallback: &TokenStream2,
1318) -> TokenStream2 {
1319    if !should_panic {
1320        return fallback.clone();
1321    }
1322
1323    let panic = quote! {
1324        ::core::panic!(#panic_message, __error)
1325    };
1326    match panic_when {
1327        Some(predicate) => quote! {
1328            {
1329                #[cfg(#predicate)]
1330                {
1331                    #panic
1332                }
1333                #[cfg(not(#predicate))]
1334                {
1335                    #fallback
1336                }
1337            }
1338        },
1339        None => panic,
1340    }
1341}
1342
1343fn gen_event_method(
1344    ev: &Event,
1345    specs: &[FieldSpec],
1346    helper: &str,
1347    p: &Provider,
1348    event_policy: EventPolicy<'_>,
1349    codegen: &CodegenContext,
1350) -> anyhow::Result<(String, TokenStream2)> {
1351    let method_ident_str = safe_ident(&ccase!(snake, &ev.symbol));
1352    let method = format_ident!("{}", method_ident_str);
1353    let helper = format_ident!("{}", helper);
1354
1355    let plans = plan_event(ev, p, specs, codegen)?;
1356
1357    let params: Vec<_> = plans
1358        .iter()
1359        .filter_map(|fp| fp.param.as_ref().map(|(id, ty)| quote! { #id: #ty }))
1360        .collect();
1361
1362    let validations: Vec<_> = plans
1363        .iter()
1364        .filter_map(|fp| fp.validation.as_ref())
1365        .collect();
1366    let temps: Vec<_> = plans.iter().filter_map(|fp| fp.temp.as_ref()).collect();
1367    let call_args: Vec<_> = plans.iter().map(|fp| &fp.call).collect();
1368
1369    let (id, version, channel, level, opcode) =
1370        (ev.id, ev.version, ev.channel, ev.level, ev.opcode);
1371    let (task, keyword) = (ev.task, ev.keyword);
1372
1373    let field_refs: Vec<String> = plans.iter().map(|fp| fp.doc_ref.clone()).collect();
1374    let doc = event_doc(ev, &field_refs);
1375    let runtime = &codegen.runtime;
1376    let event_symbol = &ev.symbol;
1377
1378    let prevalidation = if !validations.is_empty() && event_policy.input_panics.enabled {
1379        let validate = quote! {
1380            if let #runtime::Result::Err(__error) = (|| -> #runtime::Result<()> {
1381                #(#validations)*
1382                #runtime::Result::Ok(())
1383            })() {
1384                ::core::panic!(
1385                    "invalid input for ETW event `{}`: {}",
1386                    #event_symbol,
1387                    __error
1388                );
1389            }
1390        };
1391        match event_policy.input_panics.when {
1392            Some(predicate) => quote! {
1393                #[cfg(#predicate)]
1394                #validate
1395            },
1396            None => validate,
1397        }
1398    } else {
1399        TokenStream2::new()
1400    };
1401
1402    let outcome = quote! {
1403        enum __EtwEventError {
1404            Input(#runtime::Error),
1405            Write(#runtime::Error),
1406        }
1407
1408        impl ::core::convert::From<#runtime::Error> for __EtwEventError {
1409            fn from(error: #runtime::Error) -> Self {
1410                Self::Input(error)
1411            }
1412        }
1413
1414        let __outcome: ::core::result::Result<(), __EtwEventError> = (|| {
1415            const DESC: #runtime::EventDescriptor =
1416                #runtime::EventDescriptor {
1417                    id: #id,
1418                    version: #version,
1419                    channel: #channel,
1420                    level: #level,
1421                    opcode: #opcode,
1422                    task: #task,
1423                    keyword: #keyword,
1424                };
1425            if !self.ctx.enabled(#level, #keyword) {
1426                return ::core::result::Result::Ok(());
1427            }
1428            #(#validations)*
1429            #(#temps)*
1430            self.#helper(&DESC, #(#call_args),*)
1431                .map_err(__EtwEventError::Write)
1432        })();
1433    };
1434
1435    let fallback = event_error_fallback(event_policy.errors, runtime);
1436    let input_message = format!("invalid input for ETW event `{event_symbol}`: {{}}");
1437    let write_message = format!("failed to write ETW event `{event_symbol}`: {{}}");
1438    let input_handler = event_error_handler(
1439        event_policy.input_panics.enabled,
1440        event_policy.input_panics.when,
1441        &input_message,
1442        &fallback,
1443    );
1444    let write_handler = event_error_handler(
1445        event_policy.write_panics.enabled,
1446        event_policy.write_panics.when,
1447        &write_message,
1448        &fallback,
1449    );
1450    let success = match event_policy.errors {
1451        EventErrors::Propagate => quote! { #runtime::Result::Ok(()) },
1452        EventErrors::Ignore => quote! {},
1453    };
1454    let panic_doc = match (
1455        event_policy.input_panics.enabled,
1456        event_policy.write_panics.enabled,
1457    ) {
1458        (true, true) => quote! {
1459            #[doc = ""]
1460            #[doc = "# Panics"]
1461            #[doc = ""]
1462            #[doc = "Panics if input validation or the Windows event write fails."]
1463        },
1464        (true, false) => quote! {
1465            #[doc = ""]
1466            #[doc = "# Panics"]
1467            #[doc = ""]
1468            #[doc = "Panics if input validation fails."]
1469        },
1470        (false, true) => quote! {
1471            #[doc = ""]
1472            #[doc = "# Panics"]
1473            #[doc = ""]
1474            #[doc = "Panics if the Windows event write fails."]
1475        },
1476        (false, false) => quote! {},
1477    };
1478    let handle_outcome = quote! {
1479        match __outcome {
1480            ::core::result::Result::Ok(()) => {
1481                #success
1482            }
1483            ::core::result::Result::Err(__EtwEventError::Input(__error)) => {
1484                #input_handler
1485            }
1486            ::core::result::Result::Err(__EtwEventError::Write(__error)) => {
1487                #write_handler
1488            }
1489        }
1490    };
1491
1492    let method = match event_policy.errors {
1493        EventErrors::Propagate => quote! {
1494            #doc
1495            ///
1496            /// # Errors
1497            ///
1498            /// Input validation and write failures that do not panic are returned as errors.
1499            #panic_doc
1500            #[allow(clippy::too_many_arguments)]
1501            pub fn #method(&self, #(#params),*) -> #runtime::Result<()> {
1502                #prevalidation
1503                #outcome
1504                #handle_outcome
1505            }
1506        },
1507        EventErrors::Ignore => quote! {
1508            #doc
1509            ///
1510            /// Input validation and write failures that do not panic are ignored.
1511            #panic_doc
1512            #[allow(clippy::too_many_arguments)]
1513            pub fn #method(&self, #(#params),*) {
1514                #prevalidation
1515                #outcome
1516                #handle_outcome
1517            }
1518        },
1519    };
1520
1521    Ok((method_ident_str, method))
1522}
1523
1524/// Builds a shared helper function of the form
1525/// `fn __write_...(&self, desc, arg0: T0, ...) -> Result<()>`.
1526fn gen_backing(name: &str, specs: &[FieldSpec], codegen: &CodegenContext) -> TokenStream2 {
1527    let name = format_ident!("{}", name);
1528    let runtime = &codegen.runtime;
1529
1530    let args: Vec<_> = (0..specs.len())
1531        .map(|i| format_ident!("arg{}", i))
1532        .collect();
1533    let params = args.iter().zip(specs.iter()).map(|(a, s)| {
1534        let ty = &s.rust_ty;
1535        quote! { #a: #ty }
1536    });
1537
1538    // Store owned temporaries for each argument and the descriptor expression
1539    let mut temps = Vec::new();
1540    let mut descs = Vec::new();
1541    for (i, spec) in specs.iter().enumerate() {
1542        let arg = &args[i];
1543        match spec.class {
1544            FieldClass::Scalar => {
1545                descs.push(quote! { #runtime::field::scalar(&#arg) });
1546            }
1547            FieldClass::Bool => {
1548                let tmp = format_ident!("__b{}", i);
1549                temps.push(quote! { let #tmp: i32 = #arg as i32; });
1550                descs.push(quote! { #runtime::field::scalar(&#tmp) });
1551            }
1552            FieldClass::Str => {
1553                descs.push(quote! { #runtime::field::str16(#arg)? });
1554            }
1555            FieldClass::AnsiStr => {
1556                descs.push(quote! { #runtime::field::str8(#arg)? });
1557            }
1558            FieldClass::Bytes => {
1559                descs.push(quote! { #runtime::field::bytes(#arg) });
1560            }
1561            FieldClass::Slice => {
1562                descs.push(quote! { #runtime::field::slice(#arg) });
1563            }
1564            FieldClass::Sid => {
1565                descs.push(quote! { #runtime::field::sid(#arg) });
1566            }
1567        }
1568    }
1569
1570    let n = specs.len();
1571    quote! {
1572        #[allow(clippy::too_many_arguments)]
1573        fn #name(
1574            &self,
1575            desc: &#runtime::EventDescriptor,
1576            #(#params),*
1577        ) -> #runtime::Result<()> {
1578            #(#temps)*
1579            let data: [#runtime::field::EventDataDescriptor; #n] = [ #(#descs),* ];
1580            self.ctx.write(desc, &data)
1581        }
1582    }
1583}
1584
1585/// How a field's Rust value becomes an `EVENT_DATA_DESCRIPTOR`.
1586#[derive(Clone, Copy)]
1587enum FieldClass {
1588    /// Passes a `Copy` type directly.
1589    Scalar,
1590    /// Encodes a `bool` as a Windows `BOOL`.
1591    Bool,
1592    /// Uses a NUL-terminated UTF-16LE buffer after the caller converts the `&str`.
1593    Str,
1594    /// Uses a NUL-terminated byte buffer after the caller converts the ANSI string.
1595    AnsiStr,
1596    /// Passes `&[u8]` through directly.
1597    Bytes,
1598    /// Passes a contiguous slice of fixed-size `Copy` values.
1599    Slice,
1600    /// Borrows a `field::Sid`.
1601    Sid,
1602}
1603
1604struct FieldSpec {
1605    /// Provides a short fragment used to name the backing helper and deduplicate signatures.
1606    frag: &'static str,
1607    rust_ty: TokenStream2,
1608    class: FieldClass,
1609}
1610
1611/// The backing-helper name fragments (scalar and slice forms) and Rust type for a scalar
1612/// `WinType`. Returns `None` for variable-size types.
1613fn scalar_info(
1614    w: &WinType,
1615    codegen: &CodegenContext,
1616) -> Option<(&'static str, &'static str, TokenStream2)> {
1617    let runtime = &codegen.runtime;
1618    Some(match w {
1619        WinType::Int8 => ("c", "C", quote!(i8)),
1620        WinType::UInt8 => ("u", "U", quote!(u8)),
1621        WinType::Int16 => ("l", "L", quote!(i16)),
1622        WinType::UInt16 => ("h", "H", quote!(u16)),
1623        WinType::Int32 => ("d", "D", quote!(i32)),
1624        WinType::UInt32 | WinType::HexInt32 => ("q", "Q", quote!(u32)),
1625        WinType::Int64 => ("i", "I", quote!(i64)),
1626        WinType::UInt64 | WinType::HexInt64 => ("x", "X", quote!(u64)),
1627        WinType::FileTime => ("m", "M", quote!(#runtime::FileTime)),
1628        WinType::Float => ("f", "F", quote!(f32)),
1629        WinType::Double => ("g", "G", quote!(f64)),
1630        WinType::Pointer => ("p", "P", quote!(usize)),
1631        WinType::Guid => ("j", "J", quote!(#runtime::Guid)),
1632        WinType::SystemTime => ("y", "Y", quote!(#runtime::SystemTime)),
1633        _ => return None,
1634    })
1635}
1636
1637fn classify_single(w: &WinType, codegen: &CodegenContext) -> FieldSpec {
1638    let runtime = &codegen.runtime;
1639    if let Some((frag, _, rust_ty)) = scalar_info(w, codegen) {
1640        return FieldSpec {
1641            frag,
1642            rust_ty,
1643            class: FieldClass::Scalar,
1644        };
1645    }
1646
1647    match w {
1648        WinType::Boolean => FieldSpec {
1649            frag: "t",
1650            rust_ty: quote!(bool),
1651            class: FieldClass::Bool,
1652        },
1653        WinType::UnicodeString(_) => FieldSpec {
1654            frag: "z",
1655            rust_ty: quote!(&[u16]),
1656            class: FieldClass::Str,
1657        },
1658        WinType::AnsiString(_, _) => FieldSpec {
1659            frag: "a",
1660            rust_ty: quote!(&[u8]),
1661            class: FieldClass::AnsiStr,
1662        },
1663        WinType::Binary(_) => FieldSpec {
1664            frag: "s",
1665            rust_ty: quote!(&[u8]),
1666            class: FieldClass::Bytes,
1667        },
1668        WinType::Sid => FieldSpec {
1669            frag: "k",
1670            rust_ty: quote!(&#runtime::field::Sid),
1671            class: FieldClass::Sid,
1672        },
1673        _ => unreachable!("all scalar types returned above"),
1674    }
1675}
1676
1677fn classify(t: &crate::model::TypeInfo, codegen: &CodegenContext) -> FieldSpec {
1678    if t.count == Count::Single {
1679        return classify_single(&t.win_type, codegen);
1680    }
1681
1682    if let Some((_, frag, ty)) = scalar_info(&t.win_type, codegen) {
1683        return FieldSpec {
1684            frag,
1685            rust_ty: quote!(&[#ty]),
1686            class: FieldClass::Slice,
1687        };
1688    }
1689
1690    match &t.win_type {
1691        WinType::Boolean => FieldSpec {
1692            frag: "T",
1693            rust_ty: quote!(&[i32]),
1694            class: FieldClass::Slice,
1695        },
1696        WinType::UnicodeString(_) => FieldSpec {
1697            frag: "Z",
1698            rust_ty: quote!(&[u16]),
1699            class: FieldClass::Slice,
1700        },
1701        WinType::AnsiString(_, _) | WinType::Binary(_) | WinType::Sid => FieldSpec {
1702            frag: "B",
1703            rust_ty: quote!(&[u8]),
1704            class: FieldClass::Bytes,
1705        },
1706        _ => unreachable!("all scalar types returned above"),
1707    }
1708}
1709
1710fn backing_name(specs: &[FieldSpec]) -> String {
1711    if specs.is_empty() {
1712        return "__write".to_owned();
1713    }
1714
1715    let mut s = String::from("__write_");
1716    for spec in specs {
1717        s.push_str(spec.frag);
1718    }
1719    s
1720}
1721
1722/// Replaces invalid identifier characters with underscores and prepends an underscore when
1723/// required.
1724fn clean_ident(s: &str) -> String {
1725    let mut out = String::new();
1726    let mut chars = s.chars();
1727
1728    if let Some(c) = chars.next() {
1729        if is_xid_start(c) {
1730            out.push(c);
1731        } else {
1732            out.push('_');
1733            if is_xid_continue(c) {
1734                out.push(c);
1735            }
1736        }
1737    }
1738
1739    for c in chars {
1740        out.push(if is_xid_continue(c) { c } else { '_' });
1741    }
1742
1743    if out.is_empty() {
1744        out.push('_');
1745    }
1746    out
1747}
1748
1749/// Converts a string into one that is a valid identifier. The logic here may create collisions.
1750fn safe_ident(s: &str) -> String {
1751    let ident = clean_ident(s);
1752
1753    match ident.as_str() {
1754        // Special cases that "r#" will not handle get an underscore suffix
1755        "crate" | "self" | "Self" | "super" | "_" => {
1756            format!("{ident}_")
1757        }
1758        // Anything else that fails to parse gets the "r#" prefix
1759        _ if syn::parse_str::<syn::Ident>(&ident).is_err() => {
1760            format!("r#{ident}")
1761        }
1762        _ => ident,
1763    }
1764}
1765
1766#[cfg(test)]
1767mod tests {
1768    use super::*;
1769    use crate::model::{Event, Length, Provider, TypeInfo, WinType};
1770
1771    #[test]
1772    fn wrapper_args_default_to_propagating_event_errors() {
1773        let args: WrapperArgs = syn::parse_str(r#""manifest.man", PROVIDER -> Logger"#).unwrap();
1774
1775        assert_eq!(args.event_errors, EventErrors::Propagate);
1776        assert!(!args.input_panics.enabled);
1777        assert!(!args.write_panics.enabled);
1778        assert_eq!(args.overrides.len(), 1);
1779    }
1780
1781    #[test]
1782    fn wrapper_args_reject_duplicate_name_overrides() {
1783        let duplicate = syn::parse_str::<WrapperArgs>(
1784            r#""manifest.man", PROVIDER -> First, PROVIDER -> Second"#,
1785        )
1786        .err()
1787        .expect("duplicate override should fail");
1788        assert!(
1789            duplicate.to_string().contains("duplicate name override"),
1790            "unexpected message: {duplicate}"
1791        );
1792
1793        // Overriding different providers stays valid
1794        let args: WrapperArgs =
1795            syn::parse_str(r#""manifest.man", PROVIDER_A -> First, PROVIDER_B -> Second"#).unwrap();
1796        assert_eq!(args.overrides.len(), 2);
1797    }
1798
1799    #[test]
1800    fn wrapper_args_parse_unit_return_setting() {
1801        let args: WrapperArgs = syn::parse_str(
1802            r#""manifest.man", event_methods_return_unit = true, PROVIDER -> Logger"#,
1803        )
1804        .unwrap();
1805
1806        assert_eq!(args.event_errors, EventErrors::Ignore);
1807        assert_eq!(args.overrides.len(), 1);
1808
1809        let args: WrapperArgs =
1810            syn::parse_str(r#""manifest.man", event_methods_return_unit = false"#).unwrap();
1811        assert_eq!(args.event_errors, EventErrors::Propagate);
1812    }
1813
1814    #[test]
1815    fn wrapper_args_reject_invalid_or_duplicate_unit_return_setting() {
1816        assert!(
1817            syn::parse_str::<WrapperArgs>(
1818                r#""manifest.man", event_methods_return_unit = cfg(debug_assertions)"#
1819            )
1820            .is_err()
1821        );
1822
1823        let duplicate = syn::parse_str::<WrapperArgs>(
1824            r#""manifest.man",
1825                event_methods_return_unit = true,
1826                event_methods_return_unit = false"#,
1827        )
1828        .err()
1829        .expect("duplicate option should fail");
1830        assert!(
1831            duplicate
1832                .to_string()
1833                .contains("duplicate `event_methods_return_unit` option")
1834        );
1835    }
1836
1837    #[test]
1838    fn wrapper_args_parse_independent_panic_settings() {
1839        let args: WrapperArgs = syn::parse_str(
1840            r#""manifest.man",
1841                panic_on_input = cfg(debug_assertions),
1842                panic_on_write = true"#,
1843        )
1844        .unwrap();
1845
1846        assert!(args.input_panics.enabled);
1847        assert!(args.write_panics.enabled);
1848        let input = args
1849            .input_panics
1850            .when
1851            .expect("input cfg predicate should be retained");
1852        assert!(args.write_panics.when.is_none());
1853        assert_eq!(
1854            quote!(#input).to_string(),
1855            quote!(debug_assertions).to_string()
1856        );
1857    }
1858
1859    #[test]
1860    fn wrapper_args_parse_false_and_reject_invalid_panic_settings() {
1861        let args: WrapperArgs =
1862            syn::parse_str(r#""manifest.man", panic_on_input = false"#).unwrap();
1863        assert!(!args.input_panics.enabled);
1864        assert!(args.input_panics.when.is_none());
1865
1866        let error = syn::parse_str::<WrapperArgs>(r#""manifest.man", panic_on_write = sometimes"#)
1867            .err()
1868            .expect("invalid panic setting should fail");
1869
1870        assert!(
1871            error
1872                .to_string()
1873                .contains("must be `true`, `false`, or a `cfg(...)` predicate")
1874        );
1875    }
1876
1877    #[test]
1878    fn safe_ident_transforms() {
1879        // Ordinary identifiers pass through untouched
1880        assert_eq!(safe_ident("version"), "version");
1881        // Escape eligible keywords with the "r#" prefix
1882        assert_eq!(safe_ident("type"), "r#type");
1883        // Give ineligible keywords and the lone underscore an underscore suffix
1884        assert_eq!(safe_ident("crate"), "crate_");
1885        assert_eq!(safe_ident("self"), "self_");
1886        assert_eq!(safe_ident("_"), "__");
1887        // Replace invalid characters, a leading non-XID_Start character gains an underscore
1888        assert_eq!(safe_ident("worker-count"), "worker_count");
1889        assert_eq!(safe_ident("3d"), "_3d");
1890        assert_eq!(safe_ident(""), "__");
1891    }
1892
1893    fn event(params: Vec<(&str, WinType)>) -> Event {
1894        Event {
1895            symbol: "E".into(),
1896            id: 1,
1897            version: 0,
1898            level: 0,
1899            opcode: 0,
1900            task: 0,
1901            keyword: 0,
1902            channel: 0,
1903            params: params
1904                .into_iter()
1905                .map(|(name, win_type)| TypeInfo {
1906                    name: name.into(),
1907                    win_type,
1908                    count: Count::Single,
1909                })
1910                .collect(),
1911            message: None,
1912        }
1913    }
1914
1915    #[test]
1916    fn event_method_carries_message_doc() {
1917        let mut e = event(vec![("A", WinType::UInt32)]);
1918        e.message = Some("Hello %1 world".into());
1919        let codegen = CodegenContext::canonical();
1920        let specs: Vec<_> = e.params.iter().map(|t| classify(t, &codegen)).collect();
1921        let p = Provider {
1922            symbol: "P".into(),
1923            guid: 0,
1924            events: vec![],
1925        };
1926        let (_, ts) = gen_event_method(
1927            &e,
1928            &specs,
1929            "__write_q",
1930            &p,
1931            EventPolicy {
1932                errors: EventErrors::Propagate,
1933                input_panics: PanicPolicy {
1934                    enabled: false,
1935                    when: None,
1936                },
1937                write_panics: PanicPolicy {
1938                    enabled: false,
1939                    when: None,
1940                },
1941            },
1942            &codegen,
1943        )
1944        .unwrap();
1945        let rendered = ts.to_string();
1946        // The summary line and resolved message become "#[doc = ...]" attributes
1947        // with "%1" rewritten to the parameter name
1948        assert!(rendered.contains("Writes the"));
1949        assert!(rendered.contains("Hello {a} world"));
1950        assert!(rendered.contains("# Errors"));
1951    }
1952
1953    #[test]
1954    fn ignored_event_errors_generate_unit_returning_method() {
1955        let e = event(vec![("A", WinType::UInt32)]);
1956        let codegen = CodegenContext::canonical();
1957        let specs: Vec<_> = e.params.iter().map(|t| classify(t, &codegen)).collect();
1958        let p = Provider {
1959            symbol: "P".into(),
1960            guid: 0,
1961            events: vec![],
1962        };
1963
1964        let (_, ts) = gen_event_method(
1965            &e,
1966            &specs,
1967            "__write_q",
1968            &p,
1969            EventPolicy {
1970                errors: EventErrors::Ignore,
1971                input_panics: PanicPolicy {
1972                    enabled: false,
1973                    when: None,
1974                },
1975                write_panics: PanicPolicy {
1976                    enabled: false,
1977                    when: None,
1978                },
1979            },
1980            &codegen,
1981        )
1982        .unwrap();
1983        let rendered = ts.to_string();
1984
1985        assert!(rendered.contains("pub fn e"));
1986        assert!(rendered.contains("core :: mem :: drop"));
1987        assert!(
1988            rendered.contains("Input validation and write failures that do not panic are ignored")
1989        );
1990    }
1991
1992    #[test]
1993    fn panic_policy_distinguishes_input_and_write_errors() {
1994        let e = event(vec![("A", WinType::UInt32)]);
1995        let codegen = CodegenContext::canonical();
1996        let specs: Vec<_> = e.params.iter().map(|t| classify(t, &codegen)).collect();
1997        let p = Provider {
1998            symbol: "P".into(),
1999            guid: 0,
2000            events: vec![],
2001        };
2002        let predicate: Meta = syn::parse_str("debug_assertions").unwrap();
2003
2004        let (_, ts) = gen_event_method(
2005            &e,
2006            &specs,
2007            "__write_q",
2008            &p,
2009            EventPolicy {
2010                errors: EventErrors::Ignore,
2011                input_panics: PanicPolicy {
2012                    enabled: true,
2013                    when: Some(&predicate),
2014                },
2015                write_panics: PanicPolicy {
2016                    enabled: false,
2017                    when: None,
2018                },
2019            },
2020            &codegen,
2021        )
2022        .unwrap();
2023        let rendered = ts.to_string();
2024
2025        assert!(rendered.contains("invalid input for ETW event"));
2026        assert!(!rendered.contains("failed to write ETW event"));
2027        assert!(rendered.contains("cfg (debug_assertions)"));
2028        assert!(rendered.contains("cfg (not (debug_assertions))"));
2029        assert!(rendered.contains("Panics if input validation fails"));
2030
2031        let write_predicate: Meta = syn::parse_str(r#"feature = "strict-etw""#).unwrap();
2032        let (_, write) = gen_event_method(
2033            &e,
2034            &specs,
2035            "__write_q",
2036            &p,
2037            EventPolicy {
2038                errors: EventErrors::Ignore,
2039                input_panics: PanicPolicy {
2040                    enabled: false,
2041                    when: None,
2042                },
2043                write_panics: PanicPolicy {
2044                    enabled: true,
2045                    when: Some(&write_predicate),
2046                },
2047            },
2048            &codegen,
2049        )
2050        .unwrap();
2051        let rendered = write.to_string();
2052        assert!(!rendered.contains("invalid input for ETW event"));
2053        assert!(rendered.contains("failed to write ETW event"));
2054        assert!(rendered.contains(r#"feature = "strict-etw""#));
2055        assert!(rendered.contains("Panics if the Windows event write fails"));
2056    }
2057
2058    #[test]
2059    fn render_message_rewrites_placeholders() {
2060        let refs = vec!["version".to_string(), "worker_count".to_string()];
2061        assert_eq!(
2062            render_message("Started %1 with %2 workers", &refs),
2063            "Started {version} with {worker_count} workers"
2064        );
2065        // "%%" collapses to "%", an out-of-range placeholder remains literal text
2066        assert_eq!(render_message("100%% done %9", &refs), "100% done %9");
2067        // A digit run too long for usize is out of range like any other
2068        assert_eq!(
2069            render_message("%99999999999999999999999999 done", &refs),
2070            "%99999999999999999999999999 done"
2071        );
2072        // An "!..!" format specifier after the number is dropped
2073        assert_eq!(render_message("%1!s! done", &refs), "{version} done");
2074        // A hidden length field surfaces as blob.len
2075        let len_refs = vec!["blob.len".to_string(), "blob".to_string()];
2076        assert_eq!(
2077            render_message("%1 bytes in %2", &len_refs),
2078            "{blob.len} bytes in {blob}"
2079        );
2080    }
2081
2082    #[test]
2083    fn render_message_escapes_markdown() {
2084        let refs = vec!["x".to_string()];
2085        // Inline formatting characters are escaped, incidental "(" and ")" characters are not
2086        // and the inserted "{...}" field reference is emitted verbatim
2087        assert_eq!(
2088            render_message("*b* _u_ [l](h) <t> %1", &refs),
2089            "\\*b\\* \\_u\\_ \\[l\\](h) \\<t> {x}"
2090        );
2091    }
2092
2093    fn plan(e: &Event) -> anyhow::Result<Vec<FieldPlan>> {
2094        let codegen = CodegenContext::canonical();
2095        let p = Provider {
2096            symbol: "P".into(),
2097            guid: 0,
2098            events: vec![],
2099        };
2100        let specs: Vec<_> = e.params.iter().map(|t| classify(t, &codegen)).collect();
2101        plan_event(e, &p, &specs, &codegen)
2102    }
2103
2104    fn exposed_count(plans: &[FieldPlan]) -> usize {
2105        plans.iter().filter(|fp| fp.param.is_some()).count()
2106    }
2107
2108    #[test]
2109    fn fieldref_hides_and_derives_length() {
2110        let e = event(vec![
2111            ("BlobSize", WinType::UInt32),
2112            ("Blob", WinType::Binary(Length::FieldRef("BlobSize".into()))),
2113        ]);
2114        let plans = plan(&e).unwrap();
2115        // BlobSize is hidden and derived with a temporary before the call
2116        assert!(plans[0].param.is_none(), "BlobSize should be hidden");
2117        assert!(plans[0].temp.is_some(), "BlobSize should be derived");
2118        assert!(plans[0].call.to_string().starts_with("__len"));
2119        // Blob stays exposed
2120        assert!(plans[1].param.is_some());
2121        assert_eq!(exposed_count(&plans), 1);
2122    }
2123
2124    #[test]
2125    fn zero_constant_length_strings_are_rejected_during_expansion() {
2126        // A zero width cannot hold the terminator, so this is caught at expansion rather than
2127        // producing a method that fails on every call.
2128        for win_type in [
2129            WinType::UnicodeString(Length::Constant(0)),
2130            WinType::AnsiString(Length::Constant(0), AnsiEncoding::Utf8),
2131            WinType::AnsiString(Length::Constant(0), AnsiEncoding::ProviderAnsi),
2132        ] {
2133            let scalar = event(vec![("Name", win_type.clone())]);
2134            assert!(plan(&scalar).is_err(), "{win_type:?} should be rejected");
2135
2136            let mut array = event(vec![("Names", win_type.clone())]);
2137            array.params[0].count = Count::Constant(2);
2138            assert!(
2139                plan(&array).is_err(),
2140                "{win_type:?} array should be rejected"
2141            );
2142        }
2143    }
2144
2145    #[test]
2146    fn fieldref_length_keeps_scalar_strings_at_the_declared_width() {
2147        for (win_type, encoder) in [
2148            (
2149                WinType::UnicodeString(Length::FieldRef("NameLength".into())),
2150                "to_u16cstring_fixed_len",
2151            ),
2152            (
2153                WinType::AnsiString(Length::FieldRef("NameLength".into()), AnsiEncoding::Utf8),
2154                "to_cstring_fixed_len",
2155            ),
2156        ] {
2157            let e = event(vec![("NameLength", WinType::UInt16), ("Name", win_type)]);
2158            let plans = plan(&e).unwrap();
2159            // Unlike a binary length, a string length sets the field width rather than being
2160            // derived from the value, so it stays a parameter
2161            assert!(plans[0].param.is_some(), "NameLength should stay exposed");
2162            assert!(plans[0].temp.is_none());
2163            assert_eq!(exposed_count(&plans), 2);
2164            let temp = plans[1]
2165                .temp
2166                .as_ref()
2167                .expect("expected a fixed-length temp")
2168                .to_string();
2169            assert!(temp.contains(encoder), "expected {encoder} in {temp}");
2170            assert!(temp.contains("name_length"), "{temp}");
2171        }
2172    }
2173
2174    #[test]
2175    fn fieldref_length_checks_caller_encoded_scalar_strings() {
2176        let e = event(vec![
2177            ("NameLength", WinType::UInt16),
2178            (
2179                "Name",
2180                WinType::AnsiString(
2181                    Length::FieldRef("NameLength".into()),
2182                    AnsiEncoding::ProviderAnsi,
2183                ),
2184            ),
2185        ]);
2186        let plans = plan(&e).unwrap();
2187        // Provider-ANSI bytes arrive already encoded, so the width is validated instead
2188        assert!(plans[1].temp.is_none());
2189        let validation = plans[1]
2190            .validation
2191            .as_ref()
2192            .expect("expected a length check")
2193            .to_string();
2194        assert!(validation.contains("ensure_len"), "{validation}");
2195        assert!(validation.contains("name_length"), "{validation}");
2196    }
2197
2198    #[test]
2199    fn fieldref_length_on_a_scalar_string_validates_its_target() {
2200        let e = event(vec![(
2201            "Name",
2202            WinType::UnicodeString(Length::FieldRef("Nope".into())),
2203        )]);
2204        assert!(plan(&e).is_err(), "unknown length field should be rejected");
2205
2206        let e = event(vec![
2207            (
2208                "Name",
2209                WinType::UnicodeString(Length::FieldRef("NameLength".into())),
2210            ),
2211            ("NameLength", WinType::UInt16),
2212        ]);
2213        assert!(plan(&e).is_err(), "forward reference should be rejected");
2214    }
2215
2216    #[test]
2217    fn constant_binary_becomes_fixed_array() {
2218        let e = event(vec![("Blob", WinType::Binary(Length::Constant(16)))]);
2219        let plans = plan(&e).unwrap();
2220        let (_, ty) = plans[0].param.as_ref().expect("Blob should be exposed");
2221        assert!(ty.to_string().contains("16"));
2222        assert!(plans[0].temp.is_none());
2223    }
2224
2225    #[test]
2226    fn constant_unicode_becomes_fixed_len() {
2227        let e = event(vec![("Name", WinType::UnicodeString(Length::Constant(4)))]);
2228        let plans = plan(&e).unwrap();
2229        let (_, ty) = plans[0].param.as_ref().expect("Name should be exposed");
2230        assert!(ty.to_string().contains("str"));
2231        // A fixed-length temporary is emitted and passed in place of the raw parameter
2232        let temp = plans[0]
2233            .temp
2234            .as_ref()
2235            .expect("expected a fixed-length temp");
2236        assert!(temp.to_string().contains("to_u16cstring_fixed_len"));
2237        assert!(plans[0].call.to_string().starts_with("__t"));
2238    }
2239
2240    #[test]
2241    fn utf8_ansi_string_is_converted() {
2242        let e = event(vec![(
2243            "Name",
2244            WinType::AnsiString(Length::Implicit, AnsiEncoding::Utf8),
2245        )]);
2246        let plans = plan(&e).unwrap();
2247        let (_, ty) = plans[0].param.as_ref().expect("Name should be exposed");
2248        assert!(ty.to_string().contains("str"));
2249        let temp = plans[0].temp.as_ref().expect("expected a UTF-8 temp");
2250        assert!(temp.to_string().contains("to_cstring"));
2251        assert!(plans[0].call.to_string().starts_with("__t"));
2252    }
2253
2254    #[test]
2255    fn provider_ansi_string_remains_encoded_bytes() {
2256        let e = event(vec![(
2257            "Name",
2258            WinType::AnsiString(Length::Implicit, AnsiEncoding::ProviderAnsi),
2259        )]);
2260        let plans = plan(&e).unwrap();
2261        let (_, ty) = plans[0].param.as_ref().expect("Name should be exposed");
2262        assert!(ty.to_string().contains("u8"));
2263        assert!(plans[0].temp.is_none());
2264    }
2265
2266    #[test]
2267    fn constant_provider_ansi_becomes_fixed_byte_array() {
2268        let e = event(vec![(
2269            "Name",
2270            WinType::AnsiString(Length::Constant(4), AnsiEncoding::ProviderAnsi),
2271        )]);
2272        let plans = plan(&e).unwrap();
2273        let (_, ty) = plans[0].param.as_ref().expect("Name should be exposed");
2274        assert!(ty.to_string().contains("u8"));
2275        assert!(ty.to_string().contains('4'));
2276        assert!(plans[0].temp.is_none());
2277    }
2278
2279    #[test]
2280    fn constant_utf8_ansi_becomes_fixed_len() {
2281        let e = event(vec![(
2282            "Name",
2283            WinType::AnsiString(Length::Constant(4), AnsiEncoding::Utf8),
2284        )]);
2285        let plans = plan(&e).unwrap();
2286        let (_, ty) = plans[0].param.as_ref().expect("Name should be exposed");
2287        assert!(ty.to_string().contains("str"));
2288        let temp = plans[0]
2289            .temp
2290            .as_ref()
2291            .expect("expected a fixed-length ANSI temp");
2292        assert!(temp.to_string().contains("to_cstring_fixed_len"));
2293        assert!(plans[0].call.to_string().starts_with("__t"));
2294    }
2295
2296    #[test]
2297    fn fieldref_unknown_target_errors() {
2298        let e = event(vec![(
2299            "Blob",
2300            WinType::Binary(Length::FieldRef("Nope".into())),
2301        )]);
2302        assert!(plan(&e).is_err());
2303    }
2304
2305    #[test]
2306    fn fieldref_forward_reference_errors() {
2307        let e = event(vec![
2308            ("Blob", WinType::Binary(Length::FieldRef("BlobSize".into()))),
2309            ("BlobSize", WinType::UInt32),
2310        ]);
2311        assert!(plan(&e).is_err());
2312    }
2313
2314    #[test]
2315    fn fieldref_non_integer_length_errors() {
2316        let e = event(vec![
2317            ("NotAnInt", WinType::Float),
2318            ("Blob", WinType::Binary(Length::FieldRef("NotAnInt".into()))),
2319        ]);
2320        assert!(plan(&e).is_err());
2321    }
2322
2323    #[test]
2324    fn fieldref_64_bit_length_errors() {
2325        for ty in [WinType::UInt64, WinType::HexInt64] {
2326            let e = event(vec![
2327                ("TooWide", ty),
2328                ("Blob", WinType::Binary(Length::FieldRef("TooWide".into()))),
2329            ]);
2330            assert!(plan(&e).is_err());
2331        }
2332    }
2333
2334    #[test]
2335    fn fieldref_shared_by_two_blobs_errors() {
2336        let e = event(vec![
2337            ("Size", WinType::UInt32),
2338            ("A", WinType::Binary(Length::FieldRef("Size".into()))),
2339            ("B", WinType::Binary(Length::FieldRef("Size".into()))),
2340        ]);
2341        assert!(plan(&e).is_err());
2342    }
2343
2344    #[test]
2345    fn fixed_count_scalar_becomes_array_reference() {
2346        let mut e = event(vec![("Values", WinType::UInt32)]);
2347        e.params[0].count = Count::Constant(3);
2348
2349        let plans = plan(&e).unwrap();
2350        let (_, ty) = plans[0].param.as_ref().expect("Values should be exposed");
2351        let ty = ty.to_string();
2352        assert!(ty.contains("u32"));
2353        assert!(ty.contains('3'));
2354        assert!(plans[0].temp.is_none());
2355    }
2356
2357    #[test]
2358    fn value_plan_keeps_array_dimensions_orthogonal() {
2359        let mut e = event(vec![("Names", WinType::UnicodeString(Length::Constant(4)))]);
2360        e.params[0].count = Count::Constant(2);
2361        let p = Provider {
2362            symbol: "P".into(),
2363            guid: 0,
2364            events: vec![],
2365        };
2366        let index_by_name = HashMap::from([("Names", 0)]);
2367
2368        let value = build_value_plan(&index_by_name, &e, &p, 0).unwrap();
2369
2370        assert!(matches!(value.cardinality, Cardinality::Fixed(2)));
2371        assert!(matches!(
2372            value.kind,
2373            ValueKind::String {
2374                encoding: StringEncoding::Unicode,
2375                length: ElementLength::Fixed(4),
2376            }
2377        ));
2378    }
2379
2380    #[test]
2381    fn count_field_is_hidden_and_derived() {
2382        let mut e = event(vec![
2383            ("ValueCount", WinType::UInt16),
2384            ("Values", WinType::UInt32),
2385        ]);
2386        e.params[1].count = Count::FieldRef("ValueCount".into());
2387
2388        let plans = plan(&e).unwrap();
2389        assert!(plans[0].param.is_none(), "ValueCount should be hidden");
2390        assert!(plans[0].temp.is_some(), "ValueCount should be derived");
2391        let (_, ty) = plans[1].param.as_ref().expect("Values should be exposed");
2392        assert!(ty.to_string().contains("[u32]"));
2393    }
2394
2395    #[test]
2396    fn shared_count_field_checks_array_lengths() {
2397        let mut e = event(vec![
2398            ("ValueCount", WinType::UInt16),
2399            ("Primary", WinType::UInt32),
2400            ("Secondary", WinType::UInt16),
2401        ]);
2402        e.params[1].count = Count::FieldRef("ValueCount".into());
2403        e.params[2].count = Count::FieldRef("ValueCount".into());
2404
2405        let plans = plan(&e).unwrap();
2406        let temp = plans[0]
2407            .temp
2408            .as_ref()
2409            .expect("ValueCount should be derived")
2410            .to_string();
2411        assert!(temp.contains("ensure_len"));
2412        assert_eq!(exposed_count(&plans), 2);
2413    }
2414
2415    #[test]
2416    fn count_field_reference_is_validated() {
2417        let mut unknown = event(vec![("Values", WinType::UInt32)]);
2418        unknown.params[0].count = Count::FieldRef("Missing".into());
2419        assert!(plan(&unknown).is_err());
2420
2421        let mut forward = event(vec![
2422            ("Values", WinType::UInt32),
2423            ("ValueCount", WinType::UInt16),
2424        ]);
2425        forward.params[0].count = Count::FieldRef("ValueCount".into());
2426        assert!(plan(&forward).is_err());
2427
2428        let mut non_integer = event(vec![
2429            ("ValueCount", WinType::Float),
2430            ("Values", WinType::UInt32),
2431        ]);
2432        non_integer.params[1].count = Count::FieldRef("ValueCount".into());
2433        assert!(plan(&non_integer).is_err());
2434    }
2435}