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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! Decoding context built from the proto-files.

use bytes::Bytes;
use snafu::{ResultExt, Snafu};
use std::collections::{BTreeMap, HashMap};

mod builder;
mod parse;

/// Protofish error type.
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error
{
    /// Syntax error in the input files.
    #[snafu(display("Parsing error: {}", source))]
    ParseError
    {
        /// Source error.
        source: Box<dyn std::error::Error + Send + Sync>,
    },

    /// Duplicate type.
    #[snafu(display("Duplicate type: {}", name))]
    DuplicateType
    {
        /// Type.
        name: String,
    },

    /// Unknown type reference.
    #[snafu(display("Unknown type '{}' in '{}'", name, context))]
    TypeNotFound
    {
        /// Type name.
        name: String,
        /// Type that referred to the unknown type.
        context: String,
    },

    /// Wrong kind of type used in a specific context.
    #[snafu(display(
        "Invalid type '{}' ({:?}) for {}, expected {:?}",
        type_name,
        actual,
        context,
        expected
    ))]
    InvalidTypeKind
    {
        /// Type that is of the wrong kind.
        type_name: String,

        /// The context where the type was used.
        context: &'static str,

        /// Expected item type.
        expected: ItemType,

        /// Actual item type.
        actual: ItemType,
    },
}

/// Protobuf item type
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ItemType
{
    /// `message` item
    Message,

    /// `enum` item
    Enum,

    /// `service` item
    Service,
}

/// Result alias for the context errors.
pub type Result<S, E = Error> = std::result::Result<S, E>;

/// Protofish decoding context.
///
/// Contains type information parsed from the files. Required for decoding
/// incoming Protobuf messages.
#[derive(Default, Debug)]
pub struct Context
{
    packages: Vec<Package>,
    types: Vec<TypeInfo>,
    types_by_name: HashMap<String, usize>,
    services: Vec<Service>,
    services_by_name: HashMap<String, usize>,
}

#[derive(Default, Debug)]
struct Package
{
    name: Option<String>,
    types: Vec<usize>,
    services: Vec<usize>,
}

/// Message or enum type.
#[derive(Debug)]
pub enum TypeInfo
{
    /// Message.
    Message(MessageInfo),

    /// Enum.
    Enum(EnumInfo),
}

/// Message details
#[derive(Debug)]
pub struct MessageInfo
{
    /// Message name.
    pub name: String,

    /// Full message name, including package and parent type names.
    pub full_name: String,

    /// `MessageRef` that references this message.
    pub self_ref: MessageRef,

    /// Message fields.
    pub fields: BTreeMap<u64, MessageField>,

    /// `oneof` structures defined within the message.
    pub oneofs: Vec<Oneof>,

    /// References to the inner types defined within this message.
    pub inner_types: Vec<InnerType>,
}

/// Inner type reference.
#[derive(Debug)]
pub enum InnerType
{
    /// Inner `message`.
    Message(MessageRef),

    /// Inner `enum`.
    Enum(EnumRef),
}

/// Enum details
#[derive(Debug)]
pub struct EnumInfo
{
    /// Enum name.
    pub name: String,

    /// Full message name, including package and parent type names.
    pub full_name: String,

    /// `EnumRef` that references this enum.
    pub self_ref: EnumRef,

    /// Enum fields.
    pub fields: Vec<EnumField>,

    fields_by_value: HashMap<i64, usize>,
}

/// Message field details.
#[derive(Debug)]
pub struct MessageField
{
    /// Field name.
    pub name: String,

    /// Field number.
    pub number: u64,

    /// Field type
    pub field_type: ValueType,

    /// True, if this field is a repeated field.
    pub multiplicity: Multiplicity,

    /// Field options.
    pub options: Vec<ProtoOption>,

    /// Index to the ´oneof` structure in the parent type if this field is part of a `oneof`.
    pub oneof: Option<usize>,
}

/// Defines the multiplicity of the field values.
#[derive(Debug, PartialEq)]
pub enum Multiplicity
{
    /// Field is not repeated.
    Single,

    /// Field may be repeated.
    Repeated,

    /// Field is repeated by packing.
    RepeatedPacked,
}

/// Message `oneof` details.
#[derive(Debug)]
pub struct Oneof
{
    /// Name of the `oneof` structure.
    pub name: String,

    /// Field numbers of the fields contained in the `oneof`.
    pub fields: Vec<u64>,

    /// Options.
    pub options: Vec<ProtoOption>,
}

/// Enum field details.
#[derive(Debug, PartialEq, Clone)]
pub struct EnumField
{
    /// Enum field name.
    pub name: String,

    /// Enum field value.
    pub value: i64,

    /// Options.
    pub options: Vec<ProtoOption>,
}

/// Field value types.
#[derive(Clone, Debug, PartialEq)]
pub enum ValueType
{
    /// `double`
    Double,

    /// `float`
    Float,

    /// `int32`
    Int32,

    /// `int64`
    Int64,

    /// `uint32`
    UInt32,

    /// `uint64`
    UInt64,

    /// `sint32`
    SInt32,

    /// `sint64`
    SInt64,

    /// `fixed32`
    Fixed32,

    /// `fixed64`
    Fixed64,

    /// `sfixed32`
    SFixed32,

    /// `sfixed64`
    SFixed64,

    /// `bool`
    Bool,

    /// `string`
    String,

    /// `bytes`
    Bytes,

    /// A message type.
    Message(MessageRef),

    /// An enum type.
    Enum(EnumRef),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct TypeRef(usize);

/// A reference to a message. Can be resolved to `MessageInfo` through a `Context`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MessageRef(TypeRef);

/// A reference to an enum. Can be resolved to `EnumInfo` through a `Context`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EnumRef(TypeRef);

/// Service details
#[derive(Debug, PartialEq)]
pub struct Service
{
    /// Service name.
    pub name: String,

    /// Full service name, including the package name.
    pub full_name: String,

    /// List of `rpc` operations defined in the service.
    pub rpcs: Vec<Rpc>,

    /// Options.
    pub options: Vec<ProtoOption>,

    rpcs_by_name: HashMap<String, usize>,
}

/// Rpc operation
#[derive(Debug, PartialEq)]
pub struct Rpc
{
    /// Operation name.
    pub name: String,

    /// Input details.
    pub input: RpcArg,

    /// Output details.
    pub output: RpcArg,

    /// Options.
    pub options: Vec<ProtoOption>,
}

/// Rpc operation input or output details.
#[derive(Debug, PartialEq)]
pub struct RpcArg
{
    /// References to the message type.
    pub message: MessageRef,

    /// True, if this is a stream.
    pub stream: bool,
}

/// A single option.
#[derive(Debug, PartialEq, Clone)]
pub struct ProtoOption
{
    /// Option name.
    pub name: String,

    /// Optionn value.
    pub value: Constant,
}

/// Constant value, used for options.
#[derive(Debug, PartialEq, Clone)]
pub enum Constant
{
    /// An ident `foo.bar.baz`.
    Ident(String),

    /// An integer constant.
    Integer(i64),

    /// A floating point constant.
    Float(f64),

    /// A string constant.
    ///
    /// The string isn't guaranteed to be well formed UTF-8 so it's stored as
    /// Bytes here.
    String(Bytes),

    /// A boolean constant.
    Bool(bool),
}

impl Context
{
    /// Gets type info by name.
    pub fn get_type(&self, full_name: &str) -> Option<&TypeInfo>
    {
        self.types_by_name
            .get(full_name)
            .map(|idx| &self.types[*idx])
    }

    /// Gets a message type info by name.
    pub fn get_message(&self, full_name: &str) -> Option<&MessageInfo>
    {
        match self.get_type(full_name) {
            Some(TypeInfo::Message(m)) => Some(m),
            _ => None,
        }
    }

    fn resolve_type(&self, tr: TypeRef) -> Option<&TypeInfo>
    {
        self.types.get(tr.0)
    }

    /// Resolves a message reference.
    ///
    /// Will **panic** if the message defined by the `MessageRef` does not exist in this context.
    /// Such panic means the `MessageRef` came from a different context. The panic is not
    /// guaranteed, as a message with an equal `MessageRef` may exist in multiple contexts.
    pub fn resolve_message(&self, tr: MessageRef) -> &MessageInfo
    {
        match self.resolve_type(tr.0) {
            Some(TypeInfo::Message(msg)) => msg,
            _ => panic!("Message did not exist in this context"),
        }
    }

    /// Resolves a enum reference.
    ///
    /// Will **panic** if the enum defined by the `EnumRef` does not exist in this context.
    /// Such panic means the `EnumRef` came from a different context. The panic is not
    /// guaranteed, as an enum with an equal `EnumRef` may exist in multiple contexts.
    pub fn resolve_enum(&self, tr: EnumRef) -> &EnumInfo
    {
        match self.resolve_type(tr.0) {
            Some(TypeInfo::Enum(e)) => e,
            _ => panic!("Message did not exist in this context"),
        }
    }

    /// Gets a service by full name.
    pub fn get_service(&self, full_name: &str) -> Option<&Service>
    {
        self.services_by_name
            .get(full_name)
            .map(|idx| &self.services[*idx])
    }
}

impl TypeInfo
{
    pub(crate) fn full_name(&self) -> String
    {
        match self {
            TypeInfo::Message(v) => v.full_name.clone(),
            TypeInfo::Enum(v) => v.full_name.clone(),
        }
    }
}

impl EnumInfo
{
    /// Gets a field by value.
    ///
    /// If the field is aliased, an undefined field alias is returned.
    pub fn field_by_value(&self, value: i64) -> Option<&EnumField>
    {
        self.fields_by_value
            .get(&value)
            .map(|idx| &self.fields[*idx])
    }
}

impl Service
{
    /// Gets an `Rpc` info by operation name.
    pub fn rpc_by_name(&self, name: &str) -> Option<&Rpc>
    {
        self.rpcs_by_name.get(name).map(|idx| &self.rpcs[*idx])
    }
}

impl ValueType
{
    pub(crate) fn wire_type(&self) -> u8
    {
        match self {
            Self::Double => 1,
            Self::Float => 5,
            Self::Int32 => 0,
            Self::Int64 => 0,
            Self::UInt32 => 0,
            Self::UInt64 => 0,
            Self::SInt32 => 0,
            Self::SInt64 => 0,
            Self::Fixed32 => 5,
            Self::Fixed64 => 1,
            Self::SFixed32 => 5,
            Self::SFixed64 => 1,
            Self::Bool => 0,
            Self::String => 2,
            Self::Bytes => 2,
            Self::Message(..) => 2,
            Self::Enum(..) => 0,
        }
    }
}