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

Add NodeName::Block #11

Merged
merged 5 commits into from
Jan 4, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
13 changes: 6 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
![build](https://github.com/stoically/syn-rsx/workflows/build/badge.svg)
![license: MIT](https://img.shields.io/crates/l/syn-rsx.svg)

[syn](https://github.com/dtolnay/syn)-powered parser for JSX-like [TokenStreams](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html), aka RSX. The parsed result is a nested `Node` structure, similar to the browser DOM, where node name and value are syn expressions to support building proc macros.
[syn](https://github.com/dtolnay/syn)-powered parser for JSX-like [TokenStreams](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html), aka RSX. The parsed result is a nested `Node` structure, similar to the browser DOM, where node name and value are syn expressions to support building proc macros.

```rust
use quote::quote;
Expand All @@ -21,7 +21,6 @@ assert_eq!(nodes[0].children[0].value_as_string().unwrap(), "hi");

## Features


- **Not opinionated**

Every tag or attribute name is valid
Expand Down Expand Up @@ -55,15 +54,16 @@ assert_eq!(nodes[0].children[0].value_as_string().unwrap(), "hi");
- **Attribute values can be any valid syn expression without requiring braces**

```html
<div key=some::value() />
<div key="some::value()" />
gbj marked this conversation as resolved.
Show resolved Hide resolved
```

- **Braced blocks are parsed as arbitrary Rust code**

```html
<{if is_block { "div" } else { "span" }} />
gbj marked this conversation as resolved.
Show resolved Hide resolved
<div>{ let block = "in node position"; }</div>
<div { let block = "in attribute position"; } />
<div key={ let block = "in attribute value position"; } />
<div { let block="in attribute position" ; } />
<div key="{" let block="in attribute value position" ; } />
gbj marked this conversation as resolved.
Show resolved Hide resolved
```

- **Helpful error reporting out of the box**
Expand All @@ -82,7 +82,6 @@ assert_eq!(nodes[0].children[0].value_as_string().unwrap(), "hi");
slightly different requirements for parsing and it's not yet customizable
feel free to open an issue or pull request to extend the configuration.


[`syn`]: /syn
[`TokenStream`]: https://doc.rust-lang.org/proc_macro/struct.TokenStream.html
[`tokenstream`]: https://doc.rust-lang.org/proc_macro/struct.TokenStream.html
gbj marked this conversation as resolved.
Show resolved Hide resolved
[unquoted text is planned]: https://github.com/stoically/syn-rsx/issues/2
21 changes: 20 additions & 1 deletion src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,23 @@ pub struct Node {
}

impl Node {
/// Returns `String` if `name` is `Some`
/// Returns `String` if `name` is `Some` and not `NodeName::Block`
pub fn name_as_string(&self) -> Option<String> {
match self.name.as_ref() {
Some(NodeName::Block(_)) => None,
Some(name) => Some(name.to_string()),
None => None,
}
}

/// Returns `ExprBlock` if `name` is `NodeName::Block(Expr::Block)`
pub fn name_as_block(&self) -> Option<ExprBlock> {
stoically marked this conversation as resolved.
Show resolved Hide resolved
match self.name.as_ref() {
Some(NodeName::Block(Expr::Block(expr))) => Some(expr.to_owned()),
_ => None,
}
}

/// Returns `Span` if `name` is `Some`
pub fn name_span(&self) -> Option<Span> {
match self.name.as_ref() {
Expand Down Expand Up @@ -123,6 +132,9 @@ pub enum NodeName {

/// Name separated by colons, e.g. `<div on:click={foo} />`
Colon(Punctuated<Ident, Colon>),

/// Arbitrary rust code in braced `{}` blocks
Block(Expr),
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just realized, is there a specific reason that this is Expr and not ExprBlock?

}

impl NodeName {
Expand All @@ -132,6 +144,7 @@ impl NodeName {
NodeName::Path(name) => name.span(),
NodeName::Dash(name) => name.span(),
NodeName::Colon(name) => name.span(),
NodeName::Block(name) => name.span(),
}
}
}
Expand Down Expand Up @@ -159,6 +172,7 @@ impl fmt::Display for NodeName {
.map(|ident| ident.to_string())
.collect::<Vec<String>>()
.join(":"),
NodeName::Block(_) => String::from(""),
}
)
}
Expand All @@ -179,6 +193,10 @@ impl PartialEq for NodeName {
Self::Colon(other) => this == other,
_ => false,
},
Self::Block(this) => match other {
Self::Block(other) => this == other,
_ => false,
},
}
}
}
Expand All @@ -189,6 +207,7 @@ impl ToTokens for NodeName {
NodeName::Path(name) => name.to_tokens(tokens),
NodeName::Dash(name) => name.to_tokens(tokens),
NodeName::Colon(name) => name.to_tokens(tokens),
NodeName::Block(name) => name.to_tokens(tokens),
}
}
}
5 changes: 5 additions & 0 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,11 @@ impl Parser {
} else if input.peek2(Dash) {
self.node_name_punctuated_ident::<Dash, fn(_) -> Dash, Ident>(input, Dash)
.map(|ok| NodeName::Dash(ok))
} else if input.peek(Brace) {
let fork = &input.fork();
let value = self.block_expr(fork)?;
input.advance_to(fork);
Ok(NodeName::Block(value))
} else if input.peek(Ident::peek_any) {
let mut segments = Punctuated::new();
let ident = Ident::parse_any(input)?;
Expand Down
20 changes: 20 additions & 0 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,26 @@ fn test_path_as_tag_name() {
assert_eq!(nodes[0].name_as_string().unwrap(), "some::path");
}

#[test]
fn test_block_as_tag_name() {
let tokens = quote! {
<{some_logic(block)} />
};

let nodes = parse2(tokens).unwrap();
assert_eq!(nodes[0].name_as_block().is_some(), true);
}

#[test]
fn test_block_as_tag_name_with_closing_tag() {
let tokens = quote! {
<{some_logic(block)}>"Test"</{some_logic(block)}>
};

let nodes = parse2(tokens).unwrap();
assert_eq!(nodes[0].name_as_block().is_some(), true);
}

#[test]
fn test_dashed_attribute_name() {
let tokens = quote! {
Expand Down