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 item attached to an associated container, via "::".
257/// The output will look like `Cont::Item`.
258#[derive(Clone, Debug)]
259pub struct AssociatedItem<Cont, Item>(pub Cont, pub Item);
260
261/// A question mark following another expression.
262#[derive(Clone, Debug)]
263pub struct QuestionMarkAfter<Expr>(pub Expr);
264
265/// Uses the `as` expression to perform a qualified trait cast (e.g. ready for a method call).
266/// This will render as `<Type as Trait>`.
267#[derive(Clone, Debug)]
268pub struct TypeAsTrait<Type, Trait>(pub Type, pub Trait);
269
270/// Uses the `as` expression to coerce one type to another.
271/// This will render as `<Type1 as Type2>`.
272#[derive(Clone, Debug)]
273pub struct TypeAsType<Type1, Type2>(pub Type1, pub Type2);
274
275/// Declaration of an extern block, i.e. for FFI.
276/// In Rust 2024 and later, the unsafe keyword must be added for extern blocks. Thus, this struct
277/// requires that the context satisfies [ContextProvides] for [Edition].
278#[derive(Clone, Debug)]
279pub struct ExternBlock<Abi, Body> {
280    /// The ABI chosen. Must be writable
281    pub abi: Abi,
282    /// The body of the extern block. Must be writable
283    pub body: Body,
284}
285
286impl<Abi, Body> CanHaveAttributes for ExternBlock<Abi, Body> {
287    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
288        WithAttributes {
289            attr,
290            separator: AttributeSeparator::NewLine,
291            value: self,
292        }
293    }
294}
295
296/// Declaration of a module block. Renders as `mod Name {Body}`.
297#[derive(Clone, Debug)]
298pub struct ModBlock<Name, Body> {
299    /// The module name
300    pub name: Name,
301    /// The body. Must be writable
302    pub body: Body,
303}
304
305/// An if block. The condition and body must both be writable.
306#[derive(Clone, Debug)]
307pub struct IfBlock<Cond, Body>(pub Cond, pub Body);
308
309/// Represents "else" syntactically. Renders as `Before else After`.
310///
311/// This struct requires you to specify what comes before and after the else. For example:
312/// ```
313/// # use async_codegen::common::Str;
314/// # use async_codegen::context::EmptyContext;
315/// # use async_codegen::rust::{Block, Else, IfBlock};
316/// # use async_codegen::util::InMemoryOutput;
317///
318/// let if_block = IfBlock(Str("true"), Str("log::info(\"Hello\")"));
319/// let else_block = Block(Str("panic!()"));
320/// let if_else = Else(if_block, else_block);
321///
322/// let string = InMemoryOutput::print_output(EmptyContext, &if_else);
323/// assert_eq!("if true {\nlog::info(\"Hello\")\n} else {\npanic!()\n}", string)
324/// ```
325#[derive(Clone, Debug)]
326pub struct Else<Before, After>(pub Before, pub After);
327
328/// An unlabeled block.
329/// This can be used in many contexts, including merely organizing the code.
330#[derive(Clone, Debug)]
331pub struct Block<Body>(pub Body);
332
333/// Places the expression inside an unsafe block.
334/// Adds new lines inside the brackets, wrapping the inner expression.
335#[derive(Clone, Debug)]
336pub struct UnsafeBlock<Expr>(pub Expr);
337
338/// Writes a closure.
339/// Adds new lines inside the brackets, wrapping the inner expression.
340#[derive(Clone, Debug)]
341pub struct Closure<InputVars, Expr> {
342    /// The input variables.
343    /// Should be a sequence. They will be comma separated and placed within the pipes.
344    /// To use no input variables, use [NoOpSeq].
345    pub input_vars: InputVars,
346    /// The expression inside the closure block.
347    pub inside_block: Expr,
348}
349
350/// Performs a call to a function inside code.
351#[derive(Clone, Debug)]
352pub struct FunctionCall<Recv, Name, Args> {
353    /// The function receiver
354    pub receiver: Recv,
355    /// Whether the function is associated, false if it's a method
356    pub is_assoc: bool,
357    /// The function name
358    pub name: Name,
359    /// The arguments. Must be a sequence
360    pub args: Args,
361}
362
363/// Provides access to the "turbofish" syntax, i.e. `Name::<Args>`.
364/// The first tuple value must be writable, and the second must be a sequence.
365///
366/// Note that if the sequence outputs nothing, this struct will behave as if no args were
367/// specified. I.e. `Turbofish(Name, NoOpSeq)` is equivalent to just `Name`.
368#[derive(Clone, Debug)]
369pub struct Turbofish<Name, Args>(pub Name, pub Args);
370
371/// Accesses a member by name. Renders as `Owner.Member`.
372///
373/// This can be used for named fields or tuple fields. for example:
374/// ```
375/// # use async_codegen::common::Str;
376/// # use async_codegen::context::EmptyContext;
377/// # use async_codegen::rust::{MemberAccess, LetStmt, RefOf};
378/// # use async_codegen::util::InMemoryOutput;
379/// let string = InMemoryOutput::print_output(EmptyContext, &LetStmt(
380///   Str("borrowed_field"), RefOf(MemberAccess(Str("my_var"), Str("my_field")))
381/// ));
382/// assert_eq!(string, "let borrowed_field = &my_var.my_field;\n");
383/// ```
384#[derive(Clone, Debug)]
385pub struct MemberAccess<Owner, Member>(pub Owner, pub Member);
386
387/// A function declaration
388#[derive(Clone, Debug)]
389pub struct FunctionDef<Mods, Name, Args, Return, Where, Body> {
390    /// The modifiers. Must be a sequence.
391    pub mods: Mods,
392    /// The function name. Type variables can be declared here via [Parameterized]
393    pub name: Name,
394    /// The arguments. Must be a sequence
395    pub args: Args,
396    /// The return type, i.e. after the `->` arrow
397    pub return_type: Return,
398    /// The "where" conditions. Must be a sequence. Set to [NoOp] to disable.
399    /// Will render as `where C1, C2, C3, ...` where CX is a value in the sequence.
400    pub where_conds: Where,
401    /// The function body.
402    /// To only declare the function, this must be `;` so use [FunctionBodyDeclare]
403    /// To implement the function, use [FunctionBodyImplement]
404    pub body: Body,
405}
406
407impl<Mods, Name, Args, Return, Where, Body> CanHaveAttributes
408    for FunctionDef<Mods, Name, Args, Return, Where, Body>
409{
410    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
411        WithAttributes {
412            attr,
413            separator: AttributeSeparator::NewLine,
414            value: self,
415        }
416    }
417}
418
419/// Declares a function body. This is equivalent to just a semicolon.
420#[derive(Clone, Debug)]
421pub struct FunctionBodyDeclare;
422
423/// Implements a function body. Places the contents inside brackets
424#[derive(Clone, Debug)]
425pub struct FunctionBodyImplement<Inner>(pub Inner);
426
427/// A function pointer. Can be used for `fn`, `Fn`, `FnMut`, and `FnOnce`.
428///
429/// Example:
430/// ```
431/// # use async_codegen::common::{SingularSeq, Str};
432/// # use async_codegen::context::EmptyContext;
433/// # use async_codegen::rust::{FunctionPtr, FunctionPtrKind};
434/// # use async_codegen::util::InMemoryOutput;
435/// let function_ptr = FunctionPtr {
436///   kind: FunctionPtrKind::FnMut,
437///   args: SingularSeq(Str("String")),
438///   return_type: Str("bool")
439/// };
440/// let string = InMemoryOutput::print_output(EmptyContext, &function_ptr);
441/// assert_eq!("FnMut(String) -> bool", string);
442/// ```
443#[derive(Clone, Debug)]
444pub struct FunctionPtr<Args, Return> {
445    /// The function pointer kind
446    pub kind: FunctionPtrKind,
447    /// The arguments. Must be a sequence
448    pub args: Args,
449    /// The return type, i.e. after the `->` arrow
450    pub return_type: Return,
451}
452
453/// The kind of function type
454#[derive(Clone, Debug)]
455pub enum FunctionPtrKind {
456    /// An `fn` pointer. E.g. `fn(String) -> bool`.
457    FnPtr,
458    /// Represents [Fn]
459    Fn,
460    /// Represents [FnMut]
461    FnMut,
462    /// Represents [FnOnce]
463    FnOnce,
464}
465
466/// Renders as `Type=Value`. Intended to be used as a type argument, to specify associated types.
467#[derive(Clone, Debug)]
468pub struct AssociatedTypeEquals<Type, Value>(pub Type, pub Value);
469
470/// Adds a "dyn " before a type expression.
471#[derive(Clone, Debug)]
472pub struct DynOf<Type>(pub Type);
473
474/// Adds a "&" before a type expression
475#[derive(Clone, Debug)]
476pub struct RefOf<Expr>(pub Expr);
477
478/// Dereferences an expression using `*`
479#[derive(Clone, Debug)]
480pub struct Dereference<Expr>(pub Expr);
481
482/// Surrounds an expression with parentheses, rendering as `(Expr)`.
483/// Even if the expression is empty, the parentheses will still be rendered.
484#[derive(Clone, Debug)]
485pub struct ParenthesesAround<Expr>(pub Expr);
486
487/// Adds an "impl " before a type expression
488pub struct ImplOf<Type>(pub Type);
489
490/// Adds a reference with a lifetime before a type expression, i.e. `&'<lifetime> <type>`
491#[derive(Clone, Debug)]
492pub struct LifetimedRefOf<'l, Type>(pub &'l str, pub Type);
493
494/// Uses the `&raw const` syntax to get a pointer from another pointer. For example:
495/// ```
496/// # use async_codegen::common::Str;
497/// # use async_codegen::context::EmptyContext;
498/// # use async_codegen::rust::{MemberAccess, LetStmt, RawConstOf};
499/// # use async_codegen::util::InMemoryOutput;
500/// let pointer_var = Str("ptr");
501/// let let_stmt = LetStmt(pointer_var, RawConstOf(MemberAccess(Str("packed"), Str("field1"))));
502/// let string = InMemoryOutput::print_output(EmptyContext, &let_stmt);
503/// assert_eq!("let ptr = &raw const packed.field1;\n", string);
504/// ```
505#[derive(Clone, Debug)]
506pub struct RawConstOf<Expr>(pub Expr);
507
508/// Uses the `&raw must` syntax to get a pointer from another pointer. For example:
509/// ```
510/// # use async_codegen::common::Str;
511/// # use async_codegen::context::EmptyContext;
512/// # use async_codegen::rust::{MemberAccess, LetStmt, RawMutOf};
513/// # use async_codegen::util::InMemoryOutput;
514/// let pointer_var = Str("ptr");
515/// let let_stmt = LetStmt(pointer_var, RawMutOf(MemberAccess(Str("packed"), Str("field1"))));
516/// let string = InMemoryOutput::print_output(EmptyContext, &let_stmt);
517/// assert_eq!("let ptr = &raw mut packed.field1;\n", string);
518/// ```
519#[derive(Clone, Debug)]
520pub struct RawMutOf<Expr>(pub Expr);
521
522/// A `*const Type` for some arbitrary type
523#[derive(Clone, Debug)]
524pub struct ConstPtr<Type>(pub Type);
525
526/// A `*mut Type` for some arbitrary type.
527#[derive(Clone, Debug)]
528pub struct MutPtr<Type>(pub Type);
529
530/// Declares an associated type, rendering as `type VarName = Value;`.
531/// Adds new lines before and after.
532#[derive(Clone, Debug)]
533pub struct AssociatedTypeDef<VarName, Value>(pub VarName, pub Value);
534
535/// The declaration of a trait
536#[derive(Clone, Debug)]
537pub struct TraitDef<Mods, Name, TypeVars, SuperTraits, Body> {
538    /// The trait modifiers, e.g. visibility. Must be a sequence.
539    pub mods: Mods,
540    /// The name of the trait
541    pub name: Name,
542    /// The type variables. Must be a sequence
543    pub type_variables: TypeVars,
544    /// The super traits. Must be a sequence
545    pub super_traits: SuperTraits,
546    /// The trait definition's body. Use [NoOp] if none exists.
547    pub body: Body,
548}
549
550impl<Mods, Name, TypeVars, SuperTraits, Body> CanHaveAttributes
551    for TraitDef<Mods, Name, TypeVars, SuperTraits, Body>
552{
553    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
554        WithAttributes {
555            attr,
556            separator: AttributeSeparator::NewLine,
557            value: self,
558        }
559    }
560}
561
562/// The implementation declaration for a trait, applying to a certain receiver.
563#[derive(Clone, Debug)]
564pub struct TraitImpl<Mods, TypeVars, Trait, Recv, Where, Body> {
565    /// The modifiers on the `impl` block.
566    /// Set to [NoOpSeq] for none, or use `SingularSeq(ModUnsafe)` to generate an `unsafe impl`.
567    pub mods: Mods,
568    /// The type variables to use for the impl block itself. All type variables that appear later
569    /// on the trait or the receiver must be declared here, per Rust language rules.
570    ///
571    /// This field must be a sequence.
572    pub type_variables: TypeVars,
573    /// The trait being implemented
574    pub the_trait: Trait,
575    /// The receiver for which it is implemented
576    pub receiver: Recv,
577    /// The "where" conditions. Must be a sequence. Set to [NoOpSeq] to disable.
578    /// Will render as `where C1, C2, C3, ...` where CX is a value in the sequence.
579    pub where_conds: Where,
580    /// The body. Use [NoOp] if none exists.
581    pub body: Body,
582}
583
584impl<Mods, TypeVars, Trait, Recv, Where, Body> CanHaveAttributes
585    for TraitImpl<Mods, TypeVars, Trait, Recv, Where, Body>
586{
587    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
588        WithAttributes {
589            attr,
590            separator: AttributeSeparator::NewLine,
591            value: self,
592        }
593    }
594}
595
596/// An impl block.
597///
598/// For impls of a trait for a certain receiver, it is suggested to use [TraitImpl].
599#[derive(Clone, Debug)]
600pub struct Impl<Mods, TypeVars, Recv, Where, Body> {
601    /// The modifiers on the `impl` block.
602    /// Set to [NoOpSeq] for none, or use `SingularSeq(ModUnsafe)` to generate an `unsafe impl`.
603    pub mods: Mods,
604    /// The type variables to use for the impl block itself. All type variables that appear later
605    /// on the trait or the receiver must be declared here, per Rust language rules.
606    ///
607    /// This field must be a sequence.
608    pub type_variables: TypeVars,
609    /// The receiver for which the implementation exists
610    pub receiver: Recv,
611    /// The "where" conditions. Must be a sequence. Set to [NoOpSeq] to disable.
612    /// Will render as `where C1, C2, C3, ...` where CX is a value in the sequence.
613    pub where_conds: Where,
614    /// The body. Use [NoOp] if none exists.
615    pub body: Body,
616}
617
618impl<Mods, TypeVars, Recv, Where, Body> CanHaveAttributes
619    for Impl<Mods, TypeVars, Recv, Where, Body>
620{
621    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
622        WithAttributes {
623            attr,
624            separator: AttributeSeparator::NewLine,
625            value: self,
626        }
627    }
628}
629
630/// The declaration of a struct.
631#[derive(Clone, Debug)]
632pub struct StructDef<Mods, Name, Elements> {
633    /// The struct modifiers. Must be a sequence.
634    pub mods: Mods,
635    /// The kind of the struct.
636    ///
637    /// It is suggested to use either a [NamedTuple] or [StructCall]. A semicolon will be
638    /// automatically added afterward, as is needed for tuple structs, and this semicolon will not
639    /// affect structs with named fields.
640    pub kind: StructKind<Name, Elements>,
641}
642
643impl<Mods, Name, Elements> CanHaveAttributes for StructDef<Mods, Name, Elements> {
644    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
645        WithAttributes {
646            attr,
647            separator: AttributeSeparator::NewLine,
648            value: self,
649        }
650    }
651}
652
653/// Completes the struct definition as either a named tuple or a struct with named fields.
654#[derive(Clone, Debug)]
655pub enum StructKind<Name, Elements> {
656    /// A named tuple. This will function similarly to [NamedTuple], except a semicolon will
657    /// be added afterward.
658    ///
659    /// `Name` must be writable, and `Elements` must be a writable sequence for the tuple arguments.
660    Tuple(Name, Elements),
661    /// A struct with named fields. This will function similarly to [StructCall].
662    ///
663    /// `Name` must be writable, and `Elements` must be writable sequence for the struct fields.
664    NamedFields(Name, Elements),
665}
666
667/// The construction or deconstruction of a struct.
668///
669/// When rendered, will use the format `Name { Body }`. Spaces will be added automatically.
670///
671/// This should **not** be used for tuple structs, for that see [NamedTuple].
672#[derive(Clone, Debug)]
673pub struct StructCall<Name, Body> {
674    /// The struct name. Must be writable.
675    ///
676    /// If you are declaring a struct for the first time, you can use [Parameterized] in order
677    /// to declare type variables.
678    pub name: Name,
679    /// The body. Must be writable.
680    ///
681    /// It is suggested to use [StructFields] for multiple fields, or [DeclareField] or
682    /// [FillOutField] for just one.
683    pub body: Body,
684}
685
686/// Named struct fields. This will place every field on a new line with a comma afterward.
687/// It is recommended that the sequence should pass [DeclareField] or [FillOutField] depending
688/// upon whether the struct is being
689///
690/// If you have a single field, you can skip using a sequence and just use [DeclareField] or
691/// [FillOutField] directly.
692#[derive(Clone, Debug)]
693pub struct StructFields<Fields>(pub Fields);
694
695/// Declares a single field within a struct.
696///
697/// Does not add attributes. If you want to use attributes for declaration purposes, you can use
698/// [CanHaveAttributes::with_attributes] on this field.
699#[derive(Clone, Debug)]
700pub struct DeclareField<Mods, Name, FieldType> {
701    /// The field modifiers. Must be a sequence.
702    pub mods: Mods,
703    /// The name. Must be writable
704    pub name: Name,
705    /// The field type. Must be writable
706    pub field_type: FieldType,
707}
708
709impl<Mods, Name, Value> CanHaveAttributes for DeclareField<Mods, Name, Value> {
710    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
711        WithAttributes {
712            attr,
713            separator: AttributeSeparator::NewLine,
714            value: self,
715        }
716    }
717}
718
719/// Provides a field upon struct creation. Renders as `Name: Value`
720#[derive(Clone, Debug)]
721pub struct FillOutField<Name, Value>(pub Name, pub Value);
722
723/// A named tuple type.
724///
725/// Renders as `Name(A1, A2, A3, ...)` where AX is part of the argument sequence.
726/// If no arguments exist, will render only as `Name` (i.e., a unit struct).
727#[derive(Clone, Debug)]
728pub struct NamedTuple<Name, Args> {
729    pub name: Name,
730    pub args: Args,
731}
732
733/// An anonymous tuple type. This struct's tuple value must be a sequence.
734///
735/// Renders as `(A1, A2, A3, ...)` where AX is part of the argument sequence.
736#[derive(Clone, Debug)]
737pub struct AnonTuple<Args>(pub Args);
738
739/// The unit type, i.e. `()`
740pub type UnitType = AnonTuple<NoOpSeq>;
741
742impl AnonTuple<NoOpSeq> {
743    /// Creates
744    pub fn unit() -> Self {
745        Self(NoOpSeq)
746    }
747}
748
749/// Adds attributes to ANY item.
750///
751/// The first tuple value must be a sequence. The second must be a writable value. This struct
752/// is typically constructed via [CanHaveAttributes::with_attributes].
753///
754/// Rust attributes can be put in many places, so this enables you to add attributes to any
755/// writable item. For example, adding attributes to function parameters can be done like so:
756///
757/// ```rust
758/// # use async_codegen::common::{SingularSeq, Str};
759/// # use async_codegen::context::EmptyContext;
760/// # use async_codegen::rust::{Cfg, FunctionParam, MustUse, Target, WithAttributes, CanHaveAttributes};
761/// # use async_codegen::util::InMemoryOutput;
762///
763/// let function_param = FunctionParam(Str("conditional_param"), Str("Fd")).with_attributes(
764///   SingularSeq(Cfg(Target::Os(Str("linux"))))
765/// );
766/// let string = InMemoryOutput::print_output(EmptyContext, &function_param);
767/// assert_eq!("#[cfg(target_os = \"linux\")] conditional_param: Fd", string);
768/// ```
769#[derive(Clone, Debug)]
770pub struct WithAttributes<Attr, Value> {
771    /// The attributes. Must be a sequence.
772    pub attr: Attr,
773    /// The separator between each attribute
774    pub separator: AttributeSeparator,
775    /// The value
776    pub value: Value,
777}
778
779#[derive(Copy, Clone, Debug)]
780pub enum AttributeSeparator {
781    Space,
782    NewLine,
783}
784
785/// A writable that can have attributes attached to it
786pub trait CanHaveAttributes: Sized {
787    /// Adds attributes to this writable
788    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self>;
789}
790
791/// Defines an enum.
792///
793/// In order to use or refer to an enum, you can use [AssociatedItem] together with [NamedTuple]
794/// or [StructCall].
795#[derive(Clone, Debug)]
796pub struct EnumDef<Mods, Name, Entries> {
797    /// The modifiers on the type. Must be a sequence.
798    pub mods: Mods,
799    /// The name of the enum
800    pub name: Name,
801    /// The enum entries. Must be a sequence, each entry will be written on a new line with a comma
802    ///
803    /// As for the entries themselves, it is suggested to use [NamedTuple] or [StructCall]
804    /// depending on which kind of enum entry you want to create.
805    pub entries: Entries,
806}
807
808impl<Mods, Name, Entries> CanHaveAttributes for EnumDef<Mods, Name, Entries> {
809    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
810        WithAttributes {
811            attr,
812            separator: AttributeSeparator::NewLine,
813            value: self,
814        }
815    }
816}
817
818/// A type argument-parameterized expression. Used in relation to parameterized names and their
819/// arguments. Examples: `function_name<args>`, `TypeName<'lifetime, args>`, `MyType<Assoc=Value>`.
820///
821/// If no type args exist, [NoOpSeq] should be used. In any case, the second tuple value of this
822/// struct must be a sequence. If they are empty, only `Name` will be rendered.
823#[derive(Clone, Debug)]
824pub struct Parameterized<Name, TypeArgs>(pub Name, pub TypeArgs);
825
826/// A type variable with a sequence of bounds.
827/// Will render as `TypeVar: B1 + B2 + ...`
828#[derive(Clone, Debug)]
829pub struct BoundedTypeVar<TypeVar, Bounds>(pub TypeVar, pub Bounds);
830
831/// A standalone lifetime, intended to be used as a type argument or variable
832#[derive(Clone, Debug)]
833pub struct Lifetime<'l>(pub &'l str);
834
835/// Renders an individual function parameter, `Name: Type`
836#[derive(Clone, Debug)]
837pub struct FunctionParam<Name, Type>(pub Name, pub Type);
838
839impl<Name, Type> CanHaveAttributes for FunctionParam<Name, Type> {
840    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
841        WithAttributes {
842            attr,
843            separator: AttributeSeparator::Space,
844            value: self,
845        }
846    }
847}
848
849/// A sequence acceptor that writes attributes. Every attribute will be surrounded with "#[]"
850#[derive(Debug)]
851pub struct AttributesAccept<'o, O, Sep> {
852    inner: SurroundingSeqAccept<'o, O, Str<&'static str>, Combined<Str<&'static str>, Sep>>,
853}
854
855impl<'o, O, Sep> AttributesAccept<'o, O, Sep> {
856    pub fn with_separator(output: &'o mut O, separator: Sep) -> Self {
857        Self {
858            inner: SurroundingSeqAccept::new(output, Str("#["), Combined(Str("]"), separator)),
859        }
860    }
861}
862
863impl<'o, O, Sep> SequenceAccept<O> for AttributesAccept<'o, O, Sep>
864where
865    O: Output,
866    Sep: Writable<O>,
867{
868    async fn accept<W: Writable<O>>(&mut self, writable: &W) -> Result<(), O::Error> {
869        self.inner.accept(writable).await
870    }
871}