1use std::collections::BTreeMap;
2
3use anyhow::Context;
4use convert_case::{Case, Casing};
5use indexmap::IndexMap;
6use prost_reflect::prost_types::source_code_info::Location;
7use prost_reflect::{
8 DescriptorPool, EnumDescriptor, ExtensionDescriptor, FileDescriptor, Kind, MessageDescriptor,
9 ServiceDescriptor,
10};
11use quote::format_ident;
12use tonneau_cel::{CelEnum, CelValueConv};
13
14use crate::codegen::cel::{CelExpression, CelExpressions};
15use crate::codegen::prost_sanatize::{strip_enum_prefix, to_upper_camel};
16use crate::types::{
17 Comments, ProtoEnumOptions, ProtoEnumType, ProtoEnumVariant, ProtoEnumVariantOptions,
18 ProtoFieldOptions, ProtoFieldSerdeOmittable, ProtoMessageField, ProtoMessageOptions,
19 ProtoMessageType, ProtoModifiedValueType, ProtoOneOfField, ProtoOneOfOptions, ProtoOneOfType,
20 ProtoPath, ProtoService, ProtoServiceMethod, ProtoServiceMethodEndpoint, ProtoServiceMethodIo,
21 ProtoServiceOptions, ProtoType, ProtoTypeRegistry, ProtoValueType, ProtoVisibility, Tagged,
22};
23
24pub(crate) struct Extension<T> {
25 name: &'static str,
26 descriptor: Option<ExtensionDescriptor>,
27 _marker: std::marker::PhantomData<T>,
28}
29
30impl<T> Extension<T> {
31 fn new(name: &'static str, pool: &DescriptorPool) -> Self {
32 Self {
33 name,
34 descriptor: pool.get_extension_by_name(name),
35 _marker: std::marker::PhantomData,
36 }
37 }
38
39 fn descriptor(&self) -> Option<&ExtensionDescriptor> {
40 self.descriptor.as_ref()
41 }
42
43 fn decode(&self, incoming: &T::Incoming) -> anyhow::Result<Option<T>>
44 where
45 T: ProstExtension,
46 {
47 let mut messages = self.decode_all(incoming)?;
48 Ok(if messages.is_empty() {
49 None
50 } else {
51 Some(messages.swap_remove(0))
52 })
53 }
54
55 fn decode_all(&self, incoming: &T::Incoming) -> anyhow::Result<Vec<T>>
56 where
57 T: ProstExtension,
58 {
59 let extension = match &self.descriptor {
60 Some(ext) => ext,
61 None => return Ok(Vec::new()),
62 };
63
64 let descriptor = match T::get_options(incoming) {
65 Some(desc) => desc,
66 None => return Ok(Vec::new()),
67 };
68
69 let message = descriptor.get_extension(extension);
70 match message.as_ref() {
71 prost_reflect::Value::Message(message) => {
72 if message.fields().next().is_some() {
73 let message = message.transcode_to::<T>().with_context(|| {
74 format!(
75 "{} is not a valid {}",
76 self.name,
77 std::any::type_name::<T>()
78 )
79 })?;
80 Ok(vec![message])
81 } else {
82 Ok(Vec::new())
83 }
84 }
85 prost_reflect::Value::List(list) => list
86 .iter()
87 .map(|value| {
88 let message = value.as_message().context("expected a message")?;
89 message.transcode_to::<T>().context("transcoding failed")
90 })
91 .collect(),
92 _ => anyhow::bail!("expected a message or list of messages"),
93 }
94 }
95}
96
97trait ProstExtension: prost::Message + Default {
98 type Incoming;
99 fn get_options(incoming: &Self::Incoming) -> Option<prost_reflect::DynamicMessage>;
100}
101
102impl ProstExtension for tonneau_pb_prost::MessageOptions {
103 type Incoming = prost_reflect::MessageDescriptor;
104
105 fn get_options(incoming: &Self::Incoming) -> Option<prost_reflect::DynamicMessage> {
106 Some(incoming.options())
107 }
108}
109
110impl ProstExtension for tonneau_pb_prost::FieldOptions {
111 type Incoming = prost_reflect::FieldDescriptor;
112
113 fn get_options(incoming: &Self::Incoming) -> Option<prost_reflect::DynamicMessage> {
114 Some(incoming.options())
115 }
116}
117
118impl ProstExtension for tonneau_pb_prost::PredefinedConstraints {
119 type Incoming = prost_reflect::FieldDescriptor;
120
121 fn get_options(incoming: &Self::Incoming) -> Option<prost_reflect::DynamicMessage> {
122 Some(incoming.options())
123 }
124}
125
126impl ProstExtension for tonneau_pb_prost::EnumOptions {
127 type Incoming = prost_reflect::EnumDescriptor;
128
129 fn get_options(incoming: &Self::Incoming) -> Option<prost_reflect::DynamicMessage> {
130 Some(incoming.options())
131 }
132}
133
134impl ProstExtension for tonneau_pb_prost::EnumVariantOptions {
135 type Incoming = prost_reflect::EnumValueDescriptor;
136
137 fn get_options(incoming: &Self::Incoming) -> Option<prost_reflect::DynamicMessage> {
138 Some(incoming.options())
139 }
140}
141
142impl ProstExtension for tonneau_pb_prost::MethodOptions {
143 type Incoming = prost_reflect::MethodDescriptor;
144
145 fn get_options(incoming: &Self::Incoming) -> Option<prost_reflect::DynamicMessage> {
146 Some(incoming.options())
147 }
148}
149
150impl ProstExtension for tonneau_pb_prost::ServiceOptions {
151 type Incoming = prost_reflect::ServiceDescriptor;
152
153 fn get_options(incoming: &Self::Incoming) -> Option<prost_reflect::DynamicMessage> {
154 Some(incoming.options())
155 }
156}
157
158impl ProstExtension for tonneau_pb_prost::OneofOptions {
159 type Incoming = prost_reflect::OneofDescriptor;
160
161 fn get_options(incoming: &Self::Incoming) -> Option<prost_reflect::DynamicMessage> {
162 Some(incoming.options())
163 }
164}
165
166fn rename_field(field: &str, style: tonneau_pb_prost::RenameAll) -> Option<String> {
167 match style {
168 tonneau_pb_prost::RenameAll::LowerCase => Some(field.to_lowercase()),
169 tonneau_pb_prost::RenameAll::UpperCase => Some(field.to_uppercase()),
170 tonneau_pb_prost::RenameAll::PascalCase => Some(field.to_case(Case::Pascal)),
171 tonneau_pb_prost::RenameAll::CamelCase => Some(field.to_case(Case::Camel)),
172 tonneau_pb_prost::RenameAll::SnakeCase => Some(field.to_case(Case::Snake)),
173 tonneau_pb_prost::RenameAll::KebabCase => Some(field.to_case(Case::Kebab)),
174 tonneau_pb_prost::RenameAll::ScreamingSnakeCase => Some(field.to_case(Case::UpperSnake)),
175 tonneau_pb_prost::RenameAll::ScreamingKebabCase => Some(field.to_case(Case::UpperKebab)),
176 tonneau_pb_prost::RenameAll::Unspecified => None,
177 }
178}
179
180pub(crate) struct Extensions<'a> {
181 pool: &'a DescriptorPool,
182 ext_message: Extension<tonneau_pb_prost::MessageOptions>,
184 ext_field: Extension<tonneau_pb_prost::FieldOptions>,
185 ext_oneof: Extension<tonneau_pb_prost::OneofOptions>,
186 ext_predefined: Extension<tonneau_pb_prost::PredefinedConstraints>,
187
188 ext_enum: Extension<tonneau_pb_prost::EnumOptions>,
190 ext_variant: Extension<tonneau_pb_prost::EnumVariantOptions>,
191
192 ext_method: Extension<tonneau_pb_prost::MethodOptions>,
194 ext_service: Extension<tonneau_pb_prost::ServiceOptions>,
195}
196
197impl<'a> Extensions<'a> {
198 pub(crate) fn new(pool: &'a DescriptorPool) -> Self {
199 Self {
200 pool,
201 ext_message: Extension::new("tonneau.message", pool),
202 ext_field: Extension::new("tonneau.field", pool),
203 ext_predefined: Extension::new("tonneau.predefined", pool),
204 ext_enum: Extension::new("tonneau.enum", pool),
205 ext_variant: Extension::new("tonneau.variant", pool),
206 ext_method: Extension::new("tonneau.method", pool),
207 ext_service: Extension::new("tonneau.service", pool),
208 ext_oneof: Extension::new("tonneau.oneof", pool),
209 }
210 }
211
212 pub(crate) fn process(&self, registry: &mut ProtoTypeRegistry) -> anyhow::Result<()> {
213 self.pool
214 .files()
215 .map(|file| FileWalker::new(file, self))
216 .try_for_each(|file| {
217 anyhow::ensure!(
218 !file.file.package_name().is_empty(),
219 "you must provide a proto package for file: {}",
220 file.file.name()
221 );
222
223 file.process(registry)
224 })
225 }
226}
227
228struct FileWalker<'a> {
229 file: FileDescriptor,
230 extensions: &'a Extensions<'a>,
231 locations: Vec<Location>,
232}
233
234impl<'a> FileWalker<'a> {
235 fn new(file: FileDescriptor, extensions: &'a Extensions) -> Self {
236 Self {
237 extensions,
238 locations: file
239 .file_descriptor_proto()
240 .source_code_info
241 .clone()
242 .map(|mut si| {
243 si.location.retain(|l| {
244 let len = l.path.len();
245 len > 0 && len.is_multiple_of(2)
246 });
247
248 si.location.sort_by(|a, b| a.path.cmp(&b.path));
249
250 si.location
251 })
252 .unwrap_or_default(),
253 file,
254 }
255 }
256
257 fn location(&self, path: &[i32]) -> Option<&Location> {
258 let idx = self
259 .locations
260 .binary_search_by_key(&path, |location| location.path.as_slice())
261 .ok()?;
262 Some(&self.locations[idx])
263 }
264
265 fn process(&self, registry: &mut ProtoTypeRegistry) -> anyhow::Result<()> {
266 for message in self.file.messages() {
267 self.process_message(&message, registry)
269 .with_context(|| format!("message {}", message.full_name()))?;
270 }
271
272 for enum_ in self.file.enums() {
273 self.process_enum(&enum_, registry)
275 .with_context(|| format!("enum {}", enum_.full_name()))?;
276 }
277
278 for service in self.file.services() {
279 self.process_service(&service, registry)
281 .with_context(|| format!("service {}", service.full_name()))?;
282 }
283
284 Ok(())
285 }
286
287 fn process_service(
288 &self,
289 service: &ServiceDescriptor,
290 registry: &mut ProtoTypeRegistry,
291 ) -> anyhow::Result<()> {
292 if registry.get_service(service.full_name()).is_some() {
293 return Ok(());
294 }
295
296 let mut methods = IndexMap::new();
297
298 let opts = self
299 .extensions
300 .ext_service
301 .decode(service)?
302 .unwrap_or_default();
303 let service_full_name = ProtoPath::new(service.full_name());
304
305 for method in service.methods() {
306 let input = method.input();
307 let output = method.output();
308
309 let method_input = ProtoValueType::from_proto_path(input.full_name());
310 let method_output = ProtoValueType::from_proto_path(output.full_name());
311
312 let opts = self
313 .extensions
314 .ext_method
315 .decode(&method)
316 .with_context(|| format!("method {}", method.full_name()))?
317 .unwrap_or_default();
318
319 let mut endpoints = Vec::new();
320 for endpoint in opts.endpoint {
321 let Some(method) = endpoint.method else {
322 continue;
323 };
324
325 endpoints.push(ProtoServiceMethodEndpoint {
326 method,
327 request: endpoint.request,
328 response: endpoint.response,
329 });
330 }
331
332 methods.insert(
333 method.name().to_owned(),
334 ProtoServiceMethod {
335 full_name: ProtoPath::new(method.full_name()),
336 service: service_full_name.clone(),
337 comments: self
338 .location(method.path())
339 .map(location_to_comments)
340 .unwrap_or_default(),
341 input: if method.is_client_streaming() {
342 ProtoServiceMethodIo::Stream(method_input)
343 } else {
344 ProtoServiceMethodIo::Single(method_input)
345 },
346 output: if method.is_server_streaming() {
347 ProtoServiceMethodIo::Stream(method_output)
348 } else {
349 ProtoServiceMethodIo::Single(method_output)
350 },
351 endpoints,
352 cel: opts
353 .cel
354 .into_iter()
355 .map(|expr| CelExpression {
356 expression: expr.expression,
357 jsonschemas: expr.jsonschemas,
358 message: expr.message,
359 this: None,
360 })
361 .collect(),
362 },
363 );
364 }
365
366 registry.register_service(ProtoService {
367 full_name: ProtoPath::new(service.full_name()),
368 comments: self
369 .location(service.path())
370 .map(location_to_comments)
371 .unwrap_or_default(),
372 package: ProtoPath::new(service.package_name()),
373 options: ProtoServiceOptions {
374 prefix: opts.prefix,
375 },
376 methods,
377 });
378
379 Ok(())
380 }
381
382 fn process_message(
383 &self,
384 message: &MessageDescriptor,
385 registry: &mut ProtoTypeRegistry,
386 ) -> anyhow::Result<()> {
387 let opts = self.extensions.ext_message.decode(message)?;
388
389 let fields = message
390 .fields()
391 .map(|field| {
392 let opts = self
393 .extensions
394 .ext_field
395 .decode(&field)
396 .with_context(|| field.full_name().to_owned())?;
397 Ok((field, opts.unwrap_or_default()))
398 })
399 .collect::<anyhow::Result<Vec<_>>>()?;
400
401 let opts = opts.unwrap_or_default();
402 let message_full_name = ProtoPath::new(message.full_name());
403 let rename_all = opts
404 .rename_all
405 .and_then(|v| tonneau_pb_prost::RenameAll::try_from(v).ok());
406
407 let mut message_type = ProtoMessageType {
408 full_name: message_full_name.clone(),
409 comments: self
410 .location(message.path())
411 .map(location_to_comments)
412 .unwrap_or_default(),
413 package: ProtoPath::new(message.package_name()),
414 fields: IndexMap::new(),
415 options: ProtoMessageOptions {
416 cel: opts
417 .cel
418 .into_iter()
419 .map(|cel| CelExpression {
420 expression: cel.expression,
421 jsonschemas: cel.jsonschemas,
422 message: cel.message,
423 this: None,
424 })
425 .collect(),
426 },
427 };
428
429 for (field, opts) in fields {
430 let proto3_optional = field.field_descriptor_proto().proto3_optional();
432 let visibility = ProtoVisibility::from_pb(opts.visibility());
433
434 let field_opts = ProtoFieldOptions {
435 serde_omittable: ProtoFieldSerdeOmittable::from_prost_pb(
436 opts.json_omittable(),
437 proto3_optional,
438 ),
439 nullable: proto3_optional,
440 visibility,
441 flatten: opts.flatten(),
442 serde_name: opts
443 .rename
444 .or_else(|| rename_field(field.name(), rename_all?))
445 .unwrap_or_else(|| field.name().to_owned()),
446 cel_exprs: gather_cel_expressions(
447 &self.extensions.ext_predefined,
448 &field.options(),
449 )
450 .context("gathering cel expressions")?,
451 };
452
453 let Some(Some(oneof)) = (!proto3_optional).then(|| field.containing_oneof()) else {
454 message_type.fields.insert(
455 field.name().to_owned(),
456 ProtoMessageField {
457 full_name: ProtoPath::new(field.full_name()),
458 message: message_full_name.clone(),
459 comments: self
460 .location(field.path())
461 .map(location_to_comments)
462 .unwrap_or_default(),
463 ty: match field.kind() {
464 Kind::Message(message) if field.is_map() => {
465 ProtoType::Modified(ProtoModifiedValueType::Map(
466 ProtoValueType::from_pb(&message.map_entry_key_field().kind()),
467 ProtoValueType::from_pb(
468 &message.map_entry_value_field().kind(),
469 ),
470 ))
471 }
472 kind if field.is_list() => ProtoType::Modified(
474 ProtoModifiedValueType::Repeated(ProtoValueType::from_pb(&kind)),
475 ),
476 kind if proto3_optional || matches!(kind, Kind::Message(_)) => {
477 ProtoType::Modified(ProtoModifiedValueType::Optional(
478 ProtoValueType::from_pb(&kind),
479 ))
480 }
481 kind => ProtoType::Value(ProtoValueType::from_pb(&kind)),
482 },
483 options: field_opts,
484 },
485 );
486 continue;
487 };
488
489 let opts = self
490 .extensions
491 .ext_oneof
492 .decode(&oneof)?
493 .unwrap_or_default();
494 let mut entry = message_type.fields.entry(oneof.name().to_owned());
495 let oneof = match entry {
496 indexmap::map::Entry::Occupied(ref mut entry) => entry.get_mut(),
497 indexmap::map::Entry::Vacant(entry) => {
498 let visibility = ProtoVisibility::from_pb(opts.visibility());
499 let json_omittable =
500 ProtoFieldSerdeOmittable::from_prost_pb(opts.json_omittable(), false);
501
502 entry.insert(ProtoMessageField {
503 full_name: ProtoPath::new(oneof.full_name()),
504 message: message_full_name.clone(),
505 comments: self
506 .location(oneof.path())
507 .map(location_to_comments)
508 .unwrap_or_default(),
509 options: ProtoFieldOptions {
510 flatten: opts.flatten(),
511 nullable: json_omittable.is_true(),
512 serde_omittable: json_omittable,
513 serde_name: opts
514 .rename
515 .or_else(|| rename_field(oneof.name(), rename_all?))
516 .unwrap_or_else(|| oneof.name().to_owned()),
517 visibility,
518 cel_exprs: CelExpressions::default(),
519 },
520 ty: ProtoType::Modified(ProtoModifiedValueType::OneOf(ProtoOneOfType {
521 full_name: ProtoPath::new(oneof.full_name()),
522 message: message_full_name.clone(),
523 fields: IndexMap::new(),
524 options: ProtoOneOfOptions {
525 tagged: opts.tagged.clone().map(|tagged| Tagged {
526 content: tagged.content,
527 tag: tagged.tag,
528 }),
529 },
530 })),
531 })
532 }
533 };
534
535 let ProtoType::Modified(ProtoModifiedValueType::OneOf(ProtoOneOfType {
536 ref full_name,
537 ref mut fields,
538 ..
539 })) = oneof.ty
540 else {
541 panic!("field type is not a oneof but is being added to a oneof");
542 };
543
544 let field_ty = ProtoValueType::from_pb(&field.kind());
545
546 fields.insert(
547 field.name().to_owned(),
548 ProtoOneOfField {
549 full_name: ProtoPath::new(format!("{full_name}.{}", field.name())),
553 message: message_full_name.clone(),
554 comments: self
555 .location(field.path())
556 .map(location_to_comments)
557 .unwrap_or_default(),
558 ty: field_ty.clone(),
559 options: field_opts,
560 },
561 );
562 }
563
564 registry.register_message(message_type);
565
566 for child in message.child_messages() {
567 if child.is_map_entry() {
568 continue;
569 }
570
571 self.process_message(&child, registry)?;
572 }
573
574 for child in message.child_enums() {
575 self.process_enum(&child, registry)?;
576 }
577
578 Ok(())
579 }
580
581 fn process_enum(
582 &self,
583 enum_: &EnumDescriptor,
584 registry: &mut ProtoTypeRegistry,
585 ) -> anyhow::Result<()> {
586 let opts = self.extensions.ext_enum.decode(enum_)?;
587
588 let values = enum_
589 .values()
590 .map(|value| {
591 let opts = self
592 .extensions
593 .ext_variant
594 .decode(&value)
595 .with_context(|| value.full_name().to_owned())?;
596 Ok((value, opts))
597 })
598 .collect::<anyhow::Result<Vec<_>>>()?;
599
600 let opts = opts.unwrap_or_default();
601 let rename_all = opts
602 .rename_all
603 .and_then(|v| tonneau_pb_prost::RenameAll::try_from(v).ok())
604 .unwrap_or(tonneau_pb_prost::RenameAll::ScreamingSnakeCase);
605
606 let mut enum_opts = ProtoEnumType {
607 full_name: ProtoPath::new(enum_.full_name()),
608 comments: self
609 .location(enum_.path())
610 .map(location_to_comments)
611 .unwrap_or_default(),
612 package: ProtoPath::new(enum_.package_name()),
613 variants: IndexMap::new(),
614 options: ProtoEnumOptions {
615 repr_enum: opts.repr_enum(),
616 },
617 };
618
619 for (variant, opts) in values {
620 let opts = opts.unwrap_or_default();
621
622 let visibility = ProtoVisibility::from_pb(opts.visibility());
623
624 let name = strip_enum_prefix(
625 &to_upper_camel(enum_.name()),
626 &to_upper_camel(variant.name()),
627 );
628
629 enum_opts.variants.insert(
630 variant.name().to_owned(),
631 ProtoEnumVariant {
632 comments: self
633 .location(variant.path())
634 .map(location_to_comments)
635 .unwrap_or_default(),
636 full_name: ProtoPath::new(format!("{}.{}", enum_.full_name(), variant.name())),
638 value: variant.number(),
639 rust_ident: format_ident!("{name}"),
640 options: ProtoEnumVariantOptions {
641 visibility,
642 serde_name: opts
643 .rename
644 .or_else(|| rename_field(&name, rename_all))
645 .unwrap_or(name),
646 },
647 },
648 );
649 }
650
651 registry.register_enum(enum_opts);
652
653 Ok(())
654 }
655}
656
657#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone)]
658enum CelInput {
659 Root,
660 MapKey,
661 MapValue,
662 RepeatedItem,
663}
664
665pub(crate) fn gather_cel_expressions(
666 extension: &Extension<tonneau_pb_prost::PredefinedConstraints>,
667 field_options: &prost_reflect::DynamicMessage,
668) -> anyhow::Result<CelExpressions> {
669 let Some(extension) = extension.descriptor() else {
670 return Ok(CelExpressions::default());
671 };
672
673 let mut results = BTreeMap::new();
674 let mut input = CelInput::Root;
675
676 if field_options.has_extension(extension) {
677 let value = field_options.get_extension(extension);
678 let predef = value
679 .as_message()
680 .context("expected message")?
681 .transcode_to::<tonneau_pb_prost::PredefinedConstraints>()
682 .context("invalid predefined constraint")?;
683 match predef.r#type() {
684 tonneau_pb_prost::predefined_constraints::Type::Unspecified => {}
685 tonneau_pb_prost::predefined_constraints::Type::CustomExpression => {}
686 tonneau_pb_prost::predefined_constraints::Type::WrapperMapKey => {
687 input = CelInput::MapKey;
688 }
689 tonneau_pb_prost::predefined_constraints::Type::WrapperMapValue => {
690 input = CelInput::MapValue;
691 }
692 tonneau_pb_prost::predefined_constraints::Type::WrapperRepeatedItem => {
693 input = CelInput::RepeatedItem;
694 }
695 }
696 }
697
698 for (ext, value) in field_options.extensions() {
699 if &ext == extension {
700 continue;
701 }
702
703 if let Some(message) = value.as_message() {
704 explore_fields(extension, input, message, &mut results)?;
705 }
706 }
707
708 Ok(CelExpressions {
709 field: results.remove(&CelInput::Root).unwrap_or_default(),
710 map_key: results.remove(&CelInput::MapKey).unwrap_or_default(),
711 map_value: results.remove(&CelInput::MapValue).unwrap_or_default(),
712 repeated_item: results.remove(&CelInput::RepeatedItem).unwrap_or_default(),
713 })
714}
715
716fn explore_fields(
717 extension: &prost_reflect::ExtensionDescriptor,
718 input: CelInput,
719 value: &prost_reflect::DynamicMessage,
720 results: &mut BTreeMap<CelInput, Vec<CelExpression>>,
721) -> anyhow::Result<()> {
722 for (field, value) in value.fields() {
723 let options = field.options();
724 let mut input = input;
725 if options.has_extension(extension) {
726 let message = options.get_extension(extension);
727 let predef = message
728 .as_message()
729 .unwrap()
730 .transcode_to::<tonneau_pb_prost::PredefinedConstraints>()
731 .unwrap();
732 match predef.r#type() {
733 tonneau_pb_prost::predefined_constraints::Type::Unspecified => {}
734 tonneau_pb_prost::predefined_constraints::Type::CustomExpression => {
735 if let Some(list) = value.as_list() {
736 results.entry(input).or_default().extend(
737 list.iter()
738 .filter_map(|item| item.as_message())
739 .filter_map(|msg| {
740 msg.transcode_to::<tonneau_pb_prost::CelExpression>().ok()
741 })
742 .map(|expr| CelExpression {
743 expression: expr.expression,
744 jsonschemas: expr.jsonschemas,
745 message: expr.message,
746 this: None,
747 }),
748 );
749 }
750 continue;
751 }
752 tonneau_pb_prost::predefined_constraints::Type::WrapperMapKey => {
753 input = CelInput::MapKey;
754 }
755 tonneau_pb_prost::predefined_constraints::Type::WrapperMapValue => {
756 input = CelInput::MapValue;
757 }
758 tonneau_pb_prost::predefined_constraints::Type::WrapperRepeatedItem => {
759 input = CelInput::RepeatedItem;
760 }
761 }
762
763 results
764 .entry(input)
765 .or_default()
766 .extend(predef.cel.into_iter().map(|expr| CelExpression {
767 expression: expr.expression,
768 jsonschemas: expr.jsonschemas,
769 message: expr.message,
770 this: Some(prost_to_cel(value, &field.kind())),
771 }));
772 }
773
774 let Some(message) = value.as_message() else {
775 continue;
776 };
777
778 explore_fields(extension, input, message, results)?;
779 }
780
781 Ok(())
782}
783
784fn prost_to_cel(value: &prost_reflect::Value, kind: &Kind) -> tonneau_cel::CelValue<'static> {
785 match value {
786 prost_reflect::Value::String(s) => tonneau_cel::CelValue::String(s.clone().into()),
787 prost_reflect::Value::Message(msg) => tonneau_cel::CelValue::Map(
788 msg.fields()
789 .map(|(field, value)| {
790 (
791 tonneau_cel::CelValue::String(field.name().to_owned().into()),
792 prost_to_cel(value, &field.kind()),
793 )
794 })
795 .collect(),
796 ),
797 prost_reflect::Value::EnumNumber(value) => tonneau_cel::CelValue::Enum(CelEnum::new(
798 kind.as_enum().expect("enum").full_name().to_owned().into(),
799 *value,
800 )),
801 prost_reflect::Value::Bool(v) => v.conv(),
802 prost_reflect::Value::I32(v) => v.conv(),
803 prost_reflect::Value::I64(v) => v.conv(),
804 prost_reflect::Value::U32(v) => v.conv(),
805 prost_reflect::Value::U64(v) => v.conv(),
806 prost_reflect::Value::Bytes(b) => tonneau_cel::CelValue::Bytes(b.into()),
807 prost_reflect::Value::F32(v) => v.conv(),
808 prost_reflect::Value::F64(v) => v.conv(),
809 prost_reflect::Value::List(list) => {
810 tonneau_cel::CelValue::List(list.iter().map(|item| prost_to_cel(item, kind)).collect())
811 }
812 prost_reflect::Value::Map(map) => tonneau_cel::CelValue::Map(
813 map.iter()
814 .map(|(key, value)| {
815 let key = match key {
816 prost_reflect::MapKey::Bool(v) => v.conv(),
817 prost_reflect::MapKey::I32(v) => v.conv(),
818 prost_reflect::MapKey::I64(v) => v.conv(),
819 prost_reflect::MapKey::U32(v) => v.conv(),
820 prost_reflect::MapKey::U64(v) => v.conv(),
821 prost_reflect::MapKey::String(s) => {
822 tonneau_cel::CelValue::String(s.clone().into())
823 }
824 };
825
826 let v = prost_to_cel(
827 value,
828 &kind
829 .as_message()
830 .expect("map")
831 .map_entry_value_field()
832 .kind(),
833 );
834 (key, v)
835 })
836 .collect(),
837 ),
838 }
839}
840
841fn location_to_comments(location: &Location) -> Comments {
842 Comments {
843 leading: location.leading_comments.as_deref().map(Into::into),
844 detached: location
845 .leading_detached_comments
846 .iter()
847 .map(|s| s.as_str().into())
848 .collect(),
849 trailing: location.trailing_comments.as_deref().map(Into::into),
850 }
851}
852
853impl ProtoFieldSerdeOmittable {
854 pub(crate) fn from_prost_pb(value: tonneau_pb_prost::JsonOmittable, nullable: bool) -> Self {
855 match value {
856 tonneau_pb_prost::JsonOmittable::Unspecified => {
857 if nullable {
858 Self::TrueButStillSerialize
859 } else {
860 Self::False
861 }
862 }
863 tonneau_pb_prost::JsonOmittable::True => Self::True,
864 tonneau_pb_prost::JsonOmittable::False => Self::False,
865 tonneau_pb_prost::JsonOmittable::TrueButStillSerialize => Self::TrueButStillSerialize,
866 }
867 }
868}