use crate::parse::attr::DOC_ATTR;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use std::fmt::Display;
use std::ops::AddAssign;
use syn::{Attribute, Generics, Ident, Type, parse_quote};
pub fn build_type(ident: &Ident, generics: &Generics) -> Type {
let ty_gen = generics.split_for_impl().1;
parse_quote!(#ident #ty_gen)
}
pub fn bare_default_impl_tokens(
ident: &Ident,
generics: &Generics,
) -> TokenStream {
let (
impl_generics,
ty_generics,
where_clause,
) = generics.split_for_impl();
quote! {
#[automatically_derived]
impl #impl_generics Default for #ident #ty_generics #where_clause {
fn default() -> Self {
Self::new()
}
}
}
}
pub fn doc_line(text: impl Display) -> TokenStream {
let text = text.to_string();
let line = if text.is_empty() {
String::new()
} else {
format!(" {}", text.clone().trim())
};
quote! {
#[doc = #line]
}
}
pub fn doc_lines(lines: &[String]) -> TokenStream {
let lines: Vec<_> = lines.iter().map(|s|
if s.is_empty() {
s.clone()
} else {
format!(" {}", s.trim())
}
).collect();
quote! {
#(#[doc = #lines])*
}
}
#[cfg_attr(feature = "syn-debug", derive(Debug))]
#[derive(Clone)]
pub(crate) struct AppendDoc {
source: Vec<Attribute>,
append: Vec<String>,
}
impl AppendDoc {
pub fn new(source: Vec<Attribute>) -> Self {
for attr in &source {
assert!(attr.path().is_ident(DOC_ATTR));
}
Self {
source,
append: Vec::new(),
}
}
pub fn source(&self) -> &Vec<Attribute> {
&self.source
}
pub fn line(&mut self, line: impl Display) {
self.append.push(line.to_string());
}
pub fn lines(&mut self, text: impl Display) {
let text = text.to_string();
for line in text.lines() {
self.line(line);
}
}
pub fn newl(&mut self) {
self.append.push(String::new());
}
pub fn to_append_tokens(&self) -> TokenStream {
doc_lines(&self.append)
}
}
impl From<Vec<Attribute>> for AppendDoc {
fn from(value: Vec<Attribute>) -> Self {
Self::new(value)
}
}
impl AddAssign<String> for AppendDoc {
fn add_assign(&mut self, rhs: String) {
self.lines(rhs);
}
}
impl AddAssign<Vec<String>> for AppendDoc {
fn add_assign(&mut self, rhs: Vec<String>) {
for line in rhs {
self.line(line);
}
}
}
impl ToTokens for AppendDoc {
fn to_tokens(&self, tokens: &mut TokenStream) {
let source = &self.source;
let append = self.to_append_tokens();
tokens.extend(quote! {
#(#source)*
#append
});
}
}
static RENDER_PREFIX: &str = "static x: x = ";
static RENDER_SUFFIX: &str = ";";
pub fn render_expr(tokens: &TokenStream) -> Option<String> {
let content = format!("{RENDER_PREFIX}{tokens}{RENDER_SUFFIX}");
if let Ok(parsed) = syn::parse_file(&content) {
let pretty = prettyplease::unparse(&parsed);
if pretty.len() > RENDER_PREFIX.len() + RENDER_SUFFIX.len() {
let inner_i = RENDER_PREFIX.len();
let inner_f = pretty.len() - RENDER_SUFFIX.len();
return Some(pretty[inner_i..inner_f - 1].to_string());
}
}
None
}