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