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, SingularSeq, Str};
28//! use async_codegen::{Output, Writable};
29//!
30//! use async_codegen::rust::{CfgAttr, Deprecated, Function, FunctionDef, FunctionParam, ModPub, MustUse, NoMangle, Parameterized};
31//!
32//! async fn write_function<O>(output: &mut O) -> Result<(), O::Error> where O: Output {
33//!   // For more advanced usage, you can replace Str("") by other Writable implementations
34//!   let function_def = FunctionDef {
35//!     attr: SingularSeq(Deprecated::with_message(Str("because we all love deprecation"))),
36//!     mods: SingularSeq(ModPub),
37//!     decl: Function {
38//!       name: Str("my_func"),
39//!       args: CombinedSeq(
40//!         SingularSeq(FunctionParam(Str("var1"), Str("Type"))),
41//!         SingularSeq(FunctionParam(Str("var2"), Parameterized::new(Str("Option"), SingularSeq(Str("bool")))))
42//!       )
43//!     },
44//!     return_type: Parameterized::new(Str("Box"), SingularSeq(Str("str"))),
45//!     body: Str("\ntodo!()\n")
46//!   };
47//!   function_def.write_to(output).await
48//!   // Will render as:
49//!   /*
50//!   #[deprecated = "because we all love deprecation"]
51//!   pub fn my_func(var1: Type, var2: Option<bool>) -> Box<str> {
52//!     todo!()
53//!   }
54//!    */
55//! }
56//! ```
57//!
58
59use crate::common::{NoOp, Str, SurroundingSeqAccept};
60use crate::{Output, SequenceAccept, Writable};
61
62mod syntax;
63#[cfg(test)]
64mod tests;
65
66/// All possible Rust editions.
67/// This is the only type in this module meant to be used as context, and not as a writable itself.
68#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
69#[non_exhaustive]
70pub enum Edition {
71    /// This Rust edition is declared for usability purposes. However, not all [crate::Writable]
72    /// implementations are guaranteed to work with it.
73    Rust2015,
74    Rust2018,
75    Rust2021,
76    Rust2024,
77}
78
79/// An attribute enabled conditionally, i.e. `#[cfg_attr(Cond, Attr)]`
80pub struct CfgAttr<Cond, Attr>(pub Cond, pub Attr);
81
82/// The no mangle attribute.
83///
84/// Requires that the context satisfies [ContextProvides] for [Edition], because in Rust 2024 and
85/// beyond, the no-mangle attribute is an unsafe attribute.
86pub struct NoMangle;
87
88/// The attribute content for `allow(...)`. The tuple value must be a sequence.
89pub struct AllowLints<Lints>(pub Lints);
90
91/// The deprecated attribute. The three variants of this enum correspond to the deprecated
92/// attribute's multiple ways of being specified. See:
93/// https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute
94pub enum Deprecated<Msg, Since = NoOp> {
95    Basic,
96    Message(Msg),
97    Full { since: Since, note: Msg },
98}
99
100impl Default for Deprecated<NoOp, NoOp> {
101    fn default() -> Self {
102        Self::Basic
103    }
104}
105
106impl Deprecated<NoOp, NoOp> {
107    pub fn basic() -> Self {
108        Self::Basic
109    }
110}
111
112impl<Msg> Deprecated<Msg> {
113    pub fn with_message(msg: Msg) -> Self {
114        Self::Message(msg)
115    }
116}
117
118/// The must_use attribute
119pub struct MustUse;
120
121/// The public modifier
122pub struct ModPub;
123
124/// The extern modifier, with the ABI selected as the tuple value.
125///
126/// This struct includes `unsafe`. Since Rust 2024, the unsafe keyword is required for extern
127/// functions, and before Rust 2024 it is optional. To make it easy to generate code targeting
128/// multiple editions, we unconditionally emit the "unsafe" keyword alongside "extern".
129pub struct ModUnsafeExtern<Abi>(pub Abi);
130
131/// A let statement. This statement includes the semicolon and a new line.
132pub struct LetStmt<Variable, Expr>(pub Variable, pub Expr);
133
134/// An item attached to an associated container, via "::".
135/// The output will look like `Cont::Item`.
136pub struct AssociatedItem<Cont, Item>(pub Cont, pub Item);
137
138/// A question mark following another expression.
139pub struct QuestionMarkAfter<Expr>(pub Expr);
140
141/// Wraps an expression in `Ok(EXPR)`.
142pub struct OkResultOf<Expr>(pub Expr);
143
144/// Uses the `as` expression to perform a qualified trait cast (ready for a method call).
145/// I.e., this will render as `<Type as Trait>`.
146pub struct TypeAsTrait<Type, Trait>(pub Type, pub Trait);
147
148/// Declaration of an extern block, i.e. for FFI.
149/// In Rust 2024 and later, the unsafe keyword must be added for extern blocks. Thus, this struct
150/// requires that the context satisfies [ContextProvides] for [Edition].
151pub struct ExternBlock<Attr, Abi, Body> {
152    /// The attributes. Must be a sequence, and each value will be placed inside `#[]`.
153    pub attr: Attr,
154    /// The ABI chosen. Must be writable
155    pub abi: Abi,
156    /// The body of the extern block. Must be writable
157    pub body: Body,
158}
159
160/// Places the expression inside an unsafe block.
161/// Adds new lines inside the brackets, wrapping the inner expression.
162pub struct UnsafeBlock<Expr>(pub Expr);
163
164/// Writes a closure.
165/// Adds new lines inside the brackets, wrapping the inner expression.
166pub struct Closure<InputVars, Expr> {
167    /// The input variables.
168    /// Should be a sequence. They will be comma separated and placed within the pipes.
169    /// To use no input variables, use [crate::common::NoOpSeq].
170    pub input_vars: InputVars,
171    /// The expression inside the closure block.
172    pub inside_block: Expr,
173}
174
175/// Performs a call to a function inside code.
176pub struct FunctionCall<Recv, FuncName, Args> {
177    /// The function receiver
178    pub receiver: Recv,
179    /// Whether the function is associated, false if it's a method
180    pub is_assoc: bool,
181    /// The function being called
182    pub function: Function<FuncName, Args>,
183}
184
185/// The base struct for a function. Includes name and arguments.
186/// This function is re-used in other places and is likely not helpful by itself.
187pub struct Function<Name, Args> {
188    /// The function name. Must be writable.
189    pub name: Name,
190    /// The function arguments. Must be a sequence.
191    pub args: Args,
192}
193
194/// A function declaration
195pub struct FunctionDef<Attr, Mods, Name, Args, Return, Body> {
196    /// The attributes. Must be a sequence, and each value will be placed inside `#[]`.
197    pub attr: Attr,
198    /// The modifiers. Must be a sequence.
199    pub mods: Mods,
200    /// The function itself
201    pub decl: Function<Name, Args>,
202    /// The return type, i.e. after the `->` arrow
203    pub return_type: Return,
204    /// The function body. At the minimum, this must be `;` (see [`FunctionBodyDeclare`])
205    pub body: Body,
206}
207
208/// Declares a function body. This is equivalent to just a semicolon.
209pub struct FunctionBodyDeclare;
210
211/// Renders as `Type=Value`. Intended to be used as a type argument, to specify associated types.
212pub struct AssociatedTypeEquals<Type, Value>(pub Type, pub Value);
213
214/// Adds a "dyn " before a type expression.
215pub struct DynOf<Type>(pub Type);
216
217/// Adds a "&" before a type expression
218pub struct RefOf<Type>(pub Type);
219
220/// Adds an "impl " before a type expression
221pub struct ImplOf<Type>(pub Type);
222
223/// Adds a reference with a lifetime before a type expression, i.e. `&'<lifetime> <type>`
224pub struct LifetimedRefOf<'l, Type>(pub &'l str, pub Type);
225
226/// Declares an associated type, rendering as `type VarName = Value;`.
227/// Adds new lines before and after.
228pub struct AssociatedTypeDef<VarName, Value>(pub VarName, pub Value);
229
230/// The declaration of a trait
231pub struct TraitDef<Attr, Mods, Name, TypeVars, SuperTraits, Body> {
232    /// The trait attributes. Must be a sequence, and each value will be placed inside `#[]`.
233    pub attr: Attr,
234    /// The trait modifiers, e.g. visibility. Must be a sequence.
235    pub mods: Mods,
236    /// The name of the trait
237    pub name: Name,
238    /// The type variables. Must be a sequence
239    pub type_variables: TypeVars,
240    /// The super traits. Must be a sequence
241    pub super_traits: SuperTraits,
242    /// The trait definition's body. Use [NoOp] if none exists.
243    pub body: Body,
244}
245
246/// The implementation declaration for a trait, applying to a certain receiver.
247pub struct TraitImpl<TypeVars, Trait, Recv, Body> {
248    /// The type variables to use for the impl block itself. All type variables that appear later
249    /// on the trait or the receiver must be declared here, per Rust language rules.
250    ///
251    /// This field must be a sequence.
252    pub type_variables: TypeVars,
253    /// The trait being implemented
254    pub the_trait: Trait,
255    /// The receiver for which it is implemented
256    pub receiver: Recv,
257    /// The body. Use [NoOp] if none exists.
258    pub body: Body,
259}
260
261/// A type argument-parameterized expression. Used in relation to parameterized names and their
262/// arguments. Examples: `function_name<args>`, `TypeName<'lifetime, args>`, `MyType<Assoc=Value>`.
263///
264/// If no type args exist, [`crate::common::NoOpSeq`] should be used.
265pub struct Parameterized<Name, TypeArgs> {
266    name: Name,
267    type_args: TypeArgs,
268}
269
270impl<Name, TypeArgs> Parameterized<Name, TypeArgs> {
271    /// Initializes an instance
272    pub fn new(name: Name, type_args: TypeArgs) -> Self {
273        Self { name, type_args }
274    }
275}
276
277/// A type variable with a sequence of bounds.
278/// Will render as `TypeVar: B1 + B2 + ...`
279pub struct BoundedTypeVar<TypeVar, Bounds>(pub TypeVar, pub Bounds);
280
281/// A standalone lifetime, intended to be used as a type argument or variable
282pub struct Lifetime<'l>(pub &'l str);
283
284/// Renders an individual function parameter, `Name: Type`
285pub struct FunctionParam<Name, Type>(pub Name, pub Type);
286
287/// A sequence acceptor that writes attributes. Every attribute will be placed on a new line
288/// and automatically be surrounded with "#[]"
289pub struct AttributesAccept<'o, O> {
290    inner: SurroundingSeqAccept<'o, O, Str<&'static str>, Str<&'static str>>,
291}
292
293impl<'o, O> AttributesAccept<'o, O> {
294    pub fn new(output: &'o mut O) -> Self {
295        Self {
296            inner: SurroundingSeqAccept::new(output, Str("#["), Str("]\n")),
297        }
298    }
299}
300
301impl<'o, O: Output> SequenceAccept<O> for AttributesAccept<'o, O> {
302    async fn accept<W: Writable<O>>(&mut self, writable: &W) -> Result<(), O::Error> {
303        self.inner.accept(writable).await
304    }
305}