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/// The declaration of a struct.
596#[derive(Clone, Debug)]
597pub struct StructDef<Mods, Name, Elements> {
598 /// The struct modifiers. Must be a sequence.
599 pub mods: Mods,
600 /// The kind of the struct.
601 ///
602 /// It is suggested to use either a [NamedTuple] or [StructCall]. A semicolon will be
603 /// automatically added afterward, as is needed for tuple structs, and this semicolon will not
604 /// affect structs with named fields.
605 pub kind: StructKind<Name, Elements>,
606}
607
608impl<Mods, Name, Elements> CanHaveAttributes for StructDef<Mods, Name, Elements> {
609 fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
610 WithAttributes {
611 attr,
612 separator: AttributeSeparator::NewLine,
613 value: self,
614 }
615 }
616}
617
618/// Completes the struct definition as either a named tuple or a struct with named fields.
619#[derive(Clone, Debug)]
620pub enum StructKind<Name, Elements> {
621 /// A named tuple. This will function similarly to [NamedTuple], except a semicolon will
622 /// be added afterward.
623 ///
624 /// `Name` must be writable, and `Elements` must be a writable sequence for the tuple arguments.
625 Tuple(Name, Elements),
626 /// A struct with named fields. This will function similarly to [StructCall].
627 ///
628 /// `Name` must be writable, and `Elements` must be writable sequence for the struct fields.
629 NamedFields(Name, Elements),
630}
631
632/// The construction or deconstruction of a struct.
633///
634/// When rendered, will use the format `Name { Body }`. Spaces will be added automatically.
635///
636/// This should **not** be used for tuple structs, for that see [NamedTuple].
637#[derive(Clone, Debug)]
638pub struct StructCall<Name, Body> {
639 /// The struct name. Must be writable.
640 ///
641 /// If you are declaring a struct for the first time, you can use [Parameterized] in order
642 /// to declare type variables.
643 pub name: Name,
644 /// The body. Must be writable.
645 ///
646 /// It is suggested to use [StructFields] for multiple fields, or [DeclareField] or
647 /// [FillOutField] for just one.
648 pub body: Body,
649}
650
651/// Named struct fields. This will place every field on a new line with a comma afterward.
652/// It is recommended that the sequence should pass [DeclareField] or [FillOutField] depending
653/// upon whether the struct is being
654///
655/// If you have a single field, you can skip using a sequence and just use [DeclareField] or
656/// [FillOutField] directly.
657#[derive(Clone, Debug)]
658pub struct StructFields<Fields>(pub Fields);
659
660/// Declares a single field within a struct.
661///
662/// Does not add attributes. If you want to use attributes for declaration purposes, you can use
663/// [CanHaveAttributes::with_attributes] on this field.
664#[derive(Clone, Debug)]
665pub struct DeclareField<Mods, Name, Value> {
666 /// The field modifiers. Must be a sequence.
667 pub mods: Mods,
668 /// The name. Must be writable
669 pub name: Name,
670 /// The value. Must be writable
671 pub value: Value,
672}
673
674impl<Mods, Name, Value> CanHaveAttributes for DeclareField<Mods, Name, Value> {
675 fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
676 WithAttributes {
677 attr,
678 separator: AttributeSeparator::NewLine,
679 value: self,
680 }
681 }
682}
683
684/// Provides a field upon struct creation. Renders as `Name: Value`
685#[derive(Clone, Debug)]
686pub struct FillOutField<Name, Value>(pub Name, pub Value);
687
688/// A named tuple type.
689///
690/// Renders as `Name(A1, A2, A3, ...)` where AX is part of the argument sequence.
691/// If no arguments exist, will render only as `Name` (i.e., a unit struct).
692#[derive(Clone, Debug)]
693pub struct NamedTuple<Name, Args> {
694 pub name: Name,
695 pub args: Args,
696}
697
698/// An anonymous tuple type. This struct's tuple value must be a sequence.
699///
700/// Renders as `(A1, A2, A3, ...)` where AX is part of the argument sequence.
701#[derive(Clone, Debug)]
702pub struct AnonTuple<Args>(pub Args);
703
704/// The unit type, i.e. `()`
705pub type UnitType = AnonTuple<NoOpSeq>;
706
707impl AnonTuple<NoOpSeq> {
708 /// Creates
709 pub fn unit() -> Self {
710 Self(NoOpSeq)
711 }
712}
713
714/// Adds attributes to ANY item.
715///
716/// The first tuple value must be a sequence. The second must be a writable value. This struct
717/// is typically constructed via [CanHaveAttributes::with_attributes].
718///
719/// Rust attributes can be put in many places, so this enables you to add attributes to any
720/// writable item. For example, adding attributes to function parameters can be done like so:
721///
722/// ```rust
723/// # use async_codegen::common::{SingularSeq, Str};
724/// # use async_codegen::context::EmptyContext;
725/// # use async_codegen::rust::{Cfg, FunctionParam, MustUse, Target, WithAttributes, CanHaveAttributes};
726/// # use async_codegen::util::InMemoryOutput;
727///
728/// let function_param = FunctionParam(Str("conditional_param"), Str("Fd")).with_attributes(
729/// SingularSeq(Cfg(Target::Os(Str("linux"))))
730/// );
731/// let string = InMemoryOutput::print_output(EmptyContext, &function_param);
732/// assert_eq!("#[cfg(target_os = \"linux\")] conditional_param: Fd", string);
733/// ```
734#[derive(Clone, Debug)]
735pub struct WithAttributes<Attr, Value> {
736 /// The attributes. Must be a sequence.
737 pub attr: Attr,
738 /// The separator between each attribute
739 pub separator: AttributeSeparator,
740 /// The value
741 pub value: Value,
742}
743
744#[derive(Copy, Clone, Debug)]
745pub enum AttributeSeparator {
746 Space,
747 NewLine,
748}
749
750/// A writable that can have attributes attached to it
751pub trait CanHaveAttributes: Sized {
752 /// Adds attributes to this writable
753 fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self>;
754}
755
756/// Defines an enum.
757///
758/// In order to use or refer to an enum, you can use [AssociatedItem] together with [NamedTuple]
759/// or [StructCall].
760#[derive(Clone, Debug)]
761pub struct EnumDef<Mods, Name, Entries> {
762 /// The modifiers on the type. Must be a sequence.
763 pub mods: Mods,
764 /// The name of the enum
765 pub name: Name,
766 /// The enum entries. Must be a sequence, each entry will be written on a new line with a comma
767 ///
768 /// As for the entries themselves, it is suggested to use [NamedTuple] or [StructCall]
769 /// depending on which kind of enum entry you want to create.
770 pub entries: Entries,
771}
772
773impl<Mods, Name, Entries> CanHaveAttributes for EnumDef<Mods, Name, Entries> {
774 fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
775 WithAttributes {
776 attr,
777 separator: AttributeSeparator::NewLine,
778 value: self,
779 }
780 }
781}
782
783/// A type argument-parameterized expression. Used in relation to parameterized names and their
784/// arguments. Examples: `function_name<args>`, `TypeName<'lifetime, args>`, `MyType<Assoc=Value>`.
785///
786/// If no type args exist, [NoOpSeq] should be used. In any case, the second tuple value of this
787/// struct must be a sequence.
788#[derive(Clone, Debug)]
789pub struct Parameterized<Name, TypeArgs>(pub Name, pub TypeArgs);
790
791/// A type variable with a sequence of bounds.
792/// Will render as `TypeVar: B1 + B2 + ...`
793#[derive(Clone, Debug)]
794pub struct BoundedTypeVar<TypeVar, Bounds>(pub TypeVar, pub Bounds);
795
796/// A standalone lifetime, intended to be used as a type argument or variable
797#[derive(Clone, Debug)]
798pub struct Lifetime<'l>(pub &'l str);
799
800/// Renders an individual function parameter, `Name: Type`
801#[derive(Clone, Debug)]
802pub struct FunctionParam<Name, Type>(pub Name, pub Type);
803
804impl<Name, Type> CanHaveAttributes for FunctionParam<Name, Type> {
805 fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
806 WithAttributes {
807 attr,
808 separator: AttributeSeparator::Space,
809 value: self,
810 }
811 }
812}
813
814/// A sequence acceptor that writes attributes. Every attribute will be surrounded with "#[]"
815#[derive(Debug)]
816pub struct AttributesAccept<'o, O, Sep> {
817 inner: SurroundingSeqAccept<'o, O, Str<&'static str>, Combined<Str<&'static str>, Sep>>,
818}
819
820impl<'o, O, Sep> AttributesAccept<'o, O, Sep> {
821 pub fn with_separator(output: &'o mut O, separator: Sep) -> Self {
822 Self {
823 inner: SurroundingSeqAccept::new(output, Str("#["), Combined(Str("]"), separator)),
824 }
825 }
826}
827
828impl<'o, O, Sep> SequenceAccept<O> for AttributesAccept<'o, O, Sep>
829where
830 O: Output,
831 Sep: Writable<O>,
832{
833 async fn accept<W: Writable<O>>(&mut self, writable: &W) -> Result<(), O::Error> {
834 self.inner.accept(writable).await
835 }
836}