Add a function to convert a SyntaxKind to its text, where possible

This will also help for the make's quote macro.
This commit is contained in:
Chayim Refael Friedman 2024-12-30 03:54:53 +02:00
parent 737500137f
commit 505e82c19c
2 changed files with 341 additions and 0 deletions

View file

@ -404,6 +404,7 @@ fn generate_syntax_kinds(grammar: KindsSrc) -> String {
});
let punctuation =
grammar.punct.iter().map(|(_token, name)| format_ident!("{}", name)).collect::<Vec<_>>();
let punctuation_texts = grammar.punct.iter().map(|&(text, _name)| text);
let fmt_kw_as_variant = |&name| match name {
"Self" => format_ident!("SELF_TYPE_KW"),
@ -429,6 +430,7 @@ fn generate_syntax_kinds(grammar: KindsSrc) -> String {
quote! { #kw if #ed <= edition }
})
.collect::<Vec<_>>();
let edition_dependent_keywords = grammar.edition_dependent_keywords.iter().map(|&(it, _)| it);
let edition_dependent_keywords_variants = grammar
.edition_dependent_keywords
.iter()
@ -502,6 +504,20 @@ fn generate_syntax_kinds(grammar: KindsSrc) -> String {
use self::SyntaxKind::*;
impl SyntaxKind {
#[allow(unreachable_patterns)]
pub const fn text(self) -> &'static str {
match self {
TOMBSTONE | EOF | __LAST
#( | #literals )*
#( | #nodes )*
#( | #tokens )* => panic!("no text for these `SyntaxKind`s"),
#( #punctuation => #punctuation_texts ,)*
#( #strict_keywords_variants => #strict_keywords ,)*
#( #contextual_keywords_variants => #contextual_keywords ,)*
#( #edition_dependent_keywords_variants => #edition_dependent_keywords ,)*
}
}
/// Checks whether this syntax kind is a strict keyword for the given edition.
/// Strict keywords are identifiers that are always considered keywords.
pub fn is_strict_keyword(self, edition: Edition) -> bool {