Skip to main content

proto_rs/
schema.rs

1//! Protocol Buffers source parser and descriptor registry.
2//!
3//! # Registry-first loading
4//!
5//! [`Registry`] is the only cross-file source-loading abstraction.
6//! It owns source strings under protobuf import paths.
7//! Callers populate it completely before requesting a parse.
8//! The registry does not open files or contact external services.
9//! Applications may load its contents from any environment-specific source.
10//! Embedded applications can register static strings copied into allocation.
11//! Hosted applications can read files before invoking the parser.
12//! Tests can construct complete virtual source trees in memory.
13//! Re-registering a path replaces the previous source and returns it.
14//! Parsing starts from one registered root path.
15//! Only sources reachable through imports are parsed and merged.
16//! Normal imports must resolve to a registered source.
17//! Public imports must also resolve to a registered source.
18//! Missing weak imports are tolerated.
19//! Direct imports expose their declarations to the importing source.
20//! Only public imports re-export declarations to the next import level.
21//! Cyclic imports are rejected after the reachable graph is collected.
22//! Duplicate symbols across loaded sources are rejected.
23//! Registry parsing preserves the root file's package and syntax metadata.
24//!
25//! # Single-source parsing
26//!
27//! [`parse`] remains convenient for schemas without imports.
28//! It parses one source and resolves all locally declared user types.
29//! An unresolved imported type therefore produces a useful error.
30//! Cross-file users should prefer [`Registry::parse`].
31//! Neither entry point has hidden global state.
32//! Neither entry point caches descriptors between calls.
33//! Returned [`Schema`] values own their descriptors and names.
34//!
35//! # Pest grammar and lexical model
36//!
37//! The checked-in `proto.pest` grammar recognizes protobuf syntax.
38//! Pest generates the grammar parser while compiling this crate; parsing a
39//! user-provided `.proto` source never generates Rust code or message types.
40//! The same grammar produces the token stream consumed by descriptor building.
41//! It recognizes protobuf identifiers and qualified identifiers.
42//! A leading dot is retained for absolute type-name resolution.
43//! Decimal, octal, hexadecimal, exponent, signed, and large numeric literals
44//! are retained as text until a grammar position requires an integer.
45//! This permits proto2 default literals larger than a signed 64-bit value.
46//! Field numbers and enum numbers are parsed into bounded integers.
47//! Both single-quoted and double-quoted strings are recognized.
48//! Line comments beginning with `//` are ignored.
49//! Block comments delimited by `/*` and `*/` are ignored.
50//! Unterminated strings and block comments produce offset-bearing errors.
51//! Punctuation is represented as individual symbol tokens.
52//! Whitespace has no semantic meaning outside quoted strings.
53//! The lexer allocates owned token text to simplify later descriptor ownership.
54//!
55//! # File grammar
56//!
57//! Proto2 and proto3 syntax declarations are recognized.
58//! A missing syntax declaration follows the historical proto2 default.
59//! Package declarations qualify top-level messages and enums.
60//! Normal, public, and weak import declarations are retained.
61//! File options are retained and checked against their descriptor scope.
62//! Services and RPC methods are retained with resolved message endpoints.
63//! Unknown or malformed top-level statements are rejected by the grammar.
64//! Valid non-wire declarations are checked syntactically but not retained.
65//!
66//! # Message grammar
67//!
68//! Top-level and nested messages are represented by [`MessageDescriptor`].
69//! Nested names include every enclosing message component.
70//! Message fields retain source declaration order.
71//! Nested enums are stored alongside top-level enums by full name.
72//! Oneof declarations attach a shared group name to member fields.
73//! Reserved names and ranges are parsed and checked against declared fields.
74//! Extension ranges are recognized and skipped in the basic proto2 tier.
75//! Extend blocks are recognized and skipped in the basic proto2 tier.
76//! Legacy group declarations are recognized and structurally skipped.
77//! Skipping groups lets surrounding basic proto2 fields remain usable.
78//! Declared group descriptors and MessageSet semantics remain exclusions.
79//! Unknown group wire values are safely skipped, audited, and preservable.
80//!
81//! # Field descriptors
82//!
83//! [`Field`] records name, number, cardinality, type, packing, and presence.
84//! It also retains a raw proto2 default literal when one is declared.
85//! Field numbers must be positive.
86//! Field numbers may not exceed 536,870,911.
87//! The implementation-reserved range 19,000 through 19,999 is rejected.
88//! Proto2 `required`, `optional`, and `repeated` labels are retained.
89//! Proto3 unlabeled scalar fields use optional cardinality without presence.
90//! Proto3 explicit `optional` fields have explicit presence.
91//! Oneof members always have explicit presence.
92//! Resolved message fields always have explicit presence.
93//! Map declarations always have repeated cardinality internally.
94//!
95//! # Scalar types
96//!
97//! Every protobuf scalar wire type has a [`FieldType`] variant.
98//! `double` and `float` retain their IEEE width.
99//! `int32` and `int64` retain two's-complement varint semantics.
100//! `uint32` and `uint64` retain unsigned varint semantics.
101//! `sint32` and `sint64` identify zig-zag transformation.
102//! Fixed and signed-fixed variants retain their exact width.
103//! Boolean fields use the varint wire family.
104//! String fields require UTF-8 at codec decode time.
105//! Bytes fields remain opaque.
106//! Message and enum variants retain fully resolved names.
107//! Map variants own resolved key and value types.
108//!
109//! # Type resolution
110//!
111//! User-defined field types are initially retained as source names.
112//! Resolution occurs only after every reachable file has been parsed.
113//! Absolute names beginning with a dot are looked up from the schema root.
114//! Relative names are searched from the innermost message scope outward.
115//! Package scope is naturally visited while walking outward.
116//! An unqualified global candidate is checked last.
117//! Message names resolve to [`FieldType::Message`].
118//! Enum names resolve to [`FieldType::Enum`].
119//! Unknown names cause parsing to fail instead of becoming opaque placeholders.
120//! Cross-file names use the same resolution rules as local names.
121//! This phase also finalizes explicit presence and packing metadata.
122//!
123//! # Semantic pass ordering
124//!
125//! Parsing and semantic resolution are deliberately separate operations.
126//! Pest first proves that every token belongs to the protobuf grammar.
127//! The descriptor builder then checks declarations local to one source file.
128//! Registry traversal collects every source reachable from the selected root.
129//! Required imports must exist before any type lookup is attempted.
130//! Weak imports may be absent and then contribute no declarations.
131//! A depth-first graph pass rejects self-imports and longer import cycles.
132//! Visibility is computed independently for every reachable source file.
133//! Direct imports expose all declarations to the importing file.
134//! A public import additionally exposes its declarations to later importers.
135//! Ordinary transitive imports do not accidentally leak private declarations.
136//! Declaration resolution runs for every file before option uses are checked.
137//! This ordering lets consumers use options declared in imported source files.
138//! It also lets an option declaration privately import its own value message.
139//! Field and RPC types use the visibility of the file that mentions the name.
140//! Custom extension value types use the visibility of their declaring file.
141//! Option uses use the fully resolved extension descriptor from that first pass.
142//! The final merge occurs only after every file passes its local semantic checks.
143//! Merge conflicts therefore cannot leave a partially valid public [`Schema`].
144//! All maps used during these passes are deterministic allocation-backed trees.
145//!
146//! # Proto3 declaration invariants
147//!
148//! Proto3 fields cannot use the legacy `required` cardinality.
149//! An explicit `optional` field is distinguished from an implicit singular field.
150//! Message fields retain presence regardless of whether `optional` was written.
151//! Oneof members retain presence and may not carry cardinality labels.
152//! Map fields cannot be labeled, packed, nested inside oneof, or used as keys.
153//! Every map key must belong to the scalar key subset defined by protobuf.
154//! Field numbers are checked against both the numeric limit and reserved range.
155//! A field cannot reuse a reserved name or any number in a reserved interval.
156//! Field names, nested declarations, oneofs, and enum values share their proper
157//! protobuf namespaces and are rejected when those namespaces collide.
158//! Derived and explicit JSON field names must also be unique within a message.
159//! This JSON-name rule is semantic even though this crate has no JSON codec.
160//! Proto3 enum declarations must start with a member whose numeric value is zero.
161//! Duplicate enum names are always invalid.
162//! Duplicate enum numbers require an explicit `allow_alias = true` option.
163//! Enum values cannot reuse names or numbers reserved by their declaration.
164//! A proto3 field cannot refer to an enum declared by a proto2 source file.
165//! It may refer to a proto2 message because message wire semantics are compatible.
166//! Groups and ordinary extension ranges remain illegal proto3 declarations.
167//! The only accepted proto3 `extend` target is a descriptor options message.
168//! Custom-option field numbers must belong to the descriptor extension range.
169//! Unknown declarations fail instead of being silently discarded as fields.
170//!
171//! # Option resolution guarantees
172//!
173//! Every option occurrence retains its normalized source name and value text.
174//! Its lexical kind distinguishes identifiers, strings, numbers, and aggregates.
175//! Built-in names are checked against the descriptor scope where they appear.
176//! Thus a valid field option cannot be misplaced on a file or service.
177//! Boolean built-ins accept only the protobuf identifiers `true` and `false`.
178//! String built-ins require a quoted string literal.
179//! Enum-shaped built-ins require an identifier and validate their known members.
180//! Singular built-in options may not occur more than once at the same scope.
181//! A custom option name begins with a parenthesized extension reference.
182//! Absolute custom names bypass lexical lookup just like absolute type names.
183//! Relative custom names search the innermost scope and then each parent scope.
184//! The resolved extension must target the options message for the current scope.
185//! For example, a `FieldOptions` extension cannot be attached to a message.
186//! Singular custom options reject repeated assignments of the same option path.
187//! Repeated custom extension fields permit repeated assignments in source order.
188//! Scalar custom options require the matching literal category.
189//! Enum custom options accept either a symbolic identifier or numeric literal.
190//! Message-valued custom options require a braced aggregate at their root.
191//! A dotted custom-option suffix traverses resolved message fields one component
192//! at a time and rejects unknown components or traversal through scalar values.
193//! Custom map option values are rejected because extensions cannot be map fields.
194//! Descriptor option messages themselves must be visible through the Registry.
195//! This prevents a well-known type spelling from substituting for a real import.
196//!
197//! # Service descriptor guarantees
198//!
199//! Services participate in the same package namespace as messages and enums.
200//! Each service retains its source order, options, and package-qualified name.
201//! Method names must be unique within their containing service.
202//! Request and response names use ordinary protobuf lexical lookup.
203//! Both endpoints must resolve to message declarations rather than enums.
204//! Client-streaming and server-streaming modifiers are retained independently.
205//! Method option blocks and semicolon-only methods produce the same descriptor
206//! shape except for their retained option collections.
207//! Services do not affect binary message encoding but remain reflection data.
208//! Invalid services prevent the complete schema from being returned.
209//!
210//! # Wire groups versus group declarations
211//!
212//! Proto3 never permits a declared group field in its source schema.
213//! Binary protobuf still reserves start-group and end-group wire tags.
214//! A newer or legacy sender can therefore place an unknown group on the wire.
215//! The codec treats that occurrence as unknown structured data, not a declaration.
216//! It recursively verifies nesting and matching end-group field numbers.
217//! Exact bytes can be retained for compatibility forwarding and auditing.
218//! This does not synthesize a typed group descriptor or expose group members.
219//! MessageSet-shaped unknown data benefits from the same preservation behavior.
220//! Passing those wire round trips does not imply typed MessageSet reflection.
221//!
222//! # Enums
223//!
224//! [`Enum`] retains its short name, full name, and ordered values.
225//! [`EnumValue`] retains both symbolic name and signed numeric value.
226//! Negative enum values are supported.
227//! Aliases are retained as independent ordered declarations.
228//! Enum options are retained, validated, and `allow_alias` is interpreted.
229//! Unknown enum numbers remain valid at wire decode time.
230//! Proto3 enums must declare a zero-valued first member.
231//! Duplicate numeric values require `option allow_alias = true`.
232//!
233//! # Maps
234//!
235//! Map syntax is represented directly instead of exposing synthetic messages.
236//! Valid key types are signed and unsigned integer families, bool, and string.
237//! Floating-point, bytes, enum, message, and map keys are rejected.
238//! Map values may use any non-map protobuf field type.
239//! User-defined map value names resolve after the import graph is loaded.
240//! Map fields are never packed.
241//! The codec translates map descriptors to synthetic entry wire messages.
242//!
243//! # Packing
244//!
245//! Explicit `[packed = true]` and `[packed = false]` values are retained.
246//! Proto3 packable repeated fields default to packed.
247//! Proto2 packable repeated fields default to unpacked.
248//! An unresolved user type provisionally inherits the file syntax default.
249//! Resolution disables packing if that type is a message.
250//! Resolution retains the packing default if that type is an enum.
251//! Strings, bytes, maps, and messages are always marked unpacked.
252//! Decoding still accepts either representation for packable primitives.
253//!
254//! # Proto2 defaults
255//!
256//! Default option values are stored as raw normalized token text.
257//! Signed integer literals retain their sign.
258//! Large unsigned literals do not overflow the lexer.
259//! Floating exponent literals remain available to reflection callers.
260//! String and bytes defaults retain their decoded quoted contents.
261//! Boolean and enum symbolic defaults retain their identifier text.
262//! The dynamic message map represents wire presence, not accessor defaults.
263//! Callers can inspect [`Field::default`] when an absent-value view is needed.
264//! Encoding never writes an absent field merely because it declares a default.
265//! Required fields remain required independently of their default literal.
266//!
267//! # Options and non-wire declarations
268//!
269//! Built-in options are retained and validated for descriptor scope and type.
270//! The parser interprets field `packed` and `default` where they affect wire
271//! behavior and enum `allow_alias` where it affects declaration validity.
272//! Proto3 custom-option extensions of descriptor option messages are retained.
273//! Custom-option uses undergo lexical lookup, scope, duplicate, path, and value
274//! validation against the resolved extension field descriptor.
275//! Reserved names and ranges are not exposed as descriptor collections yet.
276//! Services expose ordered methods, streaming flags, options, and resolved
277//! request and response message names.
278//! Source-code comments are not retained in descriptors.
279//! These omissions do not change binary field encoding for supported messages.
280//!
281//! # Error reporting
282//!
283//! Parser errors use byte offsets into the currently parsed source.
284//! They identify missing identifiers, symbols, integers, and option values.
285//! Invalid field numbers fail before a descriptor is produced.
286//! Invalid map keys fail before a descriptor is produced.
287//! Unterminated comments, strings, groups, and messages fail parsing.
288//! Missing registry imports name the unresolved import path.
289//! Duplicate imported messages and enums name the conflicting full symbol.
290//! Unknown field types name both the type and resolution scope.
291//! A registry intentionally does not attach filesystem paths to nested errors.
292//! The caller already knows the root and registered sources being parsed.
293//!
294//! # Allocation behavior
295//!
296//! Source text is owned once by the registry.
297//! Lexing creates owned token strings for identifiers and literals.
298//! Descriptors own their final names and collections.
299//! `BTreeMap` provides deterministic lookup without a hashing dependency.
300//! Resolution creates temporary candidate-name vectors.
301//! No allocation is hidden behind a global cache.
302//! Dropping a registry releases its source text independently of parsed schemas.
303//! Dropping a schema releases every descriptor and resolved name.
304//!
305//! # Compatibility tiers
306//!
307//! Full proto3 binary behavior is exercised by the official suite adapter.
308//! Basic proto2 binary behavior uses the same dynamic descriptors and codec.
309//! Basic proto2 includes ordinary scalars, messages, enums, maps, and oneofs.
310//! Basic proto2 includes required-field checks and explicit packing options.
311//! Declared legacy groups and MessageSet reflection are unsupported.
312//! Edition 2023 syntax and its standard inherited features are implemented.
313//! Typed ordinary extensions and extension ranges are resolved and validated.
314//! JSON and text-format parsing belong to separate future codec layers.
315//! The repository's `CONFORMANCE.md` is the authoritative support declaration.
316
317use crate::{
318    Error, Result,
319    constants::{
320        BOOLEAN_FALSE, BOOLEAN_TRUE, CUSTOM_OPTION_MIN_FIELD_NUMBER, DEFAULT_RECURSION_LIMIT,
321        EDITION_2023, FEATURE_ENUM_TYPE, FEATURE_FIELD_PRESENCE, FEATURE_JSON_FORMAT,
322        FEATURE_MESSAGE_ENCODING, FEATURE_REPEATED_ENCODING, FEATURE_UTF8_VALIDATION,
323        HARDENED_SCHEMA_MAX_NESTING_DEPTH, HARDENED_SCHEMA_MAX_REGISTRY_FILES,
324        HARDENED_SCHEMA_MAX_SOURCE_BYTES, HARDENED_SCHEMA_MAX_TOKENS, KW_EDITION, KW_ENUM,
325        KW_EXTEND, KW_EXTENSIONS, KW_GROUP, KW_IMPORT, KW_MAP, KW_MAX, KW_MESSAGE, KW_ONEOF,
326        KW_OPTION, KW_OPTIONAL, KW_PACKAGE, KW_PUBLIC, KW_REPEATED, KW_REQUIRED, KW_RESERVED,
327        KW_RETURNS, KW_RPC, KW_SERVICE, KW_STREAM, KW_SYNTAX, KW_TO, KW_WEAK,
328        LONG_UNICODE_ESCAPE_DIGITS, MAX_FIELD_NUMBER, MIN_FIELD_NUMBER, OPTION_ALLOW_ALIAS,
329        OPTION_DEFAULT, OPTION_PACKED, RESERVED_FIELD_NUMBER_END, RESERVED_FIELD_NUMBER_START,
330        SHORT_UNICODE_ESCAPE_DIGITS, SYNTAX_PROTO2, SYNTAX_PROTO3, TYPE_BOOL, TYPE_BYTES,
331        TYPE_DOUBLE, TYPE_FIXED32, TYPE_FIXED64, TYPE_FLOAT, TYPE_INT32, TYPE_INT64, TYPE_SFIXED32,
332        TYPE_SFIXED64, TYPE_SINT32, TYPE_SINT64, TYPE_STRING, TYPE_UINT32, TYPE_UINT64,
333    },
334};
335use alloc::{
336    boxed::Box,
337    collections::BTreeMap,
338    format,
339    string::{String, ToString},
340    vec::Vec,
341};
342use pest::{Parser as _, error::InputLocation};
343
344/// Pest-generated parser for the checked-in proto2/proto3/Edition grammar.
345#[derive(pest_derive::Parser)]
346#[grammar = "proto.pest"]
347struct ProtoSyntaxParser;
348
349/// Converts a Pest diagnostic into the crate's stable offset-bearing error.
350fn pest_error(error: pest::error::Error<Rule>) -> Error {
351    let offset = match error.location {
352        InputLocation::Pos(offset) | InputLocation::Span((offset, _)) => offset,
353    };
354    Error::new(offset, error.to_string())
355}
356
357/// Validates the complete source against the formal Pest grammar.
358fn validate_pest_syntax(source: &str) -> Result<()> {
359    ProtoSyntaxParser::parse(Rule::proto_file, source)
360        .map(|_| ())
361        .map_err(pest_error)
362}
363
364/// Protobuf source-language edition supported by a parsed schema.
365#[derive(Clone, Copy, Debug, Eq, PartialEq)]
366pub enum Syntax {
367    /// Protocol Buffers version 2 syntax.
368    Proto2,
369    /// Protocol Buffers version 3 syntax.
370    Proto3,
371    /// Protocol Buffers Edition 2023 source and default feature set.
372    Edition2023,
373}
374
375impl Syntax {
376    /// Returns whether this language version uses proto3-like defaults.
377    const fn has_modern_defaults(self) -> bool {
378        matches!(self, Self::Proto3 | Self::Edition2023)
379    }
380
381    /// Returns whether source labels are governed by Editions rules.
382    const fn is_edition(self) -> bool {
383        matches!(self, Self::Edition2023)
384    }
385}
386
387/// Resolved singular-field presence behavior.
388#[derive(Clone, Copy, Debug, Eq, PartialEq)]
389pub enum FieldPresence {
390    /// Singular scalar fields track presence.
391    Explicit,
392    /// Singular scalar fields use default-value elision.
393    Implicit,
394    /// Absence is a message initialization error.
395    LegacyRequired,
396}
397
398/// Resolved handling of numeric values absent from an enum declaration.
399#[derive(Clone, Copy, Debug, Eq, PartialEq)]
400pub enum EnumType {
401    /// Unknown numeric values remain values of the enum field.
402    Open,
403    /// Unknown numeric values belong to the unknown-field set.
404    Closed,
405}
406
407/// Resolved wire representation for repeated packable primitives.
408#[derive(Clone, Copy, Debug, Eq, PartialEq)]
409pub enum RepeatedFieldEncoding {
410    /// Emit one length-delimited packed occurrence.
411    Packed,
412    /// Emit one ordinary occurrence per element.
413    Expanded,
414}
415
416/// Resolved wire representation for embedded messages.
417#[derive(Clone, Copy, Debug, Eq, PartialEq)]
418pub enum MessageEncoding {
419    /// Emit an ordinary length-delimited message.
420    LengthPrefixed,
421    /// Emit matching start-group and end-group tags.
422    Delimited,
423}
424
425/// Resolved validation behavior for protobuf string fields.
426#[derive(Clone, Copy, Debug, Eq, PartialEq)]
427pub enum Utf8Validation {
428    /// Reject wire strings that are not valid UTF-8.
429    Verify,
430    /// Preserve string payloads without UTF-8 validation.
431    None,
432}
433
434/// Resolved JSON availability for a declaration.
435#[derive(Clone, Copy, Debug, Eq, PartialEq)]
436pub enum JsonFormat {
437    /// JSON serialization is permitted.
438    Allow,
439    /// JSON serialization is deliberately disabled.
440    LegacyBestEffort,
441}
442
443/// Inherited protobuf language features resolved for a descriptor.
444#[derive(Clone, Copy, Debug, Eq, PartialEq)]
445pub struct FeatureSet {
446    /// Singular-field presence behavior.
447    pub field_presence: FieldPresence,
448    /// Enum openness behavior.
449    pub enum_type: EnumType,
450    /// Default repeated primitive encoding.
451    pub repeated_field_encoding: RepeatedFieldEncoding,
452    /// Embedded-message encoding.
453    pub message_encoding: MessageEncoding,
454    /// String payload validation.
455    pub utf8_validation: Utf8Validation,
456    /// JSON availability.
457    pub json_format: JsonFormat,
458}
459
460impl FeatureSet {
461    /// Returns the defaults associated with a source language version.
462    pub const fn for_syntax(syntax: Syntax) -> Self {
463        match syntax {
464            Syntax::Proto2 => Self {
465                field_presence: FieldPresence::Explicit,
466                enum_type: EnumType::Closed,
467                repeated_field_encoding: RepeatedFieldEncoding::Expanded,
468                message_encoding: MessageEncoding::LengthPrefixed,
469                utf8_validation: Utf8Validation::Verify,
470                json_format: JsonFormat::LegacyBestEffort,
471            },
472            Syntax::Proto3 => Self {
473                field_presence: FieldPresence::Implicit,
474                enum_type: EnumType::Open,
475                repeated_field_encoding: RepeatedFieldEncoding::Packed,
476                message_encoding: MessageEncoding::LengthPrefixed,
477                utf8_validation: Utf8Validation::Verify,
478                json_format: JsonFormat::Allow,
479            },
480            Syntax::Edition2023 => Self {
481                field_presence: FieldPresence::Explicit,
482                enum_type: EnumType::Open,
483                repeated_field_encoding: RepeatedFieldEncoding::Packed,
484                message_encoding: MessageEncoding::LengthPrefixed,
485                utf8_validation: Utf8Validation::Verify,
486                json_format: JsonFormat::Allow,
487            },
488        }
489    }
490}
491/// Declared occurrence rule for a protobuf field.
492#[derive(Clone, Copy, Debug, Eq, PartialEq)]
493pub enum Cardinality {
494    /// Field may occur zero or one time semantically.
495    Optional,
496    /// Proto2 field must be present.
497    Required,
498    /// Field may contain an ordered sequence of values.
499    Repeated,
500}
501/// Resolved protobuf field type used by the dynamic codec.
502#[derive(Clone, Debug, Eq, PartialEq)]
503pub enum FieldType {
504    /// IEEE-754 double-precision value.
505    Double,
506    /// IEEE-754 single-precision value.
507    Float,
508    /// Signed 32-bit varint.
509    Int32,
510    /// Signed 64-bit varint.
511    Int64,
512    /// Unsigned 32-bit varint.
513    Uint32,
514    /// Unsigned 64-bit varint.
515    Uint64,
516    /// Zig-zag encoded signed 32-bit integer.
517    Sint32,
518    /// Zig-zag encoded signed 64-bit integer.
519    Sint64,
520    /// Little-endian fixed-width unsigned 32-bit integer.
521    Fixed32,
522    /// Little-endian fixed-width unsigned 64-bit integer.
523    Fixed64,
524    /// Little-endian fixed-width signed 32-bit integer.
525    Sfixed32,
526    /// Little-endian fixed-width signed 64-bit integer.
527    Sfixed64,
528    /// Boolean varint.
529    Bool,
530    /// UTF-8 string.
531    String,
532    /// Opaque byte string.
533    Bytes,
534    /// Embedded message identified by its resolved full name.
535    Message(String),
536    /// Enumeration identified by its resolved full name.
537    Enum(String),
538    /// Synthetic map entry containing its key and value types.
539    Map(Box<FieldType>, Box<FieldType>),
540}
541/// Runtime descriptor for one protobuf message field.
542#[derive(Clone, Debug, Eq, PartialEq)]
543pub struct Field {
544    /// Source-level field name.
545    pub name: String,
546    /// Positive numeric protobuf tag.
547    pub number: u32,
548    /// Optional, required, or repeated occurrence rule.
549    pub cardinality: Cardinality,
550    /// Resolved field value type.
551    pub kind: FieldType,
552    /// Explicit or syntax-derived packed-encoding setting.
553    pub packed: Option<bool>,
554    /// Whether `packed` was written explicitly instead of derived from syntax.
555    pub packed_explicit: bool,
556    /// Containing oneof name when this field is a oneof member.
557    pub oneof: Option<String>,
558    /// Whether this singular field has explicit presence (`optional`,
559    /// `required`, a oneof member, or a message field).
560    pub explicit_presence: bool,
561    /// Raw proto2 default literal, retained for reflection and auditing.
562    pub default: Option<String>,
563    /// Source options retained in declaration order.
564    pub options: Vec<OptionSetting>,
565    /// Fully inherited feature values controlling this field's semantics.
566    pub features: FeatureSet,
567}
568/// Runtime descriptor for one protobuf message declaration.
569#[derive(Clone, Debug, Eq, PartialEq)]
570pub struct MessageDescriptor {
571    /// Unqualified source-level message name.
572    pub name: String,
573    /// Package- and nesting-qualified message name.
574    pub full_name: String,
575    /// Fields in declaration order.
576    pub fields: Vec<Field>,
577    /// Inclusive numeric ranges in which extension fields may be declared.
578    pub extension_ranges: Vec<(u32, u32)>,
579    /// Oneof declarations in source order, including their options.
580    pub oneofs: Vec<OneofDescriptor>,
581    /// Message options retained for reflection and semantic auditing.
582    pub options: Vec<OptionSetting>,
583    /// Fully inherited feature values controlling this message.
584    pub features: FeatureSet,
585}
586impl MessageDescriptor {
587    /// Finds a field descriptor by its numeric protobuf tag.
588    pub fn field_by_number(&self, number: u32) -> Option<&Field> {
589        self.fields.iter().find(|field| field.number == number)
590    }
591    /// Finds a field descriptor by its source-level protobuf name.
592    pub fn field_by_name(&self, name: &str) -> Option<&Field> {
593        self.fields.iter().find(|field| field.name == name)
594    }
595}
596impl Field {
597    /// Returns the protobuf JSON name, honoring an explicit `json_name` option.
598    pub fn json_name(&self) -> String {
599        field_json_name(self)
600    }
601}
602/// One named numeric member of a protobuf enumeration.
603#[derive(Clone, Debug, Eq, PartialEq)]
604pub struct EnumValue {
605    /// Source-level enum member name.
606    pub name: String,
607    /// Signed numeric enum value.
608    pub number: i32,
609    /// Enum-value options retained for semantic auditing.
610    pub options: Vec<OptionSetting>,
611}
612/// Runtime descriptor for a protobuf enumeration.
613#[derive(Clone, Debug, Eq, PartialEq)]
614pub struct Enum {
615    /// Unqualified source-level enum name.
616    pub name: String,
617    /// Package- and nesting-qualified enum name.
618    pub full_name: String,
619    /// Declared enumeration members.
620    pub values: Vec<EnumValue>,
621    /// Syntax of the file that declares this enumeration.
622    pub syntax: Syntax,
623    /// Enum options retained for reflection and semantic auditing.
624    pub options: Vec<OptionSetting>,
625    /// Fully inherited feature values controlling this enum.
626    pub features: FeatureSet,
627}
628/// One source-level protobuf option after lexical normalization.
629#[derive(Clone, Debug, Eq, PartialEq)]
630pub struct OptionSetting {
631    /// Built-in name or parenthesized custom-option name.
632    pub name: String,
633    /// Scalar or aggregate source value without surrounding whitespace.
634    pub value: String,
635    /// Lexical category used for built-in option type validation.
636    pub value_kind: OptionValueKind,
637}
638/// Lexical category of a protobuf option value.
639#[derive(Clone, Copy, Debug, Eq, PartialEq)]
640pub enum OptionValueKind {
641    /// Identifier value, including booleans and enum member names.
642    Identifier,
643    /// One or more adjacent quoted string literals.
644    String,
645    /// Integer or floating-point numeric literal.
646    Number,
647    /// Braced aggregate message value.
648    Aggregate,
649}
650/// One oneof declaration and its retained source options.
651#[derive(Clone, Debug, Eq, PartialEq)]
652pub struct OneofDescriptor {
653    /// Source-level oneof name.
654    pub name: String,
655    /// Oneof options retained for reflection and validation.
656    pub options: Vec<OptionSetting>,
657}
658/// One RPC method retained from a proto3 service declaration.
659#[derive(Clone, Debug, Eq, PartialEq)]
660pub struct MethodDescriptor {
661    /// Method name within its containing service.
662    pub name: String,
663    /// Fully resolved protobuf request message name.
664    pub input_type: String,
665    /// Fully resolved protobuf response message name.
666    pub output_type: String,
667    /// Whether the request side is client-streaming.
668    pub client_streaming: bool,
669    /// Whether the response side is server-streaming.
670    pub server_streaming: bool,
671    /// Method options retained for reflection and semantic auditing.
672    pub options: Vec<OptionSetting>,
673}
674/// Runtime descriptor for a protobuf service declaration.
675#[derive(Clone, Debug, Eq, PartialEq)]
676pub struct ServiceDescriptor {
677    /// Unqualified source-level service name.
678    pub name: String,
679    /// Package-qualified service name.
680    pub full_name: String,
681    /// RPC methods in source declaration order.
682    pub methods: Vec<MethodDescriptor>,
683    /// Service options retained for reflection and semantic auditing.
684    pub options: Vec<OptionSetting>,
685}
686/// Proto3 extension field that defines a custom descriptor option.
687#[derive(Clone, Debug, Eq, PartialEq)]
688pub struct CustomOptionDescriptor {
689    /// Unqualified extension field name.
690    pub name: String,
691    /// Package- and nesting-qualified extension name.
692    pub full_name: String,
693    /// Descriptor options message extended by this declaration.
694    pub extendee: String,
695    /// Field metadata describing the option's value and cardinality.
696    pub field: Field,
697}
698/// Typed field declared outside its extended message.
699#[derive(Clone, Debug, Eq, PartialEq)]
700pub struct ExtensionDescriptor {
701    /// Package- and scope-qualified extension field name.
702    pub full_name: String,
703    /// Fully resolved message receiving this extension.
704    pub extendee: String,
705    /// Resolved field metadata used by the dynamic codec.
706    pub field: Field,
707}
708/// Import modifier attached to a protobuf import declaration.
709#[derive(Clone, Copy, Debug, Eq, PartialEq)]
710pub enum ImportKind {
711    /// Required ordinary import.
712    Normal,
713    /// Required import whose declarations are re-exported to importers.
714    Public,
715    /// Optional import that may be absent from the registry.
716    Weak,
717}
718/// Parsed protobuf import declaration.
719#[derive(Clone, Debug, Eq, PartialEq)]
720pub struct Import {
721    /// Logical registry path named by the import.
722    pub path: String,
723    /// Import modifier controlling resolution behavior.
724    pub kind: ImportKind,
725}
726/// Fully parsed and type-resolved collection of protobuf declarations.
727#[derive(Clone, Debug)]
728pub struct Schema {
729    /// Syntax declared by the root source.
730    pub syntax: Syntax,
731    /// Optional package declared by the root source.
732    pub package: Option<String>,
733    /// Message descriptors indexed by fully qualified name.
734    pub messages: BTreeMap<String, MessageDescriptor>,
735    /// Enum descriptors indexed by fully qualified name.
736    pub enums: BTreeMap<String, Enum>,
737    /// Service descriptors indexed by fully qualified name.
738    pub services: BTreeMap<String, ServiceDescriptor>,
739    /// Custom option extensions indexed by fully qualified extension name.
740    pub custom_options: BTreeMap<String, CustomOptionDescriptor>,
741    /// Ordinary typed extensions indexed by qualified extension name.
742    pub extensions: BTreeMap<String, ExtensionDescriptor>,
743    /// Import declarations collected from all reachable sources.
744    pub imports: Vec<Import>,
745    /// Root-file options retained for reflection and semantic auditing.
746    pub options: Vec<OptionSetting>,
747    /// Resolved root-file feature values.
748    pub features: FeatureSet,
749}
750
751/// An allocation-backed collection of named `.proto` sources.
752///
753/// The registry is the only import resolver used by this crate. Applications
754/// load files, flash-resident strings, network resources, or generated schema
755/// text into it before parsing. The parser itself never performs I/O, which is
756/// essential for the crate's `no_std` contract.
757#[derive(Clone, Debug, Default)]
758pub struct Registry {
759    sources: BTreeMap<String, String>,
760}
761
762/// Resource limits for parsing `.proto` sources and registry import graphs.
763#[derive(Clone, Copy, Debug, Eq, PartialEq)]
764pub struct SchemaParseOptions {
765    /// Maximum bytes accepted in any one registered source.
766    pub max_source_bytes: usize,
767    /// Maximum lexical tokens retained for any one source.
768    pub max_tokens: usize,
769    /// Maximum brace nesting accepted before invoking the grammar parser.
770    pub max_nesting_depth: usize,
771    /// Maximum number of reachable sources in one registry parse.
772    pub max_registry_files: usize,
773}
774
775impl Default for SchemaParseOptions {
776    fn default() -> Self {
777        Self {
778            max_source_bytes: usize::MAX,
779            max_tokens: usize::MAX,
780            max_nesting_depth: DEFAULT_RECURSION_LIMIT,
781            max_registry_files: usize::MAX,
782        }
783    }
784}
785
786impl SchemaParseOptions {
787    /// Returns finite limits suitable for registries supplied by untrusted peers.
788    pub const fn hardened() -> Self {
789        Self {
790            max_source_bytes: HARDENED_SCHEMA_MAX_SOURCE_BYTES,
791            max_tokens: HARDENED_SCHEMA_MAX_TOKENS,
792            max_nesting_depth: HARDENED_SCHEMA_MAX_NESTING_DEPTH,
793            max_registry_files: HARDENED_SCHEMA_MAX_REGISTRY_FILES,
794        }
795    }
796}
797
798impl Registry {
799    /// Creates an empty schema registry.
800    pub const fn new() -> Self {
801        Self {
802            sources: BTreeMap::new(),
803        }
804    }
805
806    /// Registers or replaces a source under its protobuf import path.
807    ///
808    /// The path must match the text used by importing schemas. Returns the
809    /// previously registered source when the path is replaced.
810    pub fn register(
811        &mut self,
812        path: impl Into<String>,
813        source: impl Into<String>,
814    ) -> Option<String> {
815        self.sources.insert(path.into(), source.into())
816    }
817
818    /// Returns the source registered for an exact protobuf import path.
819    pub fn source(&self, path: &str) -> Option<&str> {
820        self.sources.get(path).map(String::as_str)
821    }
822
823    /// Parses a registered root and every transitively imported schema.
824    ///
825    /// `root` is a logical registry path, not a filesystem path. Only sources
826    /// reachable from that root are included in the returned descriptor set.
827    ///
828    /// # Errors
829    ///
830    /// Returns an error when a required source is absent, a source is invalid,
831    /// imported declarations conflict, or a referenced type cannot be resolved.
832    pub fn parse(&self, root: &str) -> Result<Schema> {
833        self.parse_with_options(root, &SchemaParseOptions::default())
834    }
835
836    /// Parses a root and its imports under explicit resource limits.
837    pub fn parse_with_options(&self, root: &str, options: &SchemaParseOptions) -> Result<Schema> {
838        parse_registry(root, self, options)
839    }
840
841    /// Reports how many source files are currently registered.
842    pub fn len(&self) -> usize {
843        self.sources.len()
844    }
845
846    /// Reports whether no sources have been registered yet.
847    pub fn is_empty(&self) -> bool {
848        self.sources.is_empty()
849    }
850}
851impl Schema {
852    /// Finds a regular or typed extension field by message and numeric tag.
853    pub fn field_by_number<'a>(
854        &'a self,
855        message: &'a MessageDescriptor,
856        number: u32,
857    ) -> Option<&'a Field> {
858        message.field_by_number(number).or_else(|| {
859            self.extensions
860                .values()
861                .find(|extension| {
862                    extension.extendee == message.full_name && extension.field.number == number
863                })
864                .map(|extension| &extension.field)
865        })
866    }
867
868    /// Iterates regular fields followed by typed extensions for a message.
869    pub fn fields_for<'a>(
870        &'a self,
871        message: &'a MessageDescriptor,
872    ) -> impl Iterator<Item = &'a Field> {
873        message.fields.iter().chain(
874            self.extensions
875                .values()
876                .filter(move |extension| extension.extendee == message.full_name)
877                .map(|extension| &extension.field),
878        )
879    }
880
881    /// Looks up a message by fully qualified name or by this schema's package.
882    ///
883    /// Exact full-name lookup is attempted first. If it fails and the root
884    /// schema declares a package, that package is prepended to `name`.
885    pub fn message(&self, name: &str) -> Option<&MessageDescriptor> {
886        self.messages.get(name).or_else(|| {
887            self.package
888                .as_ref()
889                .and_then(|package| self.messages.get(&format!("{package}.{name}")))
890        })
891    }
892    /// Looks up a service by fully qualified name or the root package.
893    pub fn service(&self, name: &str) -> Option<&ServiceDescriptor> {
894        self.services.get(name).or_else(|| {
895            self.package
896                .as_ref()
897                .and_then(|package| self.services.get(&format!("{package}.{name}")))
898        })
899    }
900}
901/// Lexical unit retained by the schema parser together with its source offset.
902#[derive(Clone)]
903enum Token {
904    /// Identifier, keyword, or qualified protobuf name.
905    Identifier(String),
906    /// Contents of a single- or double-quoted literal without delimiters.
907    StringLiteral(String),
908    /// Numeric-looking text whose interpretation depends on grammar position.
909    NumberLiteral(String),
910    /// One punctuation character.
911    Symbol(char),
912}
913
914/// Returns whether `value` is one unqualified protobuf identifier.
915fn is_identifier(value: &str) -> bool {
916    let mut bytes = value.bytes();
917    bytes
918        .next()
919        .is_some_and(|first| first.is_ascii_alphabetic() || first == b'_')
920        && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
921}
922
923/// Returns whether `value` is a valid dot-qualified protobuf identifier.
924fn is_full_identifier(value: &str, allow_leading_dot: bool) -> bool {
925    let value = if allow_leading_dot {
926        value.strip_prefix('.').unwrap_or(value)
927    } else {
928        value
929    };
930    !value.is_empty() && value.split('.').all(is_identifier)
931}
932
933/// Reserved names and inclusive numeric ranges collected while parsing a body.
934#[derive(Default)]
935struct ReservedDeclarations {
936    names: Vec<String>,
937    ranges: Vec<(i64, i64)>,
938}
939
940/// Rejects Unicode escapes that do not identify a Unicode scalar value.
941///
942/// Pest verifies escape spelling and digit counts. This semantic pass handles
943/// the scalar-value constraint, including surrogate code points and values
944/// above the Unicode maximum.
945fn validate_unicode_escapes(value: &str, offset: usize) -> Result<()> {
946    let bytes = value.as_bytes();
947    let mut cursor = 0;
948    while cursor < bytes.len() {
949        if bytes.get(cursor) != Some(&b'\\') {
950            cursor += 1;
951            continue;
952        }
953        let escape = bytes
954            .get(cursor + 1)
955            .ok_or_else(|| Error::new(offset, "truncated string escape"))?;
956        let digits = match escape {
957            b'u' => SHORT_UNICODE_ESCAPE_DIGITS,
958            b'U' => LONG_UNICODE_ESCAPE_DIGITS,
959            _ => {
960                cursor += 2;
961                continue;
962            }
963        };
964        let digits_start = cursor + 2;
965        let digits_end = digits_start
966            .checked_add(digits)
967            .ok_or_else(|| Error::new(offset, "Unicode escape length overflow"))?;
968        let hexadecimal = value
969            .get(digits_start..digits_end)
970            .ok_or_else(|| Error::new(offset, "truncated Unicode escape"))?;
971        let code_point = u32::from_str_radix(hexadecimal, 16)
972            .map_err(|_| Error::new(offset, "invalid Unicode escape"))?;
973        if char::from_u32(code_point).is_none() {
974            return Err(Error::new(offset, "invalid Unicode scalar value"));
975        }
976        cursor = digits_end;
977    }
978    Ok(())
979}
980
981/// Produces descriptor-builder tokens from Pest's grammar-derived token stream.
982///
983/// Pest discards comments and whitespace and retains byte spans for precise
984/// semantic diagnostics. String delimiters are removed, but escape spelling is
985/// preserved so defaults can be audited without lossy normalization.
986fn lex(source: &str) -> Result<Vec<(Token, usize)>> {
987    let mut parsed = ProtoSyntaxParser::parse(Rule::token_stream, source).map_err(pest_error)?;
988    let stream = parsed
989        .next()
990        .ok_or_else(|| Error::new(0, "Pest returned no token stream"))?;
991    let mut tokens = Vec::new();
992    for pair in stream.into_inner() {
993        let offset = pair.as_span().start();
994        let text = pair.as_str();
995        let token = match pair.as_rule() {
996            Rule::lex_identifier => Token::Identifier(text.to_string()),
997            Rule::lex_number => Token::NumberLiteral(text.to_string()),
998            Rule::string_literal => {
999                let end = text
1000                    .len()
1001                    .checked_sub(1)
1002                    .ok_or_else(|| Error::new(offset, "invalid Pest string span"))?;
1003                let contents = text
1004                    .get(1..end)
1005                    .ok_or_else(|| Error::new(offset, "invalid Pest string boundary"))?;
1006                validate_unicode_escapes(contents, offset)?;
1007                Token::StringLiteral(contents.to_string())
1008            }
1009            Rule::lex_symbol => {
1010                let symbol = text
1011                    .chars()
1012                    .next()
1013                    .ok_or_else(|| Error::new(offset, "empty Pest symbol span"))?;
1014                Token::Symbol(symbol)
1015            }
1016            Rule::EOI => continue,
1017            _ => return Err(Error::new(offset, "unexpected Pest token rule")),
1018        };
1019        tokens.push((token, offset));
1020    }
1021    Ok(tokens)
1022}
1023/// Mutable semantic descriptor-builder state for one protobuf source file.
1024struct DescriptorBuilder {
1025    /// Lexed tokens paired with byte offsets into the source.
1026    tokens: Vec<(Token, usize)>,
1027    /// Index of the next token to consume.
1028    cursor: usize,
1029    /// Syntax controlling default packing and field-presence behavior.
1030    syntax: Syntax,
1031    /// Package applied to top-level declarations in this source.
1032    package: Option<String>,
1033    /// Message descriptors accumulated by fully qualified name.
1034    messages: BTreeMap<String, MessageDescriptor>,
1035    /// Enum descriptors accumulated by fully qualified name.
1036    enums: BTreeMap<String, Enum>,
1037    /// Service descriptors accumulated by fully qualified name.
1038    services: BTreeMap<String, ServiceDescriptor>,
1039    /// Custom option extensions accumulated by fully qualified name.
1040    custom_options: BTreeMap<String, CustomOptionDescriptor>,
1041    /// Ordinary message extensions accumulated by qualified field name.
1042    extensions: BTreeMap<String, ExtensionDescriptor>,
1043    /// Import declarations retained for registry graph traversal.
1044    imports: Vec<Import>,
1045    /// File options retained in source order.
1046    options: Vec<OptionSetting>,
1047}
1048impl DescriptorBuilder {
1049    /// Returns the current token's source offset, or zero at end of input.
1050    fn offset(&self) -> usize {
1051        self.tokens
1052            .get(self.cursor)
1053            .map(|token| token.1)
1054            .unwrap_or(0)
1055    }
1056    /// Reports whether the current token is the specified identifier.
1057    fn peek_identifier(&self, expected: &str) -> bool {
1058        matches!(self.tokens.get(self.cursor),Some((Token::Identifier(value),_))if value==expected)
1059    }
1060    /// Reports whether the current token is the specified punctuation symbol.
1061    fn peek_symbol(&self, expected: char) -> bool {
1062        matches!(self.tokens.get(self.cursor),Some((Token::Symbol(value),_))if *value==expected)
1063    }
1064    /// Consumes an identifier or reports its source location as an error.
1065    fn identifier(&mut self) -> Result<String> {
1066        match self.tokens.get(self.cursor).cloned() {
1067            Some((Token::Identifier(value), _)) => {
1068                self.cursor += 1;
1069                Ok(value)
1070            }
1071            _ => Err(Error::new(self.offset(), "expected identifier")),
1072        }
1073    }
1074    /// Consumes a simple declaration name and rejects qualified identifiers.
1075    fn declaration_name(&mut self) -> Result<String> {
1076        let offset = self.offset();
1077        let name = self.identifier()?;
1078        if is_identifier(&name) {
1079            Ok(name)
1080        } else {
1081            Err(Error::new(offset, "invalid protobuf identifier"))
1082        }
1083    }
1084    /// Consumes a package name and validates every dot-separated component.
1085    fn package_name(&mut self) -> Result<String> {
1086        let offset = self.offset();
1087        let name = self.identifier()?;
1088        if is_full_identifier(&name, false) {
1089            Ok(name)
1090        } else {
1091            Err(Error::new(offset, "invalid protobuf package name"))
1092        }
1093    }
1094    /// Consumes and parses an integer token.
1095    fn integer(&mut self) -> Result<i64> {
1096        match self.tokens.get(self.cursor).cloned() {
1097            Some((Token::NumberLiteral(value), offset)) => {
1098                self.cursor += 1;
1099                let (negative, unsigned) = value
1100                    .strip_prefix('-')
1101                    .map_or((false, value.as_str()), |value| (true, value));
1102                let unsigned = unsigned.strip_prefix('+').unwrap_or(unsigned);
1103                let (digits, radix) = if let Some(digits) = unsigned
1104                    .strip_prefix("0x")
1105                    .or_else(|| unsigned.strip_prefix("0X"))
1106                {
1107                    (digits, 16)
1108                } else if unsigned.len() > 1 && unsigned.starts_with('0') {
1109                    (unsigned, 8)
1110                } else {
1111                    (unsigned, 10)
1112                };
1113                let magnitude = i128::from_str_radix(digits, radix)
1114                    .map_err(|_| Error::new(offset, "expected integer"))?;
1115                let signed = if negative {
1116                    magnitude
1117                        .checked_neg()
1118                        .ok_or_else(|| Error::new(offset, "integer is out of range"))?
1119                } else {
1120                    magnitude
1121                };
1122                i64::try_from(signed).map_err(|_| Error::new(offset, "integer is out of range"))
1123            }
1124            _ => Err(Error::new(self.offset(), "expected integer")),
1125        }
1126    }
1127    /// Consumes the requested punctuation symbol.
1128    fn expect_symbol(&mut self, expected: char) -> Result<()> {
1129        if matches!(self.tokens.get(self.cursor),Some((Token::Symbol(value),_))if *value==expected)
1130        {
1131            self.cursor += 1;
1132            Ok(())
1133        } else {
1134            Err(Error::new(self.offset(), format!("expected '{expected}'")))
1135        }
1136    }
1137    /// Consumes a punctuation symbol when present and reports whether it matched.
1138    fn consume_symbol(&mut self, expected: char) -> bool {
1139        self.expect_symbol(expected).is_ok()
1140    }
1141    /// Qualifies a declared or referenced name against its lexical scope.
1142    fn qualify(&self, scope: &str, name: &str) -> String {
1143        if let Some(name) = name.strip_prefix('.') {
1144            name.to_string()
1145        } else if scope.is_empty() {
1146            self.package
1147                .as_ref()
1148                .map(|package| format!("{package}.{name}"))
1149                .unwrap_or_else(|| name.to_string())
1150        } else {
1151            format!("{scope}.{name}")
1152        }
1153    }
1154    /// Consumes a scalar field-option value in identifier, string, or numeric form.
1155    fn option_value(&mut self) -> Result<String> {
1156        match self.tokens.get(self.cursor).cloned() {
1157            Some((Token::StringLiteral(mut value), _)) => {
1158                self.cursor += 1;
1159                while let Some((Token::StringLiteral(next), _)) = self.tokens.get(self.cursor) {
1160                    value.push_str(next);
1161                    self.cursor += 1;
1162                }
1163                Ok(value)
1164            }
1165            Some((Token::Identifier(value), _)) | Some((Token::NumberLiteral(value), _)) => {
1166                self.cursor += 1;
1167                Ok(value)
1168            }
1169            _ => Err(Error::new(self.offset(), "expected option value")),
1170        }
1171    }
1172
1173    /// Parses a built-in or parenthesized custom option name.
1174    fn option_name(&mut self) -> Result<String> {
1175        if !self.consume_symbol('(') {
1176            return self.identifier();
1177        }
1178        let extension = self.identifier()?;
1179        self.expect_symbol(')')?;
1180        let mut name = format!("({extension})");
1181        while let Some((Token::Identifier(component), _)) = self.tokens.get(self.cursor) {
1182            let Some(component) = component.strip_prefix('.') else {
1183                break;
1184            };
1185            if !is_identifier(component) {
1186                return Err(Error::new(self.offset(), "invalid custom option path"));
1187            }
1188            name.push('.');
1189            name.push_str(component);
1190            self.cursor += 1;
1191        }
1192        Ok(name)
1193    }
1194
1195    /// Consumes an aggregate option value while preserving balanced structure.
1196    fn aggregate_option_value(&mut self) -> Result<String> {
1197        self.expect_symbol('{')?;
1198        let mut value = String::from("{");
1199        let mut depth = 1usize;
1200        while depth != 0 {
1201            let (token, _) = self
1202                .tokens
1203                .get(self.cursor)
1204                .cloned()
1205                .ok_or_else(|| Error::new(self.offset(), "unterminated aggregate option"))?;
1206            self.cursor += 1;
1207            match token {
1208                Token::Symbol('{') => {
1209                    depth += 1;
1210                    value.push('{');
1211                }
1212                Token::Symbol('}') => {
1213                    depth -= 1;
1214                    value.push('}');
1215                }
1216                Token::Symbol(symbol) => value.push(symbol),
1217                Token::Identifier(text) | Token::NumberLiteral(text) => value.push_str(&text),
1218                Token::StringLiteral(text) => {
1219                    value.push('"');
1220                    value.push_str(&text);
1221                    value.push('"');
1222                }
1223            }
1224        }
1225        Ok(value)
1226    }
1227
1228    /// Parses one option assignment without consuming its outer delimiter.
1229    fn option_setting(&mut self) -> Result<OptionSetting> {
1230        let name = self.option_name()?;
1231        self.expect_symbol('=')?;
1232        let (value, value_kind) = if self.peek_symbol('{') {
1233            (self.aggregate_option_value()?, OptionValueKind::Aggregate)
1234        } else {
1235            let value_kind = match self.tokens.get(self.cursor) {
1236                Some((Token::StringLiteral(_), _)) => OptionValueKind::String,
1237                Some((Token::NumberLiteral(_), _)) => OptionValueKind::Number,
1238                Some((Token::Identifier(_), _)) => OptionValueKind::Identifier,
1239                _ => return Err(Error::new(self.offset(), "expected option value")),
1240            };
1241            (self.option_value()?, value_kind)
1242        };
1243        Ok(OptionSetting {
1244            name,
1245            value,
1246            value_kind,
1247        })
1248    }
1249
1250    /// Parses a complete `option name = value;` declaration.
1251    fn option_declaration(&mut self) -> Result<OptionSetting> {
1252        self.identifier()?;
1253        let option = self.option_setting()?;
1254        self.expect_symbol(';')?;
1255        Ok(option)
1256    }
1257
1258    /// Parses a reserved-name or reserved-number statement through its semicolon.
1259    fn parse_reserved(&mut self, minimum: i64, maximum: i64) -> Result<ReservedDeclarations> {
1260        self.identifier()?;
1261        let mut reserved = ReservedDeclarations::default();
1262        let names = matches!(
1263            self.tokens.get(self.cursor),
1264            Some((Token::StringLiteral(_), _))
1265        ) || (self.syntax.is_edition()
1266            && matches!(
1267                self.tokens.get(self.cursor),
1268                Some((Token::Identifier(_), _))
1269            ));
1270        loop {
1271            if names {
1272                let offset = self.offset();
1273                let name = match self.tokens.get(self.cursor).cloned() {
1274                    Some((Token::StringLiteral(name), _)) => {
1275                        self.cursor += 1;
1276                        name
1277                    }
1278                    Some((Token::Identifier(name), _)) if self.syntax.is_edition() => {
1279                        self.cursor += 1;
1280                        name
1281                    }
1282                    _ => return Err(Error::new(offset, "cannot mix reserved names and numbers")),
1283                };
1284                if !is_identifier(&name) {
1285                    return Err(Error::new(offset, "invalid reserved field name"));
1286                }
1287                reserved.names.push(name);
1288            } else {
1289                let start = self.integer()?;
1290                let end = if self.peek_identifier(KW_TO) {
1291                    self.identifier()?;
1292                    if self.peek_identifier(KW_MAX) {
1293                        self.identifier()?;
1294                        maximum
1295                    } else {
1296                        self.integer()?
1297                    }
1298                } else {
1299                    start
1300                };
1301                if start < minimum || start > end || end > maximum {
1302                    return Err(Error::new(self.offset(), "invalid reserved numeric range"));
1303                }
1304                reserved.ranges.push((start, end));
1305            }
1306            if !self.consume_symbol(',') {
1307                break;
1308            }
1309        }
1310        self.expect_symbol(';')?;
1311        Ok(reserved)
1312    }
1313
1314    /// Parses past a legacy proto2 group declaration without describing it.
1315    ///
1316    /// The opening label, name, tag, and balanced body are validated so parsing
1317    /// can safely resume at the next supported field. An unclosed group fails.
1318    fn skip_group(&mut self) -> Result<()> {
1319        self.identifier()?;
1320        self.identifier()?;
1321        self.expect_symbol('=')?;
1322        self.integer()?;
1323        self.expect_symbol('{')?;
1324        let mut depth = 1usize;
1325        while depth != 0 {
1326            match self.tokens.get(self.cursor) {
1327                Some((Token::Symbol('{'), _)) => depth += 1,
1328                Some((Token::Symbol('}'), _)) => depth -= 1,
1329                Some(_) => {}
1330                None => return Err(Error::new(self.offset(), "unterminated group")),
1331            }
1332            self.cursor += 1;
1333        }
1334        self.consume_symbol(';');
1335        Ok(())
1336    }
1337    /// Parses an enum declaration and inserts its descriptor into parser state.
1338    ///
1339    /// Enum options and reserved declarations are structurally validated.
1340    /// Values retain declaration order and signed numeric assignments.
1341    fn parse_enum(&mut self, scope: &str) -> Result<()> {
1342        self.identifier()?;
1343        let name = self.declaration_name()?;
1344        let full_name = self.qualify(scope, &name);
1345        self.expect_symbol('{')?;
1346        let mut values = Vec::new();
1347        let mut reserved = ReservedDeclarations::default();
1348        let mut allow_alias = false;
1349        let mut options = Vec::new();
1350        while !self.consume_symbol('}') {
1351            if self.consume_symbol(';') {
1352                continue;
1353            }
1354            if self.peek_identifier(KW_RESERVED) {
1355                let declaration = self.parse_reserved(i64::from(i32::MIN), i64::from(i32::MAX))?;
1356                reserved.names.extend(declaration.names);
1357                reserved.ranges.extend(declaration.ranges);
1358                continue;
1359            }
1360            if self.peek_identifier(KW_OPTION) {
1361                let option = self.option_declaration()?;
1362                if option.name == OPTION_ALLOW_ALIAS {
1363                    allow_alias = match option.value.as_str() {
1364                        BOOLEAN_TRUE => true,
1365                        BOOLEAN_FALSE => false,
1366                        _ => {
1367                            return Err(Error::new(
1368                                self.offset(),
1369                                "allow_alias must be true or false",
1370                            ));
1371                        }
1372                    };
1373                }
1374                options.push(option);
1375                continue;
1376            }
1377            let value_name = self.declaration_name()?;
1378            self.expect_symbol('=')?;
1379            let raw_number = self.integer()?;
1380            let number = i32::try_from(raw_number)
1381                .map_err(|_| Error::new(self.offset(), "enum value is outside int32 range"))?;
1382            let mut value_options = Vec::new();
1383            if self.consume_symbol('[') {
1384                loop {
1385                    if self.consume_symbol(']') {
1386                        break;
1387                    }
1388                    value_options.push(self.option_setting()?);
1389                    if !self.consume_symbol(']') {
1390                        self.expect_symbol(',')?;
1391                    } else {
1392                        break;
1393                    }
1394                }
1395            }
1396            self.expect_symbol(';')?;
1397            values.push(EnumValue {
1398                name: value_name,
1399                number,
1400                options: value_options,
1401            })
1402        }
1403        if values.is_empty() {
1404            return Err(Error::new(
1405                self.offset(),
1406                "enum must declare at least one value",
1407            ));
1408        }
1409        if self.syntax.has_modern_defaults()
1410            && values.first().is_some_and(|value| value.number != 0)
1411        {
1412            return Err(Error::new(
1413                self.offset(),
1414                "first proto3 enum value must be zero",
1415            ));
1416        }
1417        validate_reserved_declarations(&reserved, self.offset())?;
1418        for (index, value) in values.iter().enumerate() {
1419            if values[..index]
1420                .iter()
1421                .any(|previous| previous.name == value.name)
1422            {
1423                return Err(Error::new(self.offset(), "duplicate enum value name"));
1424            }
1425            if !allow_alias
1426                && values[..index]
1427                    .iter()
1428                    .any(|previous| previous.number == value.number)
1429            {
1430                return Err(Error::new(
1431                    self.offset(),
1432                    "duplicate enum number requires allow_alias = true",
1433                ));
1434            }
1435            if reserved.names.iter().any(|name| name == &value.name)
1436                || reserved
1437                    .ranges
1438                    .iter()
1439                    .any(|(start, end)| (*start..=*end).contains(&i64::from(value.number)))
1440            {
1441                return Err(Error::new(
1442                    self.offset(),
1443                    "enum value uses a reserved name or number",
1444                ));
1445            }
1446        }
1447        if self.messages.contains_key(&full_name) || self.enums.contains_key(&full_name) {
1448            return Err(Error::new(self.offset(), "duplicate protobuf type name"));
1449        }
1450        self.enums.insert(
1451            full_name.clone(),
1452            Enum {
1453                name,
1454                full_name,
1455                values,
1456                syntax: self.syntax,
1457                options,
1458                features: FeatureSet::for_syntax(self.syntax),
1459            },
1460        );
1461        Ok(())
1462    }
1463    /// Parses a message and its nested declarations into descriptor state.
1464    ///
1465    /// Nested messages and enums recurse with the message's full name as their
1466    /// scope. Oneof members receive their shared group name during field parsing.
1467    fn parse_message(&mut self, scope: &str) -> Result<()> {
1468        self.identifier()?;
1469        let name = self.declaration_name()?;
1470        let full_name = self.qualify(scope, &name);
1471        self.expect_symbol('{')?;
1472        let mut fields = Vec::new();
1473        let mut oneofs = Vec::<OneofDescriptor>::new();
1474        let mut reserved = ReservedDeclarations::default();
1475        let mut extension_ranges = Vec::new();
1476        let mut options = Vec::new();
1477        while !self.consume_symbol('}') {
1478            if self.consume_symbol(';') {
1479                continue;
1480            }
1481            if self.peek_identifier(KW_MESSAGE) {
1482                self.parse_message(&full_name)?;
1483                continue;
1484            }
1485            if self.peek_identifier(KW_ENUM) {
1486                self.parse_enum(&full_name)?;
1487                continue;
1488            }
1489            if self.peek_identifier(KW_ONEOF) {
1490                self.identifier()?;
1491                let oneof_name = self.declaration_name()?;
1492                if oneofs.iter().any(|oneof| oneof.name == oneof_name) {
1493                    return Err(Error::new(self.offset(), "duplicate oneof name"));
1494                }
1495                self.expect_symbol('{')?;
1496                let mut oneof_options = Vec::new();
1497                while !self.consume_symbol('}') {
1498                    if self.consume_symbol(';') {
1499                        continue;
1500                    }
1501                    if self.peek_identifier(KW_OPTION) {
1502                        oneof_options.push(self.option_declaration()?);
1503                        continue;
1504                    }
1505                    fields.push(self.parse_field(Some(oneof_name.clone()), None)?)
1506                }
1507                oneofs.push(OneofDescriptor {
1508                    name: oneof_name,
1509                    options: oneof_options,
1510                });
1511                continue;
1512            }
1513            if self.peek_identifier(KW_RESERVED) {
1514                let declaration =
1515                    self.parse_reserved(i64::from(MIN_FIELD_NUMBER), i64::from(MAX_FIELD_NUMBER))?;
1516                reserved.names.extend(declaration.names);
1517                reserved.ranges.extend(declaration.ranges);
1518                continue;
1519            }
1520            if self.peek_identifier(KW_OPTION) {
1521                options.push(self.option_declaration()?);
1522                continue;
1523            }
1524            if self.peek_identifier(KW_EXTEND) {
1525                self.parse_custom_option_extensions(&full_name)?;
1526                continue;
1527            }
1528            if self.peek_identifier(KW_EXTENSIONS) {
1529                if self.syntax == Syntax::Proto3 {
1530                    return Err(Error::new(
1531                        self.offset(),
1532                        "proto3 extensions are permitted only for custom options",
1533                    ));
1534                }
1535                let declaration =
1536                    self.parse_reserved(i64::from(MIN_FIELD_NUMBER), i64::from(MAX_FIELD_NUMBER))?;
1537                for (start, end) in declaration.ranges {
1538                    extension_ranges.push((start as u32, end as u32));
1539                }
1540                continue;
1541            }
1542            let cardinality = if self.peek_identifier(KW_REQUIRED) {
1543                if self.syntax.is_edition() {
1544                    return Err(Error::new(
1545                        self.offset(),
1546                        "required labels are not used in Editions",
1547                    ));
1548                }
1549                self.identifier()?;
1550                Some(Cardinality::Required)
1551            } else if self.peek_identifier(KW_OPTIONAL) {
1552                if self.syntax.is_edition() {
1553                    return Err(Error::new(
1554                        self.offset(),
1555                        "optional labels are not used in Editions",
1556                    ));
1557                }
1558                self.identifier()?;
1559                Some(Cardinality::Optional)
1560            } else if self.peek_identifier(KW_REPEATED) {
1561                self.identifier()?;
1562                Some(Cardinality::Repeated)
1563            } else {
1564                None
1565            };
1566            if self.peek_identifier(KW_GROUP) {
1567                if self.syntax == Syntax::Proto3 {
1568                    return Err(Error::new(
1569                        self.offset(),
1570                        "groups are not allowed in proto3",
1571                    ));
1572                }
1573                self.skip_group()?;
1574                continue;
1575            }
1576            fields.push(self.parse_field(None, cardinality)?)
1577        }
1578        let oneof_names: Vec<String> = oneofs.iter().map(|oneof| oneof.name.clone()).collect();
1579        validate_message_fields(&fields, &oneof_names, &reserved, self.offset())?;
1580        if self.syntax.has_modern_defaults() {
1581            validate_json_field_names(&fields, self.offset())?;
1582        }
1583        if self.messages.contains_key(&full_name) || self.enums.contains_key(&full_name) {
1584            return Err(Error::new(self.offset(), "duplicate protobuf type name"));
1585        }
1586        self.messages.insert(
1587            full_name.clone(),
1588            MessageDescriptor {
1589                name,
1590                full_name,
1591                fields,
1592                extension_ranges,
1593                oneofs,
1594                options,
1595                features: FeatureSet::for_syntax(self.syntax),
1596            },
1597        );
1598        Ok(())
1599    }
1600
1601    /// Parses custom-option or ordinary typed extension declarations.
1602    fn parse_custom_option_extensions(&mut self, scope: &str) -> Result<()> {
1603        self.identifier()?;
1604        let extendee = self.identifier()?;
1605        let extendee = extendee.trim_start_matches('.').to_string();
1606        let custom_option = is_custom_option_extendee(&extendee);
1607        if !custom_option && self.syntax == Syntax::Proto3 {
1608            return Err(Error::new(
1609                self.offset(),
1610                "proto3 extend target must be a descriptor options message",
1611            ));
1612        }
1613        self.expect_symbol('{')?;
1614        while !self.consume_symbol('}') {
1615            if self.consume_symbol(';') {
1616                continue;
1617            }
1618            let cardinality = if self.peek_identifier(KW_OPTIONAL) {
1619                if self.syntax.is_edition() {
1620                    return Err(Error::new(
1621                        self.offset(),
1622                        "optional labels are not used in Editions",
1623                    ));
1624                }
1625                self.identifier()?;
1626                Cardinality::Optional
1627            } else if self.peek_identifier(KW_REPEATED) {
1628                self.identifier()?;
1629                Cardinality::Repeated
1630            } else if self.peek_identifier(KW_REQUIRED) {
1631                if self.syntax.has_modern_defaults() {
1632                    return Err(Error::new(
1633                        self.offset(),
1634                        "required extension fields are not allowed here",
1635                    ));
1636                }
1637                self.identifier()?;
1638                Cardinality::Required
1639            } else {
1640                Cardinality::Optional
1641            };
1642            if self.peek_identifier(KW_GROUP) {
1643                self.skip_group()?;
1644                continue;
1645            }
1646            let mut field = self.parse_field(None, Some(cardinality))?;
1647            if custom_option && field.number < CUSTOM_OPTION_MIN_FIELD_NUMBER {
1648                return Err(Error::new(
1649                    self.offset(),
1650                    "custom option number is outside the descriptor extension range",
1651                ));
1652            }
1653            let full_name = self.qualify(scope, &field.name);
1654            if custom_option
1655                && (self.custom_options.contains_key(&full_name)
1656                    || self.custom_options.values().any(|option| {
1657                        option.extendee == extendee && option.field.number == field.number
1658                    }))
1659            {
1660                return Err(Error::new(
1661                    self.offset(),
1662                    "duplicate custom option name or number",
1663                ));
1664            }
1665            if custom_option {
1666                self.custom_options.insert(
1667                    full_name.clone(),
1668                    CustomOptionDescriptor {
1669                        name: field.name.clone(),
1670                        full_name,
1671                        extendee: extendee.clone(),
1672                        field,
1673                    },
1674                );
1675            } else {
1676                if self.extensions.contains_key(&full_name) {
1677                    return Err(Error::new(
1678                        self.offset(),
1679                        "duplicate extension name or number",
1680                    ));
1681                }
1682                field.name = full_name.clone();
1683                self.extensions.insert(
1684                    full_name.clone(),
1685                    ExtensionDescriptor {
1686                        full_name,
1687                        extendee: extendee.clone(),
1688                        field,
1689                    },
1690                );
1691            }
1692        }
1693        Ok(())
1694    }
1695
1696    /// Parses a proto3 service and retains resolved RPC-facing metadata.
1697    fn parse_service(&mut self) -> Result<()> {
1698        self.identifier()?;
1699        let name = self.declaration_name()?;
1700        let full_name = self.qualify("", &name);
1701        self.expect_symbol('{')?;
1702        let mut methods = Vec::new();
1703        let mut options = Vec::new();
1704        while !self.consume_symbol('}') {
1705            if self.consume_symbol(';') {
1706                continue;
1707            }
1708            if self.peek_identifier(KW_OPTION) {
1709                options.push(self.option_declaration()?);
1710                continue;
1711            }
1712            if !self.peek_identifier(KW_RPC) {
1713                return Err(Error::new(self.offset(), "expected service option or rpc"));
1714            }
1715            self.identifier()?;
1716            let method_name = self.declaration_name()?;
1717            if methods
1718                .iter()
1719                .any(|method: &MethodDescriptor| method.name == method_name)
1720            {
1721                return Err(Error::new(self.offset(), "duplicate rpc method name"));
1722            }
1723            self.expect_symbol('(')?;
1724            let client_streaming = if self.peek_identifier(KW_STREAM) {
1725                self.identifier()?;
1726                true
1727            } else {
1728                false
1729            };
1730            let input_type = self.identifier()?;
1731            if !is_full_identifier(&input_type, true) {
1732                return Err(Error::new(self.offset(), "invalid rpc request type"));
1733            }
1734            self.expect_symbol(')')?;
1735            if !self.peek_identifier(KW_RETURNS) {
1736                return Err(Error::new(
1737                    self.offset(),
1738                    "expected returns in rpc declaration",
1739                ));
1740            }
1741            self.identifier()?;
1742            self.expect_symbol('(')?;
1743            let server_streaming = if self.peek_identifier(KW_STREAM) {
1744                self.identifier()?;
1745                true
1746            } else {
1747                false
1748            };
1749            let output_type = self.identifier()?;
1750            if !is_full_identifier(&output_type, true) {
1751                return Err(Error::new(self.offset(), "invalid rpc response type"));
1752            }
1753            self.expect_symbol(')')?;
1754            let mut method_options = Vec::new();
1755            if !self.consume_symbol(';') {
1756                self.expect_symbol('{')?;
1757                while !self.consume_symbol('}') {
1758                    if self.consume_symbol(';') {
1759                        continue;
1760                    }
1761                    if !self.peek_identifier(KW_OPTION) {
1762                        return Err(Error::new(self.offset(), "expected rpc option"));
1763                    }
1764                    method_options.push(self.option_declaration()?);
1765                }
1766            }
1767            methods.push(MethodDescriptor {
1768                name: method_name,
1769                input_type,
1770                output_type,
1771                client_streaming,
1772                server_streaming,
1773                options: method_options,
1774            });
1775        }
1776        if self.services.contains_key(&full_name) {
1777            return Err(Error::new(self.offset(), "duplicate service name"));
1778        }
1779        self.services.insert(
1780            full_name.clone(),
1781            ServiceDescriptor {
1782                name,
1783                full_name,
1784                methods,
1785                options,
1786            },
1787        );
1788        Ok(())
1789    }
1790
1791    /// Parses and validates one ordinary, oneof, or map field declaration.
1792    ///
1793    /// This enforces legal map key types and field-number ranges, extracts the
1794    /// supported `packed` and `default` options, and computes initial presence
1795    /// and packing metadata. User-defined types are resolved in a later pass.
1796    fn parse_field(
1797        &mut self,
1798        oneof: Option<String>,
1799        declared_cardinality: Option<Cardinality>,
1800    ) -> Result<Field> {
1801        let is_map = self.peek_identifier(KW_MAP);
1802        if self.syntax == Syntax::Proto2
1803            && declared_cardinality.is_none()
1804            && oneof.is_none()
1805            && !is_map
1806        {
1807            return Err(Error::new(
1808                self.offset(),
1809                "proto2 field requires a cardinality label",
1810            ));
1811        }
1812        if self.syntax.has_modern_defaults() && declared_cardinality == Some(Cardinality::Required)
1813        {
1814            return Err(Error::new(
1815                self.offset(),
1816                "required fields are not allowed in proto3",
1817            ));
1818        }
1819        if is_map && (declared_cardinality.is_some() || oneof.is_some()) {
1820            return Err(Error::new(
1821                self.offset(),
1822                "map fields cannot have labels or belong to oneof",
1823            ));
1824        }
1825        let kind = if is_map {
1826            self.identifier()?;
1827            self.expect_symbol('<')?;
1828            let key_type = self.parse_type()?;
1829            self.expect_symbol(',')?;
1830            let value_type = self.parse_type()?;
1831            self.expect_symbol('>')?;
1832            if !matches!(
1833                key_type,
1834                FieldType::Int32
1835                    | FieldType::Int64
1836                    | FieldType::Uint32
1837                    | FieldType::Uint64
1838                    | FieldType::Sint32
1839                    | FieldType::Sint64
1840                    | FieldType::Fixed32
1841                    | FieldType::Fixed64
1842                    | FieldType::Sfixed32
1843                    | FieldType::Sfixed64
1844                    | FieldType::Bool
1845                    | FieldType::String
1846            ) {
1847                return Err(Error::new(self.offset(), "invalid protobuf map key type"));
1848            }
1849            FieldType::Map(Box::new(key_type), Box::new(value_type))
1850        } else {
1851            self.parse_type()?
1852        };
1853        let name = self.declaration_name()?;
1854        self.expect_symbol('=')?;
1855        let number = self.integer()?;
1856        let valid_range = i64::from(MIN_FIELD_NUMBER)..=i64::from(MAX_FIELD_NUMBER);
1857        let reserved_range =
1858            i64::from(RESERVED_FIELD_NUMBER_START)..=i64::from(RESERVED_FIELD_NUMBER_END);
1859        if !valid_range.contains(&number) || reserved_range.contains(&number) {
1860            return Err(Error::new(self.offset(), "invalid field number"));
1861        }
1862        let mut packed = None;
1863        let mut packed_explicit = false;
1864        let mut default = None;
1865        let mut options = Vec::new();
1866        if self.consume_symbol('[') {
1867            loop {
1868                if self.consume_symbol(']') {
1869                    break;
1870                }
1871                let option = self.option_setting()?;
1872                if option.name == OPTION_PACKED {
1873                    if packed.is_some() {
1874                        return Err(Error::new(self.offset(), "duplicate packed option"));
1875                    }
1876                    packed = match option.value.as_str() {
1877                        BOOLEAN_TRUE => Some(true),
1878                        BOOLEAN_FALSE => Some(false),
1879                        _ => {
1880                            return Err(Error::new(
1881                                self.offset(),
1882                                "packed option must be true or false",
1883                            ));
1884                        }
1885                    };
1886                    packed_explicit = true;
1887                } else if option.name == OPTION_DEFAULT {
1888                    if default.is_some() {
1889                        return Err(Error::new(self.offset(), "duplicate default option"));
1890                    }
1891                    default = Some(option.value.clone())
1892                }
1893                options.push(option);
1894                if !self.consume_symbol(']') {
1895                    self.expect_symbol(',')?;
1896                } else {
1897                    break;
1898                }
1899            }
1900        }
1901        self.expect_symbol(';')?;
1902        let cardinality = if matches!(kind, FieldType::Map(..)) {
1903            Cardinality::Repeated
1904        } else {
1905            declared_cardinality.unwrap_or(Cardinality::Optional)
1906        };
1907        if default.is_some()
1908            && (self.syntax == Syntax::Proto3
1909                || cardinality == Cardinality::Repeated
1910                || oneof.is_some()
1911                || matches!(kind, FieldType::Map(..)))
1912        {
1913            return Err(Error::new(
1914                self.offset(),
1915                "default option is not valid for this field",
1916            ));
1917        }
1918        if packed.is_some()
1919            && (cardinality != Cardinality::Repeated
1920                || matches!(
1921                    kind,
1922                    FieldType::String | FieldType::Bytes | FieldType::Map(..)
1923                ))
1924        {
1925            return Err(Error::new(
1926                self.offset(),
1927                "packed option requires a repeated primitive field",
1928            ));
1929        }
1930        let explicit_presence = declared_cardinality.is_some() || oneof.is_some();
1931        if packed.is_none()
1932            && cardinality == Cardinality::Repeated
1933            && !matches!(
1934                kind,
1935                FieldType::String | FieldType::Bytes | FieldType::Map(..)
1936            )
1937        {
1938            packed = Some(self.syntax.has_modern_defaults());
1939        }
1940        Ok(Field {
1941            name,
1942            number: number as u32,
1943            cardinality,
1944            kind,
1945            packed,
1946            packed_explicit,
1947            oneof,
1948            explicit_presence,
1949            default,
1950            options,
1951            features: FeatureSet::for_syntax(self.syntax),
1952        })
1953    }
1954    /// Parses a built-in scalar type or records a user-defined type for resolution.
1955    ///
1956    /// Unknown identifiers are intentionally stored as provisional message
1957    /// names; [`resolve_schema`] later distinguishes messages from enums using
1958    /// all declarations reachable through the registry.
1959    fn parse_type(&mut self) -> Result<FieldType> {
1960        let name = self.identifier()?;
1961        Ok(match name.as_str() {
1962            TYPE_DOUBLE => FieldType::Double,
1963            TYPE_FLOAT => FieldType::Float,
1964            TYPE_INT32 => FieldType::Int32,
1965            TYPE_INT64 => FieldType::Int64,
1966            TYPE_UINT32 => FieldType::Uint32,
1967            TYPE_UINT64 => FieldType::Uint64,
1968            TYPE_SINT32 => FieldType::Sint32,
1969            TYPE_SINT64 => FieldType::Sint64,
1970            TYPE_FIXED32 => FieldType::Fixed32,
1971            TYPE_FIXED64 => FieldType::Fixed64,
1972            TYPE_SFIXED32 => FieldType::Sfixed32,
1973            TYPE_SFIXED64 => FieldType::Sfixed64,
1974            TYPE_BOOL => FieldType::Bool,
1975            TYPE_STRING => FieldType::String,
1976            TYPE_BYTES => FieldType::Bytes,
1977            // User-defined names are resolved after every imported file has
1978            // been parsed, using protobuf's innermost-scope-first lookup.
1979            _ => FieldType::Message(name),
1980        })
1981    }
1982}
1983
1984/// Rejects duplicate reserved names and overlapping numeric ranges.
1985fn validate_reserved_declarations(reserved: &ReservedDeclarations, offset: usize) -> Result<()> {
1986    for (index, name) in reserved.names.iter().enumerate() {
1987        if reserved
1988            .names
1989            .iter()
1990            .take(index)
1991            .any(|previous| previous == name)
1992        {
1993            return Err(Error::new(offset, "duplicate reserved name"));
1994        }
1995    }
1996    for (index, (start, end)) in reserved.ranges.iter().enumerate() {
1997        if reserved
1998            .ranges
1999            .iter()
2000            .take(index)
2001            .any(|(previous_start, previous_end)| start <= previous_end && previous_start <= end)
2002        {
2003            return Err(Error::new(offset, "overlapping reserved ranges"));
2004        }
2005    }
2006    Ok(())
2007}
2008
2009/// Descriptor scope used to validate built-in and custom option placement.
2010#[derive(Clone, Copy)]
2011enum OptionTarget {
2012    File,
2013    Message,
2014    Field,
2015    Oneof,
2016    Enum,
2017    EnumValue,
2018    Service,
2019    Method,
2020}
2021
2022/// Scalar category required by one built-in protobuf option.
2023#[derive(Clone, Copy)]
2024enum BuiltinOptionType {
2025    Bool,
2026    String,
2027    Identifier,
2028    AnyScalar,
2029    /// Scalar or aggregate value whose detailed shape belongs to a descriptor message.
2030    Any,
2031}
2032
2033/// Returns the type of a built-in option valid at the supplied scope.
2034fn builtin_option_type(target: OptionTarget, name: &str) -> Option<BuiltinOptionType> {
2035    use BuiltinOptionType::{Any, AnyScalar, Bool, Identifier, String as StringOption};
2036    if matches!(
2037        name,
2038        FEATURE_FIELD_PRESENCE
2039            | FEATURE_ENUM_TYPE
2040            | FEATURE_REPEATED_ENCODING
2041            | FEATURE_MESSAGE_ENCODING
2042            | FEATURE_UTF8_VALIDATION
2043            | FEATURE_JSON_FORMAT
2044    ) {
2045        return Some(Identifier);
2046    }
2047    match target {
2048        OptionTarget::File => match name {
2049            "java_package"
2050            | "java_outer_classname"
2051            | "go_package"
2052            | "objc_class_prefix"
2053            | "csharp_namespace"
2054            | "swift_prefix"
2055            | "php_class_prefix"
2056            | "php_namespace"
2057            | "php_metadata_namespace"
2058            | "ruby_package" => Some(StringOption),
2059            "java_multiple_files"
2060            | "java_generate_equals_and_hash"
2061            | "java_string_check_utf8"
2062            | "cc_generic_services"
2063            | "java_generic_services"
2064            | "py_generic_services"
2065            | "php_generic_services"
2066            | "deprecated"
2067            | "cc_enable_arenas" => Some(Bool),
2068            "optimize_for" => Some(Identifier),
2069            _ => None,
2070        },
2071        OptionTarget::Message => match name {
2072            "message_set_wire_format"
2073            | "no_standard_descriptor_accessor"
2074            | "deprecated"
2075            | "map_entry"
2076            | "deprecated_legacy_json_field_conflicts" => Some(Bool),
2077            _ => None,
2078        },
2079        OptionTarget::Field => match name {
2080            OPTION_PACKED | "lazy" | "unverified_lazy" | "deprecated" | "weak" | "debug_redact" => {
2081                Some(Bool)
2082            }
2083            OPTION_DEFAULT => Some(AnyScalar),
2084            "json_name" => Some(StringOption),
2085            "ctype" | "jstype" | "retention" => Some(Identifier),
2086            "targets" => Some(Identifier),
2087            "edition_defaults" | "feature_support" => Some(Any),
2088            _ => None,
2089        },
2090        OptionTarget::Oneof => None,
2091        OptionTarget::Enum => match name {
2092            OPTION_ALLOW_ALIAS | "deprecated" | "deprecated_legacy_json_field_conflicts" => {
2093                Some(Bool)
2094            }
2095            _ => None,
2096        },
2097        OptionTarget::EnumValue => match name {
2098            "deprecated" | "debug_redact" => Some(Bool),
2099            "feature_support" => Some(Any),
2100            _ => None,
2101        },
2102        OptionTarget::Service => match name {
2103            "deprecated" => Some(Bool),
2104            _ => None,
2105        },
2106        OptionTarget::Method => match name {
2107            "deprecated" => Some(Bool),
2108            "idempotency_level" => Some(Identifier),
2109            _ => None,
2110        },
2111    }
2112}
2113
2114/// Applies built-in Edition feature overrides to an inherited feature set.
2115fn apply_feature_options(
2116    inherited: FeatureSet,
2117    options: &[OptionSetting],
2118    target: OptionTarget,
2119    edition: bool,
2120) -> Result<FeatureSet> {
2121    let mut features = inherited;
2122    for option in options {
2123        let recognized = match option.name.as_str() {
2124            FEATURE_FIELD_PRESENCE => {
2125                if !matches!(
2126                    target,
2127                    OptionTarget::File | OptionTarget::Message | OptionTarget::Field
2128                ) {
2129                    return Err(Error::new(0, "field_presence feature is misplaced"));
2130                }
2131                features.field_presence = match option.value.as_str() {
2132                    "EXPLICIT" => FieldPresence::Explicit,
2133                    "IMPLICIT" => FieldPresence::Implicit,
2134                    "LEGACY_REQUIRED" => FieldPresence::LegacyRequired,
2135                    _ => return Err(Error::new(0, "invalid field_presence feature value")),
2136                };
2137                true
2138            }
2139            FEATURE_ENUM_TYPE => {
2140                if !matches!(target, OptionTarget::File | OptionTarget::Enum) {
2141                    return Err(Error::new(0, "enum_type feature is misplaced"));
2142                }
2143                features.enum_type = match option.value.as_str() {
2144                    "OPEN" => EnumType::Open,
2145                    "CLOSED" => EnumType::Closed,
2146                    _ => return Err(Error::new(0, "invalid enum_type feature value")),
2147                };
2148                true
2149            }
2150            FEATURE_REPEATED_ENCODING => {
2151                if !matches!(target, OptionTarget::File | OptionTarget::Field) {
2152                    return Err(Error::new(
2153                        0,
2154                        "repeated_field_encoding feature is misplaced",
2155                    ));
2156                }
2157                features.repeated_field_encoding = match option.value.as_str() {
2158                    "PACKED" => RepeatedFieldEncoding::Packed,
2159                    "EXPANDED" => RepeatedFieldEncoding::Expanded,
2160                    _ => {
2161                        return Err(Error::new(
2162                            0,
2163                            "invalid repeated_field_encoding feature value",
2164                        ));
2165                    }
2166                };
2167                true
2168            }
2169            FEATURE_MESSAGE_ENCODING => {
2170                if !matches!(target, OptionTarget::File | OptionTarget::Field) {
2171                    return Err(Error::new(0, "message_encoding feature is misplaced"));
2172                }
2173                features.message_encoding = match option.value.as_str() {
2174                    "LENGTH_PREFIXED" => MessageEncoding::LengthPrefixed,
2175                    "DELIMITED" => MessageEncoding::Delimited,
2176                    _ => return Err(Error::new(0, "invalid message_encoding feature value")),
2177                };
2178                true
2179            }
2180            FEATURE_UTF8_VALIDATION => {
2181                if !matches!(target, OptionTarget::File | OptionTarget::Field) {
2182                    return Err(Error::new(0, "utf8_validation feature is misplaced"));
2183                }
2184                features.utf8_validation = match option.value.as_str() {
2185                    "VERIFY" => Utf8Validation::Verify,
2186                    "NONE" => Utf8Validation::None,
2187                    _ => return Err(Error::new(0, "invalid utf8_validation feature value")),
2188                };
2189                true
2190            }
2191            FEATURE_JSON_FORMAT => {
2192                if !matches!(
2193                    target,
2194                    OptionTarget::File | OptionTarget::Message | OptionTarget::Enum
2195                ) {
2196                    return Err(Error::new(0, "json_format feature is misplaced"));
2197                }
2198                features.json_format = match option.value.as_str() {
2199                    "ALLOW" => JsonFormat::Allow,
2200                    "LEGACY_BEST_EFFORT" => JsonFormat::LegacyBestEffort,
2201                    _ => return Err(Error::new(0, "invalid json_format feature value")),
2202                };
2203                true
2204            }
2205            _ => false,
2206        };
2207        if recognized && !edition {
2208            return Err(Error::new(
2209                0,
2210                "features are available only in Editions sources",
2211            ));
2212        }
2213    }
2214    Ok(features)
2215}
2216
2217/// Resolves file and lexical descriptor feature inheritance.
2218fn resolve_features(schema: &mut Schema) -> Result<()> {
2219    let edition = schema.syntax.is_edition();
2220    let root = apply_feature_options(
2221        FeatureSet::for_syntax(schema.syntax),
2222        &schema.options,
2223        OptionTarget::File,
2224        edition,
2225    )?;
2226    schema.features = root;
2227    let message_names: Vec<String> = schema.messages.keys().cloned().collect();
2228    let mut resolved_messages = BTreeMap::<String, FeatureSet>::new();
2229    for name in &message_names {
2230        let parent = message_names
2231            .iter()
2232            .filter(|candidate| {
2233                name.starts_with(candidate.as_str()) && name.as_str() != candidate.as_str()
2234            })
2235            .filter(|candidate| name.as_bytes().get(candidate.len()) == Some(&b'.'))
2236            .max_by_key(|candidate| candidate.len())
2237            .and_then(|candidate| resolved_messages.get(candidate))
2238            .copied()
2239            .unwrap_or(root);
2240        let descriptor = schema
2241            .messages
2242            .get_mut(name)
2243            .ok_or_else(|| Error::new(0, "message disappeared during feature resolution"))?;
2244        descriptor.features =
2245            apply_feature_options(parent, &descriptor.options, OptionTarget::Message, edition)?;
2246        for field in &mut descriptor.fields {
2247            field.features = apply_feature_options(
2248                descriptor.features,
2249                &field.options,
2250                OptionTarget::Field,
2251                edition,
2252            )?;
2253            if field.features.message_encoding == MessageEncoding::Delimited
2254                && !matches!(field.kind, FieldType::Message(_))
2255                && field
2256                    .options
2257                    .iter()
2258                    .any(|option| option.name == FEATURE_MESSAGE_ENCODING)
2259            {
2260                return Err(Error::new(
2261                    0,
2262                    format!(
2263                        "field {} applies DELIMITED encoding to a non-message",
2264                        field.name
2265                    ),
2266                ));
2267            }
2268            if field
2269                .options
2270                .iter()
2271                .any(|option| option.name == FEATURE_UTF8_VALIDATION)
2272                && !matches!(field.kind, FieldType::String)
2273            {
2274                return Err(Error::new(
2275                    0,
2276                    format!(
2277                        "field {} applies UTF-8 validation to a non-string",
2278                        field.name
2279                    ),
2280                ));
2281            }
2282            if field
2283                .options
2284                .iter()
2285                .any(|option| option.name == FEATURE_REPEATED_ENCODING)
2286                && field.cardinality != Cardinality::Repeated
2287            {
2288                return Err(Error::new(
2289                    0,
2290                    format!(
2291                        "field {} applies repeated encoding to a singular field",
2292                        field.name
2293                    ),
2294                ));
2295            }
2296            field.explicit_presence = field.explicit_presence
2297                || field.oneof.is_some()
2298                || matches!(field.kind, FieldType::Message(_))
2299                || field.features.field_presence != FieldPresence::Implicit;
2300            if field.default.is_some() && field.features.field_presence == FieldPresence::Implicit {
2301                return Err(Error::new(
2302                    0,
2303                    format!(
2304                        "field {} cannot combine implicit presence with a default",
2305                        field.name
2306                    ),
2307                ));
2308            }
2309            if field.cardinality == Cardinality::Repeated
2310                && !field.packed_explicit
2311                && !matches!(
2312                    field.kind,
2313                    FieldType::String
2314                        | FieldType::Bytes
2315                        | FieldType::Message(_)
2316                        | FieldType::Map(..)
2317                )
2318            {
2319                field.packed =
2320                    Some(field.features.repeated_field_encoding == RepeatedFieldEncoding::Packed);
2321            }
2322        }
2323        resolved_messages.insert(name.clone(), descriptor.features);
2324    }
2325    for enumeration in schema.enums.values_mut() {
2326        let parent = message_names
2327            .iter()
2328            .filter(|candidate| enumeration.full_name.starts_with(candidate.as_str()))
2329            .filter(|candidate| {
2330                enumeration.full_name.as_bytes().get(candidate.len()) == Some(&b'.')
2331            })
2332            .max_by_key(|candidate| candidate.len())
2333            .and_then(|candidate| resolved_messages.get(candidate))
2334            .copied()
2335            .unwrap_or(root);
2336        enumeration.features =
2337            apply_feature_options(parent, &enumeration.options, OptionTarget::Enum, edition)?;
2338    }
2339    for extension in schema.extensions.values_mut() {
2340        let scope = extension
2341            .full_name
2342            .rsplit_once('.')
2343            .map_or("", |(parent, _)| parent);
2344        let inherited = resolved_messages.get(scope).copied().unwrap_or(root);
2345        extension.field.features = apply_feature_options(
2346            inherited,
2347            &extension.field.options,
2348            OptionTarget::Field,
2349            edition,
2350        )?;
2351        extension.field.explicit_presence = extension.field.cardinality != Cardinality::Repeated
2352            && extension.field.features.field_presence != FieldPresence::Implicit;
2353        if extension.field.cardinality == Cardinality::Repeated
2354            && !extension.field.packed_explicit
2355            && !matches!(
2356                extension.field.kind,
2357                FieldType::String | FieldType::Bytes | FieldType::Message(_) | FieldType::Map(..)
2358            )
2359        {
2360            extension.field.packed = Some(
2361                extension.field.features.repeated_field_encoding == RepeatedFieldEncoding::Packed,
2362            );
2363        }
2364    }
2365    Ok(())
2366}
2367
2368/// Validates built-in option names, scopes, scalar categories, and duplicates.
2369fn validate_options(options: &[OptionSetting], target: OptionTarget) -> Result<()> {
2370    for (index, option) in options.iter().enumerate() {
2371        if option.name.starts_with('(') {
2372            continue;
2373        }
2374        let expected = builtin_option_type(target, &option.name).ok_or_else(|| {
2375            Error::new(0, format!("unknown or misplaced option: {}", option.name))
2376        })?;
2377        if options[..index]
2378            .iter()
2379            .any(|previous| previous.name == option.name)
2380        {
2381            return Err(Error::new(0, format!("duplicate option: {}", option.name)));
2382        }
2383        let valid = match expected {
2384            BuiltinOptionType::Bool => {
2385                option.value_kind == OptionValueKind::Identifier
2386                    && matches!(option.value.as_str(), BOOLEAN_TRUE | BOOLEAN_FALSE)
2387            }
2388            BuiltinOptionType::String => option.value_kind == OptionValueKind::String,
2389            BuiltinOptionType::Identifier => option.value_kind == OptionValueKind::Identifier,
2390            BuiltinOptionType::AnyScalar => option.value_kind != OptionValueKind::Aggregate,
2391            BuiltinOptionType::Any => true,
2392        };
2393        if !valid {
2394            return Err(Error::new(
2395                0,
2396                format!("invalid value for option: {}", option.name),
2397            ));
2398        }
2399        if option.name == "optimize_for"
2400            && !matches!(
2401                option.value.as_str(),
2402                "SPEED" | "CODE_SIZE" | "LITE_RUNTIME"
2403            )
2404        {
2405            return Err(Error::new(0, "invalid optimize_for value"));
2406        }
2407        if option.name == "ctype"
2408            && !matches!(option.value.as_str(), "STRING" | "CORD" | "STRING_PIECE")
2409        {
2410            return Err(Error::new(0, "invalid ctype value"));
2411        }
2412        if option.name == "jstype"
2413            && !matches!(
2414                option.value.as_str(),
2415                "JS_NORMAL" | "JS_STRING" | "JS_NUMBER"
2416            )
2417        {
2418            return Err(Error::new(0, "invalid jstype value"));
2419        }
2420        if option.name == "idempotency_level"
2421            && !matches!(
2422                option.value.as_str(),
2423                "IDEMPOTENCY_UNKNOWN" | "NO_SIDE_EFFECTS" | "IDEMPOTENT"
2424            )
2425        {
2426            return Err(Error::new(0, "invalid idempotency_level value"));
2427        }
2428    }
2429    Ok(())
2430}
2431
2432/// Returns whether a proto3 extension targets a descriptor option message.
2433fn is_custom_option_extendee(name: &str) -> bool {
2434    matches!(
2435        name,
2436        "google.protobuf.FileOptions"
2437            | "google.protobuf.MessageOptions"
2438            | "google.protobuf.FieldOptions"
2439            | "google.protobuf.OneofOptions"
2440            | "google.protobuf.EnumOptions"
2441            | "google.protobuf.EnumValueOptions"
2442            | "google.protobuf.ServiceOptions"
2443            | "google.protobuf.MethodOptions"
2444            | "google.protobuf.ExtensionRangeOptions"
2445    )
2446}
2447
2448/// Returns the descriptor options message corresponding to one option scope.
2449fn option_target_extendee(target: OptionTarget) -> &'static str {
2450    match target {
2451        OptionTarget::File => "google.protobuf.FileOptions",
2452        OptionTarget::Message => "google.protobuf.MessageOptions",
2453        OptionTarget::Field => "google.protobuf.FieldOptions",
2454        OptionTarget::Oneof => "google.protobuf.OneofOptions",
2455        OptionTarget::Enum => "google.protobuf.EnumOptions",
2456        OptionTarget::EnumValue => "google.protobuf.EnumValueOptions",
2457        OptionTarget::Service => "google.protobuf.ServiceOptions",
2458        OptionTarget::Method => "google.protobuf.MethodOptions",
2459    }
2460}
2461
2462/// Splits `(extension.name).field.path` into its extension and message path.
2463fn custom_option_parts(name: &str) -> Option<(&str, &str)> {
2464    let contents = name.strip_prefix('(')?;
2465    let closing = contents.find(')')?;
2466    let extension = &contents[..closing];
2467    let suffix = contents.get(closing + 1..)?;
2468    Some((extension, suffix.strip_prefix('.').unwrap_or(suffix)))
2469}
2470
2471/// Resolves a custom-option extension with protobuf lexical name lookup.
2472fn resolve_custom_option<'a>(
2473    source_name: &str,
2474    scope: &str,
2475    options: &'a BTreeMap<String, CustomOptionDescriptor>,
2476) -> Option<&'a CustomOptionDescriptor> {
2477    let absolute = source_name.starts_with('.');
2478    let raw = source_name.trim_start_matches('.');
2479    if absolute {
2480        return options.get(raw);
2481    }
2482    let mut current = scope;
2483    loop {
2484        let candidate = if current.is_empty() {
2485            raw.to_string()
2486        } else {
2487            format!("{current}.{raw}")
2488        };
2489        if let Some(option) = options.get(&candidate) {
2490            return Some(option);
2491        }
2492        let Some((parent, _)) = current.rsplit_once('.') else {
2493            break;
2494        };
2495        current = parent;
2496    }
2497    options.get(raw)
2498}
2499
2500/// Resolves a custom option's optional message-field suffix to its final type.
2501fn custom_option_value_type<'a>(
2502    descriptor: &'a CustomOptionDescriptor,
2503    path: &str,
2504    messages: &'a BTreeMap<String, MessageDescriptor>,
2505) -> Result<&'a FieldType> {
2506    let mut field_type = &descriptor.field.kind;
2507    if path.is_empty() {
2508        return Ok(field_type);
2509    }
2510    for component in path.split('.') {
2511        let FieldType::Message(message_name) = field_type else {
2512            return Err(Error::new(0, "custom option path traverses a scalar value"));
2513        };
2514        let message = messages.get(message_name).ok_or_else(|| {
2515            Error::new(0, format!("unknown custom option message: {message_name}"))
2516        })?;
2517        field_type = &message
2518            .field_by_name(component)
2519            .ok_or_else(|| Error::new(0, format!("unknown custom option field: {component}")))?
2520            .kind;
2521    }
2522    Ok(field_type)
2523}
2524
2525/// Reports whether an option literal has the lexical category required by a field.
2526fn custom_option_value_is_valid(
2527    field_type: &FieldType,
2528    kind: OptionValueKind,
2529    value: &str,
2530) -> bool {
2531    match field_type {
2532        FieldType::Bool => {
2533            kind == OptionValueKind::Identifier && matches!(value, BOOLEAN_TRUE | BOOLEAN_FALSE)
2534        }
2535        FieldType::String | FieldType::Bytes => kind == OptionValueKind::String,
2536        FieldType::Enum(_) => matches!(kind, OptionValueKind::Identifier | OptionValueKind::Number),
2537        FieldType::Message(_) => kind == OptionValueKind::Aggregate,
2538        FieldType::Map(..) => false,
2539        _ => kind == OptionValueKind::Number,
2540    }
2541}
2542
2543/// Validates custom-option lookup, placement, duplication, paths, and values.
2544fn validate_custom_options(
2545    settings: &[OptionSetting],
2546    target: OptionTarget,
2547    scope: &str,
2548    options: &BTreeMap<String, CustomOptionDescriptor>,
2549    messages: &BTreeMap<String, MessageDescriptor>,
2550) -> Result<()> {
2551    for (index, setting) in settings.iter().enumerate() {
2552        let Some((extension_name, path)) = custom_option_parts(&setting.name) else {
2553            continue;
2554        };
2555        let descriptor = resolve_custom_option(extension_name, scope, options)
2556            .ok_or_else(|| Error::new(0, format!("unknown custom option: {}", setting.name)))?;
2557        if descriptor.extendee != option_target_extendee(target) {
2558            return Err(Error::new(
2559                0,
2560                format!("custom option is not valid at this scope: {}", setting.name),
2561            ));
2562        }
2563        if descriptor.field.cardinality != Cardinality::Repeated
2564            && settings[..index]
2565                .iter()
2566                .any(|previous| previous.name == setting.name)
2567        {
2568            return Err(Error::new(
2569                0,
2570                format!("duplicate custom option: {}", setting.name),
2571            ));
2572        }
2573        let field_type = custom_option_value_type(descriptor, path, messages)?;
2574        if !custom_option_value_is_valid(field_type, setting.value_kind, &setting.value) {
2575            return Err(Error::new(
2576                0,
2577                format!("invalid value for custom option: {}", setting.name),
2578            ));
2579        }
2580    }
2581    Ok(())
2582}
2583
2584/// Validates every retained option at its protobuf descriptor scope.
2585fn validate_schema_options(
2586    schema: &Schema,
2587    custom_options: &BTreeMap<String, CustomOptionDescriptor>,
2588    messages: &BTreeMap<String, MessageDescriptor>,
2589) -> Result<()> {
2590    let file_scope = schema.package.as_deref().unwrap_or("");
2591    validate_options(&schema.options, OptionTarget::File)?;
2592    validate_custom_options(
2593        &schema.options,
2594        OptionTarget::File,
2595        file_scope,
2596        custom_options,
2597        messages,
2598    )?;
2599    for message in schema.messages.values() {
2600        validate_options(&message.options, OptionTarget::Message)?;
2601        validate_custom_options(
2602            &message.options,
2603            OptionTarget::Message,
2604            &message.full_name,
2605            custom_options,
2606            messages,
2607        )?;
2608        for oneof in &message.oneofs {
2609            validate_options(&oneof.options, OptionTarget::Oneof)?;
2610            validate_custom_options(
2611                &oneof.options,
2612                OptionTarget::Oneof,
2613                &message.full_name,
2614                custom_options,
2615                messages,
2616            )?;
2617        }
2618        for field in &message.fields {
2619            validate_options(&field.options, OptionTarget::Field)?;
2620            validate_custom_options(
2621                &field.options,
2622                OptionTarget::Field,
2623                &message.full_name,
2624                custom_options,
2625                messages,
2626            )?;
2627        }
2628    }
2629    for enumeration in schema.enums.values() {
2630        validate_options(&enumeration.options, OptionTarget::Enum)?;
2631        validate_custom_options(
2632            &enumeration.options,
2633            OptionTarget::Enum,
2634            &enumeration.full_name,
2635            custom_options,
2636            messages,
2637        )?;
2638        for value in &enumeration.values {
2639            validate_options(&value.options, OptionTarget::EnumValue)?;
2640            validate_custom_options(
2641                &value.options,
2642                OptionTarget::EnumValue,
2643                &enumeration.full_name,
2644                custom_options,
2645                messages,
2646            )?;
2647        }
2648    }
2649    for service in schema.services.values() {
2650        validate_options(&service.options, OptionTarget::Service)?;
2651        validate_custom_options(
2652            &service.options,
2653            OptionTarget::Service,
2654            &service.full_name,
2655            custom_options,
2656            messages,
2657        )?;
2658        for method in &service.methods {
2659            validate_options(&method.options, OptionTarget::Method)?;
2660            validate_custom_options(
2661                &method.options,
2662                OptionTarget::Method,
2663                &service.full_name,
2664                custom_options,
2665                messages,
2666            )?;
2667        }
2668    }
2669    Ok(())
2670}
2671
2672/// Derives the JSON spelling used by protobuf reflection for one field.
2673///
2674/// An explicit `json_name` takes precedence. Otherwise underscores are
2675/// removed and the following ASCII letter is capitalized, matching protoc's
2676/// lower-camel-case transformation for protobuf identifiers.
2677fn field_json_name(field: &Field) -> String {
2678    if let Some(option) = field
2679        .options
2680        .iter()
2681        .find(|option| option.name == "json_name")
2682    {
2683        return option.value.clone();
2684    }
2685    let mut name = String::new();
2686    let mut capitalize = false;
2687    for character in field.name.chars() {
2688        if character == '_' {
2689            capitalize = true;
2690        } else if capitalize {
2691            name.push(character.to_ascii_uppercase());
2692            capitalize = false;
2693        } else {
2694            name.push(character);
2695        }
2696    }
2697    name
2698}
2699
2700/// Rejects proto3 fields that become ambiguous through their JSON names.
2701///
2702/// Binary tags remain distinct in this situation, but protobuf JSON parsers
2703/// could map one input property to multiple fields. Protoc rejects the schema,
2704/// so the dynamic descriptor builder applies the same semantic rule even
2705/// though this crate does not currently implement JSON serialization.
2706fn validate_json_field_names(fields: &[Field], offset: usize) -> Result<()> {
2707    for (index, field) in fields.iter().enumerate() {
2708        let json_name = field_json_name(field);
2709        if fields[..index]
2710            .iter()
2711            .any(|previous| field_json_name(previous) == json_name)
2712        {
2713            return Err(Error::new(
2714                offset,
2715                format!("duplicate proto3 JSON field name: {json_name}"),
2716            ));
2717        }
2718    }
2719    Ok(())
2720}
2721
2722/// Validates field uniqueness, oneof names, and reserved declarations in a message.
2723fn validate_message_fields(
2724    fields: &[Field],
2725    oneof_names: &[String],
2726    reserved: &ReservedDeclarations,
2727    offset: usize,
2728) -> Result<()> {
2729    validate_reserved_declarations(reserved, offset)?;
2730    for (index, field) in fields.iter().enumerate() {
2731        if fields
2732            .iter()
2733            .take(index)
2734            .any(|previous| previous.name == field.name)
2735        {
2736            return Err(Error::new(offset, "duplicate field name"));
2737        }
2738        if fields
2739            .iter()
2740            .take(index)
2741            .any(|previous| previous.number == field.number)
2742        {
2743            return Err(Error::new(offset, "duplicate field number"));
2744        }
2745        if oneof_names.iter().any(|name| name == &field.name) {
2746            return Err(Error::new(offset, "field name conflicts with oneof name"));
2747        }
2748        if reserved.names.iter().any(|name| name == &field.name)
2749            || reserved
2750                .ranges
2751                .iter()
2752                .any(|(start, end)| (*start..=*end).contains(&i64::from(field.number)))
2753        {
2754            return Err(Error::new(offset, "field uses a reserved name or number"));
2755        }
2756    }
2757    Ok(())
2758}
2759
2760/// Parses one source file without resolving user-defined field types.
2761///
2762/// The resulting schema retains imports for later registry traversal.
2763fn validate_source_resource_limits(source: &str, options: &SchemaParseOptions) -> Result<()> {
2764    if source.len() > options.max_source_bytes {
2765        return Err(Error::new(0, "schema source exceeds configured size limit"));
2766    }
2767    let bytes = source.as_bytes();
2768    let mut cursor = 0usize;
2769    let mut depth = 0usize;
2770    let mut quote = None;
2771    let mut escaped = false;
2772    let mut line_comment = false;
2773    let mut block_comment = false;
2774    while cursor < bytes.len() {
2775        let byte = bytes[cursor];
2776        let next = bytes.get(cursor + 1).copied();
2777        if line_comment {
2778            line_comment = byte != b'\n';
2779        } else if block_comment {
2780            if byte == b'*' && next == Some(b'/') {
2781                block_comment = false;
2782                cursor += 1;
2783            }
2784        } else if let Some(delimiter) = quote {
2785            if escaped {
2786                escaped = false;
2787            } else if byte == b'\\' {
2788                escaped = true;
2789            } else if byte == delimiter {
2790                quote = None;
2791            }
2792        } else if byte == b'/' && next == Some(b'/') {
2793            line_comment = true;
2794            cursor += 1;
2795        } else if byte == b'/' && next == Some(b'*') {
2796            block_comment = true;
2797            cursor += 1;
2798        } else if matches!(byte, b'\'' | b'"') {
2799            quote = Some(byte);
2800        } else if byte == b'{' {
2801            depth = depth
2802                .checked_add(1)
2803                .ok_or_else(|| Error::new(cursor, "schema nesting counter overflow"))?;
2804            if depth > options.max_nesting_depth {
2805                return Err(Error::new(
2806                    cursor,
2807                    "schema exceeds configured nesting limit",
2808                ));
2809            }
2810        } else if byte == b'}' {
2811            depth = depth.saturating_sub(1);
2812        }
2813        cursor += 1;
2814    }
2815    Ok(())
2816}
2817
2818fn parse_file(source: &str, options: &SchemaParseOptions) -> Result<Schema> {
2819    validate_source_resource_limits(source, options)?;
2820    validate_pest_syntax(source)?;
2821    let tokens = lex(source)?;
2822    if tokens.len() > options.max_tokens {
2823        return Err(Error::new(0, "schema exceeds configured token limit"));
2824    }
2825    let mut parser = DescriptorBuilder {
2826        tokens,
2827        cursor: 0,
2828        syntax: Syntax::Proto2,
2829        package: None,
2830        messages: BTreeMap::new(),
2831        enums: BTreeMap::new(),
2832        services: BTreeMap::new(),
2833        custom_options: BTreeMap::new(),
2834        extensions: BTreeMap::new(),
2835        imports: Vec::new(),
2836        options: Vec::new(),
2837    };
2838    let mut seen_language = false;
2839    let mut seen_package = false;
2840    let mut seen_non_syntax = false;
2841    while parser.cursor < parser.tokens.len() {
2842        if parser.peek_identifier(KW_SYNTAX) || parser.peek_identifier(KW_EDITION) {
2843            if seen_language || seen_non_syntax {
2844                return Err(Error::new(
2845                    parser.offset(),
2846                    "syntax or edition declaration must occur once at the start of the file",
2847                ));
2848            }
2849            seen_language = true;
2850            let declaration = parser.identifier()?;
2851            parser.expect_symbol('=')?;
2852            let language_name = match parser.tokens.get(parser.cursor).cloned() {
2853                Some((Token::StringLiteral(value), _)) => {
2854                    parser.cursor += 1;
2855                    value
2856                }
2857                _ => {
2858                    return Err(Error::new(
2859                        parser.offset(),
2860                        "expected language version string",
2861                    ));
2862                }
2863            };
2864            parser.syntax = match (declaration.as_str(), language_name.as_str()) {
2865                (KW_SYNTAX, SYNTAX_PROTO2) => Syntax::Proto2,
2866                (KW_SYNTAX, SYNTAX_PROTO3) => Syntax::Proto3,
2867                (KW_EDITION, EDITION_2023) => Syntax::Edition2023,
2868                (KW_EDITION, _) => return Err(Error::new(parser.offset(), "unsupported edition")),
2869                _ => return Err(Error::new(parser.offset(), "unsupported syntax")),
2870            };
2871            parser.expect_symbol(';')?
2872        } else if parser.peek_identifier(KW_PACKAGE) {
2873            seen_non_syntax = true;
2874            if seen_package {
2875                return Err(Error::new(parser.offset(), "duplicate package declaration"));
2876            }
2877            seen_package = true;
2878            parser.identifier()?;
2879            parser.package = Some(parser.package_name()?);
2880            parser.expect_symbol(';')?
2881        } else if parser.peek_identifier(KW_IMPORT) {
2882            seen_non_syntax = true;
2883            parser.identifier()?;
2884            let kind = if parser.peek_identifier(KW_PUBLIC) {
2885                parser.identifier()?;
2886                ImportKind::Public
2887            } else if parser.peek_identifier(KW_WEAK) {
2888                parser.identifier()?;
2889                ImportKind::Weak
2890            } else {
2891                ImportKind::Normal
2892            };
2893            let path = match parser.tokens.get(parser.cursor).cloned() {
2894                Some((Token::StringLiteral(path), _)) => {
2895                    parser.cursor += 1;
2896                    path
2897                }
2898                _ => return Err(Error::new(parser.offset(), "expected import path string")),
2899            };
2900            parser.expect_symbol(';')?;
2901            parser.imports.push(Import { path, kind });
2902        } else if parser.peek_identifier(KW_MESSAGE) {
2903            seen_non_syntax = true;
2904            parser.parse_message("")?
2905        } else if parser.peek_identifier(KW_ENUM) {
2906            seen_non_syntax = true;
2907            parser.parse_enum("")?
2908        } else if parser.peek_identifier(KW_SERVICE) {
2909            seen_non_syntax = true;
2910            parser.parse_service()?
2911        } else if parser.peek_identifier(KW_OPTION) {
2912            seen_non_syntax = true;
2913            let option = parser.option_declaration()?;
2914            parser.options.push(option)
2915        } else if parser.peek_identifier(KW_EXTEND) {
2916            seen_non_syntax = true;
2917            parser.parse_custom_option_extensions("")?
2918        } else if parser.consume_symbol(';') {
2919            seen_non_syntax = true;
2920        } else {
2921            return Err(Error::new(
2922                parser.offset(),
2923                "unexpected top-level declaration",
2924            ));
2925        }
2926    }
2927    Ok(Schema {
2928        syntax: parser.syntax,
2929        package: parser.package,
2930        messages: parser.messages,
2931        enums: parser.enums,
2932        services: parser.services,
2933        custom_options: parser.custom_options,
2934        extensions: parser.extensions,
2935        imports: parser.imports,
2936        options: parser.options,
2937        features: FeatureSet::for_syntax(parser.syntax),
2938    })
2939}
2940
2941/// Parses and resolves one self-contained schema.
2942///
2943/// Use [`Registry::parse`] when the source contains imports.
2944///
2945/// # Errors
2946///
2947/// Returns an error for invalid syntax, invalid field declarations, or
2948/// references to message and enum types absent from this source.
2949pub fn parse(source: &str) -> Result<Schema> {
2950    parse_with_options(source, &SchemaParseOptions::default())
2951}
2952
2953/// Parses and resolves one source under explicit resource limits.
2954pub fn parse_with_options(source: &str, options: &SchemaParseOptions) -> Result<Schema> {
2955    let mut schema = parse_file(source, options)?;
2956    resolve_schema(&mut schema)?;
2957    Ok(schema)
2958}
2959
2960/// Traverses the registered import graph and combines its declarations.
2961///
2962/// A visited-path collection terminates cycles. Missing weak imports are
2963/// ignored, while missing normal/public imports and duplicate symbols fail.
2964/// The root source contributes the resulting schema's syntax and package.
2965fn parse_registry(root: &str, registry: &Registry, options: &SchemaParseOptions) -> Result<Schema> {
2966    let mut pending = alloc::vec![root.to_string()];
2967    let mut files = BTreeMap::<String, Schema>::new();
2968    while let Some(path) = pending.pop() {
2969        if files.contains_key(&path) {
2970            continue;
2971        }
2972        let source = registry
2973            .source(&path)
2974            .ok_or_else(|| Error::new(0, format!("import not found: {path}")))?;
2975        if files.len() >= options.max_registry_files {
2976            return Err(Error::new(0, "registry exceeds configured file limit"));
2977        }
2978        let file = parse_file(source, options).map_err(|error| {
2979            Error::new(
2980                error.offset,
2981                format!("while parsing registry source {path}: {}", error.message),
2982            )
2983        })?;
2984        for import in &file.imports {
2985            if registry.source(&import.path).is_none() {
2986                if import.kind == ImportKind::Weak {
2987                    continue;
2988                }
2989                return Err(Error::new(0, format!("import not found: {}", import.path)));
2990            }
2991            pending.push(import.path.clone());
2992        }
2993        files.insert(path, file);
2994    }
2995    validate_import_cycles(root, &files, &mut BTreeMap::new())?;
2996
2997    let paths: Vec<String> = files.keys().cloned().collect();
2998    let mut visibility = BTreeMap::<String, Vec<String>>::new();
2999    for path in &paths {
3000        visibility.insert(path.clone(), visible_import_paths(path, &files)?);
3001    }
3002    for path in &paths {
3003        let visible_paths = visibility
3004            .get(path)
3005            .ok_or_else(|| Error::new(0, "import visibility disappeared"))?;
3006        let mut visible_messages = BTreeMap::<String, MessageDescriptor>::new();
3007        let mut visible_enums = BTreeMap::<String, Syntax>::new();
3008        for visible_path in visible_paths {
3009            let visible = files
3010                .get(visible_path)
3011                .ok_or_else(|| Error::new(0, "visible source disappeared"))?;
3012            visible_messages.extend(visible.messages.clone());
3013            for (name, enumeration) in &visible.enums {
3014                visible_enums.insert(name.clone(), enumeration.syntax);
3015            }
3016        }
3017        let file = files
3018            .get_mut(path)
3019            .ok_or_else(|| Error::new(0, "registered source disappeared"))?;
3020        validate_symbol_namespaces(file)?;
3021        resolve_schema_declarations(file, &visible_messages, &visible_enums)?;
3022        resolve_features(file)?;
3023    }
3024    for path in &paths {
3025        let visible_paths = visibility
3026            .get(path)
3027            .ok_or_else(|| Error::new(0, "import visibility disappeared"))?;
3028        let mut visible_messages = BTreeMap::<String, MessageDescriptor>::new();
3029        let mut visible_custom_options = BTreeMap::<String, CustomOptionDescriptor>::new();
3030        for visible_path in visible_paths {
3031            let visible = files
3032                .get(visible_path)
3033                .ok_or_else(|| Error::new(0, "visible source disappeared"))?;
3034            visible_messages.extend(visible.messages.clone());
3035            visible_custom_options.extend(visible.custom_options.clone());
3036        }
3037        let file = files
3038            .get(path)
3039            .ok_or_else(|| Error::new(0, "registered source disappeared"))?;
3040        validate_schema_options(file, &visible_custom_options, &visible_messages)?;
3041    }
3042
3043    let mut schema = files
3044        .remove(root)
3045        .ok_or_else(|| Error::new(0, "root schema not found"))?;
3046    for (_, file) in files {
3047        for (name, descriptor) in file.messages {
3048            if schema.messages.insert(name.clone(), descriptor).is_some() {
3049                return Err(Error::new(0, format!("duplicate message: {name}")));
3050            }
3051        }
3052        for (name, enumeration) in file.enums {
3053            if schema.enums.insert(name.clone(), enumeration).is_some() {
3054                return Err(Error::new(0, format!("duplicate enum: {name}")));
3055            }
3056        }
3057        for (name, service) in file.services {
3058            if schema.services.insert(name.clone(), service).is_some() {
3059                return Err(Error::new(0, format!("duplicate service: {name}")));
3060            }
3061        }
3062        for (name, option) in file.custom_options {
3063            if schema.custom_options.contains_key(&name)
3064                || schema.custom_options.values().any(|existing| {
3065                    existing.extendee == option.extendee
3066                        && existing.field.number == option.field.number
3067                })
3068            {
3069                return Err(Error::new(0, format!("duplicate custom option: {name}")));
3070            }
3071            schema.custom_options.insert(name, option);
3072        }
3073        for (name, extension) in file.extensions {
3074            if schema.extensions.contains_key(&name)
3075                || schema.extensions.values().any(|existing| {
3076                    existing.extendee == extension.extendee
3077                        && existing.field.number == extension.field.number
3078                })
3079            {
3080                return Err(Error::new(0, format!("duplicate extension: {name}")));
3081            }
3082            schema.extensions.insert(name, extension);
3083        }
3084        schema.imports.extend(file.imports);
3085    }
3086    validate_symbol_namespaces(&schema)?;
3087    Ok(schema)
3088}
3089
3090/// Computes direct and publicly re-exported declarations visible to one file.
3091fn visible_import_paths(path: &str, files: &BTreeMap<String, Schema>) -> Result<Vec<String>> {
3092    let file = files
3093        .get(path)
3094        .ok_or_else(|| Error::new(0, "registered source disappeared"))?;
3095    let mut visible_paths = alloc::vec![path.to_string()];
3096    let mut public_frontier = Vec::<String>::new();
3097    for import in &file.imports {
3098        if files.contains_key(&import.path) && !visible_paths.contains(&import.path) {
3099            visible_paths.push(import.path.clone());
3100            public_frontier.push(import.path.clone());
3101        }
3102    }
3103    while let Some(imported_path) = public_frontier.pop() {
3104        let imported = files
3105            .get(&imported_path)
3106            .ok_or_else(|| Error::new(0, "visible import disappeared"))?;
3107        for public_import in imported
3108            .imports
3109            .iter()
3110            .filter(|import| import.kind == ImportKind::Public)
3111        {
3112            if files.contains_key(&public_import.path)
3113                && !visible_paths.contains(&public_import.path)
3114            {
3115                visible_paths.push(public_import.path.clone());
3116                public_frontier.push(public_import.path.clone());
3117            }
3118        }
3119    }
3120    Ok(visible_paths)
3121}
3122
3123/// Rejects cycles in the reachable registry import graph.
3124fn validate_import_cycles(
3125    path: &str,
3126    files: &BTreeMap<String, Schema>,
3127    states: &mut BTreeMap<String, u8>,
3128) -> Result<()> {
3129    match states.get(path) {
3130        Some(1) => return Err(Error::new(0, format!("cyclic protobuf import: {path}"))),
3131        Some(2) => return Ok(()),
3132        _ => {}
3133    }
3134    states.insert(path.to_string(), 1);
3135    let file = files
3136        .get(path)
3137        .ok_or_else(|| Error::new(0, format!("import not found: {path}")))?;
3138    for import in &file.imports {
3139        if files.contains_key(&import.path) {
3140            validate_import_cycles(&import.path, files, states)?;
3141        }
3142    }
3143    states.insert(path.to_string(), 2);
3144    Ok(())
3145}
3146
3147/// Resolves every deferred user-defined type and computes field presence rules.
3148///
3149/// Resolution runs after import merging so cross-file names are visible. It
3150/// also marks message fields as explicitly present and prevents non-packable
3151/// repeated strings, bytes, messages, and maps from using packed encoding.
3152fn resolve_schema(schema: &mut Schema) -> Result<()> {
3153    validate_symbol_namespaces(schema)?;
3154    let messages = schema.messages.clone();
3155    let enums: BTreeMap<String, Syntax> = schema
3156        .enums
3157        .iter()
3158        .map(|(name, enumeration)| (name.clone(), enumeration.syntax))
3159        .collect();
3160    resolve_schema_declarations(schema, &messages, &enums)?;
3161    resolve_features(schema)?;
3162    let resolved_messages = schema.messages.clone();
3163    let custom_options = schema.custom_options.clone();
3164    validate_schema_options(schema, &custom_options, &resolved_messages)
3165}
3166
3167/// Resolves fields against the declarations visible from one source file.
3168fn resolve_schema_declarations(
3169    schema: &mut Schema,
3170    messages: &BTreeMap<String, MessageDescriptor>,
3171    enums: &BTreeMap<String, Syntax>,
3172) -> Result<()> {
3173    let message_names: Vec<String> = messages.keys().cloned().collect();
3174    let enum_names: Vec<String> = enums.keys().cloned().collect();
3175    for descriptor in schema.messages.values_mut() {
3176        for field in &mut descriptor.fields {
3177            resolve(
3178                &mut field.kind,
3179                &descriptor.full_name,
3180                &message_names,
3181                &enum_names,
3182            )?;
3183            if schema.syntax.has_modern_defaults() {
3184                reject_proto2_enum_reference(&field.kind, enums)?;
3185            }
3186            if field.packed_explicit
3187                && field.packed == Some(true)
3188                && matches!(
3189                    field.kind,
3190                    FieldType::String
3191                        | FieldType::Bytes
3192                        | FieldType::Message(_)
3193                        | FieldType::Map(..)
3194                )
3195            {
3196                return Err(Error::new(
3197                    0,
3198                    format!("field {} cannot use packed encoding", field.name),
3199                ));
3200            }
3201            if field.default.is_some()
3202                && matches!(field.kind, FieldType::Message(_) | FieldType::Map(..))
3203            {
3204                return Err(Error::new(
3205                    0,
3206                    format!("field {} cannot declare a default", field.name),
3207                ));
3208            }
3209            if matches!(field.kind, FieldType::Message(_)) {
3210                field.explicit_presence = true;
3211            }
3212            if field.cardinality == Cardinality::Repeated
3213                && matches!(
3214                    field.kind,
3215                    FieldType::String
3216                        | FieldType::Bytes
3217                        | FieldType::Message(_)
3218                        | FieldType::Map(..)
3219                )
3220            {
3221                field.packed = Some(false);
3222            }
3223        }
3224    }
3225    for option in schema.custom_options.values_mut() {
3226        if !messages.contains_key(&option.extendee) {
3227            return Err(Error::new(
3228                0,
3229                format!("custom option extendee is not visible: {}", option.extendee),
3230            ));
3231        }
3232        let scope = option
3233            .full_name
3234            .rsplit_once('.')
3235            .map_or("", |(parent, _)| parent);
3236        resolve(&mut option.field.kind, scope, &message_names, &enum_names)?;
3237        validate_options(&option.field.options, OptionTarget::Field)?;
3238    }
3239    for extension in schema.extensions.values_mut() {
3240        let mut extendee_type = FieldType::Message(extension.extendee.clone());
3241        let scope = extension
3242            .full_name
3243            .rsplit_once('.')
3244            .map_or("", |(parent, _)| parent);
3245        resolve(&mut extendee_type, scope, &message_names, &enum_names)?;
3246        let FieldType::Message(extendee) = extendee_type else {
3247            return Err(Error::new(0, "extension target must be a message"));
3248        };
3249        let target = messages
3250            .get(&extendee)
3251            .ok_or_else(|| Error::new(0, "extension target is not visible"))?;
3252        if !target
3253            .extension_ranges
3254            .iter()
3255            .any(|(start, end)| (*start..=*end).contains(&extension.field.number))
3256        {
3257            return Err(Error::new(
3258                0,
3259                format!(
3260                    "extension {} is outside the target's extension ranges",
3261                    extension.full_name
3262                ),
3263            ));
3264        }
3265        if target.field_by_number(extension.field.number).is_some() {
3266            return Err(Error::new(
3267                0,
3268                "extension number collides with a regular field",
3269            ));
3270        }
3271        extension.extendee = extendee;
3272        resolve(
3273            &mut extension.field.kind,
3274            scope,
3275            &message_names,
3276            &enum_names,
3277        )?;
3278        validate_options(&extension.field.options, OptionTarget::Field)?;
3279    }
3280    let extensions: Vec<&ExtensionDescriptor> = schema.extensions.values().collect();
3281    for (index, extension) in extensions.iter().enumerate() {
3282        if extensions[..index].iter().any(|previous| {
3283            previous.extendee == extension.extendee
3284                && previous.field.number == extension.field.number
3285        }) {
3286            return Err(Error::new(
3287                0,
3288                format!(
3289                    "duplicate extension number {} for {}",
3290                    extension.field.number, extension.extendee
3291                ),
3292            ));
3293        }
3294    }
3295    for service in schema.services.values_mut() {
3296        for method in &mut service.methods {
3297            method.input_type = resolve_rpc_message(
3298                &method.input_type,
3299                &service.full_name,
3300                &message_names,
3301                &enum_names,
3302            )?;
3303            method.output_type = resolve_rpc_message(
3304                &method.output_type,
3305                &service.full_name,
3306                &message_names,
3307                &enum_names,
3308            )?;
3309        }
3310    }
3311    Ok(())
3312}
3313
3314/// Rejects proto2 enum types referenced from a proto3 source file.
3315fn reject_proto2_enum_reference(
3316    field_type: &FieldType,
3317    enums: &BTreeMap<String, Syntax>,
3318) -> Result<()> {
3319    match field_type {
3320        FieldType::Enum(name) if enums.get(name) == Some(&Syntax::Proto2) => Err(Error::new(
3321            0,
3322            format!("proto3 field cannot reference proto2 enum: {name}"),
3323        )),
3324        FieldType::Map(key, value) => {
3325            reject_proto2_enum_reference(key, enums)?;
3326            reject_proto2_enum_reference(value, enums)
3327        }
3328        _ => Ok(()),
3329    }
3330}
3331
3332/// Resolves an RPC endpoint and requires it to name a message declaration.
3333fn resolve_rpc_message(
3334    source_name: &str,
3335    scope: &str,
3336    messages: &[String],
3337    enums: &[String],
3338) -> Result<String> {
3339    let mut field_type = FieldType::Message(source_name.to_string());
3340    resolve(&mut field_type, scope, messages, enums)?;
3341    match field_type {
3342        FieldType::Message(name) => Ok(name),
3343        FieldType::Enum(name) => Err(Error::new(
3344            0,
3345            format!("rpc endpoint must be a message, not enum: {name}"),
3346        )),
3347        _ => Err(Error::new(0, "rpc endpoint must be a message")),
3348    }
3349}
3350
3351/// Validates protobuf's shared declaration namespaces before type resolution.
3352fn validate_symbol_namespaces(schema: &Schema) -> Result<()> {
3353    let mut symbols = BTreeMap::<String, &'static str>::new();
3354    for name in schema.messages.keys() {
3355        if symbols.insert(name.clone(), "message").is_some() || schema.enums.contains_key(name) {
3356            return Err(Error::new(
3357                0,
3358                format!("conflicting declaration name: {name}"),
3359            ));
3360        }
3361    }
3362    for name in schema.enums.keys() {
3363        if symbols.insert(name.clone(), "enum").is_some() {
3364            return Err(Error::new(
3365                0,
3366                format!("conflicting declaration name: {name}"),
3367            ));
3368        }
3369    }
3370    for name in schema.services.keys() {
3371        if symbols.insert(name.clone(), "service").is_some() {
3372            return Err(Error::new(
3373                0,
3374                format!("conflicting declaration name: {name}"),
3375            ));
3376        }
3377    }
3378    for name in schema.custom_options.keys() {
3379        if symbols.insert(name.clone(), "custom option").is_some() {
3380            return Err(Error::new(
3381                0,
3382                format!("conflicting declaration name: {name}"),
3383            ));
3384        }
3385    }
3386    for descriptor in schema.messages.values() {
3387        for field in &descriptor.fields {
3388            let name = format!("{}.{}", descriptor.full_name, field.name);
3389            if symbols.insert(name.clone(), "field").is_some() {
3390                return Err(Error::new(
3391                    0,
3392                    format!("conflicting declaration name: {name}"),
3393                ));
3394            }
3395        }
3396        let mut oneofs = Vec::<&str>::new();
3397        for oneof in descriptor
3398            .fields
3399            .iter()
3400            .filter_map(|field| field.oneof.as_deref())
3401        {
3402            if oneofs.contains(&oneof) {
3403                continue;
3404            }
3405            oneofs.push(oneof);
3406            let name = format!("{}.{}", descriptor.full_name, oneof);
3407            if symbols.insert(name.clone(), "oneof").is_some() {
3408                return Err(Error::new(
3409                    0,
3410                    format!("conflicting declaration name: {name}"),
3411                ));
3412            }
3413        }
3414    }
3415    for enumeration in schema.enums.values() {
3416        let parent = enumeration
3417            .full_name
3418            .rsplit_once('.')
3419            .map_or("", |(parent, _)| parent);
3420        for value in &enumeration.values {
3421            let name = if parent.is_empty() {
3422                value.name.clone()
3423            } else {
3424                format!("{parent}.{}", value.name)
3425            };
3426            if symbols.insert(name.clone(), "enum value").is_some() {
3427                return Err(Error::new(
3428                    0,
3429                    format!("conflicting declaration name: {name}"),
3430                ));
3431            }
3432        }
3433    }
3434    Ok(())
3435}
3436
3437/// Resolves one field type using protobuf's innermost-scope-first name lookup.
3438///
3439/// Absolute names bypass lexical scope. Relative names try the containing
3440/// message, each enclosing scope, and finally the unqualified global name.
3441/// Map key and value types are resolved recursively.
3442fn resolve(t: &mut FieldType, scope: &str, messages: &[String], enums: &[String]) -> Result<()> {
3443    match t {
3444        FieldType::Message(n) => {
3445            let absolute = n.starts_with('.');
3446            let raw = n.trim_start_matches('.');
3447            let mut candidates = Vec::new();
3448            if absolute {
3449                candidates.push(raw.to_string());
3450            } else {
3451                let mut current = scope;
3452                loop {
3453                    candidates.push(format!("{current}.{raw}"));
3454                    if let Some(index) = current.rfind('.') {
3455                        current = &current[..index];
3456                    } else {
3457                        break;
3458                    }
3459                }
3460                candidates.push(raw.to_string());
3461            }
3462            if let Some(name) = candidates.iter().find(|x| messages.contains(x)) {
3463                *n = name.clone();
3464            } else if let Some(name) = candidates.iter().find(|x| enums.contains(x)) {
3465                *t = FieldType::Enum(name.clone());
3466            } else {
3467                return Err(Error::new(0, format!("unknown type {n} in {scope}")));
3468            }
3469        }
3470        FieldType::Map(a, b) => {
3471            resolve(a, scope, messages, enums)?;
3472            resolve(b, scope, messages, enums)?;
3473        }
3474        _ => {}
3475    }
3476    Ok(())
3477}