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