Skip to content

proc_macro::TokenStream: provide AST node kind hint #50053

Open
@abonander

Description

@abonander
/// Enum representing AST nodes a #[proc_macro_attribute] may be applied to
// Bikeshedding welcome
pub enum SyntaxNodeKind {
    // when crates as macro inputs aren't pretty-printed as modules (#41430) 
    Crate,
    Item, // could be module, function, impl, etc. `syn` can figure the rest out
    Statement,
    Expression, 
    ExternItem, // since item kinds are restricted in `extern {}`
} 

impl TokenStream {
    /// If this token stream represents a valid syntax tree node, return its kind. 
    /// Returns `None` for raw tokens
    // Alternately it could simply panic when not available because that would only happen in
    // `#[proc_macro]` which should expect only raw tokens anyway
    pub fn syntax_node_kind(&self) -> Option<SyntaxNodeKind> {}
}

This would be exclusively for #[proc_macro_attribute]s which parse their input as AST nodes:

  • attributes that only accept one kind could assert equality and error immediately instead of attempting to parse their expected kind (allowing them to emit a concise error message instead of "expected [token] got [token]")
  • attributes that accept multiple kinds won't have to guess at what node kind they should attempt to parse

cc @alexcrichton @dtolnay @petrochenkov

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-decl-macros-2-0Area: Declarative macros 2.0 (#39412)C-feature-requestCategory: A feature request, i.e: not implemented / a PR.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions