Skip to main content

tabnas_proto/
descriptor.rs

1/* Copyright (c) 2026 Richard Rodger and other contributors, MIT License */
2
3//! FileDescriptorProto-shaped output types.
4//!
5//! This mirrors the canonical `descriptor.proto` message set (the shape
6//! `protoc --descriptor_set_out` produces, in its JSON form): camelCase
7//! fields, enum values as their string names (`TYPE_INT32`,
8//! `LABEL_REPEATED`). Only fields the parser can populate from a single
9//! `.proto` source are included; cross-file type resolution is left to a
10//! later pass, so `type_name` is stored as written.
11//!
12//! Rust port of `ts/src/descriptor.ts`.
13
14use indexmap::IndexMap;
15use serde::{Serialize, Serializer};
16use serde_json::value::RawValue;
17
18use crate::jsnum::js_number_to_string;
19
20/// A field's cardinality label.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
22pub enum FieldLabel {
23    #[serde(rename = "LABEL_OPTIONAL")]
24    Optional,
25    #[serde(rename = "LABEL_REQUIRED")]
26    Required,
27    #[serde(rename = "LABEL_REPEATED")]
28    Repeated,
29}
30
31impl FieldLabel {
32    /// The name descriptor JSON carries, such as `LABEL_REPEATED`.
33    pub fn as_str(self) -> &'static str {
34        match self {
35            FieldLabel::Optional => "LABEL_OPTIONAL",
36            FieldLabel::Required => "LABEL_REQUIRED",
37            FieldLabel::Repeated => "LABEL_REPEATED",
38        }
39    }
40}
41
42/// A field's wire type, for the types a single source file settles.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
44pub enum FieldType {
45    #[serde(rename = "TYPE_DOUBLE")]
46    Double,
47    #[serde(rename = "TYPE_FLOAT")]
48    Float,
49    #[serde(rename = "TYPE_INT64")]
50    Int64,
51    #[serde(rename = "TYPE_UINT64")]
52    Uint64,
53    #[serde(rename = "TYPE_INT32")]
54    Int32,
55    #[serde(rename = "TYPE_FIXED64")]
56    Fixed64,
57    #[serde(rename = "TYPE_FIXED32")]
58    Fixed32,
59    #[serde(rename = "TYPE_BOOL")]
60    Bool,
61    #[serde(rename = "TYPE_STRING")]
62    String,
63    #[serde(rename = "TYPE_GROUP")]
64    Group,
65    #[serde(rename = "TYPE_MESSAGE")]
66    Message,
67    #[serde(rename = "TYPE_BYTES")]
68    Bytes,
69    #[serde(rename = "TYPE_UINT32")]
70    Uint32,
71    #[serde(rename = "TYPE_ENUM")]
72    Enum,
73    #[serde(rename = "TYPE_SFIXED32")]
74    Sfixed32,
75    #[serde(rename = "TYPE_SFIXED64")]
76    Sfixed64,
77    #[serde(rename = "TYPE_SINT32")]
78    Sint32,
79    #[serde(rename = "TYPE_SINT64")]
80    Sint64,
81}
82
83impl FieldType {
84    /// The name descriptor JSON carries, such as `TYPE_INT32`.
85    pub fn as_str(self) -> &'static str {
86        match self {
87            FieldType::Double => "TYPE_DOUBLE",
88            FieldType::Float => "TYPE_FLOAT",
89            FieldType::Int64 => "TYPE_INT64",
90            FieldType::Uint64 => "TYPE_UINT64",
91            FieldType::Int32 => "TYPE_INT32",
92            FieldType::Fixed64 => "TYPE_FIXED64",
93            FieldType::Fixed32 => "TYPE_FIXED32",
94            FieldType::Bool => "TYPE_BOOL",
95            FieldType::String => "TYPE_STRING",
96            FieldType::Group => "TYPE_GROUP",
97            FieldType::Message => "TYPE_MESSAGE",
98            FieldType::Bytes => "TYPE_BYTES",
99            FieldType::Uint32 => "TYPE_UINT32",
100            FieldType::Enum => "TYPE_ENUM",
101            FieldType::Sfixed32 => "TYPE_SFIXED32",
102            FieldType::Sfixed64 => "TYPE_SFIXED64",
103            FieldType::Sint32 => "TYPE_SINT32",
104            FieldType::Sint64 => "TYPE_SINT64",
105        }
106    }
107}
108
109/// Symbol visibility, an edition-2024 feature (`export` / `local`).
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
111pub enum SymbolVisibility {
112    #[serde(rename = "VISIBILITY_EXPORT")]
113    Export,
114    #[serde(rename = "VISIBILITY_LOCAL")]
115    Local,
116}
117
118impl SymbolVisibility {
119    /// The name descriptor JSON carries, such as `VISIBILITY_EXPORT`.
120    pub fn as_str(self) -> &'static str {
121        match self {
122            SymbolVisibility::Export => "VISIBILITY_EXPORT",
123            SymbolVisibility::Local => "VISIBILITY_LOCAL",
124        }
125    }
126}
127
128/// An option's value, as the source wrote it.
129///
130/// The canonical `OptionValue` union also admits a nested map, and no
131/// input produces one: an aggregate value (`option (f) = { a: 1 };`) is
132/// kept as the text between its braces, as protoc records it (every
133/// comment turned to the spaces and newlines that hold the layout; see
134/// `aggregate.rs`), so the three variants here are the whole range the
135/// walk emits.
136#[derive(Debug, Clone, PartialEq, Serialize)]
137#[serde(untagged)]
138pub enum OptionValue {
139    Bool(bool),
140    /// A numeric constant, read exactly as JavaScript's `Number()` reads
141    /// it. Serializes as `null` when the source names a value no JSON
142    /// number can hold, which is what `JSON.stringify` writes for `NaN`
143    /// and the infinities.
144    Number(#[serde(serialize_with = "json_number")] f64),
145    Str(String),
146}
147
148/// An option set, keyed by the option name exactly as written
149/// (`ctype`, `(foo)`, `foo.(.bar.baz).qux`), in source order.
150pub type Options = IndexMap<String, OptionValue>;
151
152/// A number spelt exactly as `JSON.stringify` spells it.
153///
154/// The descriptor's JSON is the package's output format, and matching the
155/// canonical runtime means matching its TEXT, not only its value. Rust's
156/// `f64` formatting is not ECMA-262 6.1.6.1.20: it renders every float in
157/// float form (`1.0` for a field number), it switches to exponent form at
158/// different magnitudes (`1e-6` where JavaScript writes `0.000001`, and
159/// `1e+20` where JavaScript writes `100000000000000000000`), and it keeps
160/// the sign of a negative zero. [`js_number_to_string`] is the algorithm;
161/// this hands its text to `serde_json` verbatim through a `RawValue`.
162///
163/// Non-finite values have no JSON spelling at all: `JSON.stringify`
164/// writes `null` for them and so does this.
165pub(crate) fn json_number<S: Serializer>(value: &f64, serializer: S) -> Result<S::Ok, S::Error> {
166    if !value.is_finite() {
167        return serializer.serialize_none();
168    }
169    let text = js_number_to_string(*value);
170    let raw = RawValue::from_string(text).map_err(serde::ser::Error::custom)?;
171    raw.serialize(serializer)
172}
173
174/// A numeric range. `end` is EXCLUSIVE for message extension and reserved
175/// ranges and INCLUSIVE for enum reserved ranges, the same asymmetry
176/// protoc has.
177#[derive(Debug, Clone, PartialEq, Serialize)]
178pub struct DescriptorRange {
179    #[serde(serialize_with = "json_number")]
180    pub start: f64,
181    #[serde(serialize_with = "json_number")]
182    pub end: f64,
183    #[serde(skip_serializing_if = "Option::is_none")]
184    pub options: Option<Options>,
185}
186
187impl DescriptorRange {
188    /// A range with no options.
189    pub fn new(start: f64, end: f64) -> Self {
190        DescriptorRange {
191            start,
192            end,
193            options: None,
194        }
195    }
196}
197
198/// One field, extension, or synthesised map-entry leaf.
199#[derive(Debug, Clone, PartialEq, Serialize, Default)]
200#[serde(rename_all = "camelCase")]
201pub struct FieldDescriptorProto {
202    pub name: String,
203    #[serde(serialize_with = "json_number")]
204    pub number: f64,
205    #[serde(skip_serializing_if = "Option::is_none")]
206    pub label: Option<FieldLabel>,
207    #[serde(skip_serializing_if = "Option::is_none")]
208    pub r#type: Option<FieldType>,
209    /// Set for message, enum and group field types (resolution deferred).
210    #[serde(skip_serializing_if = "Option::is_none")]
211    pub type_name: Option<String>,
212    /// For an `extend` member: the message being extended, as written.
213    #[serde(skip_serializing_if = "Option::is_none")]
214    pub extendee: Option<String>,
215    /// The `json_name = "..."` pseudo-option, lifted out of `options`.
216    #[serde(skip_serializing_if = "Option::is_none")]
217    pub json_name: Option<String>,
218    /// The `default = ...` pseudo-option, lifted out of `options`. Always
219    /// a string, as in descriptor.proto; the literal is kept as written.
220    #[serde(skip_serializing_if = "Option::is_none")]
221    pub default_value: Option<String>,
222    /// proto3 explicit `optional`, which synthesises a single-field oneof.
223    #[serde(skip_serializing_if = "is_false")]
224    pub proto3_optional: bool,
225    /// The oneof this field belongs to, as an index into the message's
226    /// `oneof_decl`.
227    #[serde(skip_serializing_if = "Option::is_none")]
228    pub oneof_index: Option<usize>,
229    #[serde(skip_serializing_if = "Option::is_none")]
230    pub options: Option<Options>,
231}
232
233fn is_false(value: &bool) -> bool {
234    !*value
235}
236
237/// One `NAME = number` entry in an enum.
238#[derive(Debug, Clone, PartialEq, Serialize)]
239pub struct EnumValueDescriptorProto {
240    pub name: String,
241    #[serde(serialize_with = "json_number")]
242    pub number: f64,
243    #[serde(skip_serializing_if = "Option::is_none")]
244    pub options: Option<Options>,
245}
246
247/// An enum definition.
248#[derive(Debug, Clone, PartialEq, Serialize)]
249#[serde(rename_all = "camelCase")]
250pub struct EnumDescriptorProto {
251    pub name: String,
252    pub value: Vec<EnumValueDescriptorProto>,
253    #[serde(skip_serializing_if = "Option::is_none")]
254    pub reserved_range: Option<Vec<DescriptorRange>>,
255    #[serde(skip_serializing_if = "Option::is_none")]
256    pub reserved_name: Option<Vec<String>>,
257    #[serde(skip_serializing_if = "Option::is_none")]
258    pub visibility: Option<SymbolVisibility>,
259    #[serde(skip_serializing_if = "Option::is_none")]
260    pub options: Option<Options>,
261}
262
263impl EnumDescriptorProto {
264    /// An empty enum with the given name.
265    pub fn new(name: impl Into<String>) -> Self {
266        EnumDescriptorProto {
267            name: name.into(),
268            value: Vec::new(),
269            reserved_range: None,
270            reserved_name: None,
271            visibility: None,
272            options: None,
273        }
274    }
275}
276
277/// A oneof declaration.
278#[derive(Debug, Clone, PartialEq, Serialize)]
279pub struct OneofDescriptorProto {
280    pub name: String,
281    #[serde(skip_serializing_if = "Option::is_none")]
282    pub options: Option<Options>,
283}
284
285/// A message type.
286#[derive(Debug, Clone, PartialEq, Serialize)]
287#[serde(rename_all = "camelCase")]
288pub struct DescriptorProto {
289    pub name: String,
290    pub field: Vec<FieldDescriptorProto>,
291    pub nested_type: Vec<DescriptorProto>,
292    pub enum_type: Vec<EnumDescriptorProto>,
293    pub oneof_decl: Vec<OneofDescriptorProto>,
294    pub extension: Vec<FieldDescriptorProto>,
295    #[serde(skip_serializing_if = "Option::is_none")]
296    pub extension_range: Option<Vec<DescriptorRange>>,
297    #[serde(skip_serializing_if = "Option::is_none")]
298    pub reserved_range: Option<Vec<DescriptorRange>>,
299    #[serde(skip_serializing_if = "Option::is_none")]
300    pub reserved_name: Option<Vec<String>>,
301    #[serde(skip_serializing_if = "Option::is_none")]
302    pub visibility: Option<SymbolVisibility>,
303    #[serde(skip_serializing_if = "Option::is_none")]
304    pub options: Option<Options>,
305}
306
307impl DescriptorProto {
308    /// An empty message with the given name.
309    pub fn new(name: impl Into<String>) -> Self {
310        DescriptorProto {
311            name: name.into(),
312            field: Vec::new(),
313            nested_type: Vec::new(),
314            enum_type: Vec::new(),
315            oneof_decl: Vec::new(),
316            extension: Vec::new(),
317            extension_range: None,
318            reserved_range: None,
319            reserved_name: None,
320            visibility: None,
321            options: None,
322        }
323    }
324}
325
326/// One rpc in a service.
327#[derive(Debug, Clone, PartialEq, Serialize)]
328#[serde(rename_all = "camelCase")]
329pub struct MethodDescriptorProto {
330    pub name: String,
331    pub input_type: String,
332    pub output_type: String,
333    #[serde(skip_serializing_if = "is_false")]
334    pub client_streaming: bool,
335    #[serde(skip_serializing_if = "is_false")]
336    pub server_streaming: bool,
337    #[serde(skip_serializing_if = "Option::is_none")]
338    pub options: Option<Options>,
339}
340
341/// A service definition.
342#[derive(Debug, Clone, PartialEq, Serialize)]
343pub struct ServiceDescriptorProto {
344    pub name: String,
345    pub method: Vec<MethodDescriptorProto>,
346    #[serde(skip_serializing_if = "Option::is_none")]
347    pub options: Option<Options>,
348}
349
350/// The root descriptor for one parsed `.proto` file.
351#[derive(Debug, Clone, PartialEq, Serialize, Default)]
352#[serde(rename_all = "camelCase")]
353pub struct FileDescriptorProto {
354    /// Not present in source; callers may set it.
355    #[serde(skip_serializing_if = "Option::is_none")]
356    pub name: Option<String>,
357    #[serde(skip_serializing_if = "Option::is_none")]
358    pub package: Option<String>,
359    pub dependency: Vec<String>,
360    pub public_dependency: Vec<usize>,
361    pub weak_dependency: Vec<usize>,
362    /// `import option "..."` targets (edition 2024), when used.
363    #[serde(skip_serializing_if = "Option::is_none")]
364    pub option_dependency: Option<Vec<String>>,
365    pub message_type: Vec<DescriptorProto>,
366    pub enum_type: Vec<EnumDescriptorProto>,
367    pub service: Vec<ServiceDescriptorProto>,
368    pub extension: Vec<FieldDescriptorProto>,
369    #[serde(skip_serializing_if = "Option::is_none")]
370    pub options: Option<Options>,
371    /// `proto2` or `proto3` for syntax files; `editions` for edition
372    /// files.
373    #[serde(skip_serializing_if = "Option::is_none")]
374    pub syntax: Option<String>,
375    /// `EDITION_2023` or `EDITION_2024` for edition files, absent
376    /// otherwise.
377    #[serde(skip_serializing_if = "Option::is_none")]
378    pub edition: Option<String>,
379}
380
381/// protoc's sentinel for `to max` in a message range. Field numbers stop
382/// at 2^29-1, so an exclusive `end` is 2^29.
383pub const MAX_FIELD_NUMBER_END: f64 = 536_870_912.0;
384/// protoc's sentinel for `to max` in a `message_set_wire_format` message,
385/// which may use the full 32-bit space.
386pub const MAX_MESSAGE_SET_END: f64 = 2_147_483_647.0;
387/// protoc's sentinel for `to max` in an enum reserved range. Enum numbers
388/// are plain int32 and enum reserved ranges are inclusive.
389pub const MAX_ENUM_NUMBER: f64 = 2_147_483_647.0;
390
391/// Scalar protobuf types and their `FieldDescriptorProto` type, in the
392/// order `ts/src/descriptor.ts` declares them. A field whose type is not
393/// here is a message, enum or group reference (resolution deferred) and
394/// gets a `type_name` instead.
395pub const SCALAR_TYPES: &[(&str, FieldType)] = &[
396    ("double", FieldType::Double),
397    ("float", FieldType::Float),
398    ("int32", FieldType::Int32),
399    ("int64", FieldType::Int64),
400    ("uint32", FieldType::Uint32),
401    ("uint64", FieldType::Uint64),
402    ("sint32", FieldType::Sint32),
403    ("sint64", FieldType::Sint64),
404    ("fixed32", FieldType::Fixed32),
405    ("fixed64", FieldType::Fixed64),
406    ("sfixed32", FieldType::Sfixed32),
407    ("sfixed64", FieldType::Sfixed64),
408    ("bool", FieldType::Bool),
409    ("string", FieldType::String),
410    ("bytes", FieldType::Bytes),
411];
412
413/// The scalar type a bare type name names, or `None` for a reference the
414/// parser leaves unresolved.
415pub fn scalar_type(name: &str) -> Option<FieldType> {
416    SCALAR_TYPES
417        .iter()
418        .find(|(scalar, _)| *scalar == name)
419        .map(|(_, field_type)| *field_type)
420}