Skip to main content

buffa_codegen/adapters/
generate.rs

1//! Validate the complete request before returning any native declarations.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use proc_macro2::{Ident, TokenStream};
6use quote::quote;
7
8use crate::generated::descriptor::field_descriptor_proto::{Label, Type};
9use crate::generated::descriptor::{
10    DescriptorProto, EnumDescriptorProto, FieldDescriptorProto, FileDescriptorProto,
11};
12use crate::{GeneratedFile, GeneratedFileKind};
13
14use super::*;
15
16const MAX_FIELD_DEPTH: usize = 64;
17
18struct Schema<'a> {
19    enums: BTreeMap<String, (&'a EnumDescriptorProto, &'a str)>,
20    messages: BTreeMap<String, (&'a DescriptorProto, &'a str)>,
21    native_selectors: BTreeMap<String, BTreeSet<String>>,
22}
23
24impl<'a> Schema<'a> {
25    fn new(files: &'a [FileDescriptorProto]) -> Result<Self, AdapterError> {
26        let mut schema = Self {
27            enums: BTreeMap::new(),
28            messages: BTreeMap::new(),
29            native_selectors: BTreeMap::new(),
30        };
31        for file in files {
32            let file_name = file.name.as_deref().ok_or(ErrorReason::InvalidDescriptor)?;
33            let package = file.package.as_deref().unwrap_or_default();
34            let prefix = if package.is_empty() {
35                String::new()
36            } else {
37                format!(".{package}")
38            };
39            schema.add_enums(&prefix, &file.enum_type, file_name)?;
40            // An explicit stack also bounds traversal of adversarial hand-built
41            // descriptors without relying on the thread's recursion limit.
42            let mut pending: Vec<_> = file
43                .message_type
44                .iter()
45                .map(|m| (prefix.clone(), m))
46                .collect();
47            while let Some((parent, message)) = pending.pop() {
48                let name = message
49                    .name
50                    .as_deref()
51                    .ok_or(ErrorReason::InvalidDescriptor)?;
52                let fqn = format!("{parent}.{name}");
53                if schema
54                    .messages
55                    .insert(fqn.clone(), (message, file_name))
56                    .is_some()
57                {
58                    return Err(ErrorReason::InvalidDescriptor.into());
59                }
60                schema.add_enums(&fqn, &message.enum_type, file_name)?;
61                pending.extend(message.nested_type.iter().map(|m| (fqn.clone(), m)));
62            }
63        }
64        if schema
65            .enums
66            .keys()
67            .any(|name| schema.messages.contains_key(name))
68        {
69            return Err(ErrorReason::InvalidDescriptor.into());
70        }
71        Ok(schema)
72    }
73
74    fn add_enums(
75        &mut self,
76        parent: &str,
77        enums: &'a [EnumDescriptorProto],
78        file: &'a str,
79    ) -> Result<(), AdapterError> {
80        for descriptor in enums {
81            let name = descriptor
82                .name
83                .as_deref()
84                .ok_or(ErrorReason::InvalidDescriptor)?;
85            if self
86                .enums
87                .insert(format!("{parent}.{name}"), (descriptor, file))
88                .is_some()
89            {
90                return Err(ErrorReason::InvalidDescriptor.into());
91            }
92        }
93        Ok(())
94    }
95
96    fn enumeration(&self, name: &str) -> Result<&'a EnumDescriptorProto, AdapterError> {
97        self.enums
98            .get(name)
99            .map(|(e, _)| *e)
100            .ok_or_else(|| ErrorReason::MissingDescriptor.into())
101    }
102
103    fn message(&self, name: &str) -> Result<&'a DescriptorProto, AdapterError> {
104        self.messages
105            .get(name)
106            .map(|(m, _)| *m)
107            .ok_or_else(|| ErrorReason::MissingDescriptor.into())
108    }
109
110    fn in_scope(&self, name: &str, requested: &[String]) -> Result<(), AdapterError> {
111        let file = self
112            .enums
113            .get(name)
114            .map(|(_, f)| f)
115            .or_else(|| self.messages.get(name).map(|(_, f)| f))
116            .ok_or(ErrorReason::MissingDescriptor)?;
117        if !requested.iter().any(|f| f == file) {
118            return Err(ErrorReason::GenerationScope.into());
119        }
120        Ok(())
121    }
122
123    fn field(&self, source: &FieldSource) -> Result<&'a FieldDescriptorProto, AdapterError> {
124        if source.path.is_empty() || source.path.len() > MAX_FIELD_DEPTH {
125            return Err(ErrorReason::InvalidPayload.into());
126        }
127        let mut message = self.message(&source.message)?;
128        let mut parts = source.path.iter().peekable();
129        while let Some(part) = parts.next() {
130            let field = unique_field(message, part)?;
131            if field.label == Some(Label::LABEL_REPEATED) {
132                return Err(ErrorReason::OwnershipMismatch.into());
133            }
134            if parts.peek().is_none() {
135                return Ok(field);
136            }
137            if field.r#type != Some(Type::TYPE_MESSAGE) || field.proto3_optional == Some(true) {
138                return Err(ErrorReason::InvalidPayload.into());
139            }
140            message = self.message(
141                field
142                    .type_name
143                    .as_deref()
144                    .ok_or(ErrorReason::InvalidDescriptor)?,
145            )?;
146        }
147        Err(ErrorReason::InvalidPayload.into())
148    }
149}
150
151fn unique_field<'a>(
152    message: &'a DescriptorProto,
153    name: &str,
154) -> Result<&'a FieldDescriptorProto, AdapterError> {
155    let mut fields = message
156        .field
157        .iter()
158        .filter(|f| f.name.as_deref() == Some(name));
159    let field = fields.next().ok_or(ErrorReason::MissingDescriptor)?;
160    if fields.next().is_some() {
161        return Err(ErrorReason::InvalidDescriptor.into());
162    }
163    Ok(field)
164}
165
166fn ident(name: &str) -> Result<Ident, AdapterError> {
167    // Reject structural syntax before tokenization: a deeply nested token
168    // group must never reach a general Rust parser through a name string.
169    if !name
170        .bytes()
171        .all(|b| !b.is_ascii() || b.is_ascii_alphanumeric() || b == b'_')
172    {
173        return Err(ErrorReason::InvalidIdentifier.into());
174    }
175    // syn's identifier parser does not track every newer edition keyword.
176    // Native declarations must remain usable by consumers on those editions.
177    if name.starts_with("r#") || crate::idents::is_rust_keyword(name) {
178        return Err(ErrorReason::InvalidIdentifier.into());
179    }
180    let value: Ident = syn::parse_str(name).map_err(|_| ErrorReason::InvalidIdentifier)?;
181    if matches!(
182        name,
183        "self" | "Self" | "super" | "crate" | "_" | "r#self" | "r#Self" | "r#super" | "r#crate"
184    ) {
185        return Err(ErrorReason::InvalidIdentifier.into());
186    }
187    Ok(value)
188}
189
190fn path(name: &str) -> Result<syn::Path, AdapterError> {
191    // Only module-path syntax reaches syn. In particular, nested generics or
192    // token groups cannot exhaust the parser's stack before being rejected.
193    if !name.bytes().all(|b| {
194        !b.is_ascii()
195            || b.is_ascii_alphanumeric()
196            || b.is_ascii_whitespace()
197            || matches!(b, b'_' | b':' | b'#')
198    }) {
199        return Err(ErrorReason::InvalidRustPath.into());
200    }
201    let value: syn::Path = syn::parse_str(name).map_err(|_| ErrorReason::InvalidRustPath)?;
202    if value.segments.is_empty()
203        || value.segments.iter().any(|s| {
204            let name = s.ident.to_string();
205            !matches!(s.arguments, syn::PathArguments::None)
206                || (crate::idents::is_rust_keyword(&name)
207                    && !matches!(name.as_str(), "self" | "Self" | "super" | "crate"))
208        })
209    {
210        return Err(ErrorReason::InvalidRustPath.into());
211    }
212    Ok(value)
213}
214
215fn error(mapping: &ErrorMapping) -> Result<(syn::Path, syn::Path), AdapterError> {
216    Ok((path(&mapping.rust_type)?, path(&mapping.value)?))
217}
218
219/// Generate standalone native adapter files, validating complete coverage first.
220///
221/// Outputs have [`GeneratedFileKind::Adapter`] and are intentionally excluded
222/// from the portable module tree. Include each in its native API module. This
223/// function neither reads files nor changes descriptors or portable generation.
224///
225/// # Errors
226/// Returns a fixed [`ErrorReason`] for invalid metadata, incomplete coverage,
227/// incompatible ownership, ambiguous aliases or sources outside the request.
228pub fn generate_adapters(
229    files: &[FileDescriptorProto],
230    requested: &[String],
231    config: &AdapterConfig,
232) -> Result<Vec<GeneratedFile>, AdapterError> {
233    if config.version != 1 {
234        return Err(ErrorReason::UnsupportedVersion.into());
235    }
236    let mut schema = Schema::new(files)?;
237    for selector in &config.selectors {
238        schema
239            .native_selectors
240            .entry(selector.wire.source.clone())
241            .or_default()
242            .insert(selector.name.clone());
243    }
244    let mut names = BTreeSet::new();
245    let mut ports = BTreeMap::new();
246    for port in &config.ports {
247        ident(&port.name)?;
248        if ports
249            .insert(port.name.as_str(), path(&port.rust_trait)?)
250            .is_some()
251        {
252            return Err(ErrorReason::DuplicateName.into());
253        }
254    }
255    let mut output = BTreeMap::new();
256    let mut emit = |file: &str, name: &str, tokens: TokenStream| -> Result<(), AdapterError> {
257        ident(name)?;
258        if !names.insert(name.to_owned()) {
259            return Err(ErrorReason::DuplicateName.into());
260        }
261        let stem = file.strip_suffix(".rs").ok_or(ErrorReason::InvalidOutput)?;
262        if stem.is_empty()
263            || stem.eq_ignore_ascii_case("mod")
264            || !stem.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
265            || is_reserved_windows_file_stem(stem)
266        {
267            return Err(ErrorReason::InvalidOutput.into());
268        }
269        let syntax = syn::parse2::<syn::File>(tokens).map_err(|_| ErrorReason::InvalidSyntax)?;
270        let content = format!(
271            "{}{}",
272            crate::GENERATED_HEADER,
273            prettyplease::unparse(&syntax)
274        );
275        let generated = GeneratedFile {
276            name: file.to_owned(),
277            package: String::new(),
278            content,
279            kind: GeneratedFileKind::Adapter,
280        };
281        // Files may be written on a case-insensitive filesystem even when
282        // generation runs on a case-sensitive build host.
283        if output
284            .insert(file.to_ascii_lowercase(), generated)
285            .is_some()
286        {
287            return Err(ErrorReason::DuplicateOutput.into());
288        }
289        Ok(())
290    };
291    for selector in &config.selectors {
292        schema.in_scope(&selector.wire.source, requested)?;
293        emit(&selector.file, &selector.name, closed(&schema, selector)?)?;
294    }
295    for selector in &config.payloads {
296        schema.in_scope(&selector.source, requested)?;
297        let cases = enum_cases(schema.enumeration(&selector.source)?)?;
298        let tokens = payload_enum(
299            &schema,
300            &ports,
301            &selector.name,
302            &selector.variants,
303            &cases,
304            false,
305            None,
306        )?;
307        emit(&selector.file, &selector.name, tokens)?;
308    }
309    for adapter in &config.borrowed {
310        let (cases, oneof) = match &adapter.source {
311            BorrowedSource::Enum { source } => {
312                schema.in_scope(source, requested)?;
313                (enum_cases(schema.enumeration(source)?)?, None)
314            }
315            BorrowedSource::Oneof { message, name } => {
316                schema.in_scope(message, requested)?;
317                let descriptor = schema.message(message)?;
318                let mut declarations = descriptor
319                    .oneof_decl
320                    .iter()
321                    .enumerate()
322                    .filter(|(_, o)| o.name.as_deref() == Some(name));
323                let (index, _) = declarations.next().ok_or(ErrorReason::MissingDescriptor)?;
324                if declarations.next().is_some() {
325                    return Err(ErrorReason::InvalidDescriptor.into());
326                }
327                let index = i32::try_from(index).map_err(|_| ErrorReason::InvalidDescriptor)?;
328                let mut cases = BTreeMap::new();
329                for field in &descriptor.field {
330                    if field.oneof_index != Some(index) || field.proto3_optional == Some(true) {
331                        return Err(ErrorReason::UncoveredField.into());
332                    }
333                    let name = field
334                        .name
335                        .as_deref()
336                        .ok_or(ErrorReason::InvalidDescriptor)?;
337                    if cases
338                        .insert(
339                            name.to_owned(),
340                            field.number.ok_or(ErrorReason::InvalidDescriptor)?,
341                        )
342                        .is_some()
343                    {
344                        return Err(ErrorReason::InvalidDescriptor.into());
345                    }
346                }
347                if cases.is_empty() {
348                    return Err(ErrorReason::InvalidDescriptor.into());
349                }
350                (cases, Some(message.as_str()))
351            }
352        };
353        let tokens = payload_enum(
354            &schema,
355            &ports,
356            &adapter.name,
357            &adapter.variants,
358            &cases,
359            true,
360            oneof,
361        )?;
362        emit(&adapter.file, &adapter.name, tokens)?;
363    }
364    Ok(output.into_values().collect())
365}
366
367fn enum_values(descriptor: &EnumDescriptorProto) -> Result<BTreeMap<String, i32>, AdapterError> {
368    let mut values = BTreeMap::new();
369    for value in &descriptor.value {
370        let name = value
371            .name
372            .as_deref()
373            .ok_or(ErrorReason::InvalidDescriptor)?;
374        let number = value.number.ok_or(ErrorReason::InvalidDescriptor)?;
375        let mut bytes = name.bytes();
376        if !bytes
377            .next()
378            .is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')
379            || !bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_')
380        {
381            return Err(ErrorReason::InvalidDescriptor.into());
382        }
383        if values.insert(name.to_owned(), number).is_some() {
384            return Err(ErrorReason::InvalidDescriptor.into());
385        }
386    }
387    // Unspecified is a numeric boundary, not a unique spelling: protobuf
388    // enums may legally declare several names for zero with allow_alias.
389    if !values.values().any(|&number| number == 0) {
390        return Err(ErrorReason::InvalidDescriptor.into());
391    }
392    Ok(values)
393}
394
395fn enum_cases(descriptor: &EnumDescriptorProto) -> Result<BTreeMap<String, i32>, AdapterError> {
396    let mut cases = enum_values(descriptor)?;
397    cases.retain(|_, n| *n != 0);
398    if cases.is_empty() {
399        return Err(ErrorReason::InvalidDescriptor.into());
400    }
401    Ok(cases)
402}
403
404fn claim<'a>(
405    values: &'a BTreeMap<String, i32>,
406    claimed: &mut BTreeSet<String>,
407    source: &str,
408) -> Result<&'a i32, AdapterError> {
409    let number = values.get(source).ok_or(ErrorReason::UnknownCase)?;
410    if *number == 0 {
411        return Err(ErrorReason::UnspecifiedCase.into());
412    }
413    if !claimed.insert(source.to_owned()) {
414        return Err(ErrorReason::DuplicateCase.into());
415    }
416    Ok(number)
417}
418
419struct InputMapping<'a> {
420    wire: &'a WireEnum,
421    error: &'a ErrorMapping,
422    canonical: &'a [(String, String)],
423    normalized: &'a [Normalization],
424    rejected: &'a [String],
425}
426
427fn conversion(
428    schema: &Schema<'_>,
429    variants: &BTreeMap<String, Ident>,
430    native: &Ident,
431    mapping: InputMapping<'_>,
432) -> Result<TokenStream, AdapterError> {
433    let InputMapping {
434        wire,
435        error: error_mapping,
436        canonical,
437        normalized,
438        rejected,
439    } = mapping;
440    let values = enum_values(schema.enumeration(&wire.source)?)?;
441    let wire_type = path(&wire.rust_type)?;
442    let (error_type, error_value) = error(error_mapping)?;
443    let mut claimed = BTreeSet::new();
444    let mut accepted = BTreeMap::new();
445    for (source, target) in canonical
446        .iter()
447        .map(|(s, t)| (s, t))
448        .chain(normalized.iter().map(|n| (&n.source, &n.target)))
449    {
450        let number = *claim(&values, &mut claimed, source)?;
451        let variant = variants
452            .get(target)
453            .ok_or(ErrorReason::InvalidNormalization)?;
454        if let Some(previous) = accepted.insert(number, variant) {
455            if previous != variant {
456                return Err(ErrorReason::InvalidNormalization.into());
457            }
458        }
459    }
460    for source in rejected {
461        let number = claim(&values, &mut claimed, source)?;
462        if accepted.contains_key(number) {
463            return Err(ErrorReason::InvalidNormalization.into());
464        }
465    }
466    if values
467        .iter()
468        .any(|(name, &n)| n != 0 && !claimed.contains(name))
469    {
470        return Err(ErrorReason::UncoveredCase.into());
471    }
472    let arms = accepted
473        .iter()
474        .map(|(number, variant)| quote! { #number => ::core::result::Result::Ok(Self::#variant), });
475    // The public Unknown variant can be constructed with a recognized number.
476    // Preserve the known-value boundary before applying numeric normalizations.
477    Ok(quote! {
478        impl ::core::convert::TryFrom<::buffa::EnumValue<#wire_type>> for #native {
479            type Error = #error_type;
480            fn try_from(value: ::buffa::EnumValue<#wire_type>) -> ::core::result::Result<Self, #error_type> {
481                if value.is_unknown() {
482                    return ::core::result::Result::Err(::core::convert::Into::into(#error_value));
483                }
484                match value.to_i32() {
485                    #(#arms)*
486                    _ => ::core::result::Result::Err(::core::convert::Into::into(#error_value)),
487                }
488            }
489        }
490    })
491}
492
493fn closed(schema: &Schema<'_>, selector: &ClosedSelector) -> Result<TokenStream, AdapterError> {
494    let name = ident(&selector.name)?;
495    if selector.variants.is_empty() {
496        return Err(ErrorReason::UncoveredCase.into());
497    }
498    let mut variants = BTreeMap::new();
499    let mut occupied = BTreeSet::from([
500        String::from("ALL"),
501        String::from("identifier"),
502        String::from("from_identifier"),
503    ]);
504    let mut declarations = Vec::new();
505    let mut aliases = Vec::new();
506    let mut canonical = Vec::new();
507    let mut reverse = Vec::new();
508    let mut ordered = Vec::new();
509    let wire = path(&selector.wire.rust_type)?;
510    let mut canonical_numbers = BTreeSet::new();
511    let values = enum_values(schema.enumeration(&selector.wire.source)?)?;
512    for variant in &selector.variants {
513        let native = ident(&variant.name)?;
514        if !occupied.insert(variant.name.clone()) {
515            return Err(ErrorReason::DuplicateName.into());
516        }
517        let number = values
518            .get(&variant.source)
519            .ok_or(ErrorReason::UnknownCase)?;
520        if !canonical_numbers.insert(number) {
521            return Err(ErrorReason::InvalidNormalization.into());
522        }
523        // Wire values follow the portable generator's keyword escaping; the
524        // explicitly named native API uses the stricter identifier validator.
525        let source = crate::idents::make_field_ident(&variant.source);
526        variants.insert(variant.name.clone(), native.clone());
527        canonical.push((variant.source.clone(), variant.name.clone()));
528        ordered.push(native.clone());
529        declarations.push(quote! { #[doc = "Canonical descriptor selector."] #native, });
530        reverse.push(quote! { #name::#native => Self::#source, });
531        for alias in &variant.aliases {
532            let alias_ident = ident(alias)?;
533            if !occupied.insert(alias.clone()) {
534                return Err(ErrorReason::DuplicateName.into());
535            }
536            aliases.push(quote! {
537                #[doc = "Compatibility spelling of the canonical selector."]
538                #[allow(non_upper_case_globals)]
539                pub const #alias_ident: Self = Self::#native;
540            });
541        }
542    }
543    let conversion = conversion(
544        schema,
545        &variants,
546        &name,
547        InputMapping {
548            wire: &selector.wire,
549            error: &selector.error,
550            canonical: &canonical,
551            normalized: &selector.normalizations,
552            rejected: &selector.rejected,
553        },
554    )?;
555    let mut legacy = Vec::new();
556    let mut legacy_types = BTreeSet::from([quote!(#wire).to_string()]);
557    for source in &selector.legacy {
558        // Distinct paths prevent duplicate impls within one declaration. Rust
559        // additionally checks whether application aliases name the same type.
560        let legacy_path = path(&source.wire.rust_type)?;
561        if !legacy_types.insert(quote!(#legacy_path).to_string()) {
562            return Err(ErrorReason::InvalidNormalization.into());
563        }
564        legacy.push(conversion_for_legacy(
565            schema,
566            source,
567            &selector.error,
568            &variants,
569            &name,
570        )?);
571    }
572    let identities = identities(selector, &ordered)?;
573    let non_exhaustive = selector
574        .non_exhaustive
575        .then(|| quote! { #[non_exhaustive] });
576    Ok(quote! {
577        #[doc = "Closed native selector generated from authoritative descriptors."]
578        #non_exhaustive
579        #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
580        pub enum #name { #(#declarations)* }
581        #conversion
582        #(#legacy)*
583        #[allow(deprecated)]
584        impl ::core::convert::From<#name> for #wire {
585            fn from(value: #name) -> Self { match value { #(#reverse)* } }
586        }
587        impl #name {
588            #[doc = "Complete canonical selector set in manifest order."]
589            pub const ALL: &'static [Self] = &[#(Self::#ordered),*];
590            #(#aliases)*
591        }
592        #identities
593    })
594}
595
596fn conversion_for_legacy(
597    schema: &Schema<'_>,
598    legacy: &LegacySelector,
599    error: &ErrorMapping,
600    variants: &BTreeMap<String, Ident>,
601    name: &Ident,
602) -> Result<TokenStream, AdapterError> {
603    conversion(
604        schema,
605        variants,
606        name,
607        InputMapping {
608            wire: &legacy.wire,
609            error,
610            canonical: &[],
611            normalized: &legacy.normalizations,
612            rejected: &legacy.rejected,
613        },
614    )
615}
616
617fn identities(selector: &ClosedSelector, variants: &[Ident]) -> Result<TokenStream, AdapterError> {
618    let count = selector
619        .variants
620        .iter()
621        .filter(|v| v.identifier.is_some())
622        .count();
623    let Some(mapping) = &selector.identifier_error else {
624        if count != 0 {
625            return Err(ErrorReason::InvalidIdentifiers.into());
626        }
627        return Ok(TokenStream::new());
628    };
629    if count != variants.len() {
630        return Err(ErrorReason::InvalidIdentifiers.into());
631    }
632    let (error_type, error_value) = error(mapping)?;
633    let name = ident(&selector.name)?;
634    let numbers: Vec<_> = selector
635        .variants
636        .iter()
637        .filter_map(|v| v.identifier)
638        .collect();
639    if numbers.iter().collect::<BTreeSet<_>>().len() != numbers.len() {
640        return Err(ErrorReason::InvalidIdentifiers.into());
641    }
642    Ok(quote! {
643        impl #name {
644            #[doc = "Exact external protocol identity, distinct from the protobuf number."]
645            #[must_use]
646            pub const fn identifier(self) -> ::core::primitive::i64 { match self { #(Self::#variants => #numbers,)* } }
647            #[doc = "Resolve an exact external identity without policy substitution."]
648            #[doc = ""]
649            #[doc = "# Errors"]
650            #[doc = "Returns the configured fixed domain error for an unsupported identity."]
651            pub fn from_identifier(value: ::core::primitive::i64) -> ::core::result::Result<Self, #error_type> {
652                match value {
653                    #(#numbers => ::core::result::Result::Ok(Self::#variants),)*
654                    _ => ::core::result::Result::Err(::core::convert::Into::into(#error_value)),
655                }
656            }
657        }
658    })
659}
660
661fn payload_type(
662    schema: &Schema<'_>,
663    field: &PayloadField,
664    borrowed: bool,
665) -> Result<TokenStream, AdapterError> {
666    ident(&field.name)?;
667    let descriptor = schema.field(&field.source)?;
668    match &field.representation {
669        PayloadType::Bytes => {
670            if !borrowed {
671                return Err(ErrorReason::OwnershipMismatch.into());
672            }
673            if descriptor.r#type != Some(Type::TYPE_BYTES) {
674                return Err(ErrorReason::InvalidPayload.into());
675            }
676            Ok(quote! { &'a [::core::primitive::u8] })
677        }
678        PayloadType::Value { source, rust_type } => {
679            if !matches!(
680                descriptor.r#type,
681                Some(Type::TYPE_ENUM | Type::TYPE_MESSAGE)
682            ) || descriptor.type_name.as_deref() != Some(source)
683            {
684                return Err(ErrorReason::InvalidPayload.into());
685            }
686            match descriptor.r#type {
687                Some(Type::TYPE_ENUM) => {
688                    schema.enumeration(source)?;
689                }
690                Some(Type::TYPE_MESSAGE) => {
691                    // A Copy compatibility value can aggregate closed selectors,
692                    // but cannot smuggle byte owners or collections into a borrow.
693                    let message = schema.message(source)?;
694                    if message.field.is_empty()
695                        || message.field.iter().any(|field| {
696                            field.r#type != Some(Type::TYPE_ENUM)
697                                || field.label == Some(Label::LABEL_REPEATED)
698                                || !field
699                                    .type_name
700                                    .as_ref()
701                                    .is_some_and(|name| schema.native_selectors.contains_key(name))
702                        })
703                    {
704                        return Err(ErrorReason::OwnershipMismatch.into());
705                    }
706                }
707                _ => return Err(ErrorReason::InvalidPayload.into()),
708            }
709            let value = path(rust_type)?;
710            if descriptor.r#type == Some(Type::TYPE_ENUM) {
711                let native = value
712                    .segments
713                    .last()
714                    .ok_or(ErrorReason::InvalidRustPath)?
715                    .ident
716                    .to_string();
717                if !schema
718                    .native_selectors
719                    .get(source)
720                    .is_some_and(|names| names.contains(&native))
721                {
722                    return Err(ErrorReason::InvalidPayload.into());
723                }
724            }
725            Ok(quote! { #value })
726        }
727    }
728}
729
730fn payload_fields(payload: &Payload) -> &[PayloadField] {
731    match payload {
732        Payload::Tuple { field } => std::slice::from_ref(field),
733        Payload::Struct { fields } => fields,
734        Payload::Unit | Payload::Port { .. } => &[],
735    }
736}
737
738fn payload_enum(
739    schema: &Schema<'_>,
740    ports: &BTreeMap<&str, syn::Path>,
741    name: &str,
742    variants: &[PayloadVariant],
743    cases: &BTreeMap<String, i32>,
744    borrowed: bool,
745    oneof: Option<&str>,
746) -> Result<TokenStream, AdapterError> {
747    let name = ident(name)?;
748    let mut claimed = BTreeSet::new();
749    let mut names = BTreeSet::new();
750    let mut declarations = Vec::new();
751    let mut has_borrow = false;
752    let mut numeric_targets = BTreeMap::new();
753    let mut copy_checks = Vec::new();
754    for variant in variants {
755        let native = ident(&variant.name)?;
756        if !names.insert(variant.name.clone()) {
757            return Err(ErrorReason::DuplicateName.into());
758        }
759        if variant.cases.is_empty() {
760            return Err(ErrorReason::UncoveredCase.into());
761        }
762        for case in &variant.cases {
763            let number = claim(cases, &mut claimed, case)?;
764            if let Some(previous) = numeric_targets.insert(number, &variant.name) {
765                if previous != &variant.name {
766                    return Err(ErrorReason::InvalidNormalization.into());
767                }
768            }
769        }
770        let fields = payload_fields(&variant.payload);
771        let mut field_names = BTreeSet::new();
772        let mut sources = BTreeSet::new();
773        for field in fields {
774            if !field_names.insert(&field.name) {
775                return Err(ErrorReason::DuplicateName.into());
776            }
777            let key = (&field.source.message, &field.source.path);
778            if !sources.insert(key) {
779                return Err(ErrorReason::DuplicateCase.into());
780            }
781            if fields.iter().any(|other| {
782                other.source.message == field.source.message
783                    && other.source.path != field.source.path
784                    && other.source.path.starts_with(&field.source.path)
785            }) {
786                return Err(ErrorReason::DuplicateCase.into());
787            }
788            if matches!(field.representation, PayloadType::Value { .. }) {
789                let ty = payload_type(schema, field, borrowed)?;
790                copy_checks.push(quote! { __assert_copy::<#ty>(); });
791            }
792            if let Some(root) = oneof {
793                if field.source.message != root
794                    || !field
795                        .source
796                        .path
797                        .first()
798                        .is_some_and(|p| variant.cases.contains(p))
799                {
800                    return Err(ErrorReason::UnexpectedField.into());
801                }
802            }
803        }
804        if let Some(root) = oneof {
805            if variant.cases.len() != 1 {
806                return Err(ErrorReason::InvalidPayload.into());
807            }
808            for case in &variant.cases {
809                complete_payload(schema, root, std::slice::from_ref(case), fields)?;
810            }
811        }
812        let payload = match &variant.payload {
813            Payload::Unit => TokenStream::new(),
814            Payload::Tuple { field } => {
815                has_borrow |= matches!(field.representation, PayloadType::Bytes);
816                let ty = payload_type(schema, field, borrowed)?;
817                quote! { (#ty) }
818            }
819            Payload::Struct { fields } => {
820                if fields.is_empty() {
821                    return Err(ErrorReason::InvalidPayload.into());
822                }
823                let mut members = Vec::new();
824                for field in fields {
825                    has_borrow |= matches!(field.representation, PayloadType::Bytes);
826                    let field_name = ident(&field.name)?;
827                    let ty = payload_type(schema, field, borrowed)?;
828                    members.push(quote! { #[doc = "Projected canonical descriptor field."] #field_name: #ty, });
829                }
830                quote! { { #(#members)* } }
831            }
832            Payload::Port { name } => {
833                if !borrowed || oneof.is_some() {
834                    return Err(ErrorReason::OwnershipMismatch.into());
835                }
836                let port = ports
837                    .get(name.as_str())
838                    .ok_or(ErrorReason::InvalidPayload)?;
839                has_borrow = true;
840                quote! { (&'a dyn #port) }
841            }
842        };
843        declarations
844            .push(quote! { #[doc = "Descriptor-defined native alternative."] #native #payload, });
845    }
846    if claimed.len() != cases.len() {
847        return Err(ErrorReason::UncoveredCase.into());
848    }
849    if borrowed && !has_borrow {
850        return Err(ErrorReason::OwnershipMismatch.into());
851    }
852    let lifetime = borrowed.then(|| quote! { <'a> });
853    // Borrowed bytes and capabilities must not inherit diagnostics or an owning
854    // cleanup implementation. Copy payload selectors cannot hide an owner.
855    let derives =
856        (!borrowed).then(|| quote! { #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] });
857    let copy_guard = (!copy_checks.is_empty()).then(|| {
858        quote! {
859            const _: fn() = || {
860                fn __assert_copy<T: ::core::marker::Copy>() {}
861                #(#copy_checks)*
862            };
863        }
864    });
865    Ok(quote! {
866        #[doc = "Process-local adapter generated from authoritative descriptors."]
867        #derives
868        pub enum #name #lifetime { #(#declarations)* }
869        #copy_guard
870    })
871}
872
873fn complete_payload(
874    schema: &Schema<'_>,
875    root: &str,
876    prefix: &[String],
877    fields: &[PayloadField],
878) -> Result<(), AdapterError> {
879    let mut pending = vec![prefix.to_vec()];
880    while let Some(current) = pending.pop() {
881        if current.len() > MAX_FIELD_DEPTH {
882            return Err(ErrorReason::InvalidPayload.into());
883        }
884        if fields
885            .iter()
886            .any(|f| f.source.message == root && f.source.path == current)
887        {
888            continue;
889        }
890        let field = schema.field(&FieldSource {
891            message: root.to_owned(),
892            path: current.clone(),
893        })?;
894        let descendants = fields
895            .iter()
896            .any(|f| f.source.message == root && f.source.path.starts_with(&current));
897        if field.r#type != Some(Type::TYPE_MESSAGE) || !descendants {
898            return Err(ErrorReason::UncoveredField.into());
899        }
900        let child = schema.message(
901            field
902                .type_name
903                .as_deref()
904                .ok_or(ErrorReason::InvalidDescriptor)?,
905        )?;
906        if child.field.is_empty() {
907            return Err(ErrorReason::UncoveredField.into());
908        }
909        for member in &child.field {
910            let mut next = current.clone();
911            next.push(member.name.clone().ok_or(ErrorReason::InvalidDescriptor)?);
912            pending.push(next);
913        }
914    }
915    // A parent and its descendant cannot both be claimed as distinct payloads.
916    for field in fields {
917        if fields.iter().any(|other| {
918            other.source.path != field.source.path
919                && other.source.path.starts_with(&field.source.path)
920        }) {
921            return Err(ErrorReason::DuplicateCase.into());
922        }
923    }
924    Ok(())
925}
926
927/// These names resolve to devices on Windows even with an `.rs` extension.
928/// Apply the restriction on every host so generated files remain portable.
929fn is_reserved_windows_file_stem(stem: &str) -> bool {
930    if ["CON", "PRN", "AUX", "NUL"]
931        .iter()
932        .any(|reserved| stem.eq_ignore_ascii_case(reserved))
933    {
934        return true;
935    }
936    let Some((&number, prefix)) = stem.as_bytes().split_last() else {
937        return false;
938    };
939    (b'1'..=b'9').contains(&number)
940        && (prefix.eq_ignore_ascii_case(b"COM") || prefix.eq_ignore_ascii_case(b"LPT"))
941}