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
73impl<'w, W, O> WritableSeq<O> for &'w W where O: Output, W: WritableSeq<O> {
74    async fn for_each<S>(&self, sink: &mut S) -> Result<(), O::Error>
75    where
76        S: SequenceAccept<O>,
77    {
78        (**self).for_each(sink).await
79    }
80}
81
82/// A collector for multiple writable values. This trait is the ingredient to [`WritableSeq`] that
83/// represents how the sequence is handled. For example, `accept` can be implemented by adding
84/// commas after each element but not the last, which is what [common::CommaSeparated] does.
85pub trait SequenceAccept<O: Output> {
86    /// Writes a single writable type to this sink.
87    async fn accept<W>(&mut self, writable: &W) -> Result<(), O::Error>
88    where
89        W: Writable<O>;
90}
91
92impl<'s, S, O> SequenceAccept<O> for &'s mut S where O: Output, S: SequenceAccept<O> {
93    async fn accept<W>(&mut self, writable: &W) -> Result<(), O::Error>
94    where
95        W: Writable<O>,
96    {
97        (**self).accept(writable).await
98    }
99}
100
101/// Code generation output. This is a high-level trait intended to represent wherever you're
102/// writing to, with associated context. It can be split into that context in order to separate the
103/// I/O stream itself.
104pub trait Output {
105    /// The I/O stream type
106    type IO: IoOutput;
107    /// The context holder
108    type Ctx: Context;
109    /// The error type for write operations.
110    type Error: From<std::io::Error>;
111
112    /// Writes the given value to the output.
113    async fn write(&mut self, value: &str) -> Result<(), Self::Error>;
114
115    /// Splits into the context and the I/O stream, so that they can be used separately
116    fn split(&mut self) -> (&mut Self::IO, &Self::Ctx);
117
118    /// Gets all the context associated with this output
119    fn context(&self) -> &Self::Ctx;
120
121    /// Gets a particular context value
122    fn get_ctx<T>(&self) -> &T
123    where
124        Self::Ctx: ContextProvides<T>,
125    {
126        self.context().provide()
127    }
128}
129
130impl<'o, O> Output for &'o mut O
131where
132    O: Output,
133{
134    type IO = O::IO;
135    type Ctx = O::Ctx;
136    type Error = O::Error;
137
138    async fn write(&mut self, value: &str) -> Result<(), Self::Error> {
139        (**self).write(value).await
140    }
141
142    fn split(&mut self) -> (&mut Self::IO, &Self::Ctx) {
143        (**self).split()
144    }
145
146    fn context(&self) -> &Self::Ctx {
147        (**self).context()
148    }
149}
150
151/// An output that simply composes the I/O stream with a dynamic context
152pub struct SimpleOutput<I: IoOutput> {
153    pub io_output: I,
154    pub context: DynContext,
155}
156
157impl<I> Output for SimpleOutput<I>
158where
159    I: IoOutput,
160{
161    type IO = I;
162    type Ctx = DynContext;
163    type Error = std::io::Error;
164
165    async fn write(&mut self, value: &str) -> Result<(), Self::Error> {
166        self.io_output.write(value).await
167    }
168
169    fn split(&mut self) -> (&mut Self::IO, &Self::Ctx) {
170        (&mut self.io_output, &self.context)
171    }
172
173    fn context(&self) -> &Self::Ctx {
174        &self.context
175    }
176}
177
178/// The raw IO output.
179///
180/// This trait is not implemented by the library in a concrete way. Instead, depending on which
181/// async runtime you are using, you will have to implement it yourself.
182pub trait IoOutput {
183    /// Writes a string to the output. Yields an I/O error upon failure.
184    async fn write(&mut self, value: &str) -> Result<(), std::io::Error>;
185}
186
187impl<'o, O> IoOutput for &'o mut O
188where
189    O: IoOutput,
190{
191    async fn write(&mut self, value: &str) -> Result<(), std::io::Error> {
192        (**self).write(value).await
193    }
194}
195
196#[cfg(test)]
197mod tests {}