1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
use super::{GenerateMod, Impl, ImplFor, StreamBuilder};
use crate::parse::{GenericConstraints, Generics};
use crate::prelude::{Ident, TokenStream};
#[must_use]
/// The generator is used to generate code.
///
/// Often you will want to use [`impl_for`] to generate an `impl <trait_name> for <target_name()>`.
///
/// [`impl_for`]: #method.impl_for
pub struct Generator {
pub(crate) name: Ident,
pub(crate) generics: Option<Generics>,
pub(crate) generic_constraints: Option<GenericConstraints>,
pub(crate) stream: StreamBuilder,
}
impl Generator {
pub(crate) fn new(
name: Ident,
generics: Option<Generics>,
generic_constraints: Option<GenericConstraints>,
) -> Self {
Self {
name,
generics,
generic_constraints,
stream: StreamBuilder::new(),
}
}
/// Return the name for the struct or enum that this is going to be implemented on.
pub fn target_name(&self) -> Ident {
self.name.clone()
}
/// Generate an `impl <target_name>` implementation. See [`Impl`] for more information.
pub fn r#impl(&mut self) -> Impl<Self> {
Impl::with_parent_name(self)
}
/// Generate an `impl <target_name>` implementation. See [`Impl`] for more information.
///
/// Alias for [`impl`] which doesn't need a `r#` prefix.
///
/// [`impl`]: #method.impl
pub fn generate_impl(&mut self) -> Impl<Self> {
Impl::with_parent_name(self)
}
/// Generate an `for <trait_name> for <target_name>` implementation. See [ImplFor] for more information.
pub fn impl_for(&mut self, trait_name: impl Into<String>) -> ImplFor<Self> {
ImplFor::new(self, trait_name)
}
/// Generate an `for <..lifetimes> <trait_name> for <target_name>` implementation. See [ImplFor] for more information.
///
/// Note:
/// - Lifetimes should _not_ have the leading apostrophe.
/// - The lifetimes passed to this function will automatically depend on any other lifetime this struct or enum may have. Example:
/// - The struct is `struct Foo<'a> {}`
/// - You call `generator.impl_for_with_lifetime("Bar", &["b"])
/// - The code will be `impl<'a, 'b: 'a> Bar<'b> for Foo<'a> {}`
/// - `trait_name` should _not_ have custom lifetimes. These will be added automatically.
///
/// ```no_run
/// # use virtue::prelude::*;
/// # let mut generator: Generator = unsafe { std::mem::zeroed() };
/// generator.impl_for_with_lifetimes("Foo", ["a", "b"]);
///
/// // will output:
/// // impl<'a, 'b> Foo<'a, 'b> for StructOrEnum { }
/// ```
pub fn impl_for_with_lifetimes<ITER, T>(
&mut self,
trait_name: T,
lifetimes: ITER,
) -> ImplFor<Self>
where
ITER: IntoIterator,
ITER::Item: Into<String>,
T: Into<String>,
{
ImplFor::new_with_lifetimes(self, trait_name, lifetimes)
}
/// Generate a `mod <name> { ... }`. See [`GenerateMod`] for more info.
pub fn generate_mod(&mut self, mod_name: impl Into<String>) -> GenerateMod<Self> {
GenerateMod::new(self, mod_name)
}
/// Export the current stream to a file, making it very easy to debug the output of a derive macro.
/// This will try to find rust's `target` directory, and write `target/generated/<crate_name>/<name>_<file_postfix>.rs`.
///
/// Will return `true` if the file is written, `false` otherwise.
///
/// The outputted file is unformatted. Use `cargo fmt -- target/generated/<crate_name>/<file>.rs` to format the file.
pub fn export_to_file(&self, crate_name: &str, file_postfix: &str) -> bool {
use std::io::Write;
if let Ok(var) = std::env::var("CARGO_MANIFEST_DIR") {
let mut path = std::path::PathBuf::from(var);
loop {
{
let mut path = path.clone();
path.push("target");
if path.exists() {
path.push("generated");
path.push(crate_name);
if std::fs::create_dir_all(&path).is_err() {
return false;
}
path.push(format!("{}_{}.rs", self.target_name(), file_postfix));
if let Ok(mut file) = std::fs::File::create(path) {
let _ = file.write_all(self.stream.stream.to_string().as_bytes());
return true;
}
}
}
if let Some(parent) = path.parent() {
path = parent.to_owned();
} else {
break;
}
}
}
false
}
/// Consume the contents of this generator. This *must* be called, or else the generator will panic on drop.
pub fn finish(mut self) -> crate::prelude::Result<TokenStream> {
Ok(std::mem::take(&mut self.stream).stream)
}
}
impl Drop for Generator {
fn drop(&mut self) {
if !self.stream.stream.is_empty() && !std::thread::panicking() {
eprintln!("WARNING: Generator dropped but the stream is not empty. Please call `.finish()` on the generator");
}
}
}
impl super::Parent for Generator {
fn append(&mut self, builder: StreamBuilder) {
self.stream.append(builder);
}
fn name(&self) -> &Ident {
&self.name
}
fn generics(&self) -> Option<&Generics> {
self.generics.as_ref()
}
fn generic_constraints(&self) -> Option<&GenericConstraints> {
self.generic_constraints.as_ref()
}
}
#[cfg(test)]
mod test {
use proc_macro2::Span;
use crate::token_stream;
use super::*;
#[test]
fn impl_for_with_lifetimes() {
// No generics
let mut generator =
Generator::new(Ident::new("StructOrEnum", Span::call_site()), None, None);
let _ = generator.impl_for_with_lifetimes("Foo", ["a", "b"]);
let output = generator.finish().unwrap();
assert_eq!(
output
.into_iter()
.map(|v| v.to_string())
.collect::<String>(),
token_stream("impl<'a, 'b> Foo<'a, 'b> for StructOrEnum { }")
.map(|v| v.to_string())
.collect::<String>(),
);
//with simple generics
let mut generator = Generator::new(
Ident::new("StructOrEnum", Span::call_site()),
Generics::try_take(&mut token_stream("<T1, T2>")).unwrap(),
None,
);
let _ = generator.impl_for_with_lifetimes("Foo", ["a", "b"]);
let output = generator.finish().unwrap();
assert_eq!(
output
.into_iter()
.map(|v| v.to_string())
.collect::<String>(),
token_stream("impl<'a, 'b, T1, T2> Foo<'a, 'b> for StructOrEnum<T1, T2> { }")
.map(|v| v.to_string())
.collect::<String>()
);
// with lifetimes
let mut generator = Generator::new(
Ident::new("StructOrEnum", Span::call_site()),
Generics::try_take(&mut token_stream("<'alpha, 'beta>")).unwrap(),
None,
);
let _ = generator.impl_for_with_lifetimes("Foo", ["a", "b"]);
let output = generator.finish().unwrap();
assert_eq!(
output
.into_iter()
.map(|v| v.to_string())
.collect::<String>(),
token_stream(
"impl<'a, 'b, 'alpha, 'beta> Foo<'a, 'b> for StructOrEnum<'alpha, 'beta> { }"
)
.map(|v| v.to_string())
.collect::<String>()
);
}
}