1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Definitions for describing the format protobuf messages. These can be used
//! to generate `.proto` files that are binary compatible with the associated
//! Rust types.

mod writer;

pub use writer::DescriptorWriter;

use crate::DefaultEncoding;
use std::fmt::Display;

/// A trait for a self-describing protobuf message field.
pub trait DescribeField<T> {
    /// The type of the field.
    const FIELD_TYPE: FieldType<'static>;
    /// The type name of the field in a packed context.
    const PACKED_TYPE: Option<&'static str> = None;
}

/// A trait for a self-describing protobuf message.
///
/// This can be derived for `T` by deriving [`Protobuf`](crate::Protobuf) and
/// adding the attribute `#[mesh(package = "my.package.name")]`.
pub trait DescribeMessage<T> {
    /// The message description.
    const DESCRIPTION: MessageDescription<'static>;
}

/// A description of a message type.
#[derive(Copy, Clone)]
pub enum MessageDescription<'a> {
    /// An internally-defined type, described by the descriptor.
    Internal(&'a TopLevelDescriptor<'a>),
    /// An externally-defined type.
    External {
        /// The fully-qualified name of the message type.
        name: &'a str,
        /// The import path of the `.proto` file.
        import_path: &'a str,
    },
}

/// A type URL, used in [`ProtobufAny`](super::message::ProtobufAny) (which
/// shares an encoding with `google.protobuf.Any`).
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct TypeUrl<'a> {
    package: &'a str,
    name: &'a str,
}

impl TypeUrl<'_> {
    fn eq(&self, type_url: &str) -> bool {
        let type_url = type_url.strip_prefix("https://").unwrap_or(type_url);
        if let Some((package, name)) = type_url
            .strip_prefix("type.googleapis.com/")
            .and_then(|ty| ty.rsplit_once('.'))
        {
            self.package == package && self.name == name
        } else {
            false
        }
    }
}

impl Display for TypeUrl<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "type.googleapis.com/{}.{}", self.package, self.name)
    }
}

impl PartialEq<str> for TypeUrl<'_> {
    fn eq(&self, other: &str) -> bool {
        self.eq(other)
    }
}

impl PartialEq<TypeUrl<'_>> for str {
    fn eq(&self, other: &TypeUrl<'_>) -> bool {
        other.eq(self)
    }
}

impl MessageDescription<'_> {
    /// Returns the type URL to use with `google.protobuf.Any`.
    pub const fn type_url(&self) -> TypeUrl<'_> {
        match *self {
            MessageDescription::Internal(tld) => TypeUrl {
                package: tld.package,
                name: tld.message.name,
            },
            MessageDescription::External { name, .. } => TypeUrl { package: "", name },
        }
    }
}

/// Returns the top-level message descriptor for a type with a default encoding.
pub const fn message_description<T: DefaultEncoding>() -> MessageDescription<'static>
where
    T::Encoding: DescribeMessage<T>,
{
    <T::Encoding as DescribeMessage<T>>::DESCRIPTION
}

/// The description of a field type.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct FieldType<'a> {
    kind: FieldKind<'a>,
    sequence_type: Option<SequenceType<'a>>,
    annotation: &'a str,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
enum SequenceType<'a> {
    Optional,
    Repeated,
    Map(&'a str),
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
enum FieldKind<'a> {
    Builtin(&'a str),
    Local(&'a str),
    External {
        name: &'a str,
        import_path: &'static str,
    },
    Message(fn() -> MessageDescription<'a>),
    Tuple(&'a [FieldType<'a>]),
    KeyValue(&'a [FieldType<'a>; 2]),
}

impl<'a> FieldType<'a> {
    /// Returns a repeated version of this field type.
    ///
    /// Panics if the field type is already a sequence type.
    pub const fn repeated(mut self) -> Self {
        assert!(self.sequence_type.is_none());
        self.sequence_type = Some(SequenceType::Repeated);
        self
    }

    /// Returns a optional version of this field type.
    ///
    /// Panics if the field type is already a sequence type.
    pub const fn optional(mut self) -> Self {
        assert!(self.sequence_type.is_none());
        self.sequence_type = Some(SequenceType::Optional);
        self
    }

    /// Sets an annotation to show up in the .proto file.
    pub const fn annotate(mut self, annotation: &'a str) -> Self {
        self.annotation = annotation;
        self
    }

    /// Returns a map type.
    ///
    /// If `key` is not a builtin numeric scalar or string type, or if `value`
    /// is an optional or repeated type, then this will result in a repeated
    /// tuple instead of a protobuf `map` type. The encodings for these are the
    /// same, but `.proto` `map` types are constrained to mappings from scalars
    /// to non-optional/repeated scalars and messages.
    pub const fn map(kv: &'a [FieldType<'a>; 2]) -> Self {
        let [key, value] = kv;
        if !key.is_sequence() && !value.is_sequence() {
            if let FieldKind::Builtin(ty) = key.kind {
                if let b"uint32" | b"int32" | b"sint32" | b"uint64" | b"sint64" | b"int64"
                | b"fixed32" | b"fixed64" | b"sfixed32" | b"sfixed64" | b"bool" | b"string" =
                    ty.as_bytes()
                {
                    return Self {
                        kind: value.kind,
                        sequence_type: Some(SequenceType::Map(ty)),
                        annotation: "",
                    };
                }
            }
        }
        Self {
            kind: FieldKind::KeyValue(kv),
            sequence_type: Some(SequenceType::Repeated),
            annotation: "",
        }
    }

    /// Returns a field type for a message whose top-level descriptor is
    /// returned by `f`.
    ///
    /// This is abstracted through a function to allow for recursive types.
    /// Currently Rust does not allow a `const` to refer to a `static`, but it
    /// does allow a `const` to refer to a function that returns a `&'static`.
    pub const fn message(f: fn() -> MessageDescription<'a>) -> Self {
        Self {
            kind: FieldKind::Message(f),
            sequence_type: None,
            annotation: "",
        }
    }

    /// Returns a field type for a local message type with `name`.
    pub const fn local(name: &'a str) -> Self {
        Self {
            kind: FieldKind::Local(name),
            sequence_type: None,
            annotation: "",
        }
    }

    /// Returns a field type for a builtin type, such as `uint32`.
    pub const fn builtin(name: &'a str) -> Self {
        Self {
            kind: FieldKind::Builtin(name),
            sequence_type: None,
            annotation: "",
        }
    }

    /// Returns a field type for an anonymous tuple.
    #[allow(clippy::redundant_guards)] // https://github.com/rust-lang/rust-clippy/issues/12243
    pub const fn tuple(field_types: &'a [Self]) -> Self {
        // Use well-known types instead of new anonymous ones when possible.
        match field_types {
            [] => {
                return Self::external("google.protobuf.Empty", "google/protobuf/empty.proto");
            }
            &[Self {
                kind: FieldKind::Builtin(ty),
                sequence_type: None,
                annotation,
            }] if annotation.is_empty() => {
                let wrapper = match ty.as_bytes() {
                    b"double" => Some("google.protobuf.DoubleValue"),
                    b"float" => Some("google.protobuf.FloatValue"),
                    b"int64" => Some("google.protobuf.Int64Value"),
                    b"uint64" => Some("google.protobuf.UInt64Value"),
                    b"int32" => Some("google.protobuf.Int32Value"),
                    b"uint32" => Some("google.protobuf.UInt32Value"),
                    b"bool" => Some("google.protobuf.BoolValue"),
                    b"string" => Some("google.protobuf.StringValue"),
                    b"bytes" => Some("google.protobuf.BytesValue"),
                    _ => None,
                };
                if let Some(wrapper) = wrapper {
                    return Self::external(wrapper, "google/protobuf/wrappers.proto");
                }
            }
            _ => {}
        }
        Self {
            kind: FieldKind::Tuple(field_types),
            sequence_type: None,
            annotation: "",
        }
    }

    /// Returns a field type for an external type with the given fully-qualified
    /// name and protoc import path.
    pub const fn external(name: &'a str, import_path: &'static str) -> Self {
        Self {
            kind: FieldKind::External { name, import_path },
            sequence_type: None,
            annotation: "",
        }
    }

    /// Returns true if this is a sequence type (optional or repeated).
    pub const fn is_sequence(&self) -> bool {
        self.sequence_type.is_some()
    }

    /// Returns true if this type can use a packed encoding in a repeated
    /// context.
    pub const fn can_pack(&self) -> bool {
        if self.sequence_type.is_some() {
            return false;
        }
        match self.kind {
            FieldKind::Builtin(v) => matches!(
                v.as_bytes(),
                b"double" | b"float" | b"int64" | b"uint64" | b"int32" | b"uint32" | b"bool"
            ),
            _ => false,
        }
    }
}

/// A descriptor for a message field.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct FieldDescriptor<'a> {
    field_type: FieldType<'a>,
    field_number: u32,
    comment: &'a str,
    name: &'a str,
}

impl<'a> FieldDescriptor<'a> {
    /// Returns a new descriptor.
    pub const fn new(
        comment: &'a str,
        field_type: FieldType<'a>,
        name: &'a str,
        field_number: u32,
    ) -> Self {
        Self {
            field_type,
            field_number,
            comment,
            name,
        }
    }
}

/// A description of a protobuf `oneof`.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct OneofDescriptor<'a> {
    name: &'a str,
    variants: &'a [FieldDescriptor<'a>],
}

impl<'a> OneofDescriptor<'a> {
    /// Returns a new descriptor.
    pub const fn new(name: &'a str, variants: &'a [FieldDescriptor<'a>]) -> Self {
        Self { name, variants }
    }
}

/// A message descriptor.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct MessageDescriptor<'a> {
    comment: &'a str,
    name: &'a str,
    fields: &'a [FieldDescriptor<'a>],
    oneofs: &'a [OneofDescriptor<'a>],
    messages: &'a [MessageDescriptor<'a>],
}

impl<'a> MessageDescriptor<'a> {
    /// Creates a new message descriptor.
    pub const fn new(
        name: &'a str,
        comment: &'a str,
        fields: &'a [FieldDescriptor<'a>],
        oneofs: &'a [OneofDescriptor<'a>],
        messages: &'a [MessageDescriptor<'a>],
    ) -> Self {
        Self {
            comment,
            name,
            fields,
            oneofs,
            messages,
        }
    }
}

/// A message descriptor for a message rooted directly in a package (and not
/// nested in another message type).
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct TopLevelDescriptor<'a> {
    package: &'a str,
    message: &'a MessageDescriptor<'a>,
}

impl<'a> TopLevelDescriptor<'a> {
    /// Returns a new descriptor.
    pub const fn message(package: &'a str, message: &'a MessageDescriptor<'a>) -> Self {
        Self { package, message }
    }
}