stoically / syn-rsx

syn-powered parser for JSX-like TokenStreams
https://crates.io/crates/syn-rsx
MIT License
180 stars 24 forks source link
html jsx macros rsx syn

syn-rsx

crates.io page docs.rs page codecov build license: MIT

syn-powered parser for JSX-like TokenStreams, 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.

use std::convert::TryFrom;

use eyre::bail;
use quote::quote;
use syn_rsx::{parse2, Node, NodeAttribute, NodeElement, NodeText};

// Create HTML `TokenStream`.
let tokens = quote! { <hello world>"hi"</hello> };

// Parse the tokens into a tree of `Node`s.
let nodes = parse2(tokens)?;

// Extract some specific nodes from the tree.
let Node::Element(element) = &nodes[0] else { bail!("element") };
let Node::Attribute(attribute) = &element.attributes[0] else { bail!("attribute") };
let Node::Text(text) = &element.children[0] else { bail!("text") };

// Work with the nodes.
assert_eq!(element.name.to_string(), "hello");
assert_eq!(attribute.key.to_string(), "world");
assert_eq!(String::try_from(&text.value)?, "hi");

You might want to check out the html-to-string-macro example as well.

Features