Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 90 additions & 14 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

65 changes: 53 additions & 12 deletions crates/hypertext-macros/src/derive.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::{Data, DeriveInput, Error, spanned::Spanned};
use syn::{Data, DeriveInput, Error, LitBool, parenthesized, spanned::Spanned};

use crate::{
AttributeValue, Config, Document, Many, Maud, Rsx, Semantics,
Expand Down Expand Up @@ -146,6 +146,49 @@ pub fn default_builder(input: DeriveInput) -> syn::Result<TokenStream> {
let vis = &input.vis;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

let mut is_start_fn_present = true;
let mut is_finish_fn_present = true;
for attr in &input.attrs {
if attr.path().is_ident("builder") {
attr.parse_nested_meta(|meta| {
let is_start_fn_attr = meta.path.is_ident("start_fn");
let is_finish_fn_attr = meta.path.is_ident("finish_fn");

if is_start_fn_attr || is_finish_fn_attr {
let content;
parenthesized!(content in meta.input);
let lit_bool = content.parse::<LitBool>()?;

if is_start_fn_attr {
is_start_fn_present = lit_bool.value;
}
if is_finish_fn_attr {
is_finish_fn_present = lit_bool.value;
}
Ok(())
} else {
Err(meta.error("unexpected param for `#[builder(...)]`"))
}
})?;
}
}

let start_fn = is_start_fn_present.then(|| {
quote! {
#vis fn builder() -> Self {
<Self as ::core::default::Default>::default()
}
}
});

let finish_fn = is_finish_fn_present.then(|| {
quote! {
#vis fn build(self) -> Self {
self
}
}
});

let mut methods = Vec::new();
for field in &data_struct.fields {
if let Some(name) = &field.ident {
Expand Down Expand Up @@ -179,18 +222,16 @@ pub fn default_builder(input: DeriveInput) -> syn::Result<TokenStream> {
}
}

let output = quote! {
#[automatically_derived]
impl #impl_generics #struct_name #ty_generics #where_clause {
#vis fn builder() -> Self {
<Self as ::core::default::Default>::default()
}

#vis fn build(self) -> Self {
self
let output = if start_fn.is_none() && finish_fn.is_none() && methods.is_empty() {
quote!()
} else {
quote! {
#[automatically_derived]
impl #impl_generics #struct_name #ty_generics #where_clause {
#start_fn
#finish_fn
#(#methods)*
}

#(#methods)*
}
};

Expand Down
51 changes: 51 additions & 0 deletions crates/hypertext-macros/src/html/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::{
convert::Infallible,
iter,
ops::{Deref, DerefMut},
path::PathBuf,
};

use proc_macro2::{Ident, Span, TokenStream};
Expand All @@ -22,6 +23,21 @@ pub enum Config {
}

impl Config {
pub fn generate_file<T: Parse + Generate>(
self,
tokens: TokenStream,
) -> syn::Result<TokenStream> {
let path_lit = syn::parse2::<LitStr>(tokens)?;
let (file_tokens, dep_tracking) = read_file_tokens(&path_lit)?;
let inner = self.generate::<T>(file_tokens)?;
Ok(quote! {
{
#dep_tracking
#inner
}
})
}

pub fn generate<T: Parse + Generate>(self, tokens: TokenStream) -> syn::Result<TokenStream> {
match self {
Self::Lazy(move_) => {
Expand Down Expand Up @@ -63,6 +79,41 @@ impl Config {
}
}

fn read_file_tokens(path_lit: &LitStr) -> syn::Result<(TokenStream, TokenStream)> {
let path = PathBuf::from(path_lit.value());

if path.is_absolute() {
return Err(Error::new_spanned(
path_lit,
"absolute paths are not allowed",
));
}

let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
.map_err(|_| Error::new_spanned(path_lit, "CARGO_MANIFEST_DIR not set"))?;

let full_path = PathBuf::from(&manifest_dir).join(&path);
let full_path_str = full_path.to_string_lossy().to_string();

let contents = std::fs::read_to_string(&full_path).map_err(|e| {
Error::new_spanned(
path_lit,
format!("failed to read \"{}\": {e}", full_path.display()),
)
})?;

let file_tokens = contents
.parse::<TokenStream>()
.map_err(|e| Error::new_spanned(path_lit, format!("failed to tokenize file: {e}")))?;

let full_path_lit = LitStr::new(&full_path_str, path_lit.span());
let dep_tracking = quote! {
const _: &[u8] = ::core::include_bytes!(#full_path_lit);
};

Ok((file_tokens, dep_tracking))
}

#[derive(Debug, Clone, Copy)]
pub enum Semantics {
Move,
Expand Down
Loading
Loading