strata-macro 0.1.4

Procedural macros for Strata: rsx! declarative syntax, #[component], and dynamic! macro
Documentation
//! Recursive-descent RSX parser converting TokenCursor into an RSX AST.

use crate::ast::*;
use crate::cursor::TokenCursor;
use proc_macro::{Delimiter, Spacing, TokenStream, TokenTree};

const VOID_TAGS: &[&str] = &[
    "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source",
    "track", "wbr",
];

/// Maximum allowed RSX element hierarchy nesting depth (CWE-674 recursion prevention).
pub const MAX_MACRO_DEPTH: usize = 256;

pub fn parse_rsx(cursor: &mut TokenCursor) -> Result<Vec<RsxNode>, String> {
    let mut nodes = Vec::new();
    while !cursor.is_eof() {
        nodes.push(parse_node(cursor, 0)?);
    }
    Ok(nodes)
}

fn parse_node(cursor: &mut TokenCursor, depth: usize) -> Result<RsxNode, String> {
    if depth > MAX_MACRO_DEPTH {
        return Err(format!(
            "Recursion limit exceeded: RSX element hierarchy exceeds MAX_MACRO_DEPTH ({MAX_MACRO_DEPTH}) (CWE-674 prevention)"
        ));
    }
    if cursor.peek_punct('<') {
        parse_tag_or_fragment(cursor, depth)
    } else if cursor.peek_group(Delimiter::Brace).is_some() {
        let g = cursor.consume_group(Delimiter::Brace).unwrap();
        Ok(RsxNode::Expression(g.stream()))
    } else if let Some(lit) = cursor.consume_literal_string() {
        Ok(RsxNode::Text(lit))
    } else if let Some(id) = cursor.consume_ident() {
        Ok(RsxNode::Text(id))
    } else if let Some(tok) = cursor.next() {
        // Fallback for stray punctuation/tokens outside tags: treat as string
        Ok(RsxNode::Text(tok.to_string()))
    } else {
        Err("Unexpected end of input while parsing RSX node".to_string())
    }
}

fn parse_tag_or_fragment(cursor: &mut TokenCursor, depth: usize) -> Result<RsxNode, String> {
    cursor.consume_punct('<');

    // Case 1: Fragment opening `<>`
    if cursor.consume_punct('>') {
        return parse_fragment(cursor, depth);
    }

    // Case 2: Unexpected closing tag `</...>`
    if cursor.peek_punct('/') {
        return Err("Unexpected closing tag '</' without matching opening tag".to_string());
    }

    // Case 3: Tag path (e.g. `div`, `Sidebar`, `strata_dom::Portal`, `::strata_dom::Portal`, or `Icons::Plus`)
    let leading_colon = if cursor.peek_punct(':') && cursor.peek_punct_at(1, ':') {
        cursor.consume_punct(':');
        cursor.consume_punct(':');
        true
    } else {
        false
    };

    let first_ident = cursor.consume_ident().ok_or_else(|| {
        if leading_colon {
            "Expected identifier after leading '::' in tag path".to_string()
        } else {
            "Expected tag name or identifier after '<'".to_string()
        }
    })?;

    let mut path = vec![first_ident];
    while cursor.peek_punct(':') && cursor.peek_punct_at(1, ':') {
        if cursor.peek_punct_at(2, '<') {
            break;
        }
        cursor.consume_punct(':');
        cursor.consume_punct(':');
        let next_id = cursor
            .consume_ident()
            .ok_or_else(|| "Expected identifier after '::' in tag path".to_string())?;
        path.push(next_id);
    }

    let is_custom_component = leading_colon || path.len() > 1 || segment_starts_uppercase(&path[0]);

    // Optional generic arguments on custom components: `<List<String> ... />` or `<List::<String> ... />`
    let generics = if is_custom_component {
        parse_optional_tag_generics(cursor)?
    } else {
        None
    };

    // Parse attributes
    let attributes = parse_attributes(cursor)?;

    // Check for self-closing `/>`
    if cursor.peek_punct('/') && cursor.peek_punct_at(1, '>') {
        cursor.consume_punct('/');
        cursor.consume_punct('>');
        if is_custom_component {
            return Ok(RsxNode::Component(RsxComponent {
                leading_colon,
                path,
                generics,
                props: attributes,
                children: Vec::new(),
                self_closing: true,
            }));
        } else {
            return Ok(RsxNode::Element(RsxElement {
                tag: path[0].clone(),
                attributes,
                children: Vec::new(),
                self_closing: true,
            }));
        }
    }

    // Must be closing `>`
    if !cursor.consume_punct('>') {
        return Err(format!(
            "Expected '>' or '/>' to close opening tag for '<{}>'",
            format_tag_path(leading_colon, &path)
        ));
    }

    // Check void elements (only for standard HTML elements)
    if !is_custom_component {
        let tag_lower = path[0].to_ascii_lowercase();
        if VOID_TAGS.contains(&tag_lower.as_str()) {
            // Check if there is an explicit closing tag e.g. `</input>`
            if cursor.peek_punct('<')
                && cursor.peek_punct_at(1, '/')
                && cursor.peek_punct_at(3, '>')
            {
                let pos = cursor.current_pos();
                cursor.consume_punct('<');
                cursor.consume_punct('/');
                if let Some(close_id) = cursor.consume_ident() {
                    if close_id.eq_ignore_ascii_case(&tag_lower) {
                        cursor.consume_punct('>');
                        return Ok(RsxNode::Element(RsxElement {
                            tag: path[0].clone(),
                            attributes,
                            children: Vec::new(),
                            self_closing: true,
                        }));
                    }
                }
                cursor.set_pos(pos);
            }
            return Ok(RsxNode::Element(RsxElement {
                tag: path[0].clone(),
                attributes,
                children: Vec::new(),
                self_closing: true,
            }));
        }
    }

    // Parse children until matching closing tag `</tag>` is encountered
    let mut children = Vec::new();
    loop {
        if cursor.is_eof() {
            let formatted = format_tag_path(leading_colon, &path);
            return Err(format!(
                "Unclosed tag '<{}>': reached end of input without finding '</{}>'",
                formatted, formatted
            ));
        }

        // Check if closing tag
        if cursor.peek_punct('<') && cursor.peek_punct_at(1, '/') {
            let saved_pos = cursor.current_pos();
            cursor.consume_punct('<');
            cursor.consume_punct('/');

            let close_leading_colon = if cursor.peek_punct(':') && cursor.peek_punct_at(1, ':') {
                cursor.consume_punct(':');
                cursor.consume_punct(':');
                true
            } else {
                false
            };

            let mut close_path = Vec::new();
            if let Some(id) = cursor.consume_ident() {
                close_path.push(id);
                while cursor.peek_punct(':') && cursor.peek_punct_at(1, ':') {
                    if cursor.peek_punct_at(2, '<') {
                        break;
                    }
                    cursor.consume_punct(':');
                    cursor.consume_punct(':');
                    if let Some(next_id) = cursor.consume_ident() {
                        close_path.push(next_id);
                    } else {
                        break;
                    }
                }
            }

            // Allow optional generic args on closing tag (e.g. `</List<String>>` or `</List>`).
            let _ = parse_optional_tag_generics(cursor);

            if cursor.consume_punct('>') {
                if close_leading_colon == leading_colon && close_path == path {
                    break;
                } else {
                    return Err(format!(
                        "Mismatched closing tag: expected '</{}>', found '</{}>'",
                        format_tag_path(leading_colon, &path),
                        format_tag_path(close_leading_colon, &close_path)
                    ));
                }
            } else {
                cursor.set_pos(saved_pos);
            }
        }

        push_child_node(&mut children, parse_node(cursor, depth + 1)?);
    }

    if is_custom_component {
        Ok(RsxNode::Component(RsxComponent {
            leading_colon,
            path,
            generics,
            props: attributes,
            children,
            self_closing: false,
        }))
    } else {
        Ok(RsxNode::Element(RsxElement {
            tag: path[0].clone(),
            attributes,
            children,
            self_closing: false,
        }))
    }
}

fn parse_optional_tag_generics(cursor: &mut TokenCursor) -> Result<Option<String>, String> {
    let saved = cursor.current_pos();
    if cursor.peek_punct(':') && cursor.peek_punct_at(1, ':') && cursor.peek_punct_at(2, '<') {
        cursor.consume_punct(':');
        cursor.consume_punct(':');
    } else if !cursor.peek_punct('<') {
        return Ok(None);
    }

    if !cursor.consume_punct('<') {
        cursor.set_pos(saved);
        return Ok(None);
    }

    let mut depth = 1usize;
    let mut out = String::from("<");
    while !cursor.is_eof() && depth > 0 {
        if cursor.peek_punct('<') {
            depth += 1;
        } else if cursor.peek_punct('>') {
            depth -= 1;
        }
        if let Some(tok) = cursor.next() {
            let is_joint = matches!(
                &tok,
                TokenTree::Punct(p) if p.spacing() == Spacing::Joint || p.as_char() == '\''
            );
            out.push_str(&tok.to_string());
            if depth > 0 && !is_joint {
                out.push(' ');
            }
        }
    }
    if depth != 0 {
        return Err("Unclosed generic argument list `<...>` on component tag".to_string());
    }
    Ok(Some(out))
}

fn push_child_node(children: &mut Vec<RsxNode>, next_node: RsxNode) {
    if let RsxNode::Text(next_text) = next_node {
        if let Some(RsxNode::Text(prev_text)) = children.last_mut() {
            if matches!(
                next_text.as_str(),
                "." | "," | ":" | ";" | "!" | "?" | ")" | "]"
            ) || prev_text.ends_with('(')
                || prev_text.ends_with('[')
            {
                prev_text.push_str(&next_text);
            } else {
                prev_text.push(' ');
                prev_text.push_str(&next_text);
            }
        } else {
            children.push(RsxNode::Text(next_text));
        }
    } else {
        children.push(next_node);
    }
}

fn parse_fragment(cursor: &mut TokenCursor, depth: usize) -> Result<RsxNode, String> {
    let mut children = Vec::new();
    loop {
        if cursor.is_eof() {
            return Err("Unclosed fragment '<>': reached end of input without '</>'".to_string());
        }

        if cursor.peek_punct('<') && cursor.peek_punct_at(1, '/') && cursor.peek_punct_at(2, '>') {
            cursor.consume_punct('<');
            cursor.consume_punct('/');
            cursor.consume_punct('>');
            break;
        }

        push_child_node(&mut children, parse_node(cursor, depth + 1)?);
    }
    Ok(RsxNode::Fragment(children))
}

fn parse_attributes(cursor: &mut TokenCursor) -> Result<Vec<RsxAttribute>, String> {
    let mut attrs = Vec::new();

    while !cursor.is_eof() {
        if cursor.peek_punct('>') || (cursor.peek_punct('/') && cursor.peek_punct_at(1, '>')) {
            break;
        }

        // JSX spread syntax: `{..props}`
        if cursor.peek_group(Delimiter::Brace).is_some() {
            let g = cursor.consume_group(Delimiter::Brace).unwrap();
            let mut inner = TokenCursor::new(g.stream());
            if inner.peek_punct('.') && inner.peek_punct_at(1, '.') {
                inner.consume_punct('.');
                inner.consume_punct('.');
                let mut rest = TokenStream::new();
                while let Some(tok) = inner.next() {
                    rest.extend(std::iter::once(tok));
                }
                if rest.is_empty() {
                    return Err("Expected expression after `{..` in spread attribute".to_string());
                }
                attrs.push(RsxAttribute {
                    name: "..".to_string(),
                    value: RsxAttrValue::Spread(rest),
                });
                continue;
            }
            return Err(
                "Expected spread expression `{..expr}` inside tag attribute list".to_string(),
            );
        }

        // Attribute name (can contain hyphens like `stroke-width`, `data-state`)
        let mut name = cursor
            .consume_ident()
            .ok_or_else(|| "Expected attribute name".to_string())?;

        while cursor.peek_punct('-') {
            cursor.consume_punct('-');
            let part = cursor
                .consume_ident()
                .ok_or_else(|| "Expected identifier after '-' in attribute name".to_string())?;
            name.push('-');
            name.push_str(&part);
        }

        // Optional value
        let value = if cursor.consume_punct('=') {
            if cursor.peek_group(Delimiter::Brace).is_some() {
                let g = cursor.consume_group(Delimiter::Brace).unwrap();
                RsxAttrValue::Expression(g.stream())
            } else if let Some(lit) = cursor.consume_literal_string() {
                RsxAttrValue::Literal(lit)
            } else if let Some(id) = cursor.consume_ident() {
                let s: TokenStream = id.parse().map_err(|e| format!("{:?}", e))?;
                RsxAttrValue::Expression(s)
            } else {
                return Err(format!(
                    "Expected string literal or '{{expr}}' for attribute '{}'",
                    name
                ));
            }
        } else {
            RsxAttrValue::Flag
        };

        attrs.push(RsxAttribute { name, value });
    }

    Ok(attrs)
}