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 doc attribute on an item.
90///
91/// The generic argument of this enum is not used in all variants. Consider using the constructor
92/// functions [Self::hidden], [Self::inline], and [Self::no_inline] if applicable
93#[derive(Clone, Debug)]
94pub enum Doc<Value> {
95    /// The `#[doc(hidden)]` attribute
96    Hidden,
97    /// The `#[doc(inline)]` attribute
98    Inline,
99    /// The `#[doc(no_inline)]` attribute
100    NoInline,
101    /// Creates an alias to another item with `#[doc(alias = "Value")]`
102    Alias(Value),
103    /// Creates a documentation test attribute with `#[doc(test(Value))]`
104    Test(Value),
105}
106
107impl Doc<NoOp> {
108    /// The `#[doc(hidden)]` attribute
109    pub fn hidden() -> Doc<NoOp> {
110        Doc::Hidden
111    }
112
113    /// The `#[doc(inline)]` attribute
114    pub fn inline() -> Doc<NoOp> {
115        Doc::Inline
116    }
117
118    /// The `#[doc(no_inline)]` attribute
119    pub fn no_inline() -> Doc<NoOp> {
120        Doc::NoInline
121    }
122}
123
124/// A cfg condition for targeting an OS, OS family, or architecture. For example:
125/// ```
126/// # use async_codegen::common::{NoOpSeq, SingularSeq, Str};
127/// # use async_codegen::context::EmptyContext;
128/// # use async_codegen::rust::{FunctionBodyDeclare, Cfg, FunctionDef, Target, CanHaveAttributes};
129/// # use async_codegen::util::InMemoryOutput;
130/// let function = FunctionDef {
131///   mods: NoOpSeq,
132///   name: Str("conditional_func"),
133///   args: NoOpSeq,
134///   return_type: Str("()"),
135///   where_conds: NoOpSeq,
136///   body: FunctionBodyDeclare
137/// }.with_attributes(
138///   SingularSeq(Cfg(Target::Os(Str("linux"))))
139/// );
140/// let string = InMemoryOutput::print_output(EmptyContext, &function);
141/// assert_eq!("#[cfg(target_os = \"linux\")]\nfn conditional_func() -> ();\n\n", string);
142/// ```
143#[derive(Clone, Debug)]
144pub enum Target<Value> {
145    Os(Value),
146    Family(Value),
147    Arch(Value),
148}
149
150/// The link attribute.
151#[derive(Clone, Debug)]
152pub struct Link<Arg>(pub Arg);
153
154/// The no mangle attribute.
155///
156/// Requires that the context satisfies [ContextProvides] for [Edition], because in Rust 2024 and
157/// beyond, the no-mangle attribute is an unsafe attribute.
158#[derive(Clone, Debug)]
159pub struct NoMangle;
160
161/// The attribute content for `allow(...)`. The tuple value must be a sequence.
162#[derive(Clone, Debug)]
163pub struct AllowLints<Lints>(pub Lints);
164
165/// The deprecated attribute. The three variants of this enum correspond to the deprecated
166/// attribute's multiple ways of being specified. See:
167/// https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute
168#[derive(Clone, Debug)]
169pub enum Deprecated<Msg, Since = NoOp> {
170    Basic,
171    Message(Msg),
172    Full { since: Since, note: Msg },
173}
174
175impl Default for Deprecated<NoOp, NoOp> {
176    fn default() -> Self {
177        Self::Basic
178    }
179}
180
181impl Deprecated<NoOp, NoOp> {
182    pub fn basic() -> Self {
183        Self::Basic
184    }
185}
186
187impl<Msg> Deprecated<Msg> {
188    pub fn with_message(msg: Msg) -> Self {
189        Self::Message(msg)
190    }
191}
192
193/// The must_use attribute
194#[derive(Clone, Debug)]
195pub struct MustUse;
196
197/// The public modifier
198#[derive(Clone, Debug)]
199pub struct ModPub;
200
201/// The unsafe modifier
202#[derive(Clone, Debug)]
203pub struct ModUnsafe;
204
205/// The extern modifier, with the ABI selected as the tuple value.
206///
207/// This struct includes `unsafe`. Since Rust 2024, the unsafe keyword is required for extern
208/// functions, and before Rust 2024 it is optional. To make it easy to generate code targeting
209/// multiple editions, we unconditionally emit the "unsafe" keyword alongside "extern".
210#[derive(Clone, Debug)]
211pub struct ModUnsafeExtern<Abi>(pub Abi);
212
213/// A standalone statement. Renders the expression and adds a semicolon and a new line.
214#[derive(Clone, Debug)]
215pub struct Stmt<Expr>(pub Expr);
216
217/// A let statement. This statement includes the semicolon and a new line.
218#[derive(Clone, Debug)]
219pub struct LetStmt<Variable, Expr>(pub Variable, pub Expr);
220
221/// A mutable let statement.  This statement includes the semicolon and a new line.
222#[derive(Clone, Debug)]
223pub struct LetMutStmt<Variable, Expr>(pub Variable, pub Expr);
224
225/// An assignation. This statement includes the semicolon and a new line.
226#[derive(Clone, Debug)]
227pub struct AssignStmt<Variable, Expr>(pub Variable, pub Expr);
228
229/// A return statement. Renders as `return Expr;` with a new line at the end.
230#[derive(Clone, Debug)]
231pub struct ReturnStmt<Expr>(pub Expr);
232
233/// A let expression.
234/// This can be used, for example, as the condition of [IfBlock] in order to create an "if-let" block.
235#[derive(Clone, Debug)]
236pub struct LetExpr<Pattern, Expr>(pub Pattern, pub Expr);
237
238/// A raw string literal expression, i.e. r#"Content"#. Example:
239/// ```
240/// # use async_codegen::common::Str;
241/// # use async_codegen::context::EmptyContext;
242/// # use async_codegen::rust::RawStringLiteral;
243/// # use async_codegen::util::InMemoryOutput;
244/// let string_lit = RawStringLiteral(Str("hello_world"));
245///
246/// assert_eq!("r#\"hello_world\"#", InMemoryOutput::print_output(EmptyContext, &string_lit));
247/// ```
248#[derive(Clone, Debug)]
249pub struct RawStringLiteral<Content>(pub Content);
250
251/// An array literal with predefined elements written out.
252/// Renders as `[E1, E2, E3, ...]` where EX is in the element sequence.
253#[derive(Clone, Debug)]
254pub struct ArrayFromElements<Elements>(pub Elements);
255
256/// An array initialization literal with a default element and size.
257/// Renders as `[Default; Count]`.
258#[derive(Clone, Debug)]
259pub struct ArrayInit<Default, Count>(pub Default, pub Count);
260
261/// An item attached to an associated container, via "::".
262/// The output will look like `Cont::Item`.
263#[derive(Clone, Debug)]
264pub struct AssociatedItem<Cont, Item>(pub Cont, pub Item);
265
266/// A question mark following another expression.
267#[derive(Clone, Debug)]
268pub struct QuestionMarkAfter<Expr>(pub Expr);
269
270/// Uses the `as` expression to perform a qualified trait cast (e.g. ready for a method call).
271/// This will render as `<Type as Trait>`.
272#[derive(Clone, Debug)]
273pub struct TypeAsTrait<Type, Trait>(pub Type, pub Trait);
274
275/// Uses the `as` expression to coerce one type to another.
276/// This will render as `<Type1 as Type2>`.
277#[derive(Clone, Debug)]
278pub struct TypeAsType<Type1, Type2>(pub Type1, pub Type2);
279
280/// Declaration of an extern block, i.e. for FFI.
281/// In Rust 2024 and later, the unsafe keyword must be added for extern blocks. Thus, this struct
282/// requires that the context satisfies [ContextProvides] for [Edition].
283#[derive(Clone, Debug)]
284pub struct ExternBlock<Abi, Body> {
285    /// The ABI chosen. Must be writable
286    pub abi: Abi,
287    /// The body of the extern block. Must be writable
288    pub body: Body,
289}
290
291impl<Abi, Body> CanHaveAttributes for ExternBlock<Abi, Body> {
292    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
293        WithAttributes {
294            attr,
295            separator: AttributeSeparator::NewLine,
296            value: self,
297        }
298    }
299}
300
301/// Declaration of a module block. Renders as `mod Name {Body}`.
302#[derive(Clone, Debug)]
303pub struct ModBlock<Name, Body> {
304    /// The module name
305    pub name: Name,
306    /// The body. Must be writable
307    pub body: Body,
308}
309
310/// An if block. The condition and body must both be writable.
311#[derive(Clone, Debug)]
312pub struct IfBlock<Cond, Body>(pub Cond, pub Body);
313
314/// Represents "else" syntactically. Renders as `Before else After`.
315///
316/// This struct requires you to specify what comes before and after the else. For example:
317/// ```
318/// # use async_codegen::common::Str;
319/// # use async_codegen::context::EmptyContext;
320/// # use async_codegen::rust::{Block, Else, IfBlock};
321/// # use async_codegen::util::InMemoryOutput;
322///
323/// let if_block = IfBlock(Str("true"), Str("log::info(\"Hello\")"));
324/// let else_block = Block(Str("panic!()"));
325/// let if_else = Else(if_block, else_block);
326///
327/// let string = InMemoryOutput::print_output(EmptyContext, &if_else);
328/// assert_eq!("if true {\nlog::info(\"Hello\")\n} else {\npanic!()\n}", string)
329/// ```
330#[derive(Clone, Debug)]
331pub struct Else<Before, After>(pub Before, pub After);
332
333/// An unlabeled block.
334/// This can be used in many contexts, including merely organizing the code.
335#[derive(Clone, Debug)]
336pub struct Block<Body>(pub Body);
337
338/// Places the expression inside an unsafe block.
339/// Adds new lines inside the brackets, wrapping the inner expression.
340#[derive(Clone, Debug)]
341pub struct UnsafeBlock<Expr>(pub Expr);
342
343/// Writes a closure.
344/// Adds new lines inside the brackets, wrapping the inner expression.
345#[derive(Clone, Debug)]
346pub struct Closure<InputVars, Expr> {
347    /// The input variables.
348    /// Should be a sequence. They will be comma separated and placed within the pipes.
349    /// To use no input variables, use [NoOpSeq].
350    pub input_vars: InputVars,
351    /// The expression inside the closure block.
352    pub inside_block: Expr,
353}
354
355/// Performs a call to a function inside code.
356#[derive(Clone, Debug)]
357pub struct FunctionCall<Recv, Name, Args> {
358    /// The function receiver
359    pub receiver: Recv,
360    /// Whether the function is associated, false if it's a method
361    pub is_assoc: bool,
362    /// The function name
363    pub name: Name,
364    /// The arguments. Must be a sequence
365    pub args: Args,
366}
367
368/// Provides access to the "turbofish" syntax, i.e. `Name::<Args>`.
369/// The first tuple value must be writable, and the second must be a sequence.
370///
371/// Note that if the sequence outputs nothing, this struct will behave as if no args were
372/// specified. I.e. `Turbofish(Name, NoOpSeq)` is equivalent to just `Name`.
373#[derive(Clone, Debug)]
374pub struct Turbofish<Name, Args>(pub Name, pub Args);
375
376/// Accesses a member by name. Renders as `Owner.Member`.
377///
378/// This can be used for named fields or tuple fields. for example:
379/// ```
380/// # use async_codegen::common::Str;
381/// # use async_codegen::context::EmptyContext;
382/// # use async_codegen::rust::{MemberAccess, LetStmt, RefOf};
383/// # use async_codegen::util::InMemoryOutput;
384/// let string = InMemoryOutput::print_output(EmptyContext, &LetStmt(
385///   Str("borrowed_field"), RefOf(MemberAccess(Str("my_var"), Str("my_field")))
386/// ));
387/// assert_eq!(string, "let borrowed_field = &my_var.my_field;\n");
388/// ```
389#[derive(Clone, Debug)]
390pub struct MemberAccess<Owner, Member>(pub Owner, pub Member);
391
392/// A function declaration
393#[derive(Clone, Debug)]
394pub struct FunctionDef<Mods, Name, Args, Return, Where, Body> {
395    /// The modifiers. Must be a sequence.
396    pub mods: Mods,
397    /// The function name. Type variables can be declared here via [Parameterized]
398    pub name: Name,
399    /// The arguments. Must be a sequence
400    pub args: Args,
401    /// The return type, i.e. after the `->` arrow
402    pub return_type: Return,
403    /// The "where" conditions. Must be a sequence. Set to [NoOp] to disable.
404    /// Will render as `where C1, C2, C3, ...` where CX is a value in the sequence.
405    pub where_conds: Where,
406    /// The function body.
407    /// To only declare the function, this must be `;` so use [FunctionBodyDeclare]
408    /// To implement the function, use [FunctionBodyImplement]
409    pub body: Body,
410}
411
412impl<Mods, Name, Args, Return, Where, Body> CanHaveAttributes
413    for FunctionDef<Mods, Name, Args, Return, Where, Body>
414{
415    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
416        WithAttributes {
417            attr,
418            separator: AttributeSeparator::NewLine,
419            value: self,
420        }
421    }
422}
423
424/// Declares a function body. This is equivalent to just a semicolon.
425#[derive(Clone, Debug)]
426pub struct FunctionBodyDeclare;
427
428/// Implements a function body. Places the contents inside brackets
429#[derive(Clone, Debug)]
430pub struct FunctionBodyImplement<Inner>(pub Inner);
431
432/// A function pointer. Can be used for `fn`, `Fn`, `FnMut`, and `FnOnce`.
433///
434/// Example:
435/// ```
436/// # use async_codegen::common::{SingularSeq, Str};
437/// # use async_codegen::context::EmptyContext;
438/// # use async_codegen::rust::{FunctionPtr, FunctionPtrKind};
439/// # use async_codegen::util::InMemoryOutput;
440/// let function_ptr = FunctionPtr {
441///   kind: FunctionPtrKind::FnMut,
442///   args: SingularSeq(Str("String")),
443///   return_type: Str("bool")
444/// };
445/// let string = InMemoryOutput::print_output(EmptyContext, &function_ptr);
446/// assert_eq!("FnMut(String) -> bool", string);
447/// ```
448#[derive(Clone, Debug)]
449pub struct FunctionPtr<Args, Return> {
450    /// The function pointer kind
451    pub kind: FunctionPtrKind,
452    /// The arguments. Must be a sequence
453    pub args: Args,
454    /// The return type, i.e. after the `->` arrow
455    pub return_type: Return,
456}
457
458/// The kind of function type
459#[derive(Clone, Debug)]
460pub enum FunctionPtrKind {
461    /// An `fn` pointer. E.g. `fn(String) -> bool`.
462    FnPtr,
463    /// Represents [Fn]
464    Fn,
465    /// Represents [FnMut]
466    FnMut,
467    /// Represents [FnOnce]
468    FnOnce,
469}
470
471/// Renders as `Type=Value`. Intended to be used as a type argument, to specify associated types.
472#[derive(Clone, Debug)]
473pub struct AssociatedTypeEquals<Type, Value>(pub Type, pub Value);
474
475/// Adds a "dyn " before a type expression.
476#[derive(Clone, Debug)]
477pub struct DynOf<Type>(pub Type);
478
479/// Adds a "&" before a type expression
480#[derive(Clone, Debug)]
481pub struct RefOf<Expr>(pub Expr);
482
483/// Adds a "&mut " before a type expression
484#[derive(Clone, Debug)]
485pub struct RefMutOf<Expr>(pub Expr);
486
487/// Dereferences an expression using `*`
488#[derive(Clone, Debug)]
489pub struct Dereference<Expr>(pub Expr);
490
491/// Surrounds an expression with parentheses, rendering as `(Expr)`.
492/// Even if the expression is empty, the parentheses will still be rendered.
493#[derive(Clone, Debug)]
494pub struct ParenthesesAround<Expr>(pub Expr);
495
496/// Adds an "impl " before a type expression
497pub struct ImplOf<Type>(pub Type);
498
499/// Adds a reference with a lifetime before a type expression, i.e. `&'<lifetime> <type>`
500#[derive(Clone, Debug)]
501pub struct LifetimedRefOf<'l, Type>(pub &'l str, pub Type);
502
503/// Uses the `&raw const` syntax to get a pointer from another pointer. For example:
504/// ```
505/// # use async_codegen::common::Str;
506/// # use async_codegen::context::EmptyContext;
507/// # use async_codegen::rust::{MemberAccess, LetStmt, RawConstOf};
508/// # use async_codegen::util::InMemoryOutput;
509/// let pointer_var = Str("ptr");
510/// let let_stmt = LetStmt(pointer_var, RawConstOf(MemberAccess(Str("packed"), Str("field1"))));
511/// let string = InMemoryOutput::print_output(EmptyContext, &let_stmt);
512/// assert_eq!("let ptr = &raw const packed.field1;\n", string);
513/// ```
514#[derive(Clone, Debug)]
515pub struct RawConstOf<Expr>(pub Expr);
516
517/// Uses the `&raw must` syntax to get a pointer from another pointer. For example:
518/// ```
519/// # use async_codegen::common::Str;
520/// # use async_codegen::context::EmptyContext;
521/// # use async_codegen::rust::{MemberAccess, LetStmt, RawMutOf};
522/// # use async_codegen::util::InMemoryOutput;
523/// let pointer_var = Str("ptr");
524/// let let_stmt = LetStmt(pointer_var, RawMutOf(MemberAccess(Str("packed"), Str("field1"))));
525/// let string = InMemoryOutput::print_output(EmptyContext, &let_stmt);
526/// assert_eq!("let ptr = &raw mut packed.field1;\n", string);
527/// ```
528#[derive(Clone, Debug)]
529pub struct RawMutOf<Expr>(pub Expr);
530
531/// A `*const Type` for some arbitrary type
532#[derive(Clone, Debug)]
533pub struct ConstPtr<Type>(pub Type);
534
535/// A `*mut Type` for some arbitrary type.
536#[derive(Clone, Debug)]
537pub struct MutPtr<Type>(pub Type);
538
539/// Declares an associated type, rendering as `type VarName = Value;`.
540/// Adds new lines before and after.
541#[derive(Clone, Debug)]
542pub struct AssociatedTypeDef<VarName, Value>(pub VarName, pub Value);
543
544/// The declaration of a trait
545#[derive(Clone, Debug)]
546pub struct TraitDef<Mods, Name, TypeVars, SuperTraits, Body> {
547    /// The trait modifiers, e.g. visibility. Must be a sequence.
548    pub mods: Mods,
549    /// The name of the trait
550    pub name: Name,
551    /// The type variables. Must be a sequence
552    pub type_variables: TypeVars,
553    /// The super traits. Must be a sequence
554    pub super_traits: SuperTraits,
555    /// The trait definition's body. Use [NoOp] if none exists.
556    pub body: Body,
557}
558
559impl<Mods, Name, TypeVars, SuperTraits, Body> CanHaveAttributes
560    for TraitDef<Mods, Name, TypeVars, SuperTraits, Body>
561{
562    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
563        WithAttributes {
564            attr,
565            separator: AttributeSeparator::NewLine,
566            value: self,
567        }
568    }
569}
570
571/// The implementation declaration for a trait, applying to a certain receiver.
572#[derive(Clone, Debug)]
573pub struct TraitImpl<Mods, TypeVars, Trait, Recv, Where, Body> {
574    /// The modifiers on the `impl` block.
575    /// Set to [NoOpSeq] for none, or use `SingularSeq(ModUnsafe)` to generate an `unsafe impl`.
576    pub mods: Mods,
577    /// The type variables to use for the impl block itself. All type variables that appear later
578    /// on the trait or the receiver must be declared here, per Rust language rules.
579    ///
580    /// This field must be a sequence.
581    pub type_variables: TypeVars,
582    /// The trait being implemented
583    pub the_trait: Trait,
584    /// The receiver for which it is implemented
585    pub receiver: Recv,
586    /// The "where" conditions. Must be a sequence. Set to [NoOpSeq] to disable.
587    /// Will render as `where C1, C2, C3, ...` where CX is a value in the sequence.
588    pub where_conds: Where,
589    /// The body. Use [NoOp] if none exists.
590    pub body: Body,
591}
592
593impl<Mods, TypeVars, Trait, Recv, Where, Body> CanHaveAttributes
594    for TraitImpl<Mods, TypeVars, Trait, Recv, Where, Body>
595{
596    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
597        WithAttributes {
598            attr,
599            separator: AttributeSeparator::NewLine,
600            value: self,
601        }
602    }
603}
604
605/// An impl block.
606///
607/// For impls of a trait for a certain receiver, it is suggested to use [TraitImpl].
608#[derive(Clone, Debug)]
609pub struct Impl<Mods, TypeVars, Recv, Where, Body> {
610    /// The modifiers on the `impl` block.
611    /// Set to [NoOpSeq] for none, or use `SingularSeq(ModUnsafe)` to generate an `unsafe impl`.
612    pub mods: Mods,
613    /// The type variables to use for the impl block itself. All type variables that appear later
614    /// on the trait or the receiver must be declared here, per Rust language rules.
615    ///
616    /// This field must be a sequence.
617    pub type_variables: TypeVars,
618    /// The receiver for which the implementation exists
619    pub receiver: Recv,
620    /// The "where" conditions. Must be a sequence. Set to [NoOpSeq] to disable.
621    /// Will render as `where C1, C2, C3, ...` where CX is a value in the sequence.
622    pub where_conds: Where,
623    /// The body. Use [NoOp] if none exists.
624    pub body: Body,
625}
626
627impl<Mods, TypeVars, Recv, Where, Body> CanHaveAttributes
628    for Impl<Mods, TypeVars, Recv, Where, Body>
629{
630    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
631        WithAttributes {
632            attr,
633            separator: AttributeSeparator::NewLine,
634            value: self,
635        }
636    }
637}
638
639/// The declaration of a struct.
640#[derive(Clone, Debug)]
641pub struct StructDef<Mods, Name, Elements> {
642    /// The struct modifiers. Must be a sequence.
643    pub mods: Mods,
644    /// The kind of the struct.
645    ///
646    /// It is suggested to use either a [NamedTuple] or [StructCall]. A semicolon will be
647    /// automatically added afterward, as is needed for tuple structs, and this semicolon will not
648    /// affect structs with named fields.
649    pub kind: StructKind<Name, Elements>,
650}
651
652impl<Mods, Name, Elements> CanHaveAttributes for StructDef<Mods, Name, Elements> {
653    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
654        WithAttributes {
655            attr,
656            separator: AttributeSeparator::NewLine,
657            value: self,
658        }
659    }
660}
661
662/// Completes the struct definition as either a named tuple or a struct with named fields.
663#[derive(Clone, Debug)]
664pub enum StructKind<Name, Elements> {
665    /// A named tuple. This will function similarly to [NamedTuple], except a semicolon will
666    /// be added afterward.
667    ///
668    /// `Name` must be writable, and `Elements` must be a writable sequence for the tuple arguments.
669    Tuple(Name, Elements),
670    /// A struct with named fields. This will function similarly to [StructCall].
671    ///
672    /// `Name` must be writable, and `Elements` must be writable sequence for the struct fields.
673    NamedFields(Name, Elements),
674}
675
676/// The construction or deconstruction of a struct.
677///
678/// When rendered, will use the format `Name { Body }`. Spaces will be added automatically.
679///
680/// This should **not** be used for tuple structs, for that see [NamedTuple].
681#[derive(Clone, Debug)]
682pub struct StructCall<Name, Body> {
683    /// The struct name. Must be writable.
684    ///
685    /// If you are declaring a struct for the first time, you can use [Parameterized] in order
686    /// to declare type variables.
687    pub name: Name,
688    /// The body. Must be writable.
689    ///
690    /// It is suggested to use [StructFields] for multiple fields, or [DeclareField] or
691    /// [FillOutField] for just one.
692    pub body: Body,
693}
694
695/// Named struct fields. This will place every field on a new line with a comma afterward.
696/// It is recommended that the sequence should pass [DeclareField] or [FillOutField] depending
697/// upon whether the struct is being
698///
699/// If you have a single field, you can skip using a sequence and just use [DeclareField] or
700/// [FillOutField] directly.
701#[derive(Clone, Debug)]
702pub struct StructFields<Fields>(pub Fields);
703
704/// Declares a single field within a struct.
705///
706/// Does not add attributes. If you want to use attributes for declaration purposes, you can use
707/// [CanHaveAttributes::with_attributes] on this field.
708#[derive(Clone, Debug)]
709pub struct DeclareField<Mods, Name, FieldType> {
710    /// The field modifiers. Must be a sequence.
711    pub mods: Mods,
712    /// The name. Must be writable
713    pub name: Name,
714    /// The field type. Must be writable
715    pub field_type: FieldType,
716}
717
718impl<Mods, Name, Value> CanHaveAttributes for DeclareField<Mods, Name, Value> {
719    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
720        WithAttributes {
721            attr,
722            separator: AttributeSeparator::NewLine,
723            value: self,
724        }
725    }
726}
727
728/// Provides a field upon struct creation. Renders as `Name: Value`
729#[derive(Clone, Debug)]
730pub struct FillOutField<Name, Value>(pub Name, pub Value);
731
732/// A named tuple type.
733///
734/// Renders as `Name(A1, A2, A3, ...)` where AX is part of the argument sequence.
735/// If no arguments exist, will render only as `Name` (i.e., a unit struct).
736#[derive(Clone, Debug)]
737pub struct NamedTuple<Name, Args> {
738    pub name: Name,
739    pub args: Args,
740}
741
742/// An anonymous tuple type. This struct's tuple value must be a sequence.
743///
744/// Renders as `(A1, A2, A3, ...)` where AX is part of the argument sequence.
745#[derive(Clone, Debug)]
746pub struct AnonTuple<Args>(pub Args);
747
748/// The unit type, i.e. `()`
749pub type UnitType = AnonTuple<NoOpSeq>;
750
751impl AnonTuple<NoOpSeq> {
752    /// Creates
753    pub fn unit() -> Self {
754        Self(NoOpSeq)
755    }
756}
757
758/// Adds attributes to ANY item.
759///
760/// The first tuple value must be a sequence. The second must be a writable value. This struct
761/// is typically constructed via [CanHaveAttributes::with_attributes].
762///
763/// Rust attributes can be put in many places, so this enables you to add attributes to any
764/// writable item. For example, adding attributes to function parameters can be done like so:
765///
766/// ```rust
767/// # use async_codegen::common::{SingularSeq, Str};
768/// # use async_codegen::context::EmptyContext;
769/// # use async_codegen::rust::{Cfg, FunctionParam, MustUse, Target, WithAttributes, CanHaveAttributes};
770/// # use async_codegen::util::InMemoryOutput;
771///
772/// let function_param = FunctionParam(Str("conditional_param"), Str("Fd")).with_attributes(
773///   SingularSeq(Cfg(Target::Os(Str("linux"))))
774/// );
775/// let string = InMemoryOutput::print_output(EmptyContext, &function_param);
776/// assert_eq!("#[cfg(target_os = \"linux\")] conditional_param: Fd", string);
777/// ```
778#[derive(Clone, Debug)]
779pub struct WithAttributes<Attr, Value> {
780    /// The attributes. Must be a sequence.
781    pub attr: Attr,
782    /// The separator between each attribute
783    pub separator: AttributeSeparator,
784    /// The value
785    pub value: Value,
786}
787
788#[derive(Copy, Clone, Debug)]
789pub enum AttributeSeparator {
790    Space,
791    NewLine,
792}
793
794/// A writable that can have attributes attached to it
795pub trait CanHaveAttributes: Sized {
796    /// Adds attributes to this writable
797    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self>;
798}
799
800/// Defines an enum.
801///
802/// In order to use or refer to an enum, you can use [AssociatedItem] together with [NamedTuple]
803/// or [StructCall].
804#[derive(Clone, Debug)]
805pub struct EnumDef<Mods, Name, Entries> {
806    /// The modifiers on the type. Must be a sequence.
807    pub mods: Mods,
808    /// The name of the enum
809    pub name: Name,
810    /// The enum entries. Must be a sequence, each entry will be written on a new line with a comma
811    ///
812    /// As for the entries themselves, it is suggested to use [NamedTuple] or [StructCall]
813    /// depending on which kind of enum entry you want to create.
814    pub entries: Entries,
815}
816
817impl<Mods, Name, Entries> CanHaveAttributes for EnumDef<Mods, Name, Entries> {
818    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
819        WithAttributes {
820            attr,
821            separator: AttributeSeparator::NewLine,
822            value: self,
823        }
824    }
825}
826
827/// A type argument-parameterized expression. Used in relation to parameterized names and their
828/// arguments. Examples: `function_name<args>`, `TypeName<'lifetime, args>`, `MyType<Assoc=Value>`.
829///
830/// If no type args exist, [NoOpSeq] should be used. In any case, the second tuple value of this
831/// struct must be a sequence. If they are empty, only `Name` will be rendered.
832#[derive(Clone, Debug)]
833pub struct Parameterized<Name, TypeArgs>(pub Name, pub TypeArgs);
834
835/// A type variable with a sequence of bounds.
836/// Will render as `TypeVar: B1 + B2 + ...`
837#[derive(Clone, Debug)]
838pub struct BoundedTypeVar<TypeVar, Bounds>(pub TypeVar, pub Bounds);
839
840/// A standalone lifetime, intended to be used as a type argument or variable
841#[derive(Clone, Debug)]
842pub struct Lifetime<'l>(pub &'l str);
843
844/// Renders an individual function parameter, `Name: Type`
845#[derive(Clone, Debug)]
846pub struct FunctionParam<Name, Type>(pub Name, pub Type);
847
848impl<Name, Type> CanHaveAttributes for FunctionParam<Name, Type> {
849    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
850        WithAttributes {
851            attr,
852            separator: AttributeSeparator::Space,
853            value: self,
854        }
855    }
856}
857
858/// A sequence acceptor that writes attributes. Every attribute will be surrounded with "#[]"
859#[derive(Debug)]
860pub struct AttributesAccept<'o, O, Sep> {
861    inner: SurroundingSeqAccept<'o, O, Str<&'static str>, Combined<Str<&'static str>, Sep>>,
862}
863
864impl<'o, O, Sep> AttributesAccept<'o, O, Sep> {
865    pub fn with_separator(output: &'o mut O, separator: Sep) -> Self {
866        Self {
867            inner: SurroundingSeqAccept::new(output, Str("#["), Combined(Str("]"), separator)),
868        }
869    }
870}
871
872impl<'o, O, Sep> SequenceAccept<O> for AttributesAccept<'o, O, Sep>
873where
874    O: Output,
875    Sep: Writable<O>,
876{
877    async fn accept<W: Writable<O>>(&mut self, writable: &W) -> Result<(), O::Error> {
878        self.inner.accept(writable).await
879    }
880}