Skip to main content

tonneau_build/
types.rs

1use std::collections::BTreeMap;
2use std::fmt::Write;
3use std::sync::Arc;
4
5use indexmap::IndexMap;
6use tonneau_pb_prost::http_endpoint_options;
7
8use crate::codegen::cel::{CelExpression, CelExpressions};
9use crate::codegen::utils::{field_ident_from_str, get_common_import_path, type_ident_from_str};
10use crate::path_set::PathSet;
11use crate::{ExternPaths, Mode};
12
13#[derive(Debug, Clone, PartialEq)]
14pub(crate) enum ProtoType {
15    Value(ProtoValueType),
16    Modified(ProtoModifiedValueType),
17}
18
19impl ProtoType {
20    pub(crate) fn value_type(&self) -> Option<&ProtoValueType> {
21        match self {
22            Self::Value(value) => Some(value),
23            Self::Modified(modified) => modified.value_type(),
24        }
25    }
26
27    pub(crate) fn nested(&self) -> bool {
28        matches!(
29            self,
30            Self::Modified(ProtoModifiedValueType::Map(_, _) | ProtoModifiedValueType::Repeated(_))
31        )
32    }
33}
34
35#[derive(Debug, Clone, PartialEq)]
36pub(crate) enum ProtoValueType {
37    String,
38    Bytes,
39    Int32,
40    Int64,
41    UInt32,
42    UInt64,
43    Float,
44    Double,
45    Bool,
46    WellKnown(ProtoWellKnownType),
47    Message(ProtoPath),
48    Enum(ProtoPath),
49}
50
51#[derive(Debug, Clone, PartialEq)]
52pub(crate) enum ProtoWellKnownType {
53    Timestamp,
54    Duration,
55    Struct,
56    Value,
57    Empty,
58    ListValue,
59    Any,
60}
61
62impl ProtoValueType {
63    #[cfg(feature = "prost")]
64    pub(crate) fn from_pb(ty: &prost_reflect::Kind) -> Self {
65        match ty {
66            prost_reflect::Kind::Double => ProtoValueType::Double,
67            prost_reflect::Kind::Float => ProtoValueType::Float,
68            prost_reflect::Kind::Int32 => ProtoValueType::Int32,
69            prost_reflect::Kind::Int64 => ProtoValueType::Int64,
70            prost_reflect::Kind::Uint32 => ProtoValueType::UInt32,
71            prost_reflect::Kind::Uint64 => ProtoValueType::UInt64,
72            prost_reflect::Kind::Sint32 => ProtoValueType::Int32,
73            prost_reflect::Kind::Sint64 => ProtoValueType::Int64,
74            prost_reflect::Kind::Fixed32 => ProtoValueType::Float,
75            prost_reflect::Kind::Fixed64 => ProtoValueType::Double,
76            prost_reflect::Kind::Sfixed32 => ProtoValueType::Float,
77            prost_reflect::Kind::Sfixed64 => ProtoValueType::Double,
78            prost_reflect::Kind::Bool => ProtoValueType::Bool,
79            prost_reflect::Kind::String => ProtoValueType::String,
80            prost_reflect::Kind::Bytes => ProtoValueType::Bytes,
81            prost_reflect::Kind::Message(message) => {
82                ProtoValueType::from_proto_path(message.full_name())
83            }
84            prost_reflect::Kind::Enum(enum_) => {
85                ProtoValueType::Enum(ProtoPath::new(enum_.full_name()))
86            }
87        }
88    }
89
90    pub(crate) fn from_proto_path(path: &str) -> Self {
91        match path {
92            "google.protobuf.Timestamp" => ProtoValueType::WellKnown(ProtoWellKnownType::Timestamp),
93            "google.protobuf.Duration" => ProtoValueType::WellKnown(ProtoWellKnownType::Duration),
94            "google.protobuf.Struct" => ProtoValueType::WellKnown(ProtoWellKnownType::Struct),
95            "google.protobuf.Value" => ProtoValueType::WellKnown(ProtoWellKnownType::Value),
96            "google.protobuf.Empty" => ProtoValueType::WellKnown(ProtoWellKnownType::Empty),
97            "google.protobuf.ListValue" => ProtoValueType::WellKnown(ProtoWellKnownType::ListValue),
98            "google.protobuf.Any" => ProtoValueType::WellKnown(ProtoWellKnownType::Any),
99            "google.protobuf.BoolValue" => ProtoValueType::Bool,
100            "google.protobuf.Int32Value" => ProtoValueType::Int32,
101            "google.protobuf.Int64Value" => ProtoValueType::Int64,
102            "google.protobuf.UInt32Value" => ProtoValueType::UInt32,
103            "google.protobuf.UInt64Value" => ProtoValueType::UInt64,
104            "google.protobuf.FloatValue" => ProtoValueType::Float,
105            "google.protobuf.DoubleValue" => ProtoValueType::Double,
106            "google.protobuf.StringValue" => ProtoValueType::String,
107            "google.protobuf.BytesValue" => ProtoValueType::Bytes,
108            _ => ProtoValueType::Message(ProtoPath::new(path)),
109        }
110    }
111
112    pub(crate) fn proto_path(&self) -> &str {
113        match self {
114            ProtoValueType::WellKnown(ProtoWellKnownType::Timestamp) => "google.protobuf.Timestamp",
115            ProtoValueType::WellKnown(ProtoWellKnownType::Duration) => "google.protobuf.Duration",
116            ProtoValueType::WellKnown(ProtoWellKnownType::Struct) => "google.protobuf.Struct",
117            ProtoValueType::WellKnown(ProtoWellKnownType::Value) => "google.protobuf.Value",
118            ProtoValueType::WellKnown(ProtoWellKnownType::Empty) => "google.protobuf.Empty",
119            ProtoValueType::WellKnown(ProtoWellKnownType::ListValue) => "google.protobuf.ListValue",
120            ProtoValueType::WellKnown(ProtoWellKnownType::Any) => "google.protobuf.Any",
121            ProtoValueType::Bool => "google.protobuf.BoolValue",
122            ProtoValueType::Int32 => "google.protobuf.Int32Value",
123            ProtoValueType::Int64 => "google.protobuf.Int64Value",
124            ProtoValueType::UInt32 => "google.protobuf.UInt32Value",
125            ProtoValueType::UInt64 => "google.protobuf.UInt64Value",
126            ProtoValueType::Float => "google.protobuf.FloatValue",
127            ProtoValueType::Double => "google.protobuf.DoubleValue",
128            ProtoValueType::String => "google.protobuf.StringValue",
129            ProtoValueType::Bytes => "google.protobuf.BytesValue",
130            ProtoValueType::Enum(path) | ProtoValueType::Message(path) => path.as_ref(),
131        }
132    }
133}
134
135#[derive(Debug, Clone, PartialEq)]
136pub(crate) struct ProtoEnumType {
137    pub package: ProtoPath,
138    pub full_name: ProtoPath,
139    pub comments: Comments,
140    pub options: ProtoEnumOptions,
141    pub variants: IndexMap<String, ProtoEnumVariant>,
142}
143
144impl ProtoEnumType {
145    fn rust_path(&self, package: &str) -> syn::Path {
146        get_common_import_path(package, &self.full_name)
147    }
148}
149
150#[derive(Debug, Clone, PartialEq)]
151pub(crate) struct ProtoEnumOptions {
152    pub repr_enum: bool,
153}
154
155#[derive(Debug, Clone, PartialEq)]
156pub(crate) struct ProtoEnumVariant {
157    pub full_name: ProtoPath,
158    pub comments: Comments,
159    pub options: ProtoEnumVariantOptions,
160    pub rust_ident: syn::Ident,
161    pub value: i32,
162}
163
164#[derive(Debug, Clone, PartialEq)]
165pub(crate) struct ProtoEnumVariantOptions {
166    pub serde_name: String,
167    pub visibility: ProtoVisibility,
168}
169
170#[derive(Debug, Clone, PartialEq)]
171pub(crate) enum ProtoModifiedValueType {
172    Repeated(ProtoValueType),
173    Map(ProtoValueType, ProtoValueType),
174    Optional(ProtoValueType),
175    OneOf(ProtoOneOfType),
176}
177
178impl ProtoModifiedValueType {
179    pub(crate) fn value_type(&self) -> Option<&ProtoValueType> {
180        match self {
181            Self::Repeated(v) => Some(v),
182            Self::Map(_, v) => Some(v),
183            Self::Optional(v) => Some(v),
184            _ => None,
185        }
186    }
187}
188
189#[derive(Debug, Clone, PartialEq)]
190pub(crate) struct ProtoMessageType {
191    pub package: ProtoPath,
192    pub full_name: ProtoPath,
193    pub comments: Comments,
194    pub options: ProtoMessageOptions,
195    pub fields: IndexMap<String, ProtoMessageField>,
196}
197
198impl ProtoMessageType {
199    fn rust_path(&self, package: &str) -> syn::Path {
200        get_common_import_path(package, &self.full_name)
201    }
202}
203
204#[derive(Debug, Clone, PartialEq, Default)]
205pub(crate) struct ProtoMessageOptions {
206    pub cel: Vec<CelExpression>,
207}
208
209#[derive(Debug, Clone, PartialEq)]
210pub(crate) struct ProtoMessageField {
211    pub full_name: ProtoPath,
212    pub message: ProtoPath,
213    pub ty: ProtoType,
214    pub comments: Comments,
215    pub options: ProtoFieldOptions,
216}
217
218impl ProtoMessageField {
219    pub(crate) fn rust_ident(&self) -> syn::Ident {
220        field_ident_from_str(self.full_name.split('.').next_back().unwrap())
221    }
222}
223
224#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
225pub(crate) enum ProtoFieldSerdeOmittable {
226    True,
227    False,
228    TrueButStillSerialize,
229}
230
231impl ProtoFieldSerdeOmittable {
232    pub(crate) fn is_true(&self) -> bool {
233        matches!(self, Self::True | Self::TrueButStillSerialize)
234    }
235}
236
237#[derive(Debug, Clone, Copy, PartialEq)]
238pub(crate) enum ProtoVisibility {
239    Default,
240    Skip,
241    InputOnly,
242    OutputOnly,
243}
244
245impl ProtoVisibility {
246    pub(crate) fn from_pb(visibility: tonneau_pb_prost::Visibility) -> Self {
247        match visibility {
248            tonneau_pb_prost::Visibility::Skip => ProtoVisibility::Skip,
249            tonneau_pb_prost::Visibility::InputOnly => ProtoVisibility::InputOnly,
250            tonneau_pb_prost::Visibility::OutputOnly => ProtoVisibility::OutputOnly,
251            tonneau_pb_prost::Visibility::Unspecified => ProtoVisibility::Default,
252        }
253    }
254
255    pub(crate) fn has_output(&self) -> bool {
256        matches!(self, ProtoVisibility::OutputOnly | ProtoVisibility::Default)
257    }
258
259    pub(crate) fn has_input(&self) -> bool {
260        matches!(self, ProtoVisibility::InputOnly | ProtoVisibility::Default)
261    }
262}
263
264#[derive(Debug, Clone, PartialEq)]
265pub(crate) struct ProtoFieldOptions {
266    pub serde_name: String,
267    pub serde_omittable: ProtoFieldSerdeOmittable,
268    pub nullable: bool,
269    pub flatten: bool,
270    pub visibility: ProtoVisibility,
271    pub cel_exprs: CelExpressions,
272}
273
274#[derive(Debug, Clone, PartialEq)]
275pub(crate) struct ProtoOneOfType {
276    pub full_name: ProtoPath,
277    pub message: ProtoPath,
278    pub options: ProtoOneOfOptions,
279    pub fields: IndexMap<String, ProtoOneOfField>,
280}
281
282impl ProtoOneOfType {
283    pub(crate) fn rust_path(&self, package: &str) -> syn::Path {
284        get_common_import_path(package, &self.full_name)
285    }
286}
287
288#[derive(Debug, Clone, PartialEq)]
289pub(crate) struct ProtoOneOfOptions {
290    pub tagged: Option<Tagged>,
291}
292
293#[derive(Debug, Clone, PartialEq)]
294pub(crate) struct Tagged {
295    pub tag: String,
296    pub content: String,
297}
298
299#[derive(Debug, Clone, PartialEq)]
300pub(crate) struct ProtoOneOfField {
301    pub full_name: ProtoPath,
302    pub message: ProtoPath,
303    pub comments: Comments,
304    pub ty: ProtoValueType,
305    pub options: ProtoFieldOptions,
306}
307
308impl ProtoOneOfField {
309    pub(crate) fn rust_ident(&self) -> syn::Ident {
310        type_ident_from_str(self.full_name.split('.').next_back().unwrap())
311    }
312}
313
314#[derive(Debug, Clone, PartialEq, PartialOrd, Ord, Eq, Hash)]
315pub(crate) struct ProtoPath(pub Arc<str>);
316
317impl ProtoPath {
318    pub(crate) fn trim_last_segment(&self) -> &str {
319        // remove the last .<segment> from the path
320        let (item, _) = self.0.rsplit_once('.').unwrap_or_default();
321        item
322    }
323}
324
325impl std::ops::Deref for ProtoPath {
326    type Target = str;
327
328    fn deref(&self) -> &Self::Target {
329        &self.0
330    }
331}
332
333impl AsRef<str> for ProtoPath {
334    fn as_ref(&self) -> &str {
335        &self.0
336    }
337}
338
339impl ProtoPath {
340    pub(crate) fn new(absolute: impl std::fmt::Display) -> Self {
341        Self(absolute.to_string().into())
342    }
343}
344
345impl PartialEq<&str> for ProtoPath {
346    fn eq(&self, other: &&str) -> bool {
347        &*self.0 == *other
348    }
349}
350
351impl PartialEq<str> for ProtoPath {
352    fn eq(&self, other: &str) -> bool {
353        &*self.0 == other
354    }
355}
356
357impl std::borrow::Borrow<str> for ProtoPath {
358    fn borrow(&self) -> &str {
359        &self.0
360    }
361}
362
363impl std::fmt::Display for ProtoPath {
364    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
365        f.write_str(&self.0)
366    }
367}
368
369#[derive(Debug, Clone, PartialEq)]
370pub(crate) struct ProtoService {
371    pub full_name: ProtoPath,
372    pub package: ProtoPath,
373    pub comments: Comments,
374    pub options: ProtoServiceOptions,
375    pub methods: IndexMap<String, ProtoServiceMethod>,
376}
377
378#[derive(Debug, Clone, PartialEq)]
379pub(crate) struct ProtoServiceOptions {
380    pub prefix: Option<String>,
381}
382
383#[derive(Debug, Clone, PartialEq)]
384pub(crate) enum ProtoServiceMethodIo {
385    Single(ProtoValueType),
386    Stream(ProtoValueType),
387}
388
389impl ProtoServiceMethodIo {
390    pub(crate) fn is_stream(&self) -> bool {
391        matches!(self, ProtoServiceMethodIo::Stream(_))
392    }
393
394    pub(crate) fn value_type(&self) -> &ProtoValueType {
395        match self {
396            ProtoServiceMethodIo::Single(ty) => ty,
397            ProtoServiceMethodIo::Stream(ty) => ty,
398        }
399    }
400}
401
402#[derive(Debug, Clone, PartialEq)]
403pub(crate) struct ProtoServiceMethod {
404    pub full_name: ProtoPath,
405    pub service: ProtoPath,
406    pub comments: Comments,
407    pub input: ProtoServiceMethodIo,
408    pub output: ProtoServiceMethodIo,
409    pub endpoints: Vec<ProtoServiceMethodEndpoint>,
410    pub cel: Vec<CelExpression>,
411}
412
413#[derive(Debug, Clone, PartialEq, Default)]
414pub(crate) struct Comments {
415    pub leading: Option<Arc<str>>,
416    pub detached: Arc<[Arc<str>]>,
417    pub trailing: Option<Arc<str>>,
418}
419
420impl Comments {
421    pub(crate) fn is_empty(&self) -> bool {
422        self.leading.is_none() && self.detached.is_empty() && self.trailing.is_none()
423    }
424}
425
426impl std::fmt::Display for Comments {
427    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
428        let mut newline = false;
429        if let Some(leading) = self.leading.as_ref() {
430            leading.trim().fmt(f)?;
431            newline = true;
432        }
433
434        for detached in self.detached.iter() {
435            if newline {
436                f.write_char('\n')?;
437            }
438            newline = true;
439            detached.trim().fmt(f)?;
440        }
441
442        if let Some(detached) = self.trailing.as_ref() {
443            if newline {
444                f.write_char('\n')?;
445            }
446            detached.trim().fmt(f)?;
447        }
448
449        Ok(())
450    }
451}
452
453#[derive(Debug, Clone, PartialEq)]
454pub(crate) struct ProtoServiceMethodEndpoint {
455    pub method: http_endpoint_options::Method,
456    pub request: Option<http_endpoint_options::Request>,
457    pub response: Option<http_endpoint_options::Response>,
458}
459
460#[derive(Debug, Clone)]
461pub(crate) struct ProtoTypeRegistry {
462    messages: BTreeMap<ProtoPath, ProtoMessageType>,
463    enums: BTreeMap<ProtoPath, ProtoEnumType>,
464    services: BTreeMap<ProtoPath, ProtoService>,
465    extern_paths: ExternPaths,
466    floats_with_non_finite_vals: PathSet,
467    _mode: Mode,
468}
469
470impl ProtoTypeRegistry {
471    pub(crate) fn new(
472        mode: Mode,
473        extern_paths: ExternPaths,
474        floats_with_non_finite_vals: PathSet,
475    ) -> Self {
476        Self {
477            messages: BTreeMap::new(),
478            enums: BTreeMap::new(),
479            services: BTreeMap::new(),
480            extern_paths,
481            floats_with_non_finite_vals,
482            _mode: mode,
483        }
484    }
485
486    pub(crate) fn register_message(&mut self, message: ProtoMessageType) {
487        self.messages.insert(message.full_name.clone(), message);
488    }
489
490    pub(crate) fn register_enum(&mut self, enum_: ProtoEnumType) {
491        self.enums.insert(enum_.full_name.clone(), enum_);
492    }
493
494    pub(crate) fn register_service(&mut self, service: ProtoService) {
495        self.services.insert(service.full_name.clone(), service);
496    }
497
498    pub(crate) fn get_message(&self, full_name: &str) -> Option<&ProtoMessageType> {
499        self.messages.get(full_name)
500    }
501
502    pub(crate) fn get_enum(&self, full_name: &str) -> Option<&ProtoEnumType> {
503        self.enums.get(full_name)
504    }
505
506    pub(crate) fn get_service(&self, full_name: &str) -> Option<&ProtoService> {
507        self.services.get(full_name)
508    }
509
510    pub(crate) fn messages(&self) -> impl Iterator<Item = &ProtoMessageType> {
511        self.messages.values()
512    }
513
514    pub(crate) fn enums(&self) -> impl Iterator<Item = &ProtoEnumType> {
515        self.enums.values()
516    }
517
518    pub(crate) fn services(&self) -> impl Iterator<Item = &ProtoService> {
519        self.services.values()
520    }
521
522    pub(crate) fn resolve_rust_path(&self, package: &str, path: &str) -> Option<syn::Path> {
523        self.extern_paths
524            .resolve(path)
525            .or_else(|| Some(self.enums.get(path)?.rust_path(package)))
526            .or_else(|| Some(self.messages.get(path)?.rust_path(package)))
527    }
528
529    pub(crate) fn has_extern(&self, path: &str) -> bool {
530        self.extern_paths.contains(path)
531    }
532
533    pub(crate) fn support_non_finite_vals(&self, path: &ProtoPath) -> bool {
534        self.floats_with_non_finite_vals.contains(path)
535    }
536}