objs 0.1.0

Lightweight macros for creating typed, or untyped, named, or anonymous objects in Rust.
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
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//! # objs
//!
//! `objs` is a tiny macro library for creating **named** and **unnamed
//! (anonymous)** struct-backed objects on the fly, without having to
//! declare a `struct` up front.
//!
//! It provides three macros:
//!
//! - [`obj!`] — build an anonymous, explicitly-typed object (great for
//!   one-off values, test fixtures, or small "record" types).
//! - [`infer_obj!`] — build an anonymous object whose field types are
//!   inferred generically from the values you give it.
//! - [`let_obj!`] — declare a **named** struct type and bind an instance
//!   of it to a local variable (with the same name as the type) in a
//!   single expression, optionally mutable, optionally with `impl` blocks.
//!
//! All three macros expand to a real, ordinary Rust `struct` under the
//! hood, so the objects you get back are fully-typed, zero-cost, and can
//! implement traits like any other struct.
//!
//! ## Quick example
//!
//! ```rust
//! use objs::obj;
//!
//! let point = obj! {
//!     x: i32 = 10,
//!     y: i32 = 20,
//! };
//!
//! assert_eq!(point.x, 10);
//! assert_eq!(point.y, 20);
//! ```

/// Creates an anonymous, explicitly-typed object.
///
/// `obj!` expands to a locally-scoped `struct Object { .. }` with the
/// fields you specify, plus an instance of it initialized with the given
/// values. Because the type is explicitly annotated per field, the
/// resulting struct is a normal, concrete type — not generic — so it can
/// implement traits and be passed around like any other value.
///
/// # Syntax
///
/// ```text
/// obj! {
///     [#[attributes]]
///     field_name: FieldType = value,
///     ...
///     [; impl [Trait] { .. } ...]
/// }
/// ```
///
/// - Field list: comma-separated `name: Type = value` pairs. A trailing
///   comma is optional. The list may be empty.
/// - Attributes (e.g. `#[derive(Debug)]`, `#[allow(dead_code)]`) may be
///   placed before the field list and are forwarded to the generated
///   struct definition.
/// - After a `;`, one or more `impl [Trait] { .. }` blocks may follow to
///   implement inherent methods or traits directly on the generated
///   `Object` type.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// use objs::obj;
///
/// let point = obj! {
///     x: i32 = 10,
///     y: i32 = 20,
/// };
///
/// assert_eq!(point.x, 10);
/// assert_eq!(point.y, 20);
/// ```
///
/// Implementing a trait on the anonymous object:
///
/// ```rust
/// use objs::obj;
/// use std::fmt;
///
/// let person = obj! {
///     name: String = "Alice".to_string(),
///     age: u32 = 30;
///     impl fmt::Display {
///         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///             write!(f, "{} is {}", self.name, self.age)
///         }
///     }
/// };
///
/// assert_eq!(format!("{}", person), "Alice is 30");
/// ```
///
/// Adding inherent methods (no trait) via a bare `impl { .. }` block:
///
/// ```rust
/// use objs::obj;
///
/// let calculator = obj! {
///     factor: i32 = 2;
///     impl {
///         fn multiply(&self, val: i32) -> i32 {
///             val * self.factor
///         }
///     }
/// };
///
/// assert_eq!(calculator.multiply(5), 10);
/// ```
///
/// Forwarding attributes to the generated struct:
///
/// ```rust
/// use objs::obj;
///
/// let detailed_obj = obj! {
///     #[allow(dead_code)]
///     secret: i32 = 99,
/// };
///
/// assert_eq!(detailed_obj.secret, 99);
/// ```
///
/// An empty object is also valid:
///
/// ```rust
/// use objs::obj;
///
/// let empty = obj! {};
/// drop(empty);
/// ```
///
/// # Notes
///
/// - The generated struct is always named `Object` internally. Since it
///   is scoped to the block the macro expands into, this does not
///   collide with other uses of `obj!` elsewhere, but it does mean you
///   cannot refer to the type by name outside of that block. If you need
///   a nameable type, use [`let_obj!`] instead.
#[macro_export]
macro_rules! obj {
    (
        $(#[$attr:meta])*
        $($name:ident: $field_type:ty = $value:expr),* $(,)?
        $(; $( impl $($trt:ty)? { $($items:tt)* } )* )?
    ) => {
        {
            $(#[$attr])*
            struct Object {
                $($name: $field_type,)*
            }

            $(
                $(impl $($trt for)? Object {
                    $($items)*
                })*
            )?


            Object {
                $($name: $value,)*
            }
        }
    };
}

/// Creates an anonymous object with field types inferred from their values.
///
/// `infer_obj!` is like [`obj!`], except you don't write out the field
/// types yourself. Instead, each field's type becomes its own generic
/// parameter on the generated struct, and Rust's type inference figures
/// out the concrete type from the value expression you provide. This is
/// convenient for quick, throwaway objects where writing explicit types
/// would just be noise.
///
/// # Syntax
///
/// ```text
/// infer_obj! {
///     [#[attributes]]
///     field_name: value,
///     ...
/// }
/// ```
///
/// - Field list: comma-separated `name: value` pairs. A trailing comma is
///   optional. The list may be empty.
/// - Attributes may be placed before the field list and are forwarded to
///   the generated struct definition.
///
/// # Examples
///
/// ```rust
/// use objs::infer_obj;
///
/// let mixed = infer_obj! {
///     integer: 42,
///     float: 3.14,
///     text: "Hello",
/// };
///
/// assert_eq!(mixed.integer, 42);
/// assert_eq!(mixed.float, 3.14);
/// assert_eq!(mixed.text, "Hello");
/// ```
///
/// Objects can be nested, since the inner `infer_obj!` call is just
/// another expression:
///
/// ```rust
/// use objs::infer_obj;
///
/// let complex = infer_obj! {
///     id: 1,
///     nested: infer_obj! {
///         inner_val: "nested",
///     },
/// };
///
/// assert_eq!(complex.id, 1);
/// assert_eq!(complex.nested.inner_val, "nested");
/// ```
///
/// An empty object is also valid:
///
/// ```rust
/// use objs::infer_obj;
///
/// let empty = infer_obj! {};
/// drop(empty);
/// ```
///
/// # Notes
///
/// - `infer_obj!` does not support `impl` blocks, since the generated
///   struct is generic over each field's type — implementing a trait or
///   method on it would require naming those generic type parameters
///   yourself, defeating the purpose of the macro. If you need to
///   attach behavior, use [`obj!`] (explicit types) or [`let_obj!`]
///   (named types) instead.
/// - Each field name doubles as the generic type parameter name for that
///   field, so field names must be valid, unique generic identifiers.
#[macro_export]
macro_rules! infer_obj {
    (
        $(#[$attr:meta])*
        $($name:ident: $value:expr),* $(,)?
    ) => {
        {
            $(#[$attr])*
            #[allow(non_camel_case_types)]
            struct Object<$($name),*> {
                $($name: $name,)*
            }

            Object {
                $($name: $value,)*
            }
        }
    };
}

/// Declares a named struct type and binds an instance of it to a local
/// variable in one step.
///
/// Unlike [`obj!`] and [`infer_obj!`], which produce anonymous,
/// block-scoped types, `let_obj!` defines a real, nameable struct (using
/// the name you give it) and creates a local variable with **the same
/// name** bound to an instance of it. Because the struct type is left in
/// scope, you can also construct additional instances of it later using
/// ordinary struct-literal syntax.
///
/// # Syntax
///
/// ```text
/// let_obj! {
///     [#[attributes]]
///     [mut] TypeName {
///         field_name: FieldType = value,
///         ...
///     }
///     [impl [Trait] { .. }]...
/// }
/// ```
///
/// - `TypeName` becomes both the struct's type name and the local
///   variable's name.
/// - The optional `mut` keyword makes the bound variable mutable.
/// - Field list: comma-separated `name: Type = value` pairs, with an
///   optional trailing comma. The list may be empty.
/// - Attributes placed before `TypeName` are forwarded to the generated
///   struct definition.
/// - Zero or more `impl [Trait] { .. }` blocks may follow the field list
///   to implement inherent methods or traits on `TypeName`.
///
/// # Examples
///
/// Immutable object:
///
/// ```rust
/// use objs::let_obj;
///
/// let_obj! {
///     User {
///         id: u64 = 1001,
///         active: bool = true,
///     }
/// };
///
/// assert_eq!(User.id, 1001);
/// assert_eq!(User.active, true);
/// ```
///
/// Mutable object:
///
/// ```rust
/// use objs::let_obj;
///
/// let_obj! {
///     mut Counter {
///         count: i32 = 0,
///     }
/// };
///
/// assert_eq!(Counter.count, 0);
/// Counter.count += 5;
/// assert_eq!(Counter.count, 5);
/// ```
///
/// Implementing a trait, and reusing the generated type by name:
///
/// ```rust
/// use objs::let_obj;
///
/// trait Greeter {
///     fn greet(&self) -> String;
/// }
///
/// let_obj! {
///     Bot {
///         name: &'static str = "Robo",
///     }
///     impl Greeter {
///         fn greet(&self) -> String {
///             format!("Hello from {}", self.name)
///         }
///     }
/// };
///
/// assert_eq!(Bot.greet(), "Hello from Robo");
///
/// // The `Bot` type is left in scope, so it can be constructed again
/// // explicitly, just like a normal struct.
/// let another_bot: Bot = Bot { name: "Android" };
/// assert_eq!(another_bot.name, "Android");
/// ```
///
/// An empty object is also valid:
///
/// ```rust
/// use objs::let_obj;
///
/// let_obj! {
///     EmptyObj {}
/// };
///
/// let _copy = EmptyObj;
/// ```
///
/// # Notes
///
/// - Since the generated variable shares its name with the generated
///   type, `let_obj!` uses `#[allow(non_camel_case_types)]` and
///   `#[allow(non_snake_case)]` internally so that conventional
///   `PascalCase` type names don't trigger lint warnings when reused as
///   a variable name.
/// - Because the type is a genuine, named `struct`, it can be used
///   anywhere a normal struct can: as a function parameter or return
///   type, stored in a collection, etc.
#[macro_export]
macro_rules! let_obj {
    (
        $(#[$attr:meta])*
        $obj_name:ident { $($name:ident: $field_type:ty = $value:expr),* $(,)? }
        $( impl $($trt:ty)? { $($items:tt)* } )*
    ) => {
        $(#[$attr])*
        #[allow(non_camel_case_types)]
        struct $obj_name {
            $($name: $field_type,)*
        }

        $(impl $($trt for)? $obj_name {
            $($items)*
        })*

        #[allow(non_snake_case)]
        let $obj_name = $obj_name {
            $($name: $value,)*
        };
    };

    (
        $(#[$attr:meta])*
        mut $obj_name:ident { $($name:ident: $field_type:ty = $value:expr),* $(,)? }
        $( impl $($trt:ty)? { $($items:tt)* } )*
    ) => {
        $(#[$attr])*
        #[allow(non_camel_case_types)]
        struct $obj_name {
            $($name: $field_type,)*
        }

        $(impl $($trt for)? $obj_name { $($items)* })*


        #[allow(non_snake_case)]
        let mut $obj_name = $obj_name {
            $($name: $value,)*
        };
    };
}

#[cfg(test)]
/// AI Generated Tests
mod tests {
    // ==========================================
    // Tests for obj! (Typed Anonymous Objects)
    // ==========================================

    #[test]
    fn test_obj_basic() {
        let point = obj! {
            x: i32 = 10,
            y: i32 = 20,
        };
        assert_eq!(point.x, 10);
        assert_eq!(point.y, 20);
    }

    #[test]
    fn test_obj_trailing_comma() {
        // Test no trailing comma
        let point = obj! { x: i32 = 5, y: i32 = 10 };
        assert_eq!(point.x, 5);
    }

    #[test]
    fn test_obj_with_impl() {
        use std::fmt;

        let person = obj! {
            name: String = "Alice".to_string(),
            age: u32 = 30;
            impl fmt::Display {
                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                    write!(f, "{} is {}", self.name, self.age)
                }
            }
        };

        assert_eq!(format!("{}", person), "Alice is 30");
    }

    #[test]
    fn test_obj_with_custom_methods() {
        let calculator = obj! {
            factor: i32 = 2;
            impl {
                fn multiply(&self, val: i32) -> i32 {
                    val * self.factor
                }
            }
        };

        assert_eq!(calculator.multiply(5), 10);
    }

    #[test]
    fn test_attributes_forwarding() {
        // Ensures attributes like #[derive(Debug)] or documentation pass through correctly
        let detailed_obj = obj! {
            #[allow(dead_code)]
            secret: i32 = 99,
        };

        assert_eq!(detailed_obj.secret, 99);
    }

    // ==========================================
    // Tests for infer_obj! (Untyped Anonymous Objects)
    // ==========================================

    #[test]
    fn test_infer_obj_basic() {
        let mixed = infer_obj! {
            integer: 42,
            float: 3.14,
            text: "Hello",
        };

        assert_eq!(mixed.integer, 42);
        assert_eq!(mixed.float, 3.14);
        assert_eq!(mixed.text, "Hello");
    }

    // ==========================================
    // Tests for let_obj! (Named Variable Declarations)
    // ==========================================

    #[test]
    fn test_let_obj_immutable() {
        // This macro creates a struct named `User` and a variable named `User` in scope.
        let_obj! {
            User {
                id: u64 = 1001,
                active: bool = true,
            }
        };

        // Test the generated instance variable
        assert_eq!(User.id, 1001);
        assert_eq!(User.active, true);
    }

    #[test]
    fn test_let_obj_mutable() {
        let_obj! {
            mut Counter {
                count: i32 = 0,
            }
        };

        assert_eq!(Counter.count, 0);
        Counter.count += 5; // Verifies mutability works
        assert_eq!(Counter.count, 5);
    }

    #[test]
    fn test_let_obj_with_impl() {
        trait Greeter {
            fn greet(&self) -> String;
        }

        let_obj! {
            Bot {
                name: &'static str = "Robo",
            }
            impl Greeter {
                fn greet(&self) -> String {
                    format!("Hello from {}", self.name)
                }
            }
        };

        assert_eq!(Bot.greet(), "Hello from Robo");

        // Verifies the structural type itself can also be used explicitly
        // because let_obj! leaks the type to the local scope
        let another_bot: Bot = Bot { name: "Android" };
        assert_eq!(another_bot.name, "Android");
    }

    #[test]
    fn test_let_obj_mutability() {
        let_obj! {
        mut player {
            hp: i32 = 100,
            score: u32 = 0,
        }
    };

        // Verify initial values
        assert_eq!(player.hp, 100);
        assert_eq!(player.score, 0);

        // Mutate the fields directly
        player.hp -= 20;
        player.score += 150;

        // Verify mutations took effect
        assert_eq!(player.hp, 80);
        assert_eq!(player.score, 150);
    }

    // ==========================================
    // Edge Cases for obj!
    // ==========================================

    #[test]
    fn test_obj_empty() {
        // Tests an empty anonymous object (unit-like struct behavior)
        let empty = obj! {};

        // We can't check fields, but we can verify it compiles and can be dropped
        drop(empty);
    }

    #[test]
    fn test_obj_single_field() {
        // Tests the macro's handling of exactly one field (with and without comma)
        let single = obj! { data: i32 = 42 };
        assert_eq!(single.data, 42);

        let single_comma = obj! { data: i32 = 42, };
        assert_eq!(single_comma.data, 42);
    }

    // ==========================================
    // Edge Cases for infer_obj!
    // ==========================================

    #[test]
    fn test_infer_obj_empty() {
        // Tests an empty inferred object
        let empty_infer = infer_obj! {};
        drop(empty_infer);
    }

    #[test]
    fn test_infer_obj_single_field() {
        let single = infer_obj! { value: "only one" };
        assert_eq!(single.value, "only one");
    }

    #[test]
    fn test_infer_obj_nested() {
        // This works because Rust infers the inner generic types
        let complex = infer_obj! {
        id: 1,
        nested: infer_obj! {
            inner_val: "nested",
        },
    };

        assert_eq!(complex.id, 1);
        assert_eq!(complex.nested.inner_val, "nested");
    }

    // ==========================================
    // Edge Cases for let_obj!
    // ==========================================

    #[test]
    fn test_let_obj_empty() {
        // Tests creating an empty named object structure and variable
        let_obj! {
            EmptyObj {}
        };

        // Verifies the instance exists
        let _copy = EmptyObj;
    }

    #[test]
    fn test_let_obj_empty_mut() {
        // Tests creating an empty mutable named object structure and variable
        let_obj! {
            mut EmptyMutObj {}
        };

        let _copy = EmptyMutObj;
    }

    #[test]
    fn test_let_obj_shadowing() {
        // Tests that the macro can handle field names that match common primitive types
        // or variables existing in the outer scope.
        let local_val = 100;

        let_obj! {
            ShadowTest {
                local_val: i32 = local_val,
                u32: i32 = 200, // field named 'u32' matching a type keyword
            }
        };

        assert_eq!(ShadowTest.local_val, 100);
        assert_eq!(ShadowTest.u32, 200);
    }
}