git.delta.rocks / jrsonnet / refs/commits / c368769dca4a

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};160161use indexmap::IndexMap;162use proc_macro2::{Ident, TokenStream};163use quote::{format_ident, quote};164165use super::escape_token_macro;166167impl KindsSrc {168	pub fn new() -> Self {169		Self {170			defined_tokens: IndexMap::new(),171			defined_node_names: HashSet::new(),172			nodes: Vec::new(),173		}174	}175	pub fn define_token(&mut self, token: TokenKind) {176		assert!(177			self.defined_node_names.insert(token.name().to_owned()),178			"node name already defined: {}",179			token.name()180		);181		assert!(182			self.defined_tokens183				.insert(token.grammar_name().to_owned(), token.clone())184				.is_none(),185			"token already defined: {}",186			token.grammar_name()187		);188	}189	pub fn define_node(&mut self, node: &str) {190		assert!(191			self.defined_node_names.insert(node.to_owned()),192			"node name already defined: {node}"193		);194		self.nodes.push(node.to_string());195	}196	pub fn token(&self, tok: &str) -> Option<&TokenKind> {197		self.defined_tokens.get(tok)198	}199	pub fn is_token(&self, tok: &str) -> bool {200		self.defined_tokens.contains_key(tok)201	}202	pub fn tokens(&self) -> impl Iterator<Item = &TokenKind> {203		self.defined_tokens.iter().map(|(_, v)| v)204	}205}206207pub fn jsonnet_kinds() -> KindsSrc {208	let mut kinds = KindsSrc::new();209	define_kinds![kinds =210		"||" => "OR";211		"??" => "NULL_COAELSE";212		"&&" => "AND";213		"|" => "BIT_OR";214		"^" => "BIT_XOR";215		"&" => "BIT_AND";216		"==" => "EQ";217		"!=" => "NE";218		"<" => "LT";219		">" => "GT";220		"<=" => "LE";221		">=" => "GE";222		"<<" => "LHS";223		">>" => "RHS";224		"+" => "PLUS";225		"-" => "MINUS";226		"*" => "MUL";227		"/" => "DIV";228		"%" => "MODULO";229		"!" => "NOT";230		"~" => "BIT_NOT";231		"[" => "L_BRACK";232		"]" => "R_BRACK";233		"(" => "L_PAREN";234		")" => "R_PAREN";235		"{" => "L_BRACE";236		"}" => "R_BRACE";237		":" => "COLON";238		"::" => "COLONCOLON";239		":::" => "COLONCOLONCOLON";240		";" => "SEMI";241		"." => "DOT";242		"..." => "DOTDOTDOT";243		"," => "COMMA";244		"$" => "DOLLAR";245		"=" => "ASSIGN";246		"?" => "QUESTION_MARK";247		// Literals248		lit("FLOAT") => r"(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?";249		error("FLOAT_JUNK_AFTER_POINT") => r"(?:0|[1-9][0-9]*)\.[^0-9]";250		error("FLOAT_JUNK_AFTER_EXPONENT") => r"(?:0|[1-9][0-9]*)(?:\.[0-9]+)?[eE][^+\-0-9]";251		error("FLOAT_JUNK_AFTER_EXPONENT_SIGN") => r"(?:0|[1-9][0-9]*)(?:\.[0-9]+)?[eE][+-][^0-9]";252		lit("STRING_DOUBLE") => "\"(?s:[^\"\\\\]|\\\\.)*\"";253		error("STRING_DOUBLE_UNTERMINATED") => "\"(?s:[^\"\\\\]|\\\\.)*";254		lit("STRING_SINGLE") => "'(?s:[^'\\\\]|\\\\.)*'";255		error("STRING_SINGLE_UNTERMINATED") => "'(?s:[^'\\\\]|\\\\.)*";256		lit("STRING_DOUBLE_VERBATIM") => "@\"(?:[^\"]|\"\")*\"";257		error("STRING_DOUBLE_VERBATIM_UNTERMINATED") => "@\"(?:[^\"]|\"\")*";258		lit("STRING_SINGLE_VERBATIM") => "@'(?:[^']|'')*'";259		error("STRING_SINGLE_VERBATIM_UNTERMINATED") => "@'(?:[^']|'')*";260		error("STRING_VERBATIM_MISSING_QUOTES") => "@[^\"'\\s]\\S+";261		lit("STRING_BLOCK") => r"\|\|\|", "crate::string_block::lex_str_block_test";262		error("STRING_BLOCK_UNEXPECTED_END", lexer = true);263		error("STRING_BLOCK_MISSING_NEW_LINE", lexer = true);264		error("STRING_BLOCK_MISSING_TERMINATION", lexer = true);265		error("STRING_BLOCK_MISSING_INDENT", lexer = true);266		lit("IDENT") => r"[_a-zA-Z][_a-zA-Z0-9]*";267		lit("WHITESPACE") => r"[ \t\n\r]+";268		lit("SINGLE_LINE_SLASH_COMMENT") => r"//[^\r\n]*?(\r\n|\n)?";269		lit("SINGLE_LINE_HASH_COMMENT") => r"#[^\r\n]*?(\r\n|\n)?";270		lit("MULTI_LINE_COMMENT") => r"/\*([^*]|\*[^/])*\*/";271		error("COMMENT_TOO_SHORT") => r"/\*/";272		error("COMMENT_UNTERMINATED") =>  r"/\*([^*/]|\*[^/])+";273	];274	kinds275}