Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: lit! macro #6

Merged
merged 1 commit into from
Nov 8, 2024
Merged
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
11 changes: 11 additions & 0 deletions macros/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use proc_macro::TokenStream;
use quote::quote;
use syn::parse_macro_input;
use tiny_rsx::ast;

Expand Down Expand Up @@ -30,3 +31,13 @@ pub fn write(input: TokenStream) -> TokenStream {

expand::write(input).into()
}

pub(crate) struct LitInput {
text: String,
}

#[proc_macro]
pub fn lit(input: TokenStream) -> TokenStream {
let LitInput { text } = parse_macro_input!(input as LitInput);
quote!(::vy::PreEscaped(#text)).into()
}
26 changes: 25 additions & 1 deletion macros/src/parse.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use syn::parse::{Parse, ParseStream};
use tiny_rsx::ast::NodeTree;

use crate::{LazyInput, WriteInput};
use crate::{fmt::Formatter, LazyInput, LitInput, WriteInput};

impl Parse for LazyInput {
fn parse(input: ParseStream) -> syn::Result<Self> {
Expand Down Expand Up @@ -30,3 +30,27 @@ impl Parse for WriteInput {
})
}
}

impl Parse for LitInput {
fn parse(input: ParseStream) -> syn::Result<Self> {
let NodeTree { nodes } = NodeTree::parse(input)?;

let mut text = String::new();
let mut args = Vec::new();

let mut fmt = Formatter::new(&mut text, &mut args);

for node in &nodes {
let _ = fmt.write_node(node);
}

if let Some((_, value)) = args.into_iter().next() {
return Err(syn::Error::new_spanned(
value,
"only literals allowed",
));
}

Ok(Self { text })
}
}
5 changes: 5 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ pub use vy_core::{PreEscaped, Render};
/// ```
#[doc(inline)]
pub use vy_macros::lazy;
/// Creates an HTML string literal.
///
/// Passing any non literal values will cause a compilation error.
#[doc(inline)]
pub use vy_macros::lit;
/// Writes HTML to a [`String`].
///
/// This macro eagerly writes HTML to a [`String`].
Expand Down