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