reallyme-buffa-codegen 0.1.3

ReallyMe fork: Shared code generation logic for buffa (descriptor → Rust source)
Documentation
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
//! Owned-view wrapper codegen: `FooOwnedView` structs and field accessors.

use super::*;

/// A simple message with an implicit-presence string and an int32.
fn simple_msg_file(proto_name: &str) -> FileDescriptorProto {
    let mut file = proto3_file(proto_name);
    file.message_type.push(DescriptorProto {
        name: Some("Item".to_string()),
        field: vec![
            make_field("name", 1, Label::LABEL_OPTIONAL, Type::TYPE_STRING),
            make_field("count", 2, Label::LABEL_OPTIONAL, Type::TYPE_INT32),
        ],
        ..Default::default()
    });
    file
}

#[test]
fn test_owned_view_wrapper_struct_and_value_accessors() {
    let files = generate(
        &[simple_msg_file("item.proto")],
        &["item.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("should generate");
    let content = &joined(&files);
    assert!(
        content.contains("pub struct ItemOwnedView(::buffa::OwnedView<ItemView<'static>>)"),
        "missing ItemOwnedView wrapper struct: {content}"
    );
    // Copy field types are returned by value, tied to `&self` via elision.
    assert!(
        content.contains("pub fn name(&self) -> &'_ str"),
        "implicit-presence string accessor must return &str by value: {content}"
    );
    assert!(
        content.contains("pub fn count(&self) -> i32"),
        "scalar accessor must return i32 by value: {content}"
    );
    // Infrastructure surface.
    for needle in [
        "pub fn decode(",
        "pub fn decode_with_options(",
        "pub fn from_owned(",
        "pub fn view(&self) -> &ItemView<'_>",
        "pub fn to_owned_message(",
        "pub fn into_bytes(",
    ] {
        assert!(content.contains(needle), "missing `{needle}`: {content}");
    }
    // Conversions to/from the raw OwnedView.
    assert!(
        content.contains("From<::buffa::OwnedView<ItemView<'static>>> for ItemOwnedView"),
        "missing From<OwnedView> conversion: {content}"
    );
    assert!(
        content.contains("From<ItemOwnedView> for ::buffa::OwnedView<ItemView<'static>>"),
        "missing Into-OwnedView conversion: {content}"
    );
    // Natural-path re-export at the package root, same treatment as the view.
    assert!(
        content.contains("pub use self::__buffa::view::ItemOwnedView"),
        "missing natural-path re-export of the wrapper: {content}"
    );
    // The view-family trait impl and the AsRef escape hatch ride along with
    // the wrapper.
    assert!(
        content.contains("impl ::buffa::HasMessageView for"),
        "missing HasMessageView impl: {content}"
    );
    assert!(
        content.contains("type ViewHandle = ItemOwnedView"),
        "HasMessageView::ViewHandle must name the wrapper: {content}"
    );
    assert!(
        content.contains("AsRef<::buffa::OwnedView<ItemView<'static>>> for ItemOwnedView"),
        "missing AsRef impl: {content}"
    );
    // The `unsafe` marker every `OwnedView` constructor requires, emitted
    // via the macro so the output stays valid under `forbid(unsafe_code)`.
    assert!(
        content.contains("::buffa::unsafe_impl_view_lifetime_parametric!(ItemView);"),
        "missing ViewLifetimeParametric marker: {content}"
    );
}

#[test]
fn borrowed_only_views_do_not_expose_standard_owners() {
    let mut file = simple_msg_file("item.proto");
    let mut child = make_field("child", 1, Label::LABEL_OPTIONAL, Type::TYPE_MESSAGE);
    child.type_name = Some(".Item".into());
    file.message_type.extend([
        DescriptorProto {
            name: Some("Container".into()),
            field: vec![child],
            ..Default::default()
        },
        DescriptorProto {
            name: Some("Unrelated".into()),
            ..Default::default()
        },
    ]);
    let config = CodeGenConfig {
        borrowed_views_only_in: vec![".Item".into()],
        lazy_views: true,
        ..Default::default()
    };
    let content = joined(&generate(&[file], &["item.proto".into()], &config).unwrap());
    for name in ["Item", "Container"] {
        assert!(content.contains(&format!("pub struct {name}View<'a>")));
        assert!(content.contains(&format!("pub struct {name}LazyView<'a>")));
        assert!(!content.contains(&format!("{name}OwnedView")));
    }
    assert!(!content.contains("type ViewHandle = ItemOwnedView"));
    assert!(content.contains("type ViewHandle = UnrelatedOwnedView"));
}

/// Cleanup messages and their containers never get a standard owned-view
/// wrapper: its `from_owned` would encode the guarded owner into ordinary,
/// clonable `Bytes`.
#[test]
fn cleanup_messages_do_not_expose_standard_owners() {
    let mut file = proto3_file("cleanup.proto");
    file.package = Some("cleanup".into());
    let mut record = make_field("record", 1, Label::LABEL_OPTIONAL, Type::TYPE_MESSAGE);
    record.type_name = Some(".cleanup.Record".into());
    file.message_type.extend([
        DescriptorProto {
            name: Some("Record".into()),
            field: vec![
                make_field("handle", 1, Label::LABEL_OPTIONAL, Type::TYPE_UINT64),
                make_field("values", 2, Label::LABEL_REPEATED, Type::TYPE_FLOAT),
            ],
            nested_type: vec![DescriptorProto {
                name: Some("Inner".into()),
                field: vec![make_field(
                    "handle",
                    1,
                    Label::LABEL_OPTIONAL,
                    Type::TYPE_UINT64,
                )],
                ..Default::default()
            }],
            ..Default::default()
        },
        DescriptorProto {
            name: Some("Container".into()),
            field: vec![record],
            ..Default::default()
        },
        DescriptorProto {
            name: Some("Unrelated".into()),
            ..Default::default()
        },
    ]);
    let mut config = CodeGenConfig {
        preserve_unknown_fields: false,
        zeroize_messages: vec![".cleanup.Record".into()],
        lazy_views: true,
        ..Default::default()
    };
    // A container cannot bypass cleanup merely by wrapping a selected child.
    let error = generate(
        core::slice::from_ref(&file),
        &["cleanup.proto".into()],
        &config,
    )
    .unwrap_err();
    assert!(matches!(
        error,
        CodeGenError::InvalidZeroizeConfiguration {
            reason: ZeroizeConfigurationErrorReason::ContainingMessage,
            ..
        }
    ));
    config.zeroize_messages.push(".cleanup.Container".into());
    let content = joined(
        &generate(
            core::slice::from_ref(&file),
            &["cleanup.proto".into()],
            &config,
        )
        .unwrap(),
    );
    for name in ["Record", "Inner", "Container"] {
        assert!(content.contains(&format!("pub struct {name}View<'a>")));
        assert!(content.contains(&format!("pub struct {name}LazyView<'a>")));
        assert!(!content.contains(&format!("{name}OwnedView")), "{name}");
    }
    assert!(!content.contains("type ViewHandle = RecordOwnedView"));
    assert!(content.contains("type ViewHandle = UnrelatedOwnedView"));

    config.zeroize_messages.clear();
    config.generate_zeroize = true;
    let content = joined(&generate(&[file], &["cleanup.proto".into()], &config).unwrap());
    assert!(content.contains("pub struct UnrelatedView<'a>"));
    assert!(!content.contains("OwnedView("));
    assert!(!content.contains("type ViewHandle"));
}

#[test]
fn borrowed_only_view_rule_fails_when_unmatched() {
    let config = CodeGenConfig {
        borrowed_views_only_in: vec![".Misspelled".into()],
        ..Default::default()
    };
    assert!(matches!(
        generate(
            &[simple_msg_file("item.proto")],
            &["item.proto".into()],
            &config,
        ),
        Err(CodeGenError::BorrowedViewsRuleMatchedNothing { rule_index: 0 })
    ));
}

#[test]
fn test_owned_view_optional_string_accessor_returns_option() {
    let mut file = proto3_file("opt.proto");
    file.message_type.push(DescriptorProto {
        name: Some("Msg".to_string()),
        field: vec![FieldDescriptorProto {
            name: Some("label".to_string()),
            number: Some(1),
            label: Some(Label::LABEL_OPTIONAL),
            r#type: Some(Type::TYPE_STRING),
            proto3_optional: Some(true),
            oneof_index: Some(0),
            ..Default::default()
        }],
        oneof_decl: vec![OneofDescriptorProto {
            name: Some("_label".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    });
    let files = generate(
        &[file],
        &["opt.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("should generate");
    let content = &joined(&files);
    assert!(
        content.contains("pub fn label(&self) -> ::core::option::Option<&'_ str>"),
        "explicit-presence string accessor must return Option<&str>: {content}"
    );
}

#[test]
fn test_owned_view_message_repeated_and_map_accessors_return_refs() {
    let mut file = proto3_file("containers.proto");
    file.message_type.push(DescriptorProto {
        name: Some("Inner".to_string()),
        field: vec![make_field("v", 1, Label::LABEL_OPTIONAL, Type::TYPE_INT32)],
        ..Default::default()
    });
    let mut msg_field = make_field("inner", 1, Label::LABEL_OPTIONAL, Type::TYPE_MESSAGE);
    msg_field.type_name = Some(".Inner".to_string());
    let mut map_field = make_field("labels", 3, Label::LABEL_REPEATED, Type::TYPE_MESSAGE);
    map_field.type_name = Some(".Holder.LabelsEntry".to_string());
    let map_entry = DescriptorProto {
        name: Some("LabelsEntry".to_string()),
        field: vec![
            make_field("key", 1, Label::LABEL_OPTIONAL, Type::TYPE_STRING),
            make_field("value", 2, Label::LABEL_OPTIONAL, Type::TYPE_STRING),
        ],
        options: MessageOptions {
            map_entry: Some(true),
            ..Default::default()
        }
        .into(),
        ..Default::default()
    };
    file.message_type.push(DescriptorProto {
        name: Some("Holder".to_string()),
        field: vec![
            msg_field,
            make_field("tags", 2, Label::LABEL_REPEATED, Type::TYPE_STRING),
            map_field,
        ],
        nested_type: vec![map_entry],
        ..Default::default()
    });
    let files = generate(
        &[file],
        &["containers.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("should generate");
    let content = &joined(&files);
    // Non-Copy container fields are handed out by reference.
    assert!(
        content.contains("pub fn inner(&self) -> &::buffa::MessageFieldView<")
            || content
                .contains("pub fn inner(\n        &self,\n    ) -> &::buffa::MessageFieldView<"),
        "message-field accessor must return &MessageFieldView: {content}"
    );
    assert!(
        content.contains("&::buffa::RepeatedView<'_, &'_ str>"),
        "repeated-string accessor must return &RepeatedView<'_, &str>: {content}"
    );
    assert!(
        content.contains("&::buffa::MapView<'_, &'_ str, &'_ str>"),
        "map accessor must return &MapView<'_, &str, &str>: {content}"
    );
    // Map-entry synthetic messages must not get a wrapper.
    assert!(
        !content.contains("LabelsEntryOwnedView"),
        "map-entry synthetic message must not get an owned-view wrapper: {content}"
    );
}

#[test]
fn test_owned_view_oneof_accessor_returns_option_ref() {
    let mut file = proto3_file("oneof.proto");
    file.message_type.push(DescriptorProto {
        name: Some("Request".to_string()),
        field: vec![
            FieldDescriptorProto {
                name: Some("count".to_string()),
                number: Some(1),
                label: Some(Label::LABEL_OPTIONAL),
                r#type: Some(Type::TYPE_INT32),
                oneof_index: Some(0),
                ..Default::default()
            },
            FieldDescriptorProto {
                name: Some("text".to_string()),
                number: Some(2),
                label: Some(Label::LABEL_OPTIONAL),
                r#type: Some(Type::TYPE_STRING),
                oneof_index: Some(0),
                ..Default::default()
            },
        ],
        oneof_decl: vec![OneofDescriptorProto {
            name: Some("payload".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    });
    let files = generate(
        &[file],
        &["oneof.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("should generate");
    let content = &joined(&files);
    assert!(
        content.contains("pub fn payload("),
        "missing oneof accessor: {content}"
    );
    assert!(
        content.contains(".payload.as_ref()"),
        "oneof accessor must return Option<&Kind> via as_ref(): {content}"
    );
}

#[test]
fn test_owned_view_reserved_field_name_suppressed_with_warning() {
    let mut file = proto3_file("reserved.proto");
    file.message_type.push(DescriptorProto {
        name: Some("Blob".to_string()),
        field: vec![
            // Collides with the wrapper's inherent `bytes()` method.
            make_field("bytes", 1, Label::LABEL_OPTIONAL, Type::TYPE_STRING),
            make_field("ok", 2, Label::LABEL_OPTIONAL, Type::TYPE_STRING),
        ],
        ..Default::default()
    });
    let (files, warnings) = generate_with_diagnostics(
        &[file],
        &["reserved.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("should generate");
    let content = &joined(&files);
    // The buffer accessor keeps its meaning; no string accessor is emitted
    // for the colliding field, but the unaffected sibling still gets one.
    assert!(
        content.contains("pub fn bytes(&self) -> &::buffa::bytes::Bytes"),
        "inherent bytes() must survive: {content}"
    );
    assert!(
        !content.contains("pub fn bytes(&self) -> &'_ str"),
        "colliding field accessor must be suppressed: {content}"
    );
    assert!(
        content.contains("pub fn ok(&self) -> &'_ str"),
        "non-colliding accessor must still be generated: {content}"
    );
    assert!(
        warnings.iter().any(|w| matches!(
            w,
            CodeGenWarning::OwnedViewAccessorSuppressed { wrapper_name, field_name }
                if wrapper_name == "BlobOwnedView" && field_name == "bytes"
        )),
        "expected an OwnedViewAccessorSuppressed warning: {warnings:?}"
    );
}

#[test]
fn test_owned_view_not_generated_without_views() {
    let files = generate(
        &[simple_msg_file("noview.proto")],
        &["noview.proto".to_string()],
        &CodeGenConfig {
            generate_views: false,
            ..CodeGenConfig::default()
        },
    )
    .expect("should generate");
    let content = &joined(&files);
    assert!(
        !content.contains("OwnedView"),
        "no owned-view wrapper without generate_views: {content}"
    );
}

#[test]
fn test_owned_view_serialize_impl_gated_on_json() {
    let with_json = generate(
        &[simple_msg_file("json_on.proto")],
        &["json_on.proto".to_string()],
        &CodeGenConfig {
            generate_json: true,
            ..CodeGenConfig::default()
        },
    )
    .expect("should generate");
    let content = &joined(&with_json);
    assert!(
        content.contains("impl ::serde::Serialize for ItemOwnedView"),
        "json config must emit a Serialize forwarding impl for the wrapper: {content}"
    );

    let without_json = generate(
        &[simple_msg_file("json_off.proto")],
        &["json_off.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("should generate");
    let content = &joined(&without_json);
    assert!(
        !content.contains("impl ::serde::Serialize for ItemOwnedView"),
        "no wrapper Serialize impl without generate_json: {content}"
    );
}