async_codegen/rust/
mod.rs

1/*
2 * Copyright © 2025 Anand Beh
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//!
18//! Rust syntax elements.
19//!
20//! Note that no checking exists to make sure the elements are used correctly, i.e. the correct
21//! combination of structs. Instead, the library user is expected to have basic knowledge of how
22//! Rust syntax is composed, and to combine the structs in this module likewise.
23//!
24//! Example:
25//!
26//! ```
27//! # use async_codegen::common::{CombinedSeq, NoOpSeq, SingularSeq, Str};
28//! # use async_codegen::{Output, Writable};
29//! # use async_codegen::rust::{CanHaveAttributes, CfgAttr, Deprecated, FunctionBodyImplement, FunctionDef, FunctionParam, ModPub, MustUse, NoMangle, Parameterized};
30//!
31//! async fn write_function<O>(output: &mut O) -> Result<(), O::Error> where O: Output {
32//!   // For more advanced usage, you can replace Str("") by other Writable implementations
33//!   let function_def = FunctionDef {
34//!     mods: SingularSeq(ModPub),
35//!     name: Str("my_func"),
36//!     args: CombinedSeq(
37//!      SingularSeq(FunctionParam(Str("var1"), Str("Type"))),
38//!      SingularSeq(FunctionParam(Str("var2"), Parameterized(Str("Option"), SingularSeq(Str("bool")))))
39//!     ),
40//!     return_type: Parameterized(Str("Box"), SingularSeq(Str("str"))),
41//!     where_conds: NoOpSeq,
42//!     body: FunctionBodyImplement(Str("todo!()"))
43//!   };
44//!   function_def.write_to(output).await
45//!   // Will render as:
46//!   /*
47//!   pub fn my_func(var1: Type, var2: Option<bool>) -> Box<str> {
48//!     todo!()
49//!   }
50//!    */
51//! }
52//! ```
53//!
54
55use crate::common::{Combined, NoOp, NoOpSeq, Str, SurroundingSeqAccept};
56use crate::{Output, SequenceAccept, Writable};
57use std::fmt::Debug;
58
59mod syntax;
60#[cfg(test)]
61mod tests;
62
63/// All possible Rust editions.
64/// This is the only type in this module meant to be used as context, and not as a writable itself.
65#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
66#[non_exhaustive]
67pub enum Edition {
68    /// This Rust edition is declared for usability purposes. However, not all [Writable]
69    /// implementations are guaranteed to work with it.
70    Rust2015,
71    Rust2018,
72    Rust2021,
73    Rust2024,
74}
75
76/// Imports a single type so that it can be used later.
77/// Renders as `use Type;`. Adds a new line after the semicolon.
78#[derive(Clone, Debug)]
79pub struct UseType<Type>(pub Type);
80
81/// An attribute enabled conditionally, i.e. `#[cfg_attr(Cond, Attr)]`
82#[derive(Clone, Debug)]
83pub struct CfgAttr<Cond, Attr>(pub Cond, pub Attr);
84
85/// A cfg attribute. Renders as `cfg(Cond)`.
86#[derive(Clone, Debug)]
87pub struct Cfg<Cond>(pub Cond);
88
89/// A cfg condition for targeting an OS, OS family, or architecture. For example:
90/// ```
91/// # use async_codegen::common::{NoOpSeq, SingularSeq, Str};
92/// # use async_codegen::context::EmptyContext;
93/// # use async_codegen::rust::{FunctionBodyDeclare, Cfg, FunctionDef, Target, CanHaveAttributes};
94/// # use async_codegen::util::InMemoryOutput;
95/// let function = FunctionDef {
96///   mods: NoOpSeq,
97///   name: Str("conditional_func"),
98///   args: NoOpSeq,
99///   return_type: Str("()"),
100///   where_conds: NoOpSeq,
101///   body: FunctionBodyDeclare
102/// }.with_attributes(
103///   SingularSeq(Cfg(Target::Os(Str("linux"))))
104/// );
105/// let string = InMemoryOutput::print_output(EmptyContext, &function);
106/// assert_eq!("#[cfg(target_os = \"linux\")]\nfn conditional_func() -> ();\n", string);
107/// ```
108#[derive(Clone, Debug)]
109pub enum Target<Value> {
110    Os(Value),
111    Family(Value),
112    Arch(Value),
113}
114
115/// The link attribute.
116#[derive(Clone, Debug)]
117pub struct Link<Arg>(pub Arg);
118
119/// The no mangle attribute.
120///
121/// Requires that the context satisfies [ContextProvides] for [Edition], because in Rust 2024 and
122/// beyond, the no-mangle attribute is an unsafe attribute.
123#[derive(Clone, Debug)]
124pub struct NoMangle;
125
126/// The attribute content for `allow(...)`. The tuple value must be a sequence.
127#[derive(Clone, Debug)]
128pub struct AllowLints<Lints>(pub Lints);
129
130/// The deprecated attribute. The three variants of this enum correspond to the deprecated
131/// attribute's multiple ways of being specified. See:
132/// https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute
133#[derive(Clone, Debug)]
134pub enum Deprecated<Msg, Since = NoOp> {
135    Basic,
136    Message(Msg),
137    Full { since: Since, note: Msg },
138}
139
140impl Default for Deprecated<NoOp, NoOp> {
141    fn default() -> Self {
142        Self::Basic
143    }
144}
145
146impl Deprecated<NoOp, NoOp> {
147    pub fn basic() -> Self {
148        Self::Basic
149    }
150}
151
152impl<Msg> Deprecated<Msg> {
153    pub fn with_message(msg: Msg) -> Self {
154        Self::Message(msg)
155    }
156}
157
158/// The must_use attribute
159#[derive(Clone, Debug)]
160pub struct MustUse;
161
162/// The public modifier
163#[derive(Clone, Debug)]
164pub struct ModPub;
165
166/// The unsafe modifier
167#[derive(Clone, Debug)]
168pub struct ModUnsafe;
169
170/// The extern modifier, with the ABI selected as the tuple value.
171///
172/// This struct includes `unsafe`. Since Rust 2024, the unsafe keyword is required for extern
173/// functions, and before Rust 2024 it is optional. To make it easy to generate code targeting
174/// multiple editions, we unconditionally emit the "unsafe" keyword alongside "extern".
175#[derive(Clone, Debug)]
176pub struct ModUnsafeExtern<Abi>(pub Abi);
177
178/// A standalone statement. Renders the expression and adds a semicolon and a new line.
179#[derive(Clone, Debug)]
180pub struct Stmt<Expr>(pub Expr);
181
182/// A let statement. This statement includes the semicolon and a new line.
183#[derive(Clone, Debug)]
184pub struct LetStmt<Variable, Expr>(pub Variable, pub Expr);
185
186/// An assignation. This statement includes the semicolon and a new line.
187#[derive(Clone, Debug)]
188pub struct AssignStmt<Variable, Expr>(pub Variable, pub Expr);
189
190/// A return statement. Renders as `return Expr;` with a new line at the end.
191#[derive(Clone, Debug)]
192pub struct ReturnStmt<Expr>(pub Expr);
193
194/// A let expression.
195/// This can be used, for example, as the condition of [IfBlock] in order to create an "if-let" block.
196#[derive(Clone, Debug)]
197pub struct LetExpr<Pattern, Expr>(pub Pattern, pub Expr);
198
199/// A raw string literal expression, i.e. r#"Content"#. Example:
200/// ```
201/// # use async_codegen::common::Str;
202/// # use async_codegen::context::EmptyContext;
203/// # use async_codegen::rust::RawStringLiteral;
204/// # use async_codegen::util::InMemoryOutput;
205/// let string_lit = RawStringLiteral(Str("hello_world"));
206///
207/// assert_eq!("r#\"hello_world\"#", InMemoryOutput::print_output(EmptyContext, &string_lit));
208/// ```
209#[derive(Clone, Debug)]
210pub struct RawStringLiteral<Content>(pub Content);
211
212/// An array literal with predefined elements written out.
213/// Renders as `[E1, E2, E3, ...]` where EX is in the element sequence.
214#[derive(Clone, Debug)]
215pub struct ArrayFromElements<Elements>(pub Elements);
216
217/// An item attached to an associated container, via "::".
218/// The output will look like `Cont::Item`.
219#[derive(Clone, Debug)]
220pub struct AssociatedItem<Cont, Item>(pub Cont, pub Item);
221
222/// A question mark following another expression.
223#[derive(Clone, Debug)]
224pub struct QuestionMarkAfter<Expr>(pub Expr);
225
226/// Wraps an expression in `Ok(EXPR)`.
227#[derive(Clone, Debug)]
228pub struct OkResultOf<Expr>(pub Expr);
229
230/// Uses the `as` expression to perform a qualified trait cast (ready for a method call).
231/// I.e., this will render as `<Type as Trait>`.
232#[derive(Clone, Debug)]
233pub struct TypeAsTrait<Type, Trait>(pub Type, pub Trait);
234
235/// Declaration of an extern block, i.e. for FFI.
236/// In Rust 2024 and later, the unsafe keyword must be added for extern blocks. Thus, this struct
237/// requires that the context satisfies [ContextProvides] for [Edition].
238#[derive(Clone, Debug)]
239pub struct ExternBlock<Abi, Body> {
240    /// The ABI chosen. Must be writable
241    pub abi: Abi,
242    /// The body of the extern block. Must be writable
243    pub body: Body,
244}
245
246impl<Abi, Body> CanHaveAttributes for ExternBlock<Abi, Body> {
247    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
248        WithAttributes {
249            attr,
250            separator: "\n",
251            value: self,
252        }
253    }
254}
255
256/// Declaration of a module block. Renders as `mod Mod {Body}`.
257#[derive(Clone, Debug)]
258pub struct ModBlock<Name, Body> {
259    /// The module name
260    pub name: Name,
261    /// The body. Must be writable
262    pub body: Body,
263}
264
265/// An if block. The condition and body must both be writable.
266#[derive(Clone, Debug)]
267pub struct IfBlock<Cond, Body>(pub Cond, pub Body);
268
269/// Represents "else" syntactically. Renders as `Before else After`.
270///
271/// This struct requires you to specify what comes before and after the else. For example:
272/// ```
273/// # use async_codegen::common::Str;
274/// # use async_codegen::context::EmptyContext;
275/// # use async_codegen::rust::{Block, Else, IfBlock};
276/// # use async_codegen::util::InMemoryOutput;
277///
278/// let if_block = IfBlock(Str("true"), Str("log::info(\"Hello\")"));
279/// let else_block = Block(Str("panic!()"));
280/// let if_else = Else(if_block, else_block);
281///
282/// let string = InMemoryOutput::print_output(EmptyContext, &if_else);
283/// assert_eq!("if true {\nlog::info(\"Hello\")\n} else {\npanic!()\n}", string)
284/// ```
285#[derive(Clone, Debug)]
286pub struct Else<Before, After>(pub Before, pub After);
287
288/// An unlabeled block.
289/// This can be used in many contexts, including merely organizing the code.
290#[derive(Clone, Debug)]
291pub struct Block<Body>(pub Body);
292
293/// Places the expression inside an unsafe block.
294/// Adds new lines inside the brackets, wrapping the inner expression.
295#[derive(Clone, Debug)]
296pub struct UnsafeBlock<Expr>(pub Expr);
297
298/// Writes a closure.
299/// Adds new lines inside the brackets, wrapping the inner expression.
300#[derive(Clone, Debug)]
301pub struct Closure<InputVars, Expr> {
302    /// The input variables.
303    /// Should be a sequence. They will be comma separated and placed within the pipes.
304    /// To use no input variables, use [NoOpSeq].
305    pub input_vars: InputVars,
306    /// The expression inside the closure block.
307    pub inside_block: Expr,
308}
309
310/// Performs a call to a function inside code.
311#[derive(Clone, Debug)]
312pub struct FunctionCall<Recv, Name, Args> {
313    /// The function receiver
314    pub receiver: Recv,
315    /// Whether the function is associated, false if it's a method
316    pub is_assoc: bool,
317    /// The function name
318    pub name: Name,
319    /// The arguments. Must be a sequence
320    pub args: Args,
321}
322
323/// Provides access to the "turbofish" syntax, i.e. `Name::<Args>`.
324/// The first tuple value must be writable, and the second must be a sequence.
325///
326/// Note that if the sequence outputs nothing, this struct will behave as if no args were
327/// specified. I.e. `Turbofish(Name, NoOpSeq)` is equivalent to just `Name`.
328#[derive(Clone, Debug)]
329pub struct Turbofish<Name, Args>(pub Name, pub Args);
330
331/// A function declaration
332#[derive(Clone, Debug)]
333pub struct FunctionDef<Mods, Name, Args, Return, Where, Body> {
334    /// The modifiers. Must be a sequence.
335    pub mods: Mods,
336    /// The function name. Type variables can be declared here via [Parameterized]
337    pub name: Name,
338    /// The arguments. Must be a sequence
339    pub args: Args,
340    /// The return type, i.e. after the `->` arrow
341    pub return_type: Return,
342    /// The "where" conditions. Must be a sequence. Set to [NoOp] to disable.
343    /// Will render as `where C1, C2, C3, ...` where CX is a value in the sequence.
344    pub where_conds: Where,
345    /// The function body.
346    /// To only declare the function, this must be `;` so use [FunctionBodyDeclare]
347    /// To implement the function, use [FunctionBodyImplement]
348    pub body: Body,
349}
350
351impl<Mods, Name, Args, Return, Where, Body> CanHaveAttributes
352    for FunctionDef<Mods, Name, Args, Return, Where, Body>
353{
354    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
355        WithAttributes {
356            attr,
357            separator: "\n",
358            value: self,
359        }
360    }
361}
362
363/// Declares a function body. This is equivalent to just a semicolon.
364#[derive(Clone, Debug)]
365pub struct FunctionBodyDeclare;
366
367/// Implements a function body. Places the contents inside brackets
368#[derive(Clone, Debug)]
369pub struct FunctionBodyImplement<Inner>(pub Inner);
370
371/// A function pointer. Can be used for `fn`, `Fn`, `FnMut`, and `FnOnce`.
372///
373/// Example:
374/// ```
375/// # use async_codegen::common::{SingularSeq, Str};
376/// # use async_codegen::context::EmptyContext;
377/// # use async_codegen::rust::{FunctionPtr, FunctionPtrKind};
378/// # use async_codegen::util::InMemoryOutput;
379/// let function_ptr = FunctionPtr {
380///   kind: FunctionPtrKind::FnMut,
381///   args: SingularSeq(Str("String")),
382///   return_type: Str("bool")
383/// };
384/// let string = InMemoryOutput::print_output(EmptyContext, &function_ptr);
385/// assert_eq!("FnMut(String) -> bool", string);
386/// ```
387#[derive(Clone, Debug)]
388pub struct FunctionPtr<Args, Return> {
389    /// The function pointer kind
390    pub kind: FunctionPtrKind,
391    /// The arguments. Must be a sequence
392    pub args: Args,
393    /// The return type, i.e. after the `->` arrow
394    pub return_type: Return,
395}
396
397/// The kind of function type
398#[derive(Clone, Debug)]
399pub enum FunctionPtrKind {
400    /// An `fn` pointer. E.g. `fn(String) -> bool`.
401    FnPtr,
402    /// Represents [Fn]
403    Fn,
404    /// Represents [FnMut]
405    FnMut,
406    /// Represents [FnOnce]
407    FnOnce,
408}
409
410/// Renders as `Type=Value`. Intended to be used as a type argument, to specify associated types.
411#[derive(Clone, Debug)]
412pub struct AssociatedTypeEquals<Type, Value>(pub Type, pub Value);
413
414/// Adds a "dyn " before a type expression.
415#[derive(Clone, Debug)]
416pub struct DynOf<Type>(pub Type);
417
418/// Adds a "&" before a type expression
419#[derive(Clone, Debug)]
420pub struct RefOf<Type>(pub Type);
421
422/// Adds an "impl " before a type expression
423pub struct ImplOf<Type>(pub Type);
424
425/// Adds a reference with a lifetime before a type expression, i.e. `&'<lifetime> <type>`
426#[derive(Clone, Debug)]
427pub struct LifetimedRefOf<'l, Type>(pub &'l str, pub Type);
428
429/// Declares an associated type, rendering as `type VarName = Value;`.
430/// Adds new lines before and after.
431#[derive(Clone, Debug)]
432pub struct AssociatedTypeDef<VarName, Value>(pub VarName, pub Value);
433
434/// The declaration of a trait
435#[derive(Clone, Debug)]
436pub struct TraitDef<Mods, Name, TypeVars, SuperTraits, Body> {
437    /// The trait modifiers, e.g. visibility. Must be a sequence.
438    pub mods: Mods,
439    /// The name of the trait
440    pub name: Name,
441    /// The type variables. Must be a sequence
442    pub type_variables: TypeVars,
443    /// The super traits. Must be a sequence
444    pub super_traits: SuperTraits,
445    /// The trait definition's body. Use [NoOp] if none exists.
446    pub body: Body,
447}
448
449impl<Mods, Name, TypeVars, SuperTraits, Body> CanHaveAttributes
450    for TraitDef<Mods, Name, TypeVars, SuperTraits, Body>
451{
452    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
453        WithAttributes {
454            attr,
455            separator: "\n",
456            value: self,
457        }
458    }
459}
460
461/// The implementation declaration for a trait, applying to a certain receiver.
462#[derive(Clone, Debug)]
463pub struct TraitImpl<Mods, TypeVars, Trait, Recv, Where, Body> {
464    /// The modifiers on the `impl` block.
465    /// Set to [NoOpSeq] for none, or use `SingularSeq(ModUnsafe)` to generate an `unsafe impl`.
466    pub mods: Mods,
467    /// The type variables to use for the impl block itself. All type variables that appear later
468    /// on the trait or the receiver must be declared here, per Rust language rules.
469    ///
470    /// This field must be a sequence.
471    pub type_variables: TypeVars,
472    /// The trait being implemented
473    pub the_trait: Trait,
474    /// The receiver for which it is implemented
475    pub receiver: Recv,
476    /// The "where" conditions. Must be a sequence. Set to [NoOpSeq] to disable.
477    /// Will render as `where C1, C2, C3, ...` where CX is a value in the sequence.
478    pub where_conds: Where,
479    /// The body. Use [NoOp] if none exists.
480    pub body: Body,
481}
482
483impl<Mods, TypeVars, Trait, Recv, Where, Body> CanHaveAttributes
484    for TraitImpl<Mods, TypeVars, Trait, Recv, Where, Body>
485{
486    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
487        WithAttributes {
488            attr,
489            separator: "\n",
490            value: self,
491        }
492    }
493}
494
495/// The declaration of a struct.
496#[derive(Clone, Debug)]
497pub struct StructDef<Mods, Name, Elements> {
498    /// The struct modifiers. Must be a sequence.
499    pub mods: Mods,
500    /// The kind of the struct.
501    ///
502    /// It is suggested to use either a [NamedTuple] or [StructCall]. A semicolon will be
503    /// automatically added afterward, as is needed for tuple structs, and this semicolon will not
504    /// affect structs with named fields.
505    pub kind: StructKind<Name, Elements>,
506}
507
508impl<Mods, Name, Elements> CanHaveAttributes for StructDef<Mods, Name, Elements> {
509    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
510        WithAttributes {
511            attr,
512            separator: "\n",
513            value: self,
514        }
515    }
516}
517
518/// Completes the struct definition as either a named tuple or a struct with named fields.
519#[derive(Clone, Debug)]
520pub enum StructKind<Name, Elements> {
521    /// A named tuple. This will function similarly to [NamedTuple], except a semicolon will
522    /// be added afterward.
523    ///
524    /// `Name` must be writable, and `Elements` must be a writable sequence for the tuple arguments.
525    Tuple(Name, Elements),
526    /// A struct with named fields. This will function similarly to [StructCall].
527    ///
528    /// `Name` must be writable, and `Elements` must be writable sequence for the struct fields.
529    NamedFields(Name, Elements),
530}
531
532/// The construction or deconstruction of a struct.
533///
534/// When rendered, will use the format `Name { Body }`. Spaces will be added automatically.
535///
536/// This should **not** be used for tuple structs, for that see [NamedTuple].
537#[derive(Clone, Debug)]
538pub struct StructCall<Name, Body> {
539    /// The struct name. Must be writable.
540    ///
541    /// If you are declaring a struct for the first time, you can use [Parameterized] in order
542    /// to declare type variables.
543    pub name: Name,
544    /// The body. Must be writable.
545    ///
546    /// It is suggested to use [StructFields] for multiple fields, or [DeclareField] for just one.
547    pub body: Body,
548}
549
550/// Named struct fields. This will place every field on a new line with a comma afterward.
551/// It is recommended that the sequence should pass [DeclareField].
552///
553/// If you have a single field, you can skip using a sequence and just use [DeclareField] directly.
554pub struct StructFields<Fields>(pub Fields);
555
556/// Declares a single field within a struct. Renders as `Name: Value`.
557///
558/// Does not add attributes. If you want to use attributes for declaration purposes, you can use
559/// [CanHaveAttributes::with_attributes] on this field.
560pub struct DeclareField<Name, Value>(pub Name, pub Value);
561
562impl<Name, Value> CanHaveAttributes for DeclareField<Name, Value> {
563    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
564        WithAttributes {
565            attr,
566            separator: "\n",
567            value: self,
568        }
569    }
570}
571
572/// A named tuple type.
573///
574/// Renders as `Name(A1, A2, A3, ...)` where AX is part of the argument sequence.
575/// If no arguments exist, will render only as `Name` (i.e., a unit struct).
576pub struct NamedTuple<Name, Args> {
577    pub name: Name,
578    pub args: Args,
579}
580
581/// An anonymous tuple type. This struct's tuple value must be a sequence.
582///
583/// Renders as `(A1, A2, A3, ...)` where AX is part of the argument sequence.
584#[derive(Clone, Debug)]
585pub struct AnonTuple<Args>(pub Args);
586
587/// The unit type, i.e. `()`
588pub type UnitType = AnonTuple<NoOpSeq>;
589
590impl AnonTuple<NoOpSeq> {
591    /// Creates
592    pub fn unit() -> Self {
593        Self(NoOpSeq)
594    }
595}
596
597/// Adds attributes to ANY item.
598///
599/// The first tuple value must be a sequence. The second must be a writable value. This struct
600/// is typically constructed via [CanHaveAttributes::with_attributes].
601///
602/// Rust attributes can be put in many places, so this enables you to add attributes to any
603/// writable item. For example, adding attributes to function parameters can be done like so:
604///
605/// ```rust
606/// # use async_codegen::common::{SingularSeq, Str};
607/// # use async_codegen::context::EmptyContext;
608/// # use async_codegen::rust::{Cfg, FunctionParam, MustUse, Target, WithAttributes, CanHaveAttributes};
609/// # use async_codegen::util::InMemoryOutput;
610///
611/// let function_param = FunctionParam(Str("conditional_param"), Str("Fd")).with_attributes(
612///   SingularSeq(Cfg(Target::Os(Str("linux"))))
613/// );
614/// let string = InMemoryOutput::print_output(EmptyContext, &function_param);
615/// assert_eq!("#[cfg(target_os = \"linux\")] conditional_param: Fd", string);
616/// ```
617#[derive(Clone, Debug)]
618pub struct WithAttributes<Attr, Value> {
619    pub attr: Attr,
620    /// The separator. Usually a space or a new line, depending on what the target value is
621    pub separator: &'static str,
622    /// The value
623    pub value: Value,
624}
625
626/// A writable that can have attributes attached to it
627pub trait CanHaveAttributes: Sized {
628    /// Adds attributes to this writable
629    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self>;
630}
631
632/// Defines an enum.
633///
634/// In order to use or refer to an enum, you can use [AssociatedItem] together with [NamedTuple]
635/// or [StructCall].
636pub struct EnumDef<Mods, Name, Entries> {
637    /// The modifiers on the type. Must be a sequence.
638    pub mods: Mods,
639    /// The name of the enum
640    pub name: Name,
641    /// The enum entries. Must be a sequence, each entry will be written on a new line with a comma
642    ///
643    /// As for the entries themselves, it is suggested to use [NamedTuple] or [StructCall]
644    /// depending on which kind of enum entry you want to create.
645    pub entries: Entries,
646}
647
648impl<Mods, Name, Entries> CanHaveAttributes for EnumDef<Mods, Name, Entries> {
649    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
650        WithAttributes {
651            attr,
652            separator: "\n",
653            value: self,
654        }
655    }
656}
657
658/// A type argument-parameterized expression. Used in relation to parameterized names and their
659/// arguments. Examples: `function_name<args>`, `TypeName<'lifetime, args>`, `MyType<Assoc=Value>`.
660///
661/// If no type args exist, [NoOpSeq] should be used. In any case, the second tuple value of this
662/// struct must be a sequence.
663#[derive(Clone, Debug)]
664pub struct Parameterized<Name, TypeArgs>(pub Name, pub TypeArgs);
665
666/// A type variable with a sequence of bounds.
667/// Will render as `TypeVar: B1 + B2 + ...`
668#[derive(Clone, Debug)]
669pub struct BoundedTypeVar<TypeVar, Bounds>(pub TypeVar, pub Bounds);
670
671/// A standalone lifetime, intended to be used as a type argument or variable
672#[derive(Clone, Debug)]
673pub struct Lifetime<'l>(pub &'l str);
674
675/// Renders an individual function parameter, `Name: Type`
676#[derive(Clone, Debug)]
677pub struct FunctionParam<Name, Type>(pub Name, pub Type);
678
679impl<Name, Type> CanHaveAttributes for FunctionParam<Name, Type> {
680    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
681        WithAttributes {
682            attr,
683            separator: " ",
684            value: self,
685        }
686    }
687}
688
689/// A sequence acceptor that writes attributes. Every attribute will be surrounded with "#[]"
690#[derive(Debug)]
691pub struct AttributesAccept<'o, O, Sep> {
692    inner: SurroundingSeqAccept<'o, O, Str<&'static str>, Combined<Str<&'static str>, Sep>>,
693}
694
695impl<'o, O> AttributesAccept<'o, O, Str<&'static str>> {
696    pub fn multiline(output: &'o mut O) -> Self {
697        Self::with_separator(output, "\n")
698    }
699}
700
701impl<'o, O> AttributesAccept<'o, O, Str<&'static str>> {
702    pub fn with_separator(output: &'o mut O, separator: &'static str) -> Self {
703        Self {
704            inner: SurroundingSeqAccept::new(output, Str("#["), Combined(Str("]"), Str(separator))),
705        }
706    }
707}
708
709impl<'o, O, Sep> SequenceAccept<O> for AttributesAccept<'o, O, Sep>
710where
711    O: Output,
712    Sep: Writable<O>,
713{
714    async fn accept<W: Writable<O>>(&mut self, writable: &W) -> Result<(), O::Error> {
715        self.inner.accept(writable).await
716    }
717}