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
// SPDX-License-Identifier: Apache-2.0

//! Module providing introspection traits for [`prost`]-generated protobuf
//! types.

use crate::output::primitive_data;
use crate::output::tree;
use crate::parse::context;

/// Trait for all Rust types that represent input tree node types.
pub trait InputNode {
    /// Creates an empty output node for a protobuf datum of this type.
    ///
    /// For primitive types, this fills the value with protobuf's default.
    fn type_to_node() -> tree::Node;

    /// Creates an empty output node for a protobuf datum with this value.
    fn data_to_node(&self) -> tree::Node;

    /// Returns the name of the selected variant of a oneof field, if this
    /// is a rust enum used to represent a oneof field.
    fn oneof_variant(&self) -> Option<&'static str>;

    /// Complete the subtrees of this datum in output that have not already
    /// been parsed using UnknownField nodes. Returns whether any such nodes
    /// were added.
    fn parse_unknown(&self, context: &mut context::Context<'_>) -> bool;
}

/// Trait for all Rust types that represent protobuf messages. These are
/// always structs for which all fields implement InputNode.
pub trait ProtoMessage: InputNode {
    /// Returns the protobuf type name for messages of this type.
    fn proto_message_type() -> &'static str;
}

/// Trait for all Rust types that represent protobuf's oneof abstraction.
/// In the world of protobuf, these aren't really a thing of their own, but
/// in Rust, they are defined as enums, each variant containing a one-tuple
/// of some type implementing InputNode.
pub trait ProtoOneOf: InputNode {
    /// Returns the name of the selected variant of a oneof field.
    fn proto_oneof_variant(&self) -> &'static str;
}

/// Trait for Rust types that map to the protobuf primitive types.
pub trait ProtoPrimitive: InputNode {
    /// Returns the protobuf type name for primitives of this type.
    fn proto_primitive_type() -> &'static str;

    /// Returns the protobuf-specified default value for this primitive
    /// data type.
    fn proto_primitive_default() -> primitive_data::PrimitiveData;

    /// Returns the actual value for this primitive data type as a
    /// ProtoPrimitiveData variant.
    fn proto_primitive_data(&self) -> primitive_data::PrimitiveData;

    /// Returns whether this is the default value of the primitive.
    fn proto_primitive_is_default(&self) -> bool;
}

/// Trait for all Rust types that represent protobuf enums. These are
/// always represented as a Rust enum with no contained values for any of
/// the variants.
pub trait ProtoEnum: ProtoPrimitive {
    /// Returns the protobuf type name for enums of this type.
    fn proto_enum_type() -> &'static str;

    /// Returns the name of the default variant of an enum.
    fn proto_enum_default_variant() -> &'static str;

    /// Returns the name of the selected variant of an enum.
    fn proto_enum_variant(&self) -> &'static str;

    /// Returns the enumeration entry corresponding to the given integer
    /// value, if any.
    fn proto_enum_from_i32(x: i32) -> Option<Self>
    where
        Self: Sized;
}

/// Blanket implementation to make all protobuf enums behave like
/// primitives as well.
impl<T: ProtoEnum> ProtoPrimitive for T {
    fn proto_primitive_type() -> &'static str {
        T::proto_enum_type()
    }

    fn proto_primitive_default() -> primitive_data::PrimitiveData {
        primitive_data::PrimitiveData::Enum(T::proto_enum_default_variant())
    }

    fn proto_primitive_data(&self) -> primitive_data::PrimitiveData {
        primitive_data::PrimitiveData::Enum(self.proto_enum_variant())
    }

    fn proto_primitive_is_default(&self) -> bool {
        self.proto_enum_variant() == T::proto_enum_default_variant()
    }
}

/// Blanket implementation to make all protobuf primitives behave like
/// generic protobuf datums.
///
/// Note: if Rust would allow it, we could define blanket implementations
/// for ProtoMessage and ProtoOneOf as well, since they're always the same.
/// Unfortunately, we can only define a single blanket implementation, so
/// we opt for the one that isn't already generated via derive macros.
impl<T: ProtoPrimitive> InputNode for T {
    fn type_to_node() -> tree::Node {
        tree::NodeType::ProtoPrimitive(T::proto_primitive_type(), T::proto_primitive_default())
            .into()
    }

    fn data_to_node(&self) -> tree::Node {
        tree::NodeType::ProtoPrimitive(T::proto_primitive_type(), self.proto_primitive_data())
            .into()
    }

    fn oneof_variant(&self) -> Option<&'static str> {
        None
    }

    fn parse_unknown(&self, _context: &mut context::Context<'_>) -> bool {
        false
    }
}

impl InputNode for () {
    fn type_to_node() -> tree::Node {
        tree::NodeType::ProtoMessage("google.protobuf.Empty").into()
    }

    fn data_to_node(&self) -> tree::Node {
        tree::NodeType::ProtoMessage("google.protobuf.Empty").into()
    }

    fn oneof_variant(&self) -> Option<&'static str> {
        None
    }

    fn parse_unknown(&self, _context: &mut context::Context<'_>) -> bool {
        false
    }
}

impl ProtoMessage for () {
    fn proto_message_type() -> &'static str {
        "google.protobuf.Empty"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::input::proto::substrait;
    use crate::output::primitive_data;
    use crate::output::tree;

    #[test]
    fn message() {
        assert_eq!(substrait::Plan::proto_message_type(), "substrait.Plan");
        assert_eq!(
            substrait::Plan::type_to_node(),
            tree::Node {
                class: tree::Class::Misc,
                brief: None,
                summary: None,
                node_type: tree::NodeType::ProtoMessage("substrait.Plan"),
                data_type: None,
                data: vec![],
            }
        );

        let msg = substrait::Plan::default();
        assert_eq!(
            msg.data_to_node(),
            tree::Node {
                class: tree::Class::Misc,
                brief: None,
                summary: None,
                node_type: tree::NodeType::ProtoMessage("substrait.Plan"),
                data_type: None,
                data: vec![],
            }
        );
        assert_eq!(msg.oneof_variant(), None);
    }

    #[test]
    fn oneof() {
        assert_eq!(
            substrait::plan_rel::RelType::type_to_node(),
            tree::Node {
                class: tree::Class::Misc,
                brief: None,
                summary: None,
                node_type: tree::NodeType::ProtoMissingOneOf,
                data_type: None,
                data: vec![],
            }
        );

        let oneof = substrait::plan_rel::RelType::Rel(substrait::Rel::default());
        assert_eq!(oneof.proto_oneof_variant(), "rel");
        assert_eq!(
            oneof.data_to_node(),
            tree::Node {
                class: tree::Class::Misc,
                brief: None,
                summary: None,
                node_type: tree::NodeType::ProtoMessage("substrait.Rel"),
                data_type: None,
                data: vec![],
            }
        );
        assert_eq!(oneof.oneof_variant(), Some("rel"));
    }

    #[test]
    fn enumeration() {
        assert_eq!(
            substrait::AggregationPhase::proto_enum_type(),
            "substrait.AggregationPhase"
        );
        assert_eq!(
            substrait::AggregationPhase::proto_enum_default_variant(),
            "AGGREGATION_PHASE_UNSPECIFIED"
        );
        assert_eq!(
            substrait::AggregationPhase::Unspecified.proto_enum_variant(),
            "AGGREGATION_PHASE_UNSPECIFIED"
        );

        assert_eq!(
            substrait::AggregationPhase::proto_primitive_type(),
            "substrait.AggregationPhase"
        );
        assert_eq!(
            substrait::AggregationPhase::proto_primitive_default(),
            primitive_data::PrimitiveData::Enum("AGGREGATION_PHASE_UNSPECIFIED")
        );
        assert_eq!(
            substrait::AggregationPhase::Unspecified.proto_primitive_data(),
            primitive_data::PrimitiveData::Enum("AGGREGATION_PHASE_UNSPECIFIED")
        );

        assert_eq!(
            substrait::AggregationPhase::type_to_node(),
            tree::Node {
                class: tree::Class::Misc,
                brief: None,
                summary: None,
                node_type: tree::NodeType::ProtoPrimitive(
                    "substrait.AggregationPhase",
                    primitive_data::PrimitiveData::Enum("AGGREGATION_PHASE_UNSPECIFIED")
                ),
                data_type: None,
                data: vec![],
            }
        );
        assert_eq!(
            substrait::AggregationPhase::Unspecified.data_to_node(),
            tree::Node {
                class: tree::Class::Misc,
                brief: None,
                summary: None,
                node_type: tree::NodeType::ProtoPrimitive(
                    "substrait.AggregationPhase",
                    primitive_data::PrimitiveData::Enum("AGGREGATION_PHASE_UNSPECIFIED")
                ),
                data_type: None,
                data: vec![],
            }
        );
        assert_eq!(
            substrait::AggregationPhase::Unspecified.oneof_variant(),
            None
        );
    }

    #[test]
    fn primitive() {
        assert_eq!(u32::proto_primitive_type(), "uint32");
        assert_eq!(
            u32::proto_primitive_default(),
            primitive_data::PrimitiveData::Unsigned(0)
        );
        assert_eq!(
            42u32.proto_primitive_data(),
            primitive_data::PrimitiveData::Unsigned(42)
        );

        assert_eq!(
            u32::type_to_node(),
            tree::Node {
                class: tree::Class::Misc,
                brief: None,
                summary: None,
                node_type: tree::NodeType::ProtoPrimitive(
                    "uint32",
                    primitive_data::PrimitiveData::Unsigned(0)
                ),
                data_type: None,
                data: vec![],
            }
        );
        assert_eq!(
            42u32.data_to_node(),
            tree::Node {
                class: tree::Class::Misc,
                brief: None,
                summary: None,
                node_type: tree::NodeType::ProtoPrimitive(
                    "uint32",
                    primitive_data::PrimitiveData::Unsigned(42)
                ),
                data_type: None,
                data: vec![],
            }
        );
        assert_eq!(42u32.oneof_variant(), None);
    }
}