git.delta.rocks / jrsonnet / refs/commits / 3c2d9ee98ad3

difftreelog

source

xtask/src/sourcegen/kinds.rs7.9 KiBsourcehistory
1#[derive(Debug)]2pub struct KindsSrc {3	/// Key - how this token appears in ungrammar4	defined_tokens: IndexMap<String, TokenKind>,5	defined_node_names: HashSet<String>,6	pub nodes: Vec<String>,7}89#[derive(Debug, Clone)]10pub enum TokenKind {11	/// May exist in token tree, but never in source code12	Meta { grammar_name: String, name: String },13	/// Specific parsing/lexing errors may be emitted as this type of kind14	Error {15		grammar_name: String,16		name: String,17		#[allow(dead_code)]18		/// Is this error returned by lexer directly, or from lex.rs19		is_lexer_error: bool,20		regex: Option<String>,21		priority: Option<u32>,22	},23	/// Keyword - literal match of token24	Keyword {25		/// How this keyword appears in grammar/code, should be same as Kinds key26		code: String,27		name: String,28	},29	/// Literal - something defined by user, i.e strings, identifiers, smth30	Literal {31		/// How this keyword appears in grammar, should be same as Kinds key32		grammar_name: String,33		name: String,34		/// Regex for Logos lexer35		regex: String,36		/// Path to custom lexer37		lexer: Option<String>,38	},39}4041impl TokenKind {42	pub fn grammar_name(&self) -> &str {43		match self {44			Self::Keyword { code, .. } => code,45			Self::Literal { grammar_name, .. }46			| Self::Meta { grammar_name, .. }47			| Self::Error { grammar_name, .. } => grammar_name,48		}49	}50	/// How this keyword should appear in kinds enum, screaming snake cased51	pub fn name(&self) -> &str {52		match self {53			Self::Keyword { name, .. }54			| Self::Literal { name, .. }55			| Self::Meta { name, .. }56			| Self::Error { name, .. } => name,57		}58	}59	pub fn expand_kind(&self) -> TokenStream {60		let name = format_ident!("{}", self.name());61		let attr = match self {62			Self::Keyword { code, .. } => quote! {#[token(#code)]},63			Self::Literal { regex, lexer, .. } => {64				let lexer = lexer65					.as_deref()66					.map(TokenStream::from_str)67					.map(|r| r.expect("path is correct"));68				quote! {#[regex(#regex, #lexer)]}69			}70			Self::Error {71				regex, priority, ..72			} if regex.is_some() => {73				let priority = priority.map(|p| quote! {, priority = #p});74				quote! {#[regex(#regex #priority)]}75			}76			_ => quote! {},77		};78		quote! {79			#attr80			#name81		}82	}83	pub fn expand_t_macros(&self) -> Option<TokenStream> {84		match self {85			Self::Keyword { code, name } => {86				let code = escape_token_macro(code);87				let name = format_ident!("{name}");88				Some(quote! {89					[#code] => {$crate::SyntaxKind::#name}90				})91			}92			// Meta items should not appear in T![_]93			_ => None,94		}95	}9697	/// How this token should be referenced in code98	/// Keywords are referenced with `T![_]` macro,99	/// and literals are referenced directly by name100	pub fn reference(&self) -> TokenStream {101		if let Self::Keyword { code, .. } = self {102			let code = escape_token_macro(code);103			quote! {T![#code]}104		} else {105			let name = self.name();106			let ident = format_ident!("{name}");107			quote! {#ident}108		}109	}110111	pub fn method_name(&self) -> Ident {112		match self {113			Self::Keyword { name, .. } => {114				format_ident!("{}_token", name.to_lowercase())115			}116			Self::Literal { name, .. } => {117				format_ident!("{}_lit", name.to_lowercase())118			}119			Self::Meta { name, .. } => format_ident!("{}_meta", name.to_lowercase()),120			Self::Error { name, .. } => format_ident!("{}_error", name.to_lowercase()),121		}122	}123}124125#[macro_export]126macro_rules! define_kinds {127	($into:ident = lit($name:literal) => $regex:literal $(, $lexer:literal)? $(; $($rest:tt)*)?) => {{128		$into.define_token(TokenKind::Literal {129			grammar_name: format!("LIT_{}!", $name),130			name: $name.to_owned(),131			regex: $regex.to_owned(),132			lexer: None $(.or_else(|| Some($lexer.to_string())))?,133		});134		$(define_kinds!($into = $($rest)*))?135	}};136	($into:ident = error($name:literal$(, priority = $priority:literal)? $(, lexer = $lexer:literal)?) $(=> $regex:literal)? $(; $($rest:tt)*)?) => {{137		{138			let regex = None$(.or(Some($regex.to_owned())))?;139			let priority = None$(.or(Some($priority)))?;140			$into.define_token(TokenKind::Error {141				grammar_name: format!("ERROR_{}!", $name),142				name: format!("ERROR_{}", $name),143				is_lexer_error: false $(|| $lexer)? || regex.is_some() || priority.is_some(),144				regex,145				priority,146			});147		}148		$(define_kinds!($into = $($rest)*))?149	}};150	($into:ident = $tok:literal => $name:literal $(; $($rest:tt)*)?) => {{151		$into.define_token(TokenKind::Keyword {152			code: format!("{}", $tok),153			name: $name.to_owned(),154		});155		$(define_kinds!($into = $($rest)*))?156	}};157	($into:ident =) => {{}}158}159use std::{collections::HashSet, str::FromStr};160161pub use define_kinds;162use indexmap::IndexMap;163use proc_macro2::{Ident, TokenStream};164use quote::{format_ident, quote};165166use super::escape_token_macro;167168impl KindsSrc {169	pub fn new() -> Self {170		Self {171			defined_tokens: IndexMap::new(),172			defined_node_names: HashSet::new(),173			nodes: Vec::new(),174		}175	}176	pub fn define_token(&mut self, token: TokenKind) {177		assert!(178			self.defined_node_names.insert(token.name().to_owned()),179			"node name already defined: {}",180			token.name()181		);182		assert!(183			self.defined_tokens184				.insert(token.grammar_name().to_owned(), token.clone())185				.is_none(),186			"token already defined: {}",187			token.grammar_name()188		);189	}190	pub fn define_node(&mut self, node: &str) {191		assert!(192			self.defined_node_names.insert(node.to_owned()),193			"node name already defined: {node}"194		);195		self.nodes.push(node.to_string());196	}197	pub fn token(&self, tok: &str) -> Option<&TokenKind> {198		self.defined_tokens.get(tok)199	}200	pub fn is_token(&self, tok: &str) -> bool {201		self.defined_tokens.contains_key(tok)202	}203	pub fn tokens(&self) -> impl Iterator<Item = &TokenKind> {204		self.defined_tokens.iter().map(|(_, v)| v)205	}206}207208pub fn jsonnet_kinds() -> KindsSrc {209	let mut kinds = KindsSrc::new();210	define_kinds![kinds =211		"||" => "OR";212		"??" => "NULL_COAELSE";213		"&&" => "AND";214		"|" => "BIT_OR";215		"^" => "BIT_XOR";216		"&" => "BIT_AND";217		"==" => "EQ";218		"!=" => "NE";219		"<" => "LT";220		">" => "GT";221		"<=" => "LE";222		">=" => "GE";223		"<<" => "LHS";224		">>" => "RHS";225		"+" => "PLUS";226		"-" => "MINUS";227		"*" => "MUL";228		"/" => "DIV";229		"%" => "MODULO";230		"!" => "NOT";231		"~" => "BIT_NOT";232		"[" => "L_BRACK";233		"]" => "R_BRACK";234		"(" => "L_PAREN";235		")" => "R_PAREN";236		"{" => "L_BRACE";237		"}" => "R_BRACE";238		":" => "COLON";239		"::" => "COLONCOLON";240		":::" => "COLONCOLONCOLON";241		";" => "SEMI";242		"." => "DOT";243		"..." => "DOTDOTDOT";244		"," => "COMMA";245		"$" => "DOLLAR";246		"=" => "ASSIGN";247		"?" => "QUESTION_MARK";248		// Literals249		lit("FLOAT") => r"(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?";250		error("FLOAT_JUNK_AFTER_POINT") => r"(?:0|[1-9][0-9]*)\.[^0-9]";251		error("FLOAT_JUNK_AFTER_EXPONENT") => r"(?:0|[1-9][0-9]*)(?:\.[0-9]+)?[eE][^+\-0-9]";252		error("FLOAT_JUNK_AFTER_EXPONENT_SIGN") => r"(?:0|[1-9][0-9]*)(?:\.[0-9]+)?[eE][+-][^0-9]";253		lit("STRING_DOUBLE") => "\"(?s:[^\"\\\\]|\\\\.)*\"";254		error("STRING_DOUBLE_UNTERMINATED") => "\"(?s:[^\"\\\\]|\\\\.)*";255		lit("STRING_SINGLE") => "'(?s:[^'\\\\]|\\\\.)*'";256		error("STRING_SINGLE_UNTERMINATED") => "'(?s:[^'\\\\]|\\\\.)*";257		lit("STRING_DOUBLE_VERBATIM") => "@\"(?:[^\"]|\"\")*\"";258		error("STRING_DOUBLE_VERBATIM_UNTERMINATED") => "@\"(?:[^\"]|\"\")*";259		lit("STRING_SINGLE_VERBATIM") => "@'(?:[^']|'')*'";260		error("STRING_SINGLE_VERBATIM_UNTERMINATED") => "@'(?:[^']|'')*";261		error("STRING_VERBATIM_MISSING_QUOTES") => "@[^\"'\\s]\\S+";262		lit("STRING_BLOCK") => r"\|\|\|", "crate::string_block::lex_str_block_test";263		error("STRING_BLOCK_UNEXPECTED_END", lexer = true);264		error("STRING_BLOCK_MISSING_NEW_LINE", lexer = true);265		error("STRING_BLOCK_MISSING_TERMINATION", lexer = true);266		error("STRING_BLOCK_MISSING_INDENT", lexer = true);267		lit("IDENT") => r"[_a-zA-Z][_a-zA-Z0-9]*";268		lit("WHITESPACE") => r"[ \t\n\r]+";269		lit("SINGLE_LINE_SLASH_COMMENT") => r"//[^\r\n]*(\r\n|\n)?";270		lit("SINGLE_LINE_HASH_COMMENT") => r"#[^\r\n]*(\r\n|\n)?";271		lit("MULTI_LINE_COMMENT") => r"/\*([^*]|\*[^/])*\*/";272		error("COMMENT_TOO_SHORT") => r"/\*/";273		error("COMMENT_UNTERMINATED") =>  r"/\*([^*/]|\*[^/])+";274	];275	kinds276}