async_codegen/
lib.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#![forbid(unsafe_code)]
18#![allow(async_fn_in_trait)]
19
20//!
21//! A library for async code generation that imposes no ownership choices (can use borrowed or
22//! owned data) and is fully composable using generics and general-purpose structs.
23//!
24//! All syntax that can be generated is represented by a [`Writable`]. This is the core type of the
25//! library and it is quite simple. Any type that is supposed to be written to an output should
26//! implement this trait.
27//!
28//! Writable output is sent to an [`Output`]. Output consists of the direct I/O output as well as
29//! some context tied to it.
30//!
31
32use crate::context::{Context, ContextProvides, DynContext};
33
34/// Provides common and re-usable types, including types that are conceptual to this library and
35/// its type model.
36pub mod common;
37/// Using context for code generation requires importing this module
38pub mod context;
39/// Rust code syntax is available through this module.
40pub mod rust;
41
42/// A type that can be written to an output stream.
43///
44/// This struct is typically implemented by generic structs whenever their fields are also
45/// `Writable`. In this way, writable types depend on each other and re-use common syntax.
46pub trait Writable<O: Output> {
47    /// Writes to the output. Returns the output's error upon failure.
48    ///
49    /// A writable can always be written multiple times. Because of this, the function takes a
50    /// borrowed reference.
51    async fn write_to(&self, output: &mut O) -> Result<(), O::Error>;
52}
53
54impl<'w, W, O> Writable<O> for &'w W
55where
56    W: Writable<O>,
57    O: Output,
58{
59    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
60        (**self).write_to(output).await
61    }
62}
63
64/// A sequence of writable types. Sequences are modeled in the library by this interface, so that
65/// different separators can implement [`SequenceAccept`].
66pub trait WritableSeq<O: Output> {
67    /// Writes each writable value in the sequence
68    async fn for_each<S>(&self, sink: &mut S) -> Result<(), O::Error>
69    where
70        S: SequenceAccept<O>;
71}
72
73/// A collector for multiple writable values. This trait is the ingredient to [`WritableSeq`] that
74/// represents how the sequence is handled. For example, `accept` can be implemented by adding
75/// commas after each element but not the last, which is what [common::CommaSeparated] does.
76pub trait SequenceAccept<O: Output> {
77    /// Writes a single writable type to this sink.
78    async fn accept<W>(&mut self, writable: &W) -> Result<(), O::Error>
79    where
80        W: Writable<O>;
81}
82
83/// Code generation output. This is a high-level trait intended to represent wherever you're
84/// writing to, with associated context. It can be split into that context in order to separate the
85/// I/O stream itself.
86pub trait Output {
87    /// The I/O stream type
88    type IO: IoOutput;
89    /// The context holder
90    type Ctx: Context;
91    /// The error type for write operations.
92    type Error: From<std::io::Error>;
93
94    /// Writes the given value to the output.
95    async fn write(&mut self, value: &str) -> Result<(), Self::Error>;
96
97    /// Splits into the context and the I/O stream, so that they can be used separately
98    fn split(&mut self) -> (&mut Self::IO, &Self::Ctx);
99
100    /// Gets all the context associated with this output
101    fn context(&self) -> &Self::Ctx;
102
103    /// Gets a particular context value
104    fn get_ctx<T>(&self) -> &T
105    where
106        Self::Ctx: ContextProvides<T>,
107    {
108        self.context().provide()
109    }
110}
111
112impl<'o, O> Output for &'o mut O
113where
114    O: Output,
115{
116    type IO = O::IO;
117    type Ctx = O::Ctx;
118    type Error = O::Error;
119
120    async fn write(&mut self, value: &str) -> Result<(), Self::Error> {
121        (**self).write(value).await
122    }
123
124    fn split(&mut self) -> (&mut Self::IO, &Self::Ctx) {
125        (**self).split()
126    }
127
128    fn context(&self) -> &Self::Ctx {
129        (**self).context()
130    }
131}
132
133/// An output that simply composes the I/O stream with a dynamic context
134pub struct SimpleOutput<I: IoOutput> {
135    pub io_output: I,
136    pub context: DynContext,
137}
138
139impl<I> Output for SimpleOutput<I>
140where
141    I: IoOutput,
142{
143    type IO = I;
144    type Ctx = DynContext;
145    type Error = std::io::Error;
146
147    async fn write(&mut self, value: &str) -> Result<(), Self::Error> {
148        self.io_output.write(value).await
149    }
150
151    fn split(&mut self) -> (&mut Self::IO, &Self::Ctx) {
152        (&mut self.io_output, &self.context)
153    }
154
155    fn context(&self) -> &Self::Ctx {
156        &self.context
157    }
158}
159
160/// The raw IO output.
161///
162/// This trait is not implemented by the library in a concrete way. Instead, depending on which
163/// async runtime you are using, you will have to implement it yourself.
164pub trait IoOutput {
165    /// Writes a string to the output. Yields an I/O error upon failure.
166    async fn write(&mut self, value: &str) -> Result<(), std::io::Error>;
167}
168
169impl<'o, O> IoOutput for &'o mut O
170where
171    O: IoOutput,
172{
173    async fn write(&mut self, value: &str) -> Result<(), std::io::Error> {
174        (**self).write(value).await
175    }
176}
177
178#[cfg(test)]
179mod tests {}