Skip to content

Commit

Permalink
chore: Fix value_to_string usage, pr comments, and fmt.
Browse files Browse the repository at this point in the history
  • Loading branch information
vldm committed May 19, 2023
1 parent 9c277b5 commit 7dd296c
Show file tree
Hide file tree
Showing 10 changed files with 177 additions and 159 deletions.
10 changes: 3 additions & 7 deletions leptos_hot_reload/src/node.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::parsing::is_component_node;
use anyhow::Result;
use quote::ToTokens;
use serde::{Deserialize, Serialize};
use rstml::node::{Node, NodeAttribute};
use serde::{Deserialize, Serialize};

// A lightweight virtual DOM structure we can use to hold
// the state of a Leptos view macro template. This is because
Expand Down Expand Up @@ -92,14 +92,10 @@ impl LNode {
let name = el.name().to_string();
let mut attrs = Vec::new();

for attr in el
.open_tag
.attributes {
for attr in el.open_tag.attributes {
if let NodeAttribute::Attribute(attr) = attr {
let name = attr.key.to_string();
if let Some(value) =
attr.value_literal_string()
{
if let Some(value) = attr.value_literal_string() {
attrs.push((
name,
LAttributeValue::Static(value),
Expand Down
30 changes: 30 additions & 0 deletions leptos_hot_reload/src/parsing.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,35 @@
use rstml::node::NodeElement;

///
/// Converts `syn::Block` to simple expression
///
/// For example:
/// ```no_build
/// // "string literal" in
/// {"string literal"}
/// // number literal
/// {0x12}
/// // boolean literal
/// {true}
/// // variable
/// {path::x}
/// ```
pub fn block_to_primitive_expression(block: &syn::Block) -> Option<&syn::Expr> {
// its empty block, or block with multi lines
if block.stmts.len() != 1 {
return None;
}
match &block.stmts[0] {
syn::Stmt::Expr(e, None) => return Some(&e),
_ => {}
}
None
}

/// Converts simple literals to its string representation.
///
/// This function doesn't convert literal wrapped inside block
/// like: `{"string"}`.
pub fn value_to_string(value: &syn::Expr) -> Option<String> {
match &value {
syn::Expr::Lit(lit) => match &lit.lit {
Expand Down
30 changes: 11 additions & 19 deletions leptos_macro/src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,9 @@ use proc_macro2::{Ident, Span, TokenStream};
use quote::{format_ident, quote_spanned, ToTokens, TokenStreamExt};
use syn::{
parse::Parse, parse_quote, spanned::Spanned,
AngleBracketedGenericArguments, Attribute, FnArg, GenericArgument,
LitStr, Meta, Pat, PatIdent, Path,
PathArguments, ReturnType, Type, TypePath, Visibility,
ItemFn, Stmt, Item,
AngleBracketedGenericArguments, Attribute, FnArg, GenericArgument, Item,
ItemFn, LitStr, Meta, Pat, PatIdent, Path, PathArguments, ReturnType, Stmt,
Type, TypePath, Visibility,
};
pub struct Model {
is_transparent: bool,
Expand Down Expand Up @@ -57,22 +56,17 @@ impl Parse for Model {

// We need to remove the `#[doc = ""]` and `#[builder(_)]`
// attrs from the function signature
drain_filter(&mut item.attrs, |attr| {

match &attr.meta {
Meta::NameValue(attr) => attr.path == parse_quote!(doc),
Meta::List(attr ) => attr.path == parse_quote!(prop),
_ => false
}
drain_filter(&mut item.attrs, |attr| match &attr.meta {
Meta::NameValue(attr) => attr.path == parse_quote!(doc),
Meta::List(attr) => attr.path == parse_quote!(prop),
_ => false,
});
item.sig.inputs.iter_mut().for_each(|arg| {
if let FnArg::Typed(ty) = arg {
drain_filter(&mut ty.attrs, |attr| {
match &attr.meta {
Meta::NameValue(attr) => attr.path == parse_quote!(doc),
Meta::List(attr ) => attr.path == parse_quote!(prop),
_ => false
}
drain_filter(&mut ty.attrs, |attr| match &attr.meta {
Meta::NameValue(attr) => attr.path == parse_quote!(doc),
Meta::List(attr) => attr.path == parse_quote!(prop),
_ => false,
});
}
});
Expand Down Expand Up @@ -410,11 +404,9 @@ impl Docs {
let mut attrs = attrs
.iter()
.filter_map(|attr| {

let Meta::NameValue(attr ) = &attr.meta else {
return None
};

if !attr.path.is_ident("doc") {
return None
}
Expand Down
21 changes: 11 additions & 10 deletions leptos_macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ extern crate proc_macro_error;
use proc_macro::TokenStream;
use proc_macro2::{Span, TokenTree};
use quote::ToTokens;
use rstml::{node::KeyedAttribute, parse};
use server_fn_macro::{server_macro_impl, ServerContext};
use syn::parse_macro_input;
use rstml::{parse, node::KeyedAttribute};

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum Mode {
Expand Down Expand Up @@ -353,21 +353,22 @@ pub fn view(tokens: TokenStream) -> TokenStream {
};
let config = rstml::ParserConfig::default().recover_block(true);
let parser = rstml::Parser::new(config);
let (nodes, errors) = parser.parse_recoverable(tokens).split_vec();
let (nodes, errors) = parser.parse_recoverable(tokens).split_vec();
let errors = errors.into_iter().map(|e| e.emit_as_expr_tokens());
let nodes_output = render_view(
&cx,
&nodes,
Mode::default(),
global_class.as_ref(),
normalized_call_site(proc_macro::Span::call_site()),
);
quote!{
&cx,
&nodes,
Mode::default(),
global_class.as_ref(),
normalized_call_site(proc_macro::Span::call_site()),
);
quote! {
{
#(#errors;)*
#nodes_output
}
}.into()
}
.into()
}
_ => {
abort_call_site!(
Expand Down
24 changes: 10 additions & 14 deletions leptos_macro/src/slot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use attribute_derive::Attribute as AttributeDerive;
use proc_macro2::{Ident, TokenStream};
use quote::{ToTokens, TokenStreamExt};
use syn::{
parse::Parse, parse_quote, Field, ItemStruct, LitStr, Type, Visibility, Meta,
parse::Parse, parse_quote, Field, ItemStruct, LitStr, Meta, Type,
Visibility,
};

pub struct Model {
Expand All @@ -31,21 +32,16 @@ impl Parse for Model {

// We need to remove the `#[doc = ""]` and `#[builder(_)]`
// attrs from the function signature
drain_filter(&mut item.attrs, |attr| {
match &attr.meta {
Meta::NameValue(attr) => attr.path == parse_quote!(doc),
Meta::List(attr ) => attr.path == parse_quote!(prop),
_ => false
}
drain_filter(&mut item.attrs, |attr| match &attr.meta {
Meta::NameValue(attr) => attr.path == parse_quote!(doc),
Meta::List(attr) => attr.path == parse_quote!(prop),
_ => false,
});
item.fields.iter_mut().for_each(|arg| {
drain_filter(&mut arg.attrs, |attr| {

match &attr.meta {
Meta::NameValue(attr) => attr.path == parse_quote!(doc),
Meta::List(attr ) => attr.path == parse_quote!(prop),
_ => false
}
drain_filter(&mut arg.attrs, |attr| match &attr.meta {
Meta::NameValue(attr) => attr.path == parse_quote!(doc),
Meta::List(attr) => attr.path == parse_quote!(prop),
_ => false,
});
});

Expand Down
108 changes: 59 additions & 49 deletions leptos_macro/src/template.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
use crate::attribute_value;
use leptos_hot_reload::parsing::is_component_node;
use itertools::Either;
use leptos_hot_reload::parsing::{
block_to_primitive_expression, is_component_node, value_to_string,
};
use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, quote_spanned, ToTokens};
use syn::{spanned::Spanned, ExprBlock};
use rstml::node::{Node, NodeAttribute, NodeElement, KeyedAttribute, NodeBlock};
use rstml::node::{
KeyedAttribute, Node, NodeAttribute, NodeBlock, NodeElement,
};
use syn::spanned::Spanned;
use uuid::Uuid;

pub(crate) fn render_template(cx: &Ident, nodes: &[Node]) -> TokenStream {
Expand Down Expand Up @@ -247,7 +252,10 @@ fn next_sibling_node(
if is_component_node(sibling) {
next_sibling_node(children, idx + 1, next_el_id)
} else {
Ok(Some(child_ident(*next_el_id + 1, sibling.name().span())))
Ok(Some(child_ident(
*next_el_id + 1,
sibling.name().span(),
)))
}
}
Node::Block(sibling) => {
Expand Down Expand Up @@ -387,13 +395,9 @@ fn child_to_tokens(
))
}
}
//TODO Should we ewerywhere use syn::expr?
Node::Text(node) => block_to_tokens(
cx,
&syn::ExprLit{
attrs: vec![],
lit: node.value.clone().into()
}.into(),
Either::Left(node.value_string()),
node.value.span(),
parent,
prev_sib,
Expand All @@ -403,14 +407,10 @@ fn child_to_tokens(
expressions,
navigations,
),
Node::Block(NodeBlock::ValidBlock(b)) => block_to_tokens(
Node::RawText(node) => block_to_tokens(
cx,
&ExprBlock {
attrs: vec![],
label: None,
block: b.clone()
}.into(),
b.span(),
Either::Left(node.to_string_best()),
node.span(),
parent,
prev_sib,
next_sib,
Expand All @@ -419,11 +419,29 @@ fn child_to_tokens(
expressions,
navigations,
),

// TODO: Do we need to handle invalid blocks?
Node::Block(b @ NodeBlock::Invalid{..}) => block_to_tokens(
Node::Block(NodeBlock::ValidBlock(b)) => {
let value = match block_to_primitive_expression(b)
.and_then(value_to_string)
{
Some(v) => Either::Left(v),
None => Either::Right(b.into_token_stream()),
};
block_to_tokens(
cx,
value,
b.span(),
parent,
prev_sib,
next_sib,
next_el_id,
template,
expressions,
navigations,
)
}
Node::Block(b @ NodeBlock::Invalid { .. }) => block_to_tokens(
cx,
&syn::Expr::Verbatim(b.to_token_stream()),
Either::Right(b.into_token_stream()),
b.span(),
parent,
prev_sib,
Expand All @@ -440,7 +458,7 @@ fn child_to_tokens(
#[allow(clippy::too_many_arguments)]
fn block_to_tokens(
_cx: &Ident,
value: &syn::Expr,
value: Either<String, TokenStream>,
span: Span,
parent: &Ident,
prev_sib: Option<Ident>,
Expand All @@ -450,17 +468,6 @@ fn block_to_tokens(
expressions: &mut Vec<TokenStream>,
navigations: &mut Vec<TokenStream>,
) -> PrevSibChange {
let str_value = match value {
syn::Expr::Lit(lit) => match &lit.lit {
syn::Lit::Str(s) => Some(s.value()),
syn::Lit::Char(c) => Some(c.value().to_string()),
syn::Lit::Int(i) => Some(i.base10_digits().to_string()),
syn::Lit::Float(f) => Some(f.base10_digits().to_string()),
_ => None,
},
_ => None,
};

// code to navigate to this text node

let (name, location) = /* if is_first_child && mode == Mode::Client {
Expand Down Expand Up @@ -494,27 +501,30 @@ fn block_to_tokens(
}
};

if let Some(v) = str_value {
navigations.push(location);
template.push_str(&v);
match value {
Either::Left(v) => {
navigations.push(location);
template.push_str(&v);

if let Some(name) = name {
PrevSibChange::Sib(name)
} else {
PrevSibChange::Parent
if let Some(name) = name {
PrevSibChange::Sib(name)
} else {
PrevSibChange::Parent
}
}
} else {
template.push_str("<!>");
navigations.push(location);
Either::Right(value) => {
template.push_str("<!>");
navigations.push(location);

expressions.push(quote! {
leptos::leptos_dom::mount_child(#mount_kind, &{#value}.into_view(cx));
});
expressions.push(quote! {
leptos::leptos_dom::mount_child(#mount_kind, &{#value}.into_view(cx));
});

if let Some(name) = name {
PrevSibChange::Sib(name)
} else {
PrevSibChange::Parent
if let Some(name) = name {
PrevSibChange::Sib(name)
} else {
PrevSibChange::Parent
}
}
}
}
Expand Down
Loading

0 comments on commit 7dd296c

Please sign in to comment.