repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/type_ext.rs | crates/rome_js_syntax/src/type_ext.rs | use std::iter;
use crate::AnyTsType;
impl AnyTsType {
/// Try to extract non `TsParenthesizedType` from `AnyTsType`
pub fn omit_parentheses(self) -> AnyTsType {
let first = self.as_ts_parenthesized_type().and_then(|x| x.ty().ok());
iter::successors(first, |x| {
let parenthesized = x.as_ts_parenthesized_type()?;
parenthesized.ty().ok()
})
.last()
.unwrap_or(self)
}
/// Returns `true` if `self` is a literal type.
///
/// ### Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_js_syntax::T;
/// use rome_js_syntax::AnyTsType;
///
/// let boolean_literal = make::ts_boolean_literal_type(make::token(T![true]));
/// let bigint_literal = make::ts_bigint_literal_type(make::js_number_literal("1n")).build();
/// let null_literal = make::ts_null_literal_type(make::token(T![null]));
/// let number_literal = make::ts_number_literal_type(make::js_number_literal("1")).build();
/// let string_literal = make::ts_string_literal_type(make::js_string_literal("s"));
/// let undefined = make::ts_undefined_type(make::token(T![undefined]));
///
/// assert!(AnyTsType::TsBooleanLiteralType(boolean_literal).is_literal_type());
/// assert!(AnyTsType::TsBigintLiteralType(bigint_literal).is_literal_type());
/// assert!(AnyTsType::TsNullLiteralType(null_literal).is_literal_type());
/// assert!(AnyTsType::TsNumberLiteralType(number_literal).is_literal_type());
/// assert!(AnyTsType::TsStringLiteralType(string_literal).is_literal_type());
/// assert!(AnyTsType::TsUndefinedType(undefined).is_literal_type());
/// ```
pub fn is_literal_type(&self) -> bool {
matches!(
self,
AnyTsType::TsBooleanLiteralType(_)
| AnyTsType::TsBigintLiteralType(_)
| AnyTsType::TsNullLiteralType(_)
| AnyTsType::TsNumberLiteralType(_)
| AnyTsType::TsStringLiteralType(_)
| AnyTsType::TsUndefinedType(_)
)
}
/// Returns `true` if `self` is a primitive type.
///
/// ### Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_js_syntax::T;
/// use rome_js_syntax::AnyTsType;
///
/// let boolean = make::ts_boolean_type(make::token(T![boolean]));
/// let bigint = make::ts_bigint_type(make::token(T![bigint]));
/// let number = make::ts_number_type(make::token(T![number]));
/// let string = make::ts_string_type(make::token(T![string]));
///
/// assert!(AnyTsType::TsBooleanType(boolean).is_primitive_type());
/// assert!(AnyTsType::TsBigintType(bigint).is_primitive_type());
/// assert!(AnyTsType::TsNumberType(number).is_primitive_type());
/// assert!(AnyTsType::TsStringType(string).is_primitive_type());
/// ```
pub fn is_primitive_type(&self) -> bool {
matches!(
self,
AnyTsType::TsBooleanType(_)
| AnyTsType::TsBigintType(_)
| AnyTsType::TsNumberType(_)
| AnyTsType::TsStringType(_)
)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/numbers.rs | crates/rome_js_syntax/src/numbers.rs | //! JS Number parsing.
use std::str::FromStr;
/// Split given string into radix and number string.
///
/// It also removes any underscores.
pub fn split_into_radix_and_number(num: &str) -> (u32, String) {
let (radix, raw) = parse_js_number_prefix(num).unwrap_or((10, num));
let raw = raw.replace('_', "");
(radix, raw)
}
fn parse_js_number_prefix(num: &str) -> Option<(u32, &str)> {
let mut chars = num.chars();
let c = chars.next()?;
if c != '0' {
return None;
}
Some(match chars.next()? {
'x' | 'X' => (16, chars.as_str()),
'o' | 'O' => (8, chars.as_str()),
'b' | 'B' => (2, chars.as_str()),
// Legacy octal literals
'0'..='7' if !chars.as_str().contains(['8', '9']) => (8, &num[1..]),
_ => return None,
})
}
/// Parse a js number as a string into a number.
pub fn parse_js_number(num: &str) -> Option<f64> {
let (radix, raw) = split_into_radix_and_number(num);
if radix == 10 {
f64::from_str(&raw).ok()
} else {
i64::from_str_radix(&raw, radix).map(|num| num as f64).ok()
}
}
#[cfg(test)]
mod tests {
use super::split_into_radix_and_number;
use rome_js_factory::syntax::{JsNumberLiteralExpression, JsSyntaxKind::*};
use rome_js_factory::JsSyntaxTreeBuilder;
use rome_rowan::AstNode;
fn assert_float(literal: &str, value: f64) {
let mut tree_builder = JsSyntaxTreeBuilder::new();
tree_builder.start_node(JS_NUMBER_LITERAL_EXPRESSION);
tree_builder.token(JS_NUMBER_LITERAL, literal);
tree_builder.finish_node();
let node = tree_builder.finish();
let number_literal = JsNumberLiteralExpression::cast(node).unwrap();
assert_eq!(number_literal.as_number(), Some(value))
}
#[test]
fn base_10_float() {
assert_float("1234", 1234.0);
assert_float("0", 0.0);
assert_float("9e999", f64::INFINITY);
assert_float("9e-999", 0.0);
}
#[test]
fn base_16_float() {
assert_float("0xFF", 255.0);
assert_float("0XFF", 255.0);
assert_float("0x0", 0.0);
assert_float("0xABC", 2748.0);
assert_float("0XABC", 2748.0);
}
#[test]
fn base_2_float() {
assert_float("0b0000", 0.0);
assert_float("0B0000", 0.0);
assert_float("0b11111111", 255.0);
assert_float("0B11111111", 255.0);
}
#[test]
fn base_8_float() {
assert_float("0o77", 63.0);
assert_float("0O77", 63.0);
assert_float("0o0", 0.0);
assert_float("0O0", 0.0);
}
#[test]
fn base_8_legacy_float() {
assert_float("051", 41.0);
assert_float("058", 58.0);
}
fn assert_split(raw: &str, expected_radix: u32, expected_num: &str) {
let (radix, num) = split_into_radix_and_number(raw);
assert_eq!(radix, expected_radix);
assert_eq!(num, expected_num);
}
#[test]
fn split_hex() {
assert_split("0x12", 16, "12");
assert_split("0X12", 16, "12");
assert_split("0x1_2", 16, "12");
assert_split("0X1_2", 16, "12");
}
#[test]
fn split_binary() {
assert_split("0b01", 2, "01");
assert_split("0b01", 2, "01");
assert_split("0b0_1", 2, "01");
assert_split("0b0_1", 2, "01");
}
#[test]
fn split_octal() {
assert_split("0o12", 8, "12");
assert_split("0o12", 8, "12");
assert_split("0o1_2", 8, "12");
assert_split("0o1_2", 8, "12");
}
#[test]
fn split_legacy_octal() {
assert_split("012", 8, "12");
assert_split("012", 8, "12");
assert_split("01_2", 8, "12");
assert_split("01_2", 8, "12");
}
#[test]
fn split_legacy_decimal() {
assert_split("1234", 10, "1234");
assert_split("1234", 10, "1234");
assert_split("12_34", 10, "1234");
assert_split("12_34", 10, "1234");
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/parameter_ext.rs | crates/rome_js_syntax/src/parameter_ext.rs | use crate::{
AnyJsBindingPattern, AnyJsConstructorParameter, AnyJsFormalParameter, AnyJsParameter,
JsConstructorParameterList, JsConstructorParameters, JsDecoratorList, JsLanguage,
JsParameterList, JsParameters,
};
use rome_rowan::{
declare_node_union, AstNodeList, AstSeparatedList, AstSeparatedListNodesIterator, SyntaxResult,
};
/// An enumeration representing different types of JavaScript/TypeScript parameter lists.
///
/// This enum can represent a regular JavaScript/TypeScript parameter list (i.e., for functions)
/// or a JavaScript/TypeScript constructor parameter list (i.e., for class constructors).
///
/// # Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_js_syntax::{AnyJsBinding, AnyJsBindingPattern, AnyJsConstructorParameter, AnyJsFormalParameter, AnyJsParameter};
/// use rome_js_syntax::parameter_ext::AnyJsParameterList;
///
/// // Create a function parameter list
/// let parameter_list = make::js_parameter_list(
/// Some(AnyJsParameter::AnyJsFormalParameter(
/// AnyJsFormalParameter::JsFormalParameter(
/// make::js_formal_parameter(
/// make::js_decorator_list([]),
/// AnyJsBindingPattern::AnyJsBinding(AnyJsBinding::JsIdentifierBinding(
/// make::js_identifier_binding(make::ident("params")),
/// )),
/// )
/// .build(),
/// ),
/// )),
/// None,
/// );
/// let function_params = AnyJsParameterList::JsParameterList(parameter_list);
///
/// // Create a constructor parameter list
/// let constructor_parameter_list = make::js_constructor_parameter_list(
/// Some(AnyJsConstructorParameter::AnyJsFormalParameter(
/// AnyJsFormalParameter::JsFormalParameter(
/// make::js_formal_parameter(
/// make::js_decorator_list([]),
/// AnyJsBindingPattern::AnyJsBinding(AnyJsBinding::JsIdentifierBinding(
/// make::js_identifier_binding(make::ident("params")),
/// )),
/// )
/// .build(),
/// ),
/// )),
/// None,
/// );
///
/// let constructor_params = AnyJsParameterList::JsConstructorParameterList(constructor_parameter_list);
/// ```
///
/// # Variants
///
/// * `JsParameterList` - A list of parameters for a JavaScript function.
/// * `JsConstructorParameterList` - A list of parameters for a JavaScript constructor.
#[derive(Debug)]
pub enum AnyJsParameterList {
JsParameterList(JsParameterList),
JsConstructorParameterList(JsConstructorParameterList),
}
impl From<JsParameterList> for AnyJsParameterList {
fn from(list: JsParameterList) -> Self {
AnyJsParameterList::JsParameterList(list)
}
}
impl From<JsConstructorParameterList> for AnyJsParameterList {
fn from(list: JsConstructorParameterList) -> Self {
AnyJsParameterList::JsConstructorParameterList(list)
}
}
impl AnyJsParameterList {
///
/// This method allows to get the length of a parameter list, regardless
/// of whether it's a standard parameter list or a constructor parameter list.
///
/// # Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_js_syntax::parameter_ext::AnyJsParameterList;
/// use rome_js_syntax::{
/// AnyJsBinding, AnyJsBindingPattern, AnyJsConstructorParameter, AnyJsFormalParameter,
/// AnyJsParameter, T,
/// };
///
/// let parameter_list = make::js_parameter_list(
/// Some(AnyJsParameter::AnyJsFormalParameter(
/// AnyJsFormalParameter::JsFormalParameter(
/// make::js_formal_parameter(
/// make::js_decorator_list([]),
/// AnyJsBindingPattern::AnyJsBinding(AnyJsBinding::JsIdentifierBinding(
/// make::js_identifier_binding(make::ident("params")),
/// )),
/// )
/// .build(),
/// ),
/// )),
/// None,
/// );
///
/// let params = AnyJsParameterList::JsParameterList(parameter_list);
/// assert_eq!(params.len(), 1);
///
/// let constructor_parameter_list = make::js_constructor_parameter_list(
/// Some(AnyJsConstructorParameter::AnyJsFormalParameter(
/// AnyJsFormalParameter::JsFormalParameter(
/// make::js_formal_parameter(
/// make::js_decorator_list([]),
/// AnyJsBindingPattern::AnyJsBinding(AnyJsBinding::JsIdentifierBinding(
/// make::js_identifier_binding(make::ident("params")),
/// )),
/// )
/// .build(),
/// ),
/// )),
/// None,
/// );
///
/// let params = AnyJsParameterList::JsConstructorParameterList(constructor_parameter_list);
/// assert_eq!(params.len(), 1);
/// ```
///
/// # Returns
///
/// Returns the length of the parameter list.
pub fn len(&self) -> usize {
match self {
AnyJsParameterList::JsParameterList(parameters) => parameters.len(),
AnyJsParameterList::JsConstructorParameterList(parameters) => parameters.len(),
}
}
///
/// This method checks if a parameter list is empty.
///
/// # Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_js_syntax::parameter_ext::AnyJsParameterList;
/// use rome_js_syntax::{
/// AnyJsBinding, AnyJsBindingPattern, AnyJsConstructorParameter, AnyJsFormalParameter,
/// AnyJsParameter, T,
/// };
///
/// let parameter_list = make::js_parameter_list(
/// Some(AnyJsParameter::AnyJsFormalParameter(
/// AnyJsFormalParameter::JsFormalParameter(
/// make::js_formal_parameter(
/// make::js_decorator_list([]),
/// AnyJsBindingPattern::AnyJsBinding(AnyJsBinding::JsIdentifierBinding(
/// make::js_identifier_binding(make::ident("params")),
/// )),
/// )
/// .build(),
/// ),
/// )),
/// None,
/// );
///
/// let params = AnyJsParameterList::JsParameterList(parameter_list);
/// assert_eq!(params.is_empty(), false);
///
/// let constructor_parameter_list = make::js_constructor_parameter_list(
/// None,
/// None,
/// );
///
/// let params = AnyJsParameterList::JsConstructorParameterList(constructor_parameter_list);
/// assert!(params.is_empty());
/// ```
///
/// # Returns
///
/// Returns true if the parameter list contains no parameters, false otherwise.
pub fn is_empty(&self) -> bool {
match self {
AnyJsParameterList::JsParameterList(parameters) => parameters.is_empty(),
AnyJsParameterList::JsConstructorParameterList(parameters) => parameters.is_empty(),
}
}
///
/// This method allows to get the first parameter in the parameter list.
///
/// # Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_js_syntax::parameter_ext::{AnyJsParameterList, AnyParameter};
/// use rome_js_syntax::{
/// AnyJsBinding, AnyJsBindingPattern, AnyJsConstructorParameter, AnyJsFormalParameter,
/// AnyJsParameter, T,
/// };
/// use rome_rowan::SyntaxResult;
///
/// let parameter_list = make::js_parameter_list(
/// Some(AnyJsParameter::AnyJsFormalParameter(
/// AnyJsFormalParameter::JsFormalParameter(
/// make::js_formal_parameter(
/// make::js_decorator_list([]),
/// AnyJsBindingPattern::AnyJsBinding(AnyJsBinding::JsIdentifierBinding(
/// make::js_identifier_binding(make::ident("param1")),
/// )),
/// )
/// .build(),
/// ),
/// )),
/// None,
/// );
///
/// let params = AnyJsParameterList::JsParameterList(parameter_list);
/// let first_param = params.first().unwrap();
/// assert_eq!(first_param.is_ok(), true);
///
/// let empty_parameter_list = make::js_constructor_parameter_list(None, None);
/// let empty_params = AnyJsParameterList::JsConstructorParameterList(empty_parameter_list);
/// assert!(empty_params.first().is_none());
/// ```
///
/// # Returns
///
/// Returns the first parameter in the parameter list if it exists.
pub fn first(&self) -> Option<SyntaxResult<AnyParameter>> {
Some(match self {
AnyJsParameterList::JsParameterList(parameters) => {
parameters.first()?.map(|parameter| parameter.into())
}
AnyJsParameterList::JsConstructorParameterList(parameters) => {
parameters.first()?.map(|parameter| parameter.into())
}
})
}
///
/// This method allows you to iterate over the parameters in a `JsParameterList` or a `JsConstructorParameterList`,
/// depending on the variant of the `AnyJsParameterList` enum.
///
/// # Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_js_syntax::parameter_ext::AnyJsParameterList;
/// use rome_js_syntax::{
/// AnyJsBinding, AnyJsBindingPattern, AnyJsConstructorParameter, AnyJsFormalParameter,
/// AnyJsParameter, T,
/// };
///
/// let parameter_list = make::js_parameter_list(
/// Some(AnyJsParameter::AnyJsFormalParameter(
/// AnyJsFormalParameter::JsFormalParameter(
/// make::js_formal_parameter(
/// make::js_decorator_list([]),
/// AnyJsBindingPattern::AnyJsBinding(AnyJsBinding::JsIdentifierBinding(
/// make::js_identifier_binding(make::ident("param1")),
/// )),
/// )
/// .build(),
/// ),
/// )),
/// None,
/// );
///
/// let params = AnyJsParameterList::JsParameterList(parameter_list);
/// let mut iter = params.iter();
///
/// assert_eq!(iter.next().is_some(), true);
/// assert_eq!(iter.next().is_none(), true);
/// ```
///
/// # Returns
///
/// Returns an iterator over the parameters in the list.
///
pub fn iter(&self) -> AnyJsParameterListNodeIter {
match self {
AnyJsParameterList::JsParameterList(list) => {
AnyJsParameterListNodeIter::JsParameterList(list.iter())
}
AnyJsParameterList::JsConstructorParameterList(list) => {
AnyJsParameterListNodeIter::JsConstructorParameterList(list.iter())
}
}
}
///
/// This method allows to get the last parameter in the parameter list.
///
/// # Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_js_syntax::parameter_ext::AnyJsParameterList;
/// use rome_js_syntax::{
/// AnyJsBinding, AnyJsBindingPattern, AnyJsConstructorParameter, AnyJsFormalParameter,
/// AnyJsParameter, T,
/// };
///
/// let parameter_list = make::js_parameter_list(
/// Some(AnyJsParameter::AnyJsFormalParameter(
/// AnyJsFormalParameter::JsFormalParameter(
/// make::js_formal_parameter(
/// make::js_decorator_list([]),
/// AnyJsBindingPattern::AnyJsBinding(AnyJsBinding::JsIdentifierBinding(
/// make::js_identifier_binding(make::ident("param1")),
/// )),
/// )
/// .build(),
/// ),
/// )),
/// None,
/// );
///
/// let params = AnyJsParameterList::JsParameterList(parameter_list);
/// let last_param = params.last().unwrap();
/// assert_eq!(last_param.is_ok(), true);
///
/// let empty_parameter_list = make::js_parameter_list(None, None);
/// let empty_params = AnyJsParameterList::JsParameterList(empty_parameter_list);
/// assert!(empty_params.last().is_none());
/// ```
///
/// # Returns
///
/// Returns the last parameter in the parameter list if it exists.
///
pub fn last(&self) -> Option<SyntaxResult<AnyParameter>> {
Some(match self {
AnyJsParameterList::JsParameterList(parameters) => {
parameters.last()?.map(|parameter| parameter.into())
}
AnyJsParameterList::JsConstructorParameterList(parameters) => {
parameters.last()?.map(|parameter| parameter.into())
}
})
}
///
/// This method checks if any parameters in the given list are decorated.
///
/// # Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_js_syntax::parameter_ext::{AnyJsParameterList, AnyParameter};
/// use rome_js_syntax::{
/// AnyJsBinding, AnyJsBindingPattern, AnyJsConstructorParameter, AnyJsDecorator,
/// AnyJsFormalParameter, AnyJsParameter, T,
/// };
/// use rome_rowan::SyntaxResult;
///
/// let parameter_list = make::js_parameter_list(
/// Some(AnyJsParameter::AnyJsFormalParameter(
/// AnyJsFormalParameter::JsFormalParameter(
/// make::js_formal_parameter(
/// make::js_decorator_list([]),
/// AnyJsBindingPattern::AnyJsBinding(AnyJsBinding::JsIdentifierBinding(
/// make::js_identifier_binding(make::ident("param1")),
/// )),
/// )
/// .build(),
/// ),
/// )),
/// None,
/// );
///
/// let params = AnyJsParameterList::JsParameterList(parameter_list);
/// let has_any_decorated_parameter = params.has_any_decorated_parameter();
/// assert_eq!(has_any_decorated_parameter, false);
///
/// let decorator = make::js_decorator(
/// make::token(T![@]),
/// AnyJsDecorator::JsIdentifierExpression(make::js_identifier_expression(
/// make::js_reference_identifier(make::ident("decorator")),
/// )),
/// );
/// let parameter_list = make::js_parameter_list(
/// Some(AnyJsParameter::AnyJsFormalParameter(
/// AnyJsFormalParameter::JsFormalParameter(
/// make::js_formal_parameter(
/// make::js_decorator_list(Some(decorator)),
/// AnyJsBindingPattern::AnyJsBinding(AnyJsBinding::JsIdentifierBinding(
/// make::js_identifier_binding(make::ident("param1")),
/// )),
/// )
/// .build(),
/// ),
/// )),
/// None,
/// );
///
/// let params = AnyJsParameterList::JsParameterList(parameter_list);
/// let has_any_decorated_parameter = params.has_any_decorated_parameter();
/// assert_eq!(has_any_decorated_parameter, true);
/// ```
///
/// # Returns
///
/// Returns `true` if the list contains any decorated parameters.
///
pub fn has_any_decorated_parameter(&self) -> bool {
self.iter().any(|parameter| {
parameter.map_or(false, |parameter| match parameter {
AnyParameter::AnyJsConstructorParameter(parameter) => {
parameter.has_any_decorated_parameter()
}
AnyParameter::AnyJsParameter(parameter) => parameter.has_any_decorated_parameter(),
})
})
}
}
/// An iterator over the parameters in an `AnyJsParameterList`.
///
/// This iterator can traverse a regular JavaScript/TypeScript parameter list (i.e., for functions)
/// or a JavaScript/TypeScript constructor parameter list (i.e., for class constructors), depending
/// on the variant of the `AnyJsParameterListNodeIter` enum.
pub enum AnyJsParameterListNodeIter {
JsParameterList(AstSeparatedListNodesIterator<JsLanguage, AnyJsParameter>),
JsConstructorParameterList(
AstSeparatedListNodesIterator<JsLanguage, AnyJsConstructorParameter>,
),
}
impl Iterator for AnyJsParameterListNodeIter {
type Item = SyntaxResult<AnyParameter>;
fn next(&mut self) -> Option<Self::Item> {
Some(match self {
AnyJsParameterListNodeIter::JsParameterList(inner) => {
inner.next()?.map(AnyParameter::from)
}
AnyJsParameterListNodeIter::JsConstructorParameterList(inner) => {
inner.next()?.map(AnyParameter::from)
}
})
}
}
declare_node_union! {
/// The `AnyParameter` union can represent either a standard JavaScript/TypeScript parameter
/// or a JavaScript/TypeScript constructor parameter. This is useful in contexts where a
/// function could accept either type of parameter.
pub AnyParameter = AnyJsConstructorParameter | AnyJsParameter
}
impl AnyParameter {
pub fn binding(&self) -> Option<AnyJsBindingPattern> {
match self {
AnyParameter::AnyJsConstructorParameter(parameter) => match parameter {
AnyJsConstructorParameter::AnyJsFormalParameter(parameter) => {
parameter.as_js_formal_parameter()?.binding().ok()
}
AnyJsConstructorParameter::JsRestParameter(parameter) => parameter.binding().ok(),
AnyJsConstructorParameter::TsPropertyParameter(parameter) => parameter
.formal_parameter()
.ok()?
.as_js_formal_parameter()?
.binding()
.ok(),
},
AnyParameter::AnyJsParameter(parameter) => match parameter {
AnyJsParameter::AnyJsFormalParameter(parameter) => {
parameter.as_js_formal_parameter()?.binding().ok()
}
AnyJsParameter::JsRestParameter(parameter) => parameter.binding().ok(),
AnyJsParameter::TsThisParameter(_) => None,
},
}
}
}
declare_node_union! {
/// The `AnyJsParameters` union can represent either a standard JavaScript/TypeScript parameters
/// or a JavaScript/TypeScript constructor parameters. This is useful in contexts where a
/// function could accept either type of parameters.
pub AnyJsParameters = JsParameters | JsConstructorParameters
}
impl AnyJsConstructorParameter {
/// This method returns a list of decorators for a parameter if it exists.
pub fn decorators(&self) -> Option<JsDecoratorList> {
match self {
AnyJsConstructorParameter::AnyJsFormalParameter(parameter) => parameter.decorators(),
AnyJsConstructorParameter::JsRestParameter(parameter) => Some(parameter.decorators()),
AnyJsConstructorParameter::TsPropertyParameter(parameter) => {
Some(parameter.decorators())
}
}
}
/// This method checks if any parameters in the given list are decorated.
pub fn has_any_decorated_parameter(&self) -> bool {
self.decorators()
.map_or(false, |decorators| !decorators.is_empty())
}
}
impl AnyJsParameter {
/// This method returns a list of decorators for a parameter if it exists.
pub fn decorators(&self) -> Option<JsDecoratorList> {
match self {
AnyJsParameter::AnyJsFormalParameter(parameter) => parameter.decorators(),
AnyJsParameter::JsRestParameter(parameter) => Some(parameter.decorators()),
AnyJsParameter::TsThisParameter(_) => None,
}
}
/// This method checks if any parameters in the given list are decorated.
pub fn has_any_decorated_parameter(&self) -> bool {
self.decorators()
.map_or(false, |decorators| !decorators.is_empty())
}
}
impl AnyJsFormalParameter {
/// This method returns a list of decorators for a parameter if it exists.
pub fn decorators(&self) -> Option<JsDecoratorList> {
match self {
AnyJsFormalParameter::JsBogusParameter(_) => None,
AnyJsFormalParameter::JsFormalParameter(parameter) => Some(parameter.decorators()),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/union_ext.rs | crates/rome_js_syntax/src/union_ext.rs | use crate::{
AnyJsArrowFunctionParameters, AnyJsBinding, AnyJsClass, AnyJsClassMember, AnyJsClassMemberName,
AnyJsFunction, AnyJsFunctionBody, AnyTsPropertyAnnotation, AnyTsVariableAnnotation,
JsClassMemberList, JsDecoratorList, JsExtendsClause, JsSyntaxToken, TsImplementsClause,
TsReturnTypeAnnotation, TsTypeAnnotation, TsTypeParameters,
};
use rome_rowan::{AstSeparatedList, SyntaxResult};
impl AnyJsClass {
pub fn decorators(&self) -> JsDecoratorList {
match self {
AnyJsClass::JsClassDeclaration(declaration) => declaration.decorators(),
AnyJsClass::JsClassExpression(expression) => expression.decorators(),
AnyJsClass::JsClassExportDefaultDeclaration(declaration) => declaration.decorators(),
}
}
pub fn abstract_token(&self) -> Option<JsSyntaxToken> {
match self {
AnyJsClass::JsClassDeclaration(declaration) => declaration.abstract_token(),
AnyJsClass::JsClassExpression(_) => None,
AnyJsClass::JsClassExportDefaultDeclaration(clause) => clause.abstract_token(),
}
}
pub fn class_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
AnyJsClass::JsClassDeclaration(declaration) => declaration.class_token(),
AnyJsClass::JsClassExpression(expression) => expression.class_token(),
AnyJsClass::JsClassExportDefaultDeclaration(declaration) => declaration.class_token(),
}
}
pub fn id(&self) -> SyntaxResult<Option<AnyJsBinding>> {
match self {
AnyJsClass::JsClassDeclaration(declaration) => declaration.id().map(Some),
AnyJsClass::JsClassExpression(expression) => Ok(expression.id()),
AnyJsClass::JsClassExportDefaultDeclaration(declaration) => Ok(declaration.id()),
}
}
pub fn type_parameters(&self) -> Option<TsTypeParameters> {
match self {
AnyJsClass::JsClassDeclaration(declaration) => declaration.type_parameters(),
AnyJsClass::JsClassExpression(expression) => expression.type_parameters(),
AnyJsClass::JsClassExportDefaultDeclaration(clause) => clause.type_parameters(),
}
}
pub fn extends_clause(&self) -> Option<JsExtendsClause> {
match self {
AnyJsClass::JsClassDeclaration(declaration) => declaration.extends_clause(),
AnyJsClass::JsClassExpression(expression) => expression.extends_clause(),
AnyJsClass::JsClassExportDefaultDeclaration(declaration) => {
declaration.extends_clause()
}
}
}
pub fn implements_clause(&self) -> Option<TsImplementsClause> {
match self {
AnyJsClass::JsClassDeclaration(declaration) => declaration.implements_clause(),
AnyJsClass::JsClassExpression(expression) => expression.implements_clause(),
AnyJsClass::JsClassExportDefaultDeclaration(declaration) => {
declaration.implements_clause()
}
}
}
pub fn l_curly_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
AnyJsClass::JsClassDeclaration(declaration) => declaration.l_curly_token(),
AnyJsClass::JsClassExpression(expression) => expression.l_curly_token(),
AnyJsClass::JsClassExportDefaultDeclaration(declaration) => declaration.l_curly_token(),
}
}
pub fn members(&self) -> JsClassMemberList {
match self {
AnyJsClass::JsClassDeclaration(declaration) => declaration.members(),
AnyJsClass::JsClassExpression(expression) => expression.members(),
AnyJsClass::JsClassExportDefaultDeclaration(declaration) => declaration.members(),
}
}
pub fn r_curly_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
AnyJsClass::JsClassDeclaration(declaration) => declaration.r_curly_token(),
AnyJsClass::JsClassExpression(expression) => expression.r_curly_token(),
AnyJsClass::JsClassExportDefaultDeclaration(declaration) => declaration.r_curly_token(),
}
}
}
impl AnyJsClassMember {
/// Returns the `name` of the member if it has any.
pub fn name(&self) -> SyntaxResult<Option<AnyJsClassMemberName>> {
match self {
AnyJsClassMember::JsConstructorClassMember(constructor) => constructor
.name()
.map(|name| Some(AnyJsClassMemberName::from(name))),
AnyJsClassMember::JsEmptyClassMember(_) => Ok(None),
AnyJsClassMember::JsGetterClassMember(getter) => getter.name().map(Some),
AnyJsClassMember::JsMethodClassMember(method) => method.name().map(Some),
AnyJsClassMember::JsPropertyClassMember(property) => property.name().map(Some),
AnyJsClassMember::JsSetterClassMember(setter) => setter.name().map(Some),
AnyJsClassMember::JsStaticInitializationBlockClassMember(_) => Ok(None),
AnyJsClassMember::JsBogusMember(_) => Ok(None),
AnyJsClassMember::TsConstructorSignatureClassMember(constructor) => constructor
.name()
.map(|name| Some(AnyJsClassMemberName::from(name))),
AnyJsClassMember::TsGetterSignatureClassMember(getter) => getter.name().map(Some),
AnyJsClassMember::TsIndexSignatureClassMember(_) => Ok(None),
AnyJsClassMember::TsMethodSignatureClassMember(method) => method.name().map(Some),
AnyJsClassMember::TsPropertySignatureClassMember(property) => property.name().map(Some),
AnyJsClassMember::TsInitializedPropertySignatureClassMember(property) => {
property.name().map(Some)
}
AnyJsClassMember::TsSetterSignatureClassMember(setter) => setter.name().map(Some),
}
}
/// Tests if the member has a [`JsLiteralMemberName`](crate::JsLiteralMemberName) of `name`.
pub fn has_name(&self, name: &str) -> SyntaxResult<bool> {
match self.name()? {
Some(AnyJsClassMemberName::JsLiteralMemberName(literal)) => {
Ok(literal.value()?.text_trimmed() == name)
}
_ => Ok(false),
}
}
}
impl AnyJsClassMemberName {
pub const fn is_computed(&self) -> bool {
matches!(self, AnyJsClassMemberName::JsComputedMemberName(_))
}
}
impl AnyJsFunction {
pub fn async_token(&self) -> Option<JsSyntaxToken> {
match self {
AnyJsFunction::JsArrowFunctionExpression(expr) => expr.async_token(),
AnyJsFunction::JsFunctionExpression(expr) => expr.async_token(),
AnyJsFunction::JsFunctionDeclaration(declaration) => declaration.async_token(),
AnyJsFunction::JsFunctionExportDefaultDeclaration(declaration) => {
declaration.async_token()
}
}
}
pub fn is_async(&self) -> bool {
self.async_token().is_some()
}
pub fn function_token(&self) -> SyntaxResult<Option<JsSyntaxToken>> {
match self {
AnyJsFunction::JsArrowFunctionExpression(_) => Ok(None),
AnyJsFunction::JsFunctionExpression(expr) => expr.function_token().map(Some),
AnyJsFunction::JsFunctionDeclaration(declaration) => {
declaration.function_token().map(Some)
}
AnyJsFunction::JsFunctionExportDefaultDeclaration(declaration) => {
declaration.function_token().map(Some)
}
}
}
pub fn star_token(&self) -> Option<JsSyntaxToken> {
match self {
AnyJsFunction::JsArrowFunctionExpression(_) => None,
AnyJsFunction::JsFunctionExpression(expr) => expr.star_token(),
AnyJsFunction::JsFunctionDeclaration(declaration) => declaration.star_token(),
AnyJsFunction::JsFunctionExportDefaultDeclaration(declaration) => {
declaration.star_token()
}
}
}
pub fn is_generator(&self) -> bool {
self.star_token().is_some()
}
pub fn id(&self) -> SyntaxResult<Option<AnyJsBinding>> {
match self {
AnyJsFunction::JsArrowFunctionExpression(_) => Ok(None),
AnyJsFunction::JsFunctionExpression(expr) => Ok(expr.id()),
AnyJsFunction::JsFunctionDeclaration(declaration) => declaration.id().map(Some),
AnyJsFunction::JsFunctionExportDefaultDeclaration(declaration) => Ok(declaration.id()),
}
}
pub fn type_parameters(&self) -> Option<TsTypeParameters> {
match self {
AnyJsFunction::JsArrowFunctionExpression(expr) => expr.type_parameters(),
AnyJsFunction::JsFunctionExpression(expr) => expr.type_parameters(),
AnyJsFunction::JsFunctionDeclaration(declaration) => declaration.type_parameters(),
AnyJsFunction::JsFunctionExportDefaultDeclaration(declaration) => {
declaration.type_parameters()
}
}
}
pub fn parameters(&self) -> SyntaxResult<AnyJsArrowFunctionParameters> {
match self {
AnyJsFunction::JsArrowFunctionExpression(expr) => expr.parameters(),
AnyJsFunction::JsFunctionExpression(expr) => expr
.parameters()
.map(AnyJsArrowFunctionParameters::JsParameters),
AnyJsFunction::JsFunctionDeclaration(declaration) => declaration
.parameters()
.map(AnyJsArrowFunctionParameters::JsParameters),
AnyJsFunction::JsFunctionExportDefaultDeclaration(declaration) => declaration
.parameters()
.map(AnyJsArrowFunctionParameters::JsParameters),
}
}
pub fn return_type_annotation(&self) -> Option<TsReturnTypeAnnotation> {
match self {
AnyJsFunction::JsArrowFunctionExpression(expr) => expr.return_type_annotation(),
AnyJsFunction::JsFunctionExpression(expr) => expr.return_type_annotation(),
AnyJsFunction::JsFunctionDeclaration(declaration) => {
declaration.return_type_annotation()
}
AnyJsFunction::JsFunctionExportDefaultDeclaration(declaration) => {
declaration.return_type_annotation()
}
}
}
pub fn body(&self) -> SyntaxResult<AnyJsFunctionBody> {
match self {
AnyJsFunction::JsArrowFunctionExpression(expr) => expr.body(),
AnyJsFunction::JsFunctionExpression(expr) => {
expr.body().map(AnyJsFunctionBody::JsFunctionBody)
}
AnyJsFunction::JsFunctionDeclaration(declaration) => {
declaration.body().map(AnyJsFunctionBody::JsFunctionBody)
}
AnyJsFunction::JsFunctionExportDefaultDeclaration(declaration) => {
declaration.body().map(AnyJsFunctionBody::JsFunctionBody)
}
}
}
}
impl AnyTsVariableAnnotation {
pub fn type_annotation(&self) -> SyntaxResult<Option<TsTypeAnnotation>> {
match self {
AnyTsVariableAnnotation::TsDefiniteVariableAnnotation(definite) => {
definite.type_annotation().map(Some)
}
AnyTsVariableAnnotation::TsTypeAnnotation(type_annotation) => {
Ok(Some(type_annotation.clone()))
}
}
}
}
impl AnyTsPropertyAnnotation {
pub fn type_annotation(&self) -> SyntaxResult<Option<TsTypeAnnotation>> {
match self {
AnyTsPropertyAnnotation::TsDefinitePropertyAnnotation(definite) => {
definite.type_annotation().map(Some)
}
AnyTsPropertyAnnotation::TsOptionalPropertyAnnotation(optional) => {
Ok(optional.type_annotation())
}
AnyTsPropertyAnnotation::TsTypeAnnotation(type_annotation) => {
Ok(Some(type_annotation.clone()))
}
}
}
}
impl AnyJsArrowFunctionParameters {
pub fn len(&self) -> usize {
match self {
AnyJsArrowFunctionParameters::AnyJsBinding(_) => 1,
AnyJsArrowFunctionParameters::JsParameters(parameters) => parameters.items().len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/expr_ext.rs | crates/rome_js_syntax/src/expr_ext.rs | //! Extensions for things which are not easily generated in ast expr nodes
use crate::numbers::parse_js_number;
use crate::static_value::StaticValue;
use crate::{
inner_string_text, AnyJsCallArgument, AnyJsExpression, AnyJsLiteralExpression,
AnyJsObjectMemberName, AnyJsTemplateElement, JsArrayExpression, JsArrayHole,
JsAssignmentExpression, JsBinaryExpression, JsCallExpression, JsComputedMemberAssignment,
JsComputedMemberExpression, JsLiteralMemberName, JsLogicalExpression, JsNewExpression,
JsNumberLiteralExpression, JsObjectExpression, JsPostUpdateExpression, JsReferenceIdentifier,
JsRegexLiteralExpression, JsStaticMemberExpression, JsStringLiteralExpression, JsSyntaxKind,
JsSyntaxToken, JsTemplateChunkElement, JsTemplateExpression, JsUnaryExpression,
OperatorPrecedence, T,
};
use crate::{JsPreUpdateExpression, JsSyntaxKind::*};
use core::iter;
use rome_rowan::{
declare_node_union, AstNode, AstNodeList, AstSeparatedList, NodeOrToken, SyntaxResult,
TextRange, TokenText,
};
use std::collections::HashSet;
const GLOBAL_THIS: &str = "globalThis";
const UNDEFINED: &str = "undefined";
const WINDOW: &str = "window";
impl JsReferenceIdentifier {
/// Returns `true` if this identifier refers to the `undefined` symbol.
///
/// ## Examples
///
/// ```
/// use rome_js_factory::make::{js_reference_identifier, ident};
///
/// assert!(js_reference_identifier(ident("undefined")).is_undefined());
/// assert!(!js_reference_identifier(ident("x")).is_undefined());
/// ```
pub fn is_undefined(&self) -> bool {
self.has_name(UNDEFINED)
}
/// Returns `true` if this identifier refers to the `globalThis` symbol.
///
/// ## Examples
///
/// ```
/// use rome_js_factory::make::{js_reference_identifier, ident};
///
/// assert!(js_reference_identifier(ident("globalThis")).is_global_this());
/// assert!(!js_reference_identifier(ident("x")).is_global_this());
/// ```
pub fn is_global_this(&self) -> bool {
self.has_name(GLOBAL_THIS)
}
/// Returns `true` if this identifier has the given name.
///
/// ## Examples
///
/// ```
/// use rome_js_factory::make::{js_reference_identifier, ident};
///
/// assert!(js_reference_identifier(ident("foo")).has_name("foo"));
/// assert!(!js_reference_identifier(ident("bar")).has_name("foo"));
/// ```
pub fn has_name(&self, name: &str) -> bool {
self.value_token()
.map(|token| token.text_trimmed() == name)
.unwrap_or_default()
}
pub fn name(&self) -> SyntaxResult<TokenText> {
Ok(self.value_token()?.token_text_trimmed())
}
}
impl JsLiteralMemberName {
/// Returns the name of the member as a syntax text
///
/// ## Examples
///
/// Getting the name of a static member containing a string literal
///
/// ```
/// use rome_js_syntax::{JsSyntaxKind, JsLanguage, JsSyntaxNode, JsLiteralMemberName};
/// use rome_js_factory::JsSyntaxTreeBuilder;
/// use rome_rowan::AstNode;
///
/// let node: JsSyntaxNode =
/// JsSyntaxTreeBuilder::wrap_with_node(JsSyntaxKind::JS_LITERAL_MEMBER_NAME, |builder| {
/// builder.token(JsSyntaxKind::JS_STRING_LITERAL, "\"abcd\"");
/// });
///
/// let static_member_name = JsLiteralMemberName::unwrap_cast(node);
///
/// assert_eq!("abcd", static_member_name.name().unwrap());
/// ```
///
/// Getting the name of a static member containing a number literal
///
/// ```
/// use rome_js_syntax::{JsSyntaxKind, JsLanguage, JsSyntaxNode, JsLiteralMemberName};
/// use rome_js_factory::JsSyntaxTreeBuilder;
/// use rome_rowan::AstNode;
///
/// let node: JsSyntaxNode =
/// JsSyntaxTreeBuilder::wrap_with_node(JsSyntaxKind::JS_LITERAL_MEMBER_NAME, |builder| {
/// builder.token(JsSyntaxKind::JS_NUMBER_LITERAL, "5");
/// });
///
/// let static_member_name = JsLiteralMemberName::unwrap_cast(node);
///
/// assert_eq!("5", static_member_name.name().unwrap());
/// ```
///
/// Getting the name of a static member containing an identifier
///
/// ```
/// use rome_js_syntax::{JsSyntaxKind, JsLanguage, JsSyntaxNode, JsLiteralMemberName};
/// use rome_js_factory::JsSyntaxTreeBuilder;
/// use rome_rowan::AstNode;
///
/// let node: JsSyntaxNode =
/// JsSyntaxTreeBuilder::wrap_with_node(JsSyntaxKind::JS_LITERAL_MEMBER_NAME, |builder| {
/// builder.token(JsSyntaxKind::IDENT, "abcd");
/// });
///
/// let static_member_name = JsLiteralMemberName::unwrap_cast(node);
///
/// assert_eq!("abcd", static_member_name.name().unwrap().text());
/// ```
pub fn name(&self) -> SyntaxResult<TokenText> {
Ok(inner_string_text(&self.value()?))
}
}
/// A binary operation applied to two expressions
///
/// The variants are ordered based on their precedence
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum JsBinaryOperator {
/// `<`
LessThan,
/// `>`
GreaterThan,
/// `<=`
LessThanOrEqual,
/// `>=`
GreaterThanOrEqual,
/// `==`
Equality,
/// `===`
StrictEquality,
/// `!=`
Inequality,
/// `!==`
StrictInequality,
/// `+`
Plus,
/// `-`
Minus,
/// `*`
Times,
/// `/`
Divide,
/// `%`
Remainder,
/// `**`
Exponent,
/// `<<`
LeftShift,
/// `>>`
RightShift,
/// `>>>`
UnsignedRightShift,
/// `&`
BitwiseAnd,
/// `|`
BitwiseOr,
/// `^`
BitwiseXor,
}
impl JsBinaryOperator {
pub const fn precedence(&self) -> OperatorPrecedence {
match self {
JsBinaryOperator::LessThan
| JsBinaryOperator::GreaterThan
| JsBinaryOperator::LessThanOrEqual
| JsBinaryOperator::GreaterThanOrEqual => OperatorPrecedence::Relational,
JsBinaryOperator::Equality
| JsBinaryOperator::StrictEquality
| JsBinaryOperator::Inequality
| JsBinaryOperator::StrictInequality => OperatorPrecedence::Equality,
JsBinaryOperator::Plus | JsBinaryOperator::Minus => OperatorPrecedence::Additive,
JsBinaryOperator::Times | JsBinaryOperator::Divide | JsBinaryOperator::Remainder => {
OperatorPrecedence::Multiplicative
}
JsBinaryOperator::Exponent => OperatorPrecedence::Exponential,
JsBinaryOperator::LeftShift
| JsBinaryOperator::RightShift
| JsBinaryOperator::UnsignedRightShift => OperatorPrecedence::Shift,
JsBinaryOperator::BitwiseAnd => OperatorPrecedence::BitwiseAnd,
JsBinaryOperator::BitwiseOr => OperatorPrecedence::BitwiseOr,
JsBinaryOperator::BitwiseXor => OperatorPrecedence::BitwiseXor,
}
}
}
impl JsBinaryExpression {
pub fn operator(&self) -> SyntaxResult<JsBinaryOperator> {
let kind = match self.operator_token()?.kind() {
T![<] => JsBinaryOperator::LessThan,
T![>] => JsBinaryOperator::GreaterThan,
T![<=] => JsBinaryOperator::LessThanOrEqual,
T![>=] => JsBinaryOperator::GreaterThanOrEqual,
T![==] => JsBinaryOperator::Equality,
T![===] => JsBinaryOperator::StrictEquality,
T![!=] => JsBinaryOperator::Inequality,
T![!==] => JsBinaryOperator::StrictInequality,
T![+] => JsBinaryOperator::Plus,
T![-] => JsBinaryOperator::Minus,
T![*] => JsBinaryOperator::Times,
T![/] => JsBinaryOperator::Divide,
T![%] => JsBinaryOperator::Remainder,
T![**] => JsBinaryOperator::Exponent,
T![<<] => JsBinaryOperator::LeftShift,
T![>>] => JsBinaryOperator::RightShift,
T![>>>] => JsBinaryOperator::UnsignedRightShift,
T![&] => JsBinaryOperator::BitwiseAnd,
T![|] => JsBinaryOperator::BitwiseOr,
T![^] => JsBinaryOperator::BitwiseXor,
_ => unreachable!(),
};
Ok(kind)
}
/// Whether this is a numeric operation, such as `+`, `-`, `*`, `%`, `**`.
pub fn is_numeric_operation(&self) -> bool {
matches!(
self.operator_token().map(|t| t.kind()),
Ok(T![+] | T![-] | T![*] | T![/] | T![%] | T![**])
)
}
/// Whether this is a binary operation, such as `<<`, `>>`, `>>>`, `&`, `|`, `^`.
pub fn is_binary_operation(&self) -> bool {
matches!(
self.operator_token().map(|t| t.kind()),
Ok(T![<<] | T![>>] | T![>>>] | T![&] | T![|] | T![^])
)
}
/// Whether this is a comparison operation, such as `>`, `<`, `==`, `!=`, `===`, etc.
pub fn is_comparison_operator(&self) -> bool {
matches!(
self.operator_token().map(|t| t.kind()),
Ok(T![>] | T![<] | T![>=] | T![<=] | T![==] | T![===] | T![!=] | T![!==])
)
}
/// Whether this is a comparison operation similar to the optional chain
/// ```js
/// foo !== undefined;
/// foo != undefined;
/// foo !== null;
/// foo != null;
///```
pub fn is_optional_chain_like(&self) -> SyntaxResult<bool> {
if matches!(
self.operator(),
Ok(JsBinaryOperator::StrictInequality | JsBinaryOperator::Inequality)
) {
Ok(self
.right()?
.as_static_value()
.map_or(false, |x| x.is_null_or_undefined()))
} else {
Ok(false)
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub enum JsLogicalOperator {
/// `??`
NullishCoalescing,
/// `||`
LogicalOr,
/// `&&`
LogicalAnd,
}
impl JsLogicalOperator {
pub const fn precedence(&self) -> OperatorPrecedence {
match self {
JsLogicalOperator::NullishCoalescing => OperatorPrecedence::Coalesce,
JsLogicalOperator::LogicalOr => OperatorPrecedence::LogicalOr,
JsLogicalOperator::LogicalAnd => OperatorPrecedence::LogicalAnd,
}
}
}
impl JsLogicalExpression {
pub fn operator(&self) -> SyntaxResult<JsLogicalOperator> {
let kind = match self.operator_token()?.kind() {
T![&&] => JsLogicalOperator::LogicalAnd,
T![||] => JsLogicalOperator::LogicalOr,
T![??] => JsLogicalOperator::NullishCoalescing,
_ => unreachable!(),
};
Ok(kind)
}
}
impl JsArrayHole {
pub fn hole_token(&self) -> Option<JsSyntaxToken> {
None
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum JsUnaryOperator {
/// `delete`
Delete,
/// `void`
Void,
/// `typeof`
Typeof,
/// `+`
Plus,
/// `-`
Minus,
/// `~`
BitwiseNot,
/// `!`
LogicalNot,
}
impl JsUnaryOperator {
pub const fn precedence(&self) -> OperatorPrecedence {
OperatorPrecedence::Unary
}
}
impl JsUnaryExpression {
pub fn operator(&self) -> SyntaxResult<JsUnaryOperator> {
let operator = self.operator_token()?;
Ok(match operator.kind() {
T![+] => JsUnaryOperator::Plus,
T![-] => JsUnaryOperator::Minus,
T![~] => JsUnaryOperator::BitwiseNot,
T![!] => JsUnaryOperator::LogicalNot,
T![typeof] => JsUnaryOperator::Typeof,
T![void] => JsUnaryOperator::Void,
T![delete] => JsUnaryOperator::Delete,
_ => unreachable!(),
})
}
pub fn is_void(&self) -> SyntaxResult<bool> {
let operator = self.operator()?;
Ok(matches!(operator, JsUnaryOperator::Void))
}
/// This function checks that `JsUnaryExpression` is a signed numeric literal:
/// ```js
/// +123
/// -321
/// ```
pub fn is_signed_numeric_literal(&self) -> SyntaxResult<bool> {
let argument = self.argument()?;
let is_signed = matches!(
self.operator()?,
JsUnaryOperator::Plus | JsUnaryOperator::Minus
);
let is_numeric_literal = matches!(
argument,
AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsNumberLiteralExpression(_)
)
);
Ok(is_signed && is_numeric_literal)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum JsPreUpdateOperator {
/// `++`
Increment,
/// `--`
Decrement,
}
impl JsPreUpdateOperator {
pub const fn precedence(&self) -> OperatorPrecedence {
OperatorPrecedence::Unary
}
}
impl JsPreUpdateExpression {
pub fn operator(&self) -> SyntaxResult<JsPreUpdateOperator> {
let operator = self.operator_token()?;
Ok(match operator.kind() {
T![++] => JsPreUpdateOperator::Increment,
T![--] => JsPreUpdateOperator::Decrement,
_ => unreachable!(),
})
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum JsPostUpdateOperator {
/// `++`
Increment,
/// `--`
Decrement,
}
impl JsPostUpdateOperator {
pub const fn precedence(&self) -> OperatorPrecedence {
OperatorPrecedence::Unary
}
}
impl JsPostUpdateExpression {
pub fn operator(&self) -> SyntaxResult<JsPostUpdateOperator> {
let operator = self.operator_token()?;
Ok(match operator.kind() {
T![++] => JsPostUpdateOperator::Increment,
T![--] => JsPostUpdateOperator::Decrement,
_ => unreachable!(),
})
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum JsAssignmentOperator {
Assign,
AddAssign,
SubtractAssign,
TimesAssign,
SlashAssign,
RemainderAssign,
ExponentAssign,
LeftShiftAssign,
RightShiftAssign,
UnsignedRightShiftAssign,
BitwiseAndAssign,
BitwiseOrAssign,
BitwiseXorAssign,
LogicalAndAssign,
LogicalOrAssign,
NullishCoalescingAssign,
}
impl JsAssignmentExpression {
pub fn operator(&self) -> SyntaxResult<JsAssignmentOperator> {
let operator = match self.operator_token()?.kind() {
T![=] => JsAssignmentOperator::Assign,
T![+=] => JsAssignmentOperator::AddAssign,
T![-=] => JsAssignmentOperator::SubtractAssign,
T![*=] => JsAssignmentOperator::TimesAssign,
T![/=] => JsAssignmentOperator::SlashAssign,
T![%=] => JsAssignmentOperator::RemainderAssign,
T![**=] => JsAssignmentOperator::ExponentAssign,
T![>>=] => JsAssignmentOperator::LeftShiftAssign,
T![<<=] => JsAssignmentOperator::RightShiftAssign,
T![>>>=] => JsAssignmentOperator::UnsignedRightShiftAssign,
T![&=] => JsAssignmentOperator::BitwiseAndAssign,
T![|=] => JsAssignmentOperator::BitwiseOrAssign,
T![^=] => JsAssignmentOperator::BitwiseXorAssign,
T![&&=] => JsAssignmentOperator::LogicalAndAssign,
T![||=] => JsAssignmentOperator::LogicalOrAssign,
T![??=] => JsAssignmentOperator::NullishCoalescingAssign,
_ => unreachable!(),
};
Ok(operator)
}
}
impl JsArrayExpression {
pub fn has_trailing_comma(&self) -> bool {
self.elements().trailing_separator().is_some()
}
}
impl JsObjectExpression {
pub fn has_trailing_comma(&self) -> bool {
self.members().trailing_separator().is_some()
}
pub fn is_empty(&self) -> bool {
self.members().is_empty()
}
}
impl JsNumberLiteralExpression {
pub fn as_number(&self) -> Option<f64> {
parse_js_number(self.value_token().unwrap().text())
}
}
impl JsStringLiteralExpression {
/// Get the inner text of a string not including the quotes
///
/// ## Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_rowan::TriviaPieceKind;
///
///let string = make::js_string_literal_expression(make::js_string_literal("foo")
/// .with_leading_trivia(vec![(TriviaPieceKind::Whitespace, " ")]));
/// assert_eq!(string.inner_string_text().unwrap().text(), "foo");
/// ```
pub fn inner_string_text(&self) -> SyntaxResult<TokenText> {
Ok(inner_string_text(&self.value_token()?))
}
}
impl JsTemplateExpression {
/// Returns true if `self` is a template expression without a tag and without template elements.
///
/// # Examples
///
/// ```
/// use rome_js_factory::make;
/// use rome_js_syntax::{AnyJsExpression, AnyJsTemplateElement, JsSyntaxKind, JsSyntaxToken};
/// use std::iter;
///
/// let tick = make::token(JsSyntaxKind::BACKTICK);
/// let empty_str = make::js_template_expression(
/// tick.clone(),
/// make::js_template_element_list([]),
/// tick.clone(),
/// ).build();
///
/// let chunk = AnyJsTemplateElement::JsTemplateChunkElement(
/// make::js_template_chunk_element(
/// JsSyntaxToken::new_detached(JsSyntaxKind::TEMPLATE_CHUNK, "text", [], [])
/// )
/// );
/// let constant_str = make::js_template_expression(
/// tick.clone(),
/// make::js_template_element_list([chunk.clone()]),
/// tick.clone(),
/// ).build();
///
/// let constant_str2 = make::js_template_expression(
/// tick.clone(),
/// make::js_template_element_list([chunk.clone(), chunk]),
/// tick.clone(),
/// ).build();
///
/// let template_elt = AnyJsTemplateElement::JsTemplateElement(
/// make::js_template_element(
/// JsSyntaxToken::new_detached(JsSyntaxKind::DOLLAR_CURLY, "${", [], []),
/// AnyJsExpression::JsIdentifierExpression(
/// make::js_identifier_expression(
/// make::js_reference_identifier(make::ident("var")),
/// ),
/// ),
/// make::token(JsSyntaxKind::R_CURLY),
/// )
/// );
/// let template_str = make::js_template_expression(
/// tick.clone(),
/// make::js_template_element_list([template_elt]),
/// tick,
/// ).build();
///
/// assert!(empty_str.is_constant());
/// assert!(constant_str.is_constant());
/// assert!(constant_str2.is_constant());
/// assert!(!template_str.is_constant());
/// ```
///
pub fn is_constant(&self) -> bool {
self.tag().is_none()
&& self
.elements()
.into_iter()
.all(|e| JsTemplateChunkElement::can_cast(e.syntax().kind()))
}
/// The string chunks of the template. aka:
/// `foo ${bar} foo` breaks down into:
/// `QUASIS ELEMENT{EXPR} QUASIS`
pub fn quasis(&self) -> impl Iterator<Item = JsSyntaxToken> {
self.syntax()
.children_with_tokens()
.filter_map(NodeOrToken::into_token)
.filter(|t| t.kind() == TEMPLATE_CHUNK)
}
pub fn template_range(&self) -> Option<TextRange> {
let start = self
.syntax()
.children_with_tokens()
.filter_map(|x| x.into_token())
.find(|tok| tok.kind() == BACKTICK)?;
Some(TextRange::new(
start.text_range().start(),
self.syntax().text_range().end(),
))
}
}
impl JsRegexLiteralExpression {
pub fn pattern(&self) -> SyntaxResult<String> {
let token = self.value_token()?;
let text_trimmed = token.text_trimmed();
// SAFETY: a valid regex literal must have a end slash
let end_slash_pos = text_trimmed
.rfind('/')
.expect("regex literal must have an end slash");
Ok(String::from(&text_trimmed[1..end_slash_pos]))
}
pub fn flags(&self) -> SyntaxResult<String> {
let token = self.value_token()?;
let text_trimmed = token.text_trimmed();
// SAFETY: a valid regex literal must have a end slash
let end_slash_pos = text_trimmed
.rfind('/')
.expect("regex literal must have an end slash");
Ok(String::from(&text_trimmed[end_slash_pos..]))
}
}
impl AnyJsExpression {
/// Try to extract non `JsParenthesizedExpression` from `JsAnyExpression`
pub fn omit_parentheses(self) -> AnyJsExpression {
let first = self
.as_js_parenthesized_expression()
.and_then(|expression| expression.expression().ok());
iter::successors(first, |expression| {
let parenthesized = expression.as_js_parenthesized_expression()?;
parenthesized.expression().ok()
})
.last()
.unwrap_or(self)
}
pub fn precedence(&self) -> SyntaxResult<OperatorPrecedence> {
let precedence = match self {
AnyJsExpression::JsSequenceExpression(_) => OperatorPrecedence::Comma,
AnyJsExpression::JsYieldExpression(_) => OperatorPrecedence::Yield,
AnyJsExpression::JsConditionalExpression(_) => OperatorPrecedence::Conditional,
AnyJsExpression::JsAssignmentExpression(_) => OperatorPrecedence::Assignment,
AnyJsExpression::JsInExpression(_)
| AnyJsExpression::JsInstanceofExpression(_)
| AnyJsExpression::TsAsExpression(_)
| AnyJsExpression::TsSatisfiesExpression(_) => OperatorPrecedence::Relational,
AnyJsExpression::JsLogicalExpression(expression) => expression.operator()?.precedence(),
AnyJsExpression::JsBinaryExpression(expression) => expression.operator()?.precedence(),
AnyJsExpression::TsTypeAssertionExpression(_)
| AnyJsExpression::TsNonNullAssertionExpression(_)
| AnyJsExpression::JsUnaryExpression(_)
| AnyJsExpression::JsAwaitExpression(_) => OperatorPrecedence::Unary,
AnyJsExpression::JsPostUpdateExpression(_)
| AnyJsExpression::JsPreUpdateExpression(_) => OperatorPrecedence::Update,
AnyJsExpression::JsCallExpression(_)
| AnyJsExpression::JsImportCallExpression(_)
| AnyJsExpression::JsSuperExpression(_) => OperatorPrecedence::LeftHandSide,
AnyJsExpression::JsNewExpression(expression) => {
if expression.arguments().is_none() {
OperatorPrecedence::NewWithoutArguments
} else {
OperatorPrecedence::LeftHandSide
}
}
AnyJsExpression::JsComputedMemberExpression(_)
| AnyJsExpression::JsStaticMemberExpression(_)
| AnyJsExpression::JsImportMetaExpression(_)
| AnyJsExpression::TsInstantiationExpression(_)
| AnyJsExpression::JsNewTargetExpression(_) => OperatorPrecedence::Member,
AnyJsExpression::JsThisExpression(_)
| AnyJsExpression::AnyJsLiteralExpression(_)
| AnyJsExpression::JsArrayExpression(_)
| AnyJsExpression::JsArrowFunctionExpression(_)
| AnyJsExpression::JsClassExpression(_)
| AnyJsExpression::JsFunctionExpression(_)
| AnyJsExpression::JsIdentifierExpression(_)
| AnyJsExpression::JsObjectExpression(_)
| AnyJsExpression::JsxTagExpression(_) => OperatorPrecedence::Primary,
AnyJsExpression::JsTemplateExpression(template) => {
if template.tag().is_some() {
OperatorPrecedence::Member
} else {
OperatorPrecedence::Primary
}
}
AnyJsExpression::JsBogusExpression(_) => OperatorPrecedence::lowest(),
AnyJsExpression::JsParenthesizedExpression(_) => OperatorPrecedence::highest(),
};
Ok(precedence)
}
/// Return identifier if the expression is an identifier expression.
pub fn as_js_reference_identifier(&self) -> Option<JsReferenceIdentifier> {
self.as_js_identifier_expression()?.name().ok()
}
pub fn as_static_value(&self) -> Option<StaticValue> {
match self {
AnyJsExpression::AnyJsLiteralExpression(literal) => literal.as_static_value(),
AnyJsExpression::JsTemplateExpression(template) => {
let element_list = template.elements();
if element_list.len() == 0 {
let range = template
.l_tick_token()
.ok()?
.text_trimmed_range()
.add_start(1.into());
return Some(StaticValue::EmptyString(range));
}
if element_list.len() > 1 {
return None;
}
match element_list.first()? {
AnyJsTemplateElement::JsTemplateChunkElement(element) => {
Some(StaticValue::String(element.template_chunk_token().ok()?))
}
_ => None,
}
}
AnyJsExpression::JsIdentifierExpression(identifier) => {
let identifier_token = identifier.name().ok()?.value_token().ok()?;
match identifier_token.text_trimmed() {
UNDEFINED => Some(StaticValue::Undefined(identifier_token)),
_ => None,
}
}
_ => None,
}
}
}
impl AnyJsLiteralExpression {
pub fn value_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
AnyJsLiteralExpression::JsBigintLiteralExpression(expression) => {
expression.value_token()
}
AnyJsLiteralExpression::JsBooleanLiteralExpression(expression) => {
expression.value_token()
}
AnyJsLiteralExpression::JsNullLiteralExpression(expression) => expression.value_token(),
AnyJsLiteralExpression::JsNumberLiteralExpression(expression) => {
expression.value_token()
}
AnyJsLiteralExpression::JsRegexLiteralExpression(expression) => {
expression.value_token()
}
AnyJsLiteralExpression::JsStringLiteralExpression(expression) => {
expression.value_token()
}
}
}
pub fn as_static_value(&self) -> Option<StaticValue> {
match self {
AnyJsLiteralExpression::JsBigintLiteralExpression(bigint) => {
Some(StaticValue::BigInt(bigint.value_token().ok()?))
}
AnyJsLiteralExpression::JsBooleanLiteralExpression(boolean) => {
Some(StaticValue::Boolean(boolean.value_token().ok()?))
}
AnyJsLiteralExpression::JsNullLiteralExpression(null) => {
Some(StaticValue::Null(null.value_token().ok()?))
}
AnyJsLiteralExpression::JsNumberLiteralExpression(number) => {
Some(StaticValue::Number(number.value_token().ok()?))
}
AnyJsLiteralExpression::JsRegexLiteralExpression(_) => None,
AnyJsLiteralExpression::JsStringLiteralExpression(string) => {
Some(StaticValue::String(string.value_token().ok()?))
}
}
}
}
impl JsStaticMemberExpression {
/// Returns `true` if this is an optional member access
///
/// ```javascript
/// a.b -> false,
/// a?.b -> true
/// a?.[b][c][d].e -> false
/// ```
pub fn is_optional(&self) -> bool {
self.operator_token()
.map_or(false, |token| token.kind() == JsSyntaxKind::QUESTIONDOT)
}
/// Returns true if this member has an optional token or any member expression on the left side.
///
/// ```javascript
/// a.b -> false
/// a?.b-> true
/// a?.[b][c][d].e -> true
/// ```
pub fn is_optional_chain(&self) -> bool {
is_optional_chain(self.clone().into())
}
}
impl JsComputedMemberExpression {
/// Returns `true` if this is an optional member access
///
/// ```javascript
/// a[b] -> false,
/// a?.[b] -> true
/// a?.b.c.d[e] -> false
/// ```
pub fn is_optional(&self) -> bool {
self.optional_chain_token().is_some()
}
/// Returns true if this member has an optional token or any member expression on the left side.
///
/// ```javascript
/// a[b] -> false
/// a?.[b]-> true
/// a?.b.c.d[e] -> true
/// ```
pub fn is_optional_chain(&self) -> bool {
is_optional_chain(self.clone().into())
}
}
declare_node_union! {
pub AnyJsComputedMember = JsComputedMemberExpression | JsComputedMemberAssignment
}
impl AnyJsComputedMember {
pub fn object(&self) -> SyntaxResult<AnyJsExpression> {
match self {
AnyJsComputedMember::JsComputedMemberExpression(expression) => expression.object(),
AnyJsComputedMember::JsComputedMemberAssignment(assignment) => assignment.object(),
}
}
pub fn l_brack_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
AnyJsComputedMember::JsComputedMemberExpression(expression) => {
expression.l_brack_token()
}
AnyJsComputedMember::JsComputedMemberAssignment(assignment) => {
assignment.l_brack_token()
}
}
}
pub fn optional_chain_token(&self) -> Option<JsSyntaxToken> {
match self {
AnyJsComputedMember::JsComputedMemberExpression(expression) => {
expression.optional_chain_token()
}
AnyJsComputedMember::JsComputedMemberAssignment(_) => None,
}
}
pub fn member(&self) -> SyntaxResult<AnyJsExpression> {
match self {
AnyJsComputedMember::JsComputedMemberExpression(expression) => expression.member(),
AnyJsComputedMember::JsComputedMemberAssignment(assignment) => assignment.member(),
}
}
pub fn r_brack_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
AnyJsComputedMember::JsComputedMemberExpression(expression) => {
expression.r_brack_token()
}
AnyJsComputedMember::JsComputedMemberAssignment(assignment) => {
assignment.r_brack_token()
}
}
}
}
declare_node_union! {
pub AnyJsMemberExpression = JsStaticMemberExpression | JsComputedMemberExpression
}
impl AnyJsMemberExpression {
pub fn object(&self) -> SyntaxResult<AnyJsExpression> {
match self {
AnyJsMemberExpression::JsStaticMemberExpression(expr) => expr.object(),
AnyJsMemberExpression::JsComputedMemberExpression(expr) => expr.object(),
}
}
/// Returns the member name of `self` if `self` is a static member or a computed member with a literal string.
///
/// ## Examples
///
/// ```
/// use rome_js_syntax::{AnyJsExpression, AnyJsLiteralExpression, AnyJsMemberExpression, T};
/// use rome_js_factory::make;
///
/// let math_id = make::js_reference_identifier(make::ident("Math"));
/// let math_id = make::js_identifier_expression(math_id);
/// let pow_ident_token = make::ident("pow");
/// let pow_name = make::js_name(pow_ident_token);
/// let static_member = make::js_static_member_expression(math_id.clone().into(), make::token(T![.]), pow_name.into());
/// let static_member: AnyJsMemberExpression = static_member.into();
/// let member_name = static_member.member_name().unwrap();
/// assert_eq!(member_name.text(), "pow");
///
/// let pow_str_token = make::js_string_literal("pow");
/// let pow_str_literal = make::js_string_literal_expression(pow_str_token.clone());
/// let pow_str_literal = AnyJsExpression::AnyJsLiteralExpression(AnyJsLiteralExpression::from(pow_str_literal));
/// let computed_member = make::js_computed_member_expression(math_id.into(), make::token(T!['[']), pow_str_literal, make::token(T![']'])).build();
/// let computed_member: AnyJsMemberExpression = computed_member.into();
/// let member_name = computed_member.member_name().unwrap();
/// assert_eq!(member_name.text(), "pow");
/// ```
pub fn member_name(&self) -> Option<StaticValue> {
let value = match self {
AnyJsMemberExpression::JsStaticMemberExpression(e) => {
StaticValue::String(e.member().ok()?.as_js_name()?.value_token().ok()?)
}
AnyJsMemberExpression::JsComputedMemberExpression(e) => {
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/static_value.rs | crates/rome_js_syntax/src/static_value.rs | use rome_rowan::TextRange;
use crate::{JsSyntaxKind, JsSyntaxToken};
#[derive(Debug, Clone, Eq, PartialEq)]
/// static values defined in JavaScript's expressions
pub enum StaticValue {
Boolean(JsSyntaxToken),
Null(JsSyntaxToken),
Undefined(JsSyntaxToken),
Number(JsSyntaxToken),
BigInt(JsSyntaxToken),
// The string can be empty.
String(JsSyntaxToken),
/// This is used to represent the empty template string.
EmptyString(TextRange),
}
impl StaticValue {
/// Return `true` if the value is falsy
///
/// ## Examples
///
/// ```
/// use rome_js_syntax::{T, static_value::StaticValue};
/// use rome_js_factory::make;
///
/// let bool = make::token(T![false]);
/// assert!(StaticValue::Boolean(bool).is_falsy());
/// ```
pub fn is_falsy(&self) -> bool {
match self {
StaticValue::Boolean(token) => token.text_trimmed() == "false",
StaticValue::Null(_) | StaticValue::Undefined(_) | StaticValue::EmptyString(_) => true,
StaticValue::Number(token) => token.text_trimmed() == "0",
StaticValue::BigInt(token) => token.text_trimmed() == "0n",
StaticValue::String(_) => self.text().is_empty(),
}
}
/// Return a string of the static value
///
/// ## Examples
///
/// ```
/// use rome_js_syntax::{T, static_value::StaticValue};
/// use rome_js_factory::make;
///
/// let bool = make::token(T![false]);
/// assert_eq!(StaticValue::Boolean(bool).text(), "false");
/// ```
pub fn text(&self) -> &str {
match self {
StaticValue::Boolean(token)
| StaticValue::Null(token)
| StaticValue::Undefined(token)
| StaticValue::Number(token)
| StaticValue::BigInt(token) => token.text_trimmed(),
StaticValue::String(token) => {
let text = token.text_trimmed();
if matches!(
token.kind(),
JsSyntaxKind::JS_STRING_LITERAL | JsSyntaxKind::JSX_STRING_LITERAL
) {
// SAFETY: string literal token have a delimiters at the start and the end of the string
return &text[1..text.len() - 1];
}
text
}
StaticValue::EmptyString(_) => "",
}
}
/// Return teh range of the static value.
///
/// ## Examples
///
/// ```
/// use rome_js_syntax::{T, static_value::StaticValue};
/// use rome_js_factory::make;
///
/// let bool = make::token(T![false]);
/// assert_eq!(StaticValue::Boolean(bool.clone()).range(), bool.text_trimmed_range());
/// ```
pub fn range(&self) -> TextRange {
match self {
StaticValue::Boolean(token)
| StaticValue::Null(token)
| StaticValue::Undefined(token)
| StaticValue::Number(token)
| StaticValue::BigInt(token)
| StaticValue::String(token) => token.text_trimmed_range(),
StaticValue::EmptyString(range) => *range,
}
}
/// Return `true` if the static value doesn't match the given string value and it is
/// 1. A string literal
/// 2. A template literal with no substitutions
///
/// ## Examples
///
/// ```
/// use rome_js_syntax::static_value::StaticValue;
/// use rome_js_factory::make;
/// use rome_rowan::TriviaPieceKind;
///
/// let str_literal = make::js_string_literal("foo")
/// .with_leading_trivia(vec![(TriviaPieceKind::Whitespace, " ")]);
/// assert!(StaticValue::String(str_literal).is_not_string_constant("bar"));
/// ```
pub fn is_not_string_constant(&self, text: &str) -> bool {
match self {
StaticValue::String(_) | StaticValue::EmptyString(_) => self.text() != text,
_ => false,
}
}
/// Return a string if the static value is
/// 1. A string literal
/// 2. A template literal with no substitutions
///
/// ## Examples
///
/// ```
/// use rome_js_syntax::static_value::StaticValue;
/// use rome_js_factory::make;
/// use rome_rowan::TriviaPieceKind;
///
/// let str_literal = make::js_string_literal("foo")
/// .with_leading_trivia(vec![(TriviaPieceKind::Whitespace, " ")]);
/// assert_eq!(StaticValue::String(str_literal).as_string_constant().unwrap(), "foo");
/// ```
pub fn as_string_constant(&self) -> Option<&str> {
match self {
StaticValue::String(_) | StaticValue::EmptyString(_) => Some(self.text()),
_ => None,
}
}
/// Return `true` if the value is null or undefined
///
/// ## Examples
///
/// ```
/// use rome_js_syntax::{T, static_value::StaticValue};
/// use rome_js_factory::make::{js_null_literal_expression, token};
///
/// let null = js_null_literal_expression(token(T![null]));
/// assert!(StaticValue::Null(null.value_token().ok().unwrap()).is_null_or_undefined());
/// ```
pub fn is_null_or_undefined(&self) -> bool {
matches!(self, StaticValue::Null(_) | StaticValue::Undefined(_))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/identifier_ext.rs | crates/rome_js_syntax/src/identifier_ext.rs | use crate::{JsIdentifierAssignment, JsReferenceIdentifier, JsSyntaxToken, JsxReferenceIdentifier};
use rome_rowan::{declare_node_union, SyntaxResult};
declare_node_union! {
pub AnyJsIdentifierUsage = JsReferenceIdentifier | JsIdentifierAssignment | JsxReferenceIdentifier
}
impl AnyJsIdentifierUsage {
pub fn value_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
AnyJsIdentifierUsage::JsReferenceIdentifier(node) => node.value_token(),
AnyJsIdentifierUsage::JsIdentifierAssignment(node) => node.name_token(),
AnyJsIdentifierUsage::JsxReferenceIdentifier(node) => node.value_token(),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/generated.rs | crates/rome_js_syntax/src/generated.rs | #[rustfmt::skip]
pub(super) mod nodes;
#[rustfmt::skip]
pub(super) mod nodes_mut;
#[rustfmt::skip]
pub mod macros;
#[macro_use]
pub mod kind;
pub use kind::*;
pub use nodes::*;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/generated/nodes_mut.rs | crates/rome_js_syntax/src/generated/nodes_mut.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use crate::{generated::nodes::*, JsSyntaxToken as SyntaxToken};
use rome_rowan::AstNode;
use std::iter::once;
impl JsAccessorModifier {
pub fn with_modifier_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
}
impl JsArrayAssignmentPattern {
pub fn with_l_brack_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_elements(self, element: JsArrayAssignmentPatternElementList) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_r_brack_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into()))),
)
}
}
impl JsArrayAssignmentPatternRestElement {
pub fn with_dotdotdot_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_pattern(self, element: AnyJsAssignmentPattern) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))),
)
}
}
impl JsArrayBindingPattern {
pub fn with_l_brack_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_elements(self, element: JsArrayBindingPatternElementList) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_r_brack_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into()))),
)
}
}
impl JsArrayBindingPatternRestElement {
pub fn with_dotdotdot_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_pattern(self, element: AnyJsBindingPattern) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))),
)
}
}
impl JsArrayExpression {
pub fn with_l_brack_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_elements(self, element: JsArrayElementList) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_r_brack_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into()))),
)
}
}
impl JsArrayHole {}
impl JsArrowFunctionExpression {
pub fn with_async_token(self, element: Option<SyntaxToken>) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(element.map(|element| element.into()))),
)
}
pub fn with_type_parameters(self, element: Option<TsTypeParameters>) -> Self {
Self::unwrap_cast(self.syntax.splice_slots(
1usize..=1usize,
once(element.map(|element| element.into_syntax().into())),
))
}
pub fn with_parameters(self, element: AnyJsArrowFunctionParameters) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_return_type_annotation(self, element: Option<TsReturnTypeAnnotation>) -> Self {
Self::unwrap_cast(self.syntax.splice_slots(
3usize..=3usize,
once(element.map(|element| element.into_syntax().into())),
))
}
pub fn with_fat_arrow_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(4usize..=4usize, once(Some(element.into()))),
)
}
pub fn with_body(self, element: AnyJsFunctionBody) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(5usize..=5usize, once(Some(element.into_syntax().into()))),
)
}
}
impl JsAssignmentExpression {
pub fn with_left(self, element: AnyJsAssignmentPattern) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_operator_token_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into()))),
)
}
pub fn with_right(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))),
)
}
}
impl JsAssignmentWithDefault {
pub fn with_pattern(self, element: AnyJsAssignmentPattern) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_eq_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into()))),
)
}
pub fn with_default(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))),
)
}
}
impl JsAwaitExpression {
pub fn with_await_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_argument(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))),
)
}
}
impl JsBigintLiteralExpression {
pub fn with_value_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
}
impl JsBinaryExpression {
pub fn with_left(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_operator_token_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into()))),
)
}
pub fn with_right(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))),
)
}
}
impl JsBindingPatternWithDefault {
pub fn with_pattern(self, element: AnyJsBindingPattern) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_eq_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into()))),
)
}
pub fn with_default(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))),
)
}
}
impl JsBlockStatement {
pub fn with_l_curly_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_statements(self, element: JsStatementList) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_r_curly_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into()))),
)
}
}
impl JsBooleanLiteralExpression {
pub fn with_value_token_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
}
impl JsBreakStatement {
pub fn with_break_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_label_token(self, element: Option<SyntaxToken>) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(element.map(|element| element.into()))),
)
}
pub fn with_semicolon_token(self, element: Option<SyntaxToken>) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(element.map(|element| element.into()))),
)
}
}
impl JsCallArguments {
pub fn with_l_paren_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_args(self, element: JsCallArgumentList) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_r_paren_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into()))),
)
}
}
impl JsCallExpression {
pub fn with_callee(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_optional_chain_token(self, element: Option<SyntaxToken>) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(element.map(|element| element.into()))),
)
}
pub fn with_type_arguments(self, element: Option<TsTypeArguments>) -> Self {
Self::unwrap_cast(self.syntax.splice_slots(
2usize..=2usize,
once(element.map(|element| element.into_syntax().into())),
))
}
pub fn with_arguments(self, element: JsCallArguments) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(3usize..=3usize, once(Some(element.into_syntax().into()))),
)
}
}
impl JsCaseClause {
pub fn with_case_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_test(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_colon_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into()))),
)
}
pub fn with_consequent(self, element: JsStatementList) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(3usize..=3usize, once(Some(element.into_syntax().into()))),
)
}
}
impl JsCatchClause {
pub fn with_catch_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_declaration(self, element: Option<JsCatchDeclaration>) -> Self {
Self::unwrap_cast(self.syntax.splice_slots(
1usize..=1usize,
once(element.map(|element| element.into_syntax().into())),
))
}
pub fn with_body(self, element: JsBlockStatement) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))),
)
}
}
impl JsCatchDeclaration {
pub fn with_l_paren_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_binding(self, element: AnyJsBindingPattern) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_type_annotation(self, element: Option<TsTypeAnnotation>) -> Self {
Self::unwrap_cast(self.syntax.splice_slots(
2usize..=2usize,
once(element.map(|element| element.into_syntax().into())),
))
}
pub fn with_r_paren_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(3usize..=3usize, once(Some(element.into()))),
)
}
}
impl JsClassDeclaration {
pub fn with_decorators(self, element: JsDecoratorList) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_abstract_token(self, element: Option<SyntaxToken>) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(element.map(|element| element.into()))),
)
}
pub fn with_class_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into()))),
)
}
pub fn with_id(self, element: AnyJsBinding) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(3usize..=3usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_type_parameters(self, element: Option<TsTypeParameters>) -> Self {
Self::unwrap_cast(self.syntax.splice_slots(
4usize..=4usize,
once(element.map(|element| element.into_syntax().into())),
))
}
pub fn with_extends_clause(self, element: Option<JsExtendsClause>) -> Self {
Self::unwrap_cast(self.syntax.splice_slots(
5usize..=5usize,
once(element.map(|element| element.into_syntax().into())),
))
}
pub fn with_implements_clause(self, element: Option<TsImplementsClause>) -> Self {
Self::unwrap_cast(self.syntax.splice_slots(
6usize..=6usize,
once(element.map(|element| element.into_syntax().into())),
))
}
pub fn with_l_curly_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(7usize..=7usize, once(Some(element.into()))),
)
}
pub fn with_members(self, element: JsClassMemberList) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(8usize..=8usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_r_curly_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(9usize..=9usize, once(Some(element.into()))),
)
}
}
impl JsClassExportDefaultDeclaration {
pub fn with_decorators(self, element: JsDecoratorList) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_abstract_token(self, element: Option<SyntaxToken>) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(element.map(|element| element.into()))),
)
}
pub fn with_class_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into()))),
)
}
pub fn with_id(self, element: Option<AnyJsBinding>) -> Self {
Self::unwrap_cast(self.syntax.splice_slots(
3usize..=3usize,
once(element.map(|element| element.into_syntax().into())),
))
}
pub fn with_type_parameters(self, element: Option<TsTypeParameters>) -> Self {
Self::unwrap_cast(self.syntax.splice_slots(
4usize..=4usize,
once(element.map(|element| element.into_syntax().into())),
))
}
pub fn with_extends_clause(self, element: Option<JsExtendsClause>) -> Self {
Self::unwrap_cast(self.syntax.splice_slots(
5usize..=5usize,
once(element.map(|element| element.into_syntax().into())),
))
}
pub fn with_implements_clause(self, element: Option<TsImplementsClause>) -> Self {
Self::unwrap_cast(self.syntax.splice_slots(
6usize..=6usize,
once(element.map(|element| element.into_syntax().into())),
))
}
pub fn with_l_curly_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(7usize..=7usize, once(Some(element.into()))),
)
}
pub fn with_members(self, element: JsClassMemberList) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(8usize..=8usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_r_curly_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(9usize..=9usize, once(Some(element.into()))),
)
}
}
impl JsClassExpression {
pub fn with_decorators(self, element: JsDecoratorList) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_class_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into()))),
)
}
pub fn with_id(self, element: Option<AnyJsBinding>) -> Self {
Self::unwrap_cast(self.syntax.splice_slots(
2usize..=2usize,
once(element.map(|element| element.into_syntax().into())),
))
}
pub fn with_type_parameters(self, element: Option<TsTypeParameters>) -> Self {
Self::unwrap_cast(self.syntax.splice_slots(
3usize..=3usize,
once(element.map(|element| element.into_syntax().into())),
))
}
pub fn with_extends_clause(self, element: Option<JsExtendsClause>) -> Self {
Self::unwrap_cast(self.syntax.splice_slots(
4usize..=4usize,
once(element.map(|element| element.into_syntax().into())),
))
}
pub fn with_implements_clause(self, element: Option<TsImplementsClause>) -> Self {
Self::unwrap_cast(self.syntax.splice_slots(
5usize..=5usize,
once(element.map(|element| element.into_syntax().into())),
))
}
pub fn with_l_curly_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(6usize..=6usize, once(Some(element.into()))),
)
}
pub fn with_members(self, element: JsClassMemberList) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(7usize..=7usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_r_curly_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(8usize..=8usize, once(Some(element.into()))),
)
}
}
impl JsComputedMemberAssignment {
pub fn with_object(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_l_brack_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into()))),
)
}
pub fn with_member(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_r_brack_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(3usize..=3usize, once(Some(element.into()))),
)
}
}
impl JsComputedMemberExpression {
pub fn with_object(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_optional_chain_token(self, element: Option<SyntaxToken>) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(element.map(|element| element.into()))),
)
}
pub fn with_l_brack_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into()))),
)
}
pub fn with_member(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(3usize..=3usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_r_brack_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(4usize..=4usize, once(Some(element.into()))),
)
}
}
impl JsComputedMemberName {
pub fn with_l_brack_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_expression(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_r_brack_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into()))),
)
}
}
impl JsConditionalExpression {
pub fn with_test(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_question_mark_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into()))),
)
}
pub fn with_consequent(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_colon_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(3usize..=3usize, once(Some(element.into()))),
)
}
pub fn with_alternate(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(4usize..=4usize, once(Some(element.into_syntax().into()))),
)
}
}
impl JsConstructorClassMember {
pub fn with_modifiers(self, element: JsConstructorModifierList) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_name(self, element: JsLiteralMemberName) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_parameters(self, element: JsConstructorParameters) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_body(self, element: JsFunctionBody) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(3usize..=3usize, once(Some(element.into_syntax().into()))),
)
}
}
impl JsConstructorParameters {
pub fn with_l_paren_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_parameters(self, element: JsConstructorParameterList) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_r_paren_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into()))),
)
}
}
impl JsContinueStatement {
pub fn with_continue_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_label_token(self, element: Option<SyntaxToken>) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(element.map(|element| element.into()))),
)
}
pub fn with_semicolon_token(self, element: Option<SyntaxToken>) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(element.map(|element| element.into()))),
)
}
}
impl JsDebuggerStatement {
pub fn with_debugger_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_semicolon_token(self, element: Option<SyntaxToken>) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(element.map(|element| element.into()))),
)
}
}
impl JsDecorator {
pub fn with_at_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_expression(self, element: AnyJsDecorator) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))),
)
}
}
impl JsDefaultClause {
pub fn with_default_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_colon_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into()))),
)
}
pub fn with_consequent(self, element: JsStatementList) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))),
)
}
}
impl JsDefaultImportSpecifier {
pub fn with_local_name(self, element: AnyJsBinding) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_trailing_comma_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into()))),
)
}
}
impl JsDirective {
pub fn with_value_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_semicolon_token(self, element: Option<SyntaxToken>) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(element.map(|element| element.into()))),
)
}
}
impl JsDoWhileStatement {
pub fn with_do_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_body(self, element: AnyJsStatement) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_while_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(2usize..=2usize, once(Some(element.into()))),
)
}
pub fn with_l_paren_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(3usize..=3usize, once(Some(element.into()))),
)
}
pub fn with_test(self, element: AnyJsExpression) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(4usize..=4usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_r_paren_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(5usize..=5usize, once(Some(element.into()))),
)
}
pub fn with_semicolon_token(self, element: Option<SyntaxToken>) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(6usize..=6usize, once(element.map(|element| element.into()))),
)
}
}
impl JsElseClause {
pub fn with_else_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
pub fn with_alternate(self, element: AnyJsStatement) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))),
)
}
}
impl JsEmptyClassMember {
pub fn with_semicolon_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
}
impl JsEmptyStatement {
pub fn with_semicolon_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into()))),
)
}
}
impl JsExport {
pub fn with_decorators(self, element: JsDecoratorList) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))),
)
}
pub fn with_export_token(self, element: SyntaxToken) -> Self {
Self::unwrap_cast(
self.syntax
.splice_slots(1usize..=1usize, once(Some(element.into()))),
)
}
pub fn with_export_clause(self, element: AnyJsExportClause) -> Self {
Self::unwrap_cast(
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/generated/kind.rs | crates/rome_js_syntax/src/generated/kind.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
#![allow(clippy::all)]
#![allow(bad_style, missing_docs, unreachable_pub)]
#[doc = r" The kind of syntax node, e.g. `IDENT`, `FUNCTION_KW`, or `FOR_STMT`."]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[repr(u16)]
pub enum JsSyntaxKind {
#[doc(hidden)]
TOMBSTONE,
#[doc = r" Marks the end of the file.May have trivia attached"]
EOF,
SEMICOLON,
COMMA,
L_PAREN,
R_PAREN,
L_CURLY,
R_CURLY,
L_BRACK,
R_BRACK,
L_ANGLE,
R_ANGLE,
TILDE,
QUESTION,
QUESTION2,
QUESTIONDOT,
AMP,
PIPE,
PLUS,
PLUS2,
STAR,
STAR2,
SLASH,
CARET,
PERCENT,
DOT,
DOT3,
COLON,
EQ,
EQ2,
EQ3,
FAT_ARROW,
BANG,
NEQ,
NEQ2,
MINUS,
MINUS2,
LTEQ,
GTEQ,
PLUSEQ,
MINUSEQ,
PIPEEQ,
AMPEQ,
CARETEQ,
SLASHEQ,
STAREQ,
PERCENTEQ,
AMP2,
PIPE2,
SHL,
SHR,
USHR,
SHLEQ,
SHREQ,
USHREQ,
AMP2EQ,
PIPE2EQ,
STAR2EQ,
QUESTION2EQ,
AT,
BACKTICK,
BREAK_KW,
CASE_KW,
CATCH_KW,
CLASS_KW,
CONST_KW,
CONTINUE_KW,
DEBUGGER_KW,
DEFAULT_KW,
DELETE_KW,
DO_KW,
ELSE_KW,
ENUM_KW,
EXPORT_KW,
EXTENDS_KW,
FALSE_KW,
FINALLY_KW,
FOR_KW,
FUNCTION_KW,
IF_KW,
IN_KW,
INSTANCEOF_KW,
IMPORT_KW,
NEW_KW,
NULL_KW,
RETURN_KW,
SUPER_KW,
SWITCH_KW,
THIS_KW,
THROW_KW,
TRY_KW,
TRUE_KW,
TYPEOF_KW,
VAR_KW,
VOID_KW,
WHILE_KW,
WITH_KW,
IMPLEMENTS_KW,
INTERFACE_KW,
LET_KW,
PACKAGE_KW,
PRIVATE_KW,
PROTECTED_KW,
PUBLIC_KW,
STATIC_KW,
YIELD_KW,
ABSTRACT_KW,
ACCESSOR_KW,
AS_KW,
SATISFIES_KW,
ASSERTS_KW,
ASSERT_KW,
ANY_KW,
ASYNC_KW,
AWAIT_KW,
BOOLEAN_KW,
CONSTRUCTOR_KW,
DECLARE_KW,
GET_KW,
INFER_KW,
IS_KW,
KEYOF_KW,
MODULE_KW,
NAMESPACE_KW,
NEVER_KW,
READONLY_KW,
REQUIRE_KW,
NUMBER_KW,
OBJECT_KW,
SET_KW,
STRING_KW,
SYMBOL_KW,
TYPE_KW,
UNDEFINED_KW,
UNIQUE_KW,
UNKNOWN_KW,
FROM_KW,
GLOBAL_KW,
BIGINT_KW,
OVERRIDE_KW,
OF_KW,
OUT_KW,
USING_KW,
JS_NUMBER_LITERAL,
JS_BIGINT_LITERAL,
JS_STRING_LITERAL,
JS_REGEX_LITERAL,
JSX_TEXT_LITERAL,
JSX_STRING_LITERAL,
TARGET,
META,
HASH,
TEMPLATE_CHUNK,
DOLLAR_CURLY,
ERROR_TOKEN,
IDENT,
JSX_IDENT,
NEWLINE,
WHITESPACE,
COMMENT,
MULTILINE_COMMENT,
JS_SHEBANG,
JS_MODULE,
JS_MODULE_ITEM_LIST,
JS_SCRIPT,
JS_EXPRESSION_SNIPPED,
JS_DIRECTIVE,
JS_DIRECTIVE_LIST,
JS_STATEMENT_LIST,
JS_BLOCK_STATEMENT,
JS_FUNCTION_BODY,
JS_VARIABLE_STATEMENT,
JS_VARIABLE_DECLARATION,
JS_VARIABLE_DECLARATOR_LIST,
JS_VARIABLE_DECLARATOR,
JS_VARIABLE_DECLARATION_CLAUSE,
TS_DEFINITE_VARIABLE_ANNOTATION,
JS_INITIALIZER_CLAUSE,
JS_EMPTY_STATEMENT,
JS_EXPRESSION_STATEMENT,
JS_IF_STATEMENT,
JS_ELSE_CLAUSE,
JS_DO_WHILE_STATEMENT,
JS_WHILE_STATEMENT,
JS_FOR_STATEMENT,
JS_FOR_IN_STATEMENT,
JS_FOR_OF_STATEMENT,
JS_FOR_VARIABLE_DECLARATION,
JS_CONTINUE_STATEMENT,
JS_BREAK_STATEMENT,
JS_RETURN_STATEMENT,
JS_WITH_STATEMENT,
JS_SWITCH_STATEMENT,
JS_SWITCH_CASE_LIST,
JS_CASE_CLAUSE,
JS_DEFAULT_CLAUSE,
JS_LABELED_STATEMENT,
JS_THROW_STATEMENT,
JS_TRY_STATEMENT,
JS_TRY_FINALLY_STATEMENT,
JS_CATCH_CLAUSE,
JS_CATCH_DECLARATION,
JS_FINALLY_CLAUSE,
JS_DEBUGGER_STATEMENT,
JS_FUNCTION_DECLARATION,
JS_PARAMETERS,
JS_PARAMETER_LIST,
JS_FORMAL_PARAMETER,
JS_REST_PARAMETER,
TS_THIS_PARAMETER,
TS_PROPERTY_PARAMETER,
TS_PROPERTY_PARAMETER_MODIFIER_LIST,
TS_TYPE_ANNOTATION,
TS_RETURN_TYPE_ANNOTATION,
JS_IDENTIFIER_BINDING,
JS_IDENTIFIER_EXPRESSION,
JS_REFERENCE_IDENTIFIER,
JS_NAME,
JS_PRIVATE_NAME,
JS_THIS_EXPRESSION,
JS_ARRAY_EXPRESSION,
JS_ARRAY_ELEMENT_LIST,
JS_ARRAY_HOLE,
JS_COMPUTED_MEMBER_NAME,
JS_LITERAL_MEMBER_NAME,
JS_OBJECT_EXPRESSION,
JS_OBJECT_MEMBER_LIST,
JS_PROPERTY_OBJECT_MEMBER,
JS_GETTER_OBJECT_MEMBER,
JS_SETTER_OBJECT_MEMBER,
JS_METHOD_OBJECT_MEMBER,
JS_SUPER_EXPRESSION,
JS_PARENTHESIZED_EXPRESSION,
JS_NEW_EXPRESSION,
JS_FUNCTION_EXPRESSION,
JS_STATIC_MEMBER_EXPRESSION,
JS_COMPUTED_MEMBER_EXPRESSION,
JS_CALL_EXPRESSION,
JS_UNARY_EXPRESSION,
JS_PRE_UPDATE_EXPRESSION,
JS_POST_UPDATE_EXPRESSION,
JS_BINARY_EXPRESSION,
JS_INSTANCEOF_EXPRESSION,
JS_IN_EXPRESSION,
JS_LOGICAL_EXPRESSION,
JS_CONDITIONAL_EXPRESSION,
JS_ASSIGNMENT_EXPRESSION,
JS_SEQUENCE_EXPRESSION,
JS_CALL_ARGUMENTS,
JS_CALL_ARGUMENT_LIST,
JS_STRING_LITERAL_EXPRESSION,
JS_NUMBER_LITERAL_EXPRESSION,
JS_BIGINT_LITERAL_EXPRESSION,
JS_BOOLEAN_LITERAL_EXPRESSION,
JS_NULL_LITERAL_EXPRESSION,
JS_REGEX_LITERAL_EXPRESSION,
JS_TEMPLATE_EXPRESSION,
JS_TEMPLATE_ELEMENT,
JS_TEMPLATE_CHUNK_ELEMENT,
JS_TEMPLATE_ELEMENT_LIST,
JS_IMPORT_CALL_EXPRESSION,
JS_NEW_TARGET_EXPRESSION,
JS_IMPORT_META_EXPRESSION,
JS_SHORTHAND_PROPERTY_OBJECT_MEMBER,
JS_SPREAD,
JS_OBJECT_BINDING_PATTERN,
JS_ARRAY_BINDING_PATTERN,
JS_ARRAY_BINDING_PATTERN_ELEMENT_LIST,
JS_BINDING_PATTERN_WITH_DEFAULT,
JS_ARRAY_BINDING_PATTERN_REST_ELEMENT,
JS_OBJECT_BINDING_PATTERN_PROPERTY_LIST,
JS_OBJECT_BINDING_PATTERN_REST,
JS_OBJECT_BINDING_PATTERN_PROPERTY,
JS_OBJECT_BINDING_PATTERN_SHORTHAND_PROPERTY,
JS_ARROW_FUNCTION_EXPRESSION,
JS_YIELD_EXPRESSION,
JS_YIELD_ARGUMENT,
JS_CLASS_DECLARATION,
JS_CLASS_EXPRESSION,
JS_CLASS_MEMBER_LIST,
JS_STATIC_MODIFIER,
JS_ACCESSOR_MODIFIER,
TS_DECLARE_MODIFIER,
TS_READONLY_MODIFIER,
TS_ABSTRACT_MODIFIER,
TS_OVERRIDE_MODIFIER,
TS_ACCESSIBILITY_MODIFIER,
TS_CONST_MODIFIER,
TS_IN_MODIFIER,
TS_OUT_MODIFIER,
JS_EXTENDS_CLAUSE,
TS_IMPLEMENTS_CLAUSE,
JS_PRIVATE_CLASS_MEMBER_NAME,
JS_CONSTRUCTOR_CLASS_MEMBER,
TS_CONSTRUCTOR_SIGNATURE_CLASS_MEMBER,
JS_CONSTRUCTOR_MODIFIER_LIST,
JS_CONSTRUCTOR_PARAMETER_LIST,
JS_CONSTRUCTOR_PARAMETERS,
JS_PROPERTY_CLASS_MEMBER,
JS_PROPERTY_MODIFIER_LIST,
TS_OPTIONAL_PROPERTY_ANNOTATION,
TS_DEFINITE_PROPERTY_ANNOTATION,
JS_STATIC_INITIALIZATION_BLOCK_CLASS_MEMBER,
JS_METHOD_CLASS_MEMBER,
JS_METHOD_MODIFIER_LIST,
JS_GETTER_CLASS_MEMBER,
JS_SETTER_CLASS_MEMBER,
JS_EMPTY_CLASS_MEMBER,
JS_ASSIGNMENT_WITH_DEFAULT,
JS_PARENTHESIZED_ASSIGNMENT,
JS_IDENTIFIER_ASSIGNMENT,
JS_STATIC_MEMBER_ASSIGNMENT,
JS_COMPUTED_MEMBER_ASSIGNMENT,
TS_NON_NULL_ASSERTION_ASSIGNMENT,
TS_AS_ASSIGNMENT,
TS_SATISFIES_ASSIGNMENT,
TS_TYPE_ASSERTION_ASSIGNMENT,
JS_ARRAY_ASSIGNMENT_PATTERN,
JS_ARRAY_ASSIGNMENT_PATTERN_ELEMENT_LIST,
JS_ARRAY_ASSIGNMENT_PATTERN_REST_ELEMENT,
JS_OBJECT_ASSIGNMENT_PATTERN,
JS_OBJECT_ASSIGNMENT_PATTERN_PROPERTY_LIST,
JS_OBJECT_ASSIGNMENT_PATTERN_SHORTHAND_PROPERTY,
JS_OBJECT_ASSIGNMENT_PATTERN_PROPERTY,
JS_OBJECT_ASSIGNMENT_PATTERN_REST,
JS_IMPORT,
JS_IMPORT_BARE_CLAUSE,
JS_IMPORT_DEFAULT_CLAUSE,
JS_IMPORT_NAMESPACE_CLAUSE,
JS_IMPORT_NAMED_CLAUSE,
JS_NAMED_IMPORT_SPECIFIERS,
JS_NAMED_IMPORT_SPECIFIER_LIST,
JS_NAMESPACE_IMPORT_SPECIFIER,
JS_DEFAULT_IMPORT_SPECIFIER,
JS_NAMED_IMPORT_SPECIFIER,
JS_SHORTHAND_NAMED_IMPORT_SPECIFIER,
JS_IMPORT_ASSERTION,
JS_IMPORT_ASSERTION_ENTRY_LIST,
JS_IMPORT_ASSERTION_ENTRY,
JS_MODULE_SOURCE,
JS_EXPORT,
JS_EXPORT_NAMED_CLAUSE,
JS_EXPORT_NAMED_SPECIFIER_LIST,
JS_EXPORT_NAMED_SHORTHAND_SPECIFIER,
JS_EXPORT_NAMED_SPECIFIER,
JS_EXPORT_DEFAULT_EXPRESSION_CLAUSE,
JS_EXPORT_DEFAULT_DECLARATION_CLAUSE,
JS_CLASS_EXPORT_DEFAULT_DECLARATION,
JS_FUNCTION_EXPORT_DEFAULT_DECLARATION,
JS_EXPORT_FROM_CLAUSE,
JS_EXPORT_NAMED_FROM_CLAUSE,
JS_EXPORT_NAMED_FROM_SPECIFIER_LIST,
JS_EXPORT_NAMED_FROM_SPECIFIER,
JS_EXPORT_AS_CLAUSE,
TS_EXPORT_AS_NAMESPACE_CLAUSE,
TS_EXPORT_ASSIGNMENT_CLAUSE,
TS_EXPORT_DECLARE_CLAUSE,
JS_LITERAL_EXPORT_NAME,
JS_AWAIT_EXPRESSION,
JS_DECORATOR,
JS_DECORATOR_LIST,
TS_IDENTIFIER_BINDING,
TS_ANY_TYPE,
TS_UNKNOWN_TYPE,
TS_NUMBER_TYPE,
TS_NON_PRIMITIVE_TYPE,
TS_BOOLEAN_TYPE,
TS_BIGINT_TYPE,
TS_STRING_TYPE,
TS_SYMBOL_TYPE,
TS_VOID_TYPE,
TS_UNDEFINED_TYPE,
TS_NEVER_TYPE,
TS_THIS_TYPE,
TS_TYPEOF_TYPE,
TS_PARENTHESIZED_TYPE,
TS_MAPPED_TYPE,
TS_MAPPED_TYPE_OPTIONAL_MODIFIER_CLAUSE,
TS_MAPPED_TYPE_READONLY_MODIFIER_CLAUSE,
TS_MAPPED_TYPE_AS_CLAUSE,
TS_TYPE_ALIAS_DECLARATION,
TS_MODULE_DECLARATION,
TS_GLOBAL_DECLARATION,
TS_QUALIFIED_MODULE_NAME,
TS_MODULE_BLOCK,
TS_EXTERNAL_MODULE_DECLARATION,
TS_EMPTY_EXTERNAL_MODULE_DECLARATION_BODY,
TS_QUALIFIED_NAME,
TS_REFERENCE_TYPE,
TS_UNION_TYPE,
TS_UNION_TYPE_VARIANT_LIST,
TS_INTERSECTION_TYPE,
TS_INTERSECTION_TYPE_ELEMENT_LIST,
TS_OBJECT_TYPE,
TS_TYPE_MEMBER_LIST,
TS_INTERFACE_DECLARATION,
TS_EXTENDS_CLAUSE,
TS_PROPERTY_SIGNATURE_TYPE_MEMBER,
TS_METHOD_SIGNATURE_TYPE_MEMBER,
TS_CALL_SIGNATURE_TYPE_MEMBER,
TS_CONSTRUCT_SIGNATURE_TYPE_MEMBER,
TS_GETTER_SIGNATURE_TYPE_MEMBER,
TS_SETTER_SIGNATURE_TYPE_MEMBER,
TS_INDEX_SIGNATURE_TYPE_MEMBER,
TS_IMPORT_TYPE,
TS_IMPORT_TYPE_QUALIFIER,
TS_ARRAY_TYPE,
TS_INDEXED_ACCESS_TYPE,
TS_TUPLE_TYPE,
TS_TUPLE_TYPE_ELEMENT_LIST,
TS_REST_TUPLE_TYPE_ELEMENT,
TS_OPTIONAL_TUPLE_TYPE_ELEMENT,
TS_NAMED_TUPLE_TYPE_ELEMENT,
TS_TYPE_OPERATOR_TYPE,
TS_INFER_TYPE,
TS_CONSTRUCTOR_TYPE,
TS_FUNCTION_TYPE,
TS_PREDICATE_RETURN_TYPE,
TS_ASSERTS_RETURN_TYPE,
TS_ASSERTS_CONDITION,
TS_TYPE_PARAMETERS,
TS_TYPE_PARAMETER_LIST,
TS_TYPE_PARAMETER,
TS_TYPE_PARAMETER_MODIFIER_LIST,
TS_TYPE_PARAMETER_NAME,
TS_TYPE_CONSTRAINT_CLAUSE,
TS_DEFAULT_TYPE_CLAUSE,
TS_STRING_LITERAL_TYPE,
TS_NUMBER_LITERAL_TYPE,
TS_BIGINT_LITERAL_TYPE,
TS_BOOLEAN_LITERAL_TYPE,
TS_NULL_LITERAL_TYPE,
TS_TEMPLATE_LITERAL_TYPE,
TS_TEMPLATE_ELEMENT_LIST,
TS_TEMPLATE_CHUNK_ELEMENT,
TS_TEMPLATE_ELEMENT,
TS_TYPE_ARGUMENTS,
TS_TYPE_ARGUMENT_LIST,
TS_TYPE_LIST,
TS_EXTENDS,
TS_CONDITIONAL_TYPE,
TS_NON_NULL_ASSERTION_EXPRESSION,
TS_TYPE_ASSERTION_EXPRESSION,
TS_AS_EXPRESSION,
TS_SATISFIES_EXPRESSION,
TS_INSTANTIATION_EXPRESSION,
TS_ENUM_DECLARATION,
TS_ENUM_MEMBER_LIST,
TS_ENUM_MEMBER,
TS_IMPORT_EQUALS_DECLARATION,
TS_EXTERNAL_MODULE_REFERENCE,
TS_NAME_WITH_TYPE_ARGUMENTS,
TS_DECLARE_FUNCTION_DECLARATION,
TS_DECLARE_FUNCTION_EXPORT_DEFAULT_DECLARATION,
TS_DECLARE_STATEMENT,
TS_INDEX_SIGNATURE_PARAMETER,
TS_PROPERTY_SIGNATURE_CLASS_MEMBER,
TS_INITIALIZED_PROPERTY_SIGNATURE_CLASS_MEMBER,
TS_PROPERTY_SIGNATURE_MODIFIER_LIST,
TS_METHOD_SIGNATURE_CLASS_MEMBER,
TS_METHOD_SIGNATURE_MODIFIER_LIST,
TS_GETTER_SIGNATURE_CLASS_MEMBER,
TS_SETTER_SIGNATURE_CLASS_MEMBER,
TS_INDEX_SIGNATURE_CLASS_MEMBER,
TS_INDEX_SIGNATURE_MODIFIER_LIST,
JSX_NAME,
JSX_NAMESPACE_NAME,
JSX_REFERENCE_IDENTIFIER,
JSX_TAG_EXPRESSION,
JSX_ELEMENT,
JSX_FRAGMENT,
JSX_OPENING_FRAGMENT,
JSX_CLOSING_FRAGMENT,
JSX_SELF_CLOSING_ELEMENT,
JSX_OPENING_ELEMENT,
JSX_CLOSING_ELEMENT,
JSX_MEMBER_NAME,
JSX_TEXT,
JSX_ATTRIBUTE_LIST,
JSX_ATTRIBUTE,
JSX_SPREAD_ATTRIBUTE,
JSX_ATTRIBUTE_INITIALIZER_CLAUSE,
JSX_EXPRESSION_ATTRIBUTE_VALUE,
JSX_CHILD_LIST,
JSX_EXPRESSION_CHILD,
JSX_SPREAD_CHILD,
JSX_STRING,
JS_BOGUS,
JS_BOGUS_EXPRESSION,
JS_BOGUS_STATEMENT,
JS_BOGUS_MEMBER,
JS_BOGUS_BINDING,
JS_BOGUS_PARAMETER,
JS_BOGUS_IMPORT_ASSERTION_ENTRY,
JS_BOGUS_NAMED_IMPORT_SPECIFIER,
JS_BOGUS_ASSIGNMENT,
TS_BOGUS_TYPE,
#[doc(hidden)]
__LAST,
}
use self::JsSyntaxKind::*;
impl JsSyntaxKind {
pub const fn is_punct(self) -> bool {
match self {
SEMICOLON | COMMA | L_PAREN | R_PAREN | L_CURLY | R_CURLY | L_BRACK | R_BRACK
| L_ANGLE | R_ANGLE | TILDE | QUESTION | QUESTION2 | QUESTIONDOT | AMP | PIPE
| PLUS | PLUS2 | STAR | STAR2 | SLASH | CARET | PERCENT | DOT | DOT3 | COLON | EQ
| EQ2 | EQ3 | FAT_ARROW | BANG | NEQ | NEQ2 | MINUS | MINUS2 | LTEQ | GTEQ | PLUSEQ
| MINUSEQ | PIPEEQ | AMPEQ | CARETEQ | SLASHEQ | STAREQ | PERCENTEQ | AMP2 | PIPE2
| SHL | SHR | USHR | SHLEQ | SHREQ | USHREQ | AMP2EQ | PIPE2EQ | STAR2EQ
| QUESTION2EQ | AT | BACKTICK => true,
_ => false,
}
}
pub const fn is_literal(self) -> bool {
match self {
JS_NUMBER_LITERAL | JS_BIGINT_LITERAL | JS_STRING_LITERAL | JS_REGEX_LITERAL
| JSX_TEXT_LITERAL | JSX_STRING_LITERAL => true,
_ => false,
}
}
pub const fn is_list(self) -> bool {
match self {
JS_MODULE_ITEM_LIST
| JS_DIRECTIVE_LIST
| JS_STATEMENT_LIST
| JS_VARIABLE_DECLARATOR_LIST
| JS_SWITCH_CASE_LIST
| JS_PARAMETER_LIST
| TS_PROPERTY_PARAMETER_MODIFIER_LIST
| JS_ARRAY_ELEMENT_LIST
| JS_OBJECT_MEMBER_LIST
| JS_CALL_ARGUMENT_LIST
| JS_TEMPLATE_ELEMENT_LIST
| JS_ARRAY_BINDING_PATTERN_ELEMENT_LIST
| JS_OBJECT_BINDING_PATTERN_PROPERTY_LIST
| JS_CLASS_MEMBER_LIST
| JS_CONSTRUCTOR_MODIFIER_LIST
| JS_CONSTRUCTOR_PARAMETER_LIST
| JS_PROPERTY_MODIFIER_LIST
| JS_METHOD_MODIFIER_LIST
| JS_ARRAY_ASSIGNMENT_PATTERN_ELEMENT_LIST
| JS_OBJECT_ASSIGNMENT_PATTERN_PROPERTY_LIST
| JS_NAMED_IMPORT_SPECIFIER_LIST
| JS_IMPORT_ASSERTION_ENTRY_LIST
| JS_EXPORT_NAMED_SPECIFIER_LIST
| JS_EXPORT_NAMED_FROM_SPECIFIER_LIST
| JS_DECORATOR_LIST
| TS_UNION_TYPE_VARIANT_LIST
| TS_INTERSECTION_TYPE_ELEMENT_LIST
| TS_TYPE_MEMBER_LIST
| TS_TUPLE_TYPE_ELEMENT_LIST
| TS_TYPE_PARAMETER_LIST
| TS_TYPE_PARAMETER_MODIFIER_LIST
| TS_TEMPLATE_ELEMENT_LIST
| TS_TYPE_ARGUMENT_LIST
| TS_TYPE_LIST
| TS_ENUM_MEMBER_LIST
| TS_PROPERTY_SIGNATURE_MODIFIER_LIST
| TS_METHOD_SIGNATURE_MODIFIER_LIST
| TS_INDEX_SIGNATURE_MODIFIER_LIST
| JSX_ATTRIBUTE_LIST
| JSX_CHILD_LIST => true,
_ => false,
}
}
pub fn from_keyword(ident: &str) -> Option<JsSyntaxKind> {
let kw = match ident {
"break" => BREAK_KW,
"case" => CASE_KW,
"catch" => CATCH_KW,
"class" => CLASS_KW,
"const" => CONST_KW,
"continue" => CONTINUE_KW,
"debugger" => DEBUGGER_KW,
"default" => DEFAULT_KW,
"delete" => DELETE_KW,
"do" => DO_KW,
"else" => ELSE_KW,
"enum" => ENUM_KW,
"export" => EXPORT_KW,
"extends" => EXTENDS_KW,
"false" => FALSE_KW,
"finally" => FINALLY_KW,
"for" => FOR_KW,
"function" => FUNCTION_KW,
"if" => IF_KW,
"in" => IN_KW,
"instanceof" => INSTANCEOF_KW,
"import" => IMPORT_KW,
"new" => NEW_KW,
"null" => NULL_KW,
"return" => RETURN_KW,
"super" => SUPER_KW,
"switch" => SWITCH_KW,
"this" => THIS_KW,
"throw" => THROW_KW,
"try" => TRY_KW,
"true" => TRUE_KW,
"typeof" => TYPEOF_KW,
"var" => VAR_KW,
"void" => VOID_KW,
"while" => WHILE_KW,
"with" => WITH_KW,
"implements" => IMPLEMENTS_KW,
"interface" => INTERFACE_KW,
"let" => LET_KW,
"package" => PACKAGE_KW,
"private" => PRIVATE_KW,
"protected" => PROTECTED_KW,
"public" => PUBLIC_KW,
"static" => STATIC_KW,
"yield" => YIELD_KW,
"abstract" => ABSTRACT_KW,
"accessor" => ACCESSOR_KW,
"as" => AS_KW,
"satisfies" => SATISFIES_KW,
"asserts" => ASSERTS_KW,
"assert" => ASSERT_KW,
"any" => ANY_KW,
"async" => ASYNC_KW,
"await" => AWAIT_KW,
"boolean" => BOOLEAN_KW,
"constructor" => CONSTRUCTOR_KW,
"declare" => DECLARE_KW,
"get" => GET_KW,
"infer" => INFER_KW,
"is" => IS_KW,
"keyof" => KEYOF_KW,
"module" => MODULE_KW,
"namespace" => NAMESPACE_KW,
"never" => NEVER_KW,
"readonly" => READONLY_KW,
"require" => REQUIRE_KW,
"number" => NUMBER_KW,
"object" => OBJECT_KW,
"set" => SET_KW,
"string" => STRING_KW,
"symbol" => SYMBOL_KW,
"type" => TYPE_KW,
"undefined" => UNDEFINED_KW,
"unique" => UNIQUE_KW,
"unknown" => UNKNOWN_KW,
"from" => FROM_KW,
"global" => GLOBAL_KW,
"bigint" => BIGINT_KW,
"override" => OVERRIDE_KW,
"of" => OF_KW,
"out" => OUT_KW,
"using" => USING_KW,
_ => return None,
};
Some(kw)
}
pub const fn to_string(&self) -> Option<&'static str> {
let tok = match self {
SEMICOLON => ";",
COMMA => ",",
L_PAREN => "(",
R_PAREN => ")",
L_CURLY => "{",
R_CURLY => "}",
L_BRACK => "[",
R_BRACK => "]",
L_ANGLE => "<",
R_ANGLE => ">",
TILDE => "~",
QUESTION => "?",
QUESTION2 => "??",
QUESTIONDOT => "?.",
AMP => "&",
PIPE => "|",
PLUS => "+",
PLUS2 => "++",
STAR => "*",
STAR2 => "**",
SLASH => "/",
CARET => "^",
PERCENT => "%",
DOT => ".",
DOT3 => "...",
COLON => ":",
EQ => "=",
EQ2 => "==",
EQ3 => "===",
FAT_ARROW => "=>",
BANG => "!",
NEQ => "!=",
NEQ2 => "!==",
MINUS => "-",
MINUS2 => "--",
LTEQ => "<=",
GTEQ => ">=",
PLUSEQ => "+=",
MINUSEQ => "-=",
PIPEEQ => "|=",
AMPEQ => "&=",
CARETEQ => "^=",
SLASHEQ => "/=",
STAREQ => "*=",
PERCENTEQ => "%=",
AMP2 => "&&",
PIPE2 => "||",
SHL => "<<",
SHR => ">>",
USHR => ">>>",
SHLEQ => "<<=",
SHREQ => ">>=",
USHREQ => ">>>=",
AMP2EQ => "&&=",
PIPE2EQ => "||=",
STAR2EQ => "**=",
QUESTION2EQ => "??=",
AT => "@",
BACKTICK => "`",
BREAK_KW => "break",
CASE_KW => "case",
CATCH_KW => "catch",
CLASS_KW => "class",
CONST_KW => "const",
CONTINUE_KW => "continue",
DEBUGGER_KW => "debugger",
DEFAULT_KW => "default",
DELETE_KW => "delete",
DO_KW => "do",
ELSE_KW => "else",
ENUM_KW => "enum",
EXPORT_KW => "export",
EXTENDS_KW => "extends",
FALSE_KW => "false",
FINALLY_KW => "finally",
FOR_KW => "for",
FUNCTION_KW => "function",
IF_KW => "if",
IN_KW => "in",
INSTANCEOF_KW => "instanceof",
IMPORT_KW => "import",
NEW_KW => "new",
NULL_KW => "null",
RETURN_KW => "return",
SUPER_KW => "super",
SWITCH_KW => "switch",
THIS_KW => "this",
THROW_KW => "throw",
TRY_KW => "try",
TRUE_KW => "true",
TYPEOF_KW => "typeof",
VAR_KW => "var",
VOID_KW => "void",
WHILE_KW => "while",
WITH_KW => "with",
IMPLEMENTS_KW => "implements",
INTERFACE_KW => "interface",
LET_KW => "let",
PACKAGE_KW => "package",
PRIVATE_KW => "private",
PROTECTED_KW => "protected",
PUBLIC_KW => "public",
STATIC_KW => "static",
YIELD_KW => "yield",
ABSTRACT_KW => "abstract",
ACCESSOR_KW => "accessor",
AS_KW => "as",
SATISFIES_KW => "satisfies",
ASSERTS_KW => "asserts",
ASSERT_KW => "assert",
ANY_KW => "any",
ASYNC_KW => "async",
AWAIT_KW => "await",
BOOLEAN_KW => "boolean",
CONSTRUCTOR_KW => "constructor",
DECLARE_KW => "declare",
GET_KW => "get",
INFER_KW => "infer",
IS_KW => "is",
KEYOF_KW => "keyof",
MODULE_KW => "module",
NAMESPACE_KW => "namespace",
NEVER_KW => "never",
READONLY_KW => "readonly",
REQUIRE_KW => "require",
NUMBER_KW => "number",
OBJECT_KW => "object",
SET_KW => "set",
STRING_KW => "string",
SYMBOL_KW => "symbol",
TYPE_KW => "type",
UNDEFINED_KW => "undefined",
UNIQUE_KW => "unique",
UNKNOWN_KW => "unknown",
FROM_KW => "from",
GLOBAL_KW => "global",
BIGINT_KW => "bigint",
OVERRIDE_KW => "override",
OF_KW => "of",
OUT_KW => "out",
USING_KW => "using",
JS_STRING_LITERAL => "string literal",
_ => return None,
};
Some(tok)
}
}
#[doc = r" Utility macro for creating a SyntaxKind through simple macro syntax"]
#[macro_export]
macro_rules ! T { [;] => { $ crate :: JsSyntaxKind :: SEMICOLON } ; [,] => { $ crate :: JsSyntaxKind :: COMMA } ; ['('] => { $ crate :: JsSyntaxKind :: L_PAREN } ; [')'] => { $ crate :: JsSyntaxKind :: R_PAREN } ; ['{'] => { $ crate :: JsSyntaxKind :: L_CURLY } ; ['}'] => { $ crate :: JsSyntaxKind :: R_CURLY } ; ['['] => { $ crate :: JsSyntaxKind :: L_BRACK } ; [']'] => { $ crate :: JsSyntaxKind :: R_BRACK } ; [<] => { $ crate :: JsSyntaxKind :: L_ANGLE } ; [>] => { $ crate :: JsSyntaxKind :: R_ANGLE } ; [~] => { $ crate :: JsSyntaxKind :: TILDE } ; [?] => { $ crate :: JsSyntaxKind :: QUESTION } ; [??] => { $ crate :: JsSyntaxKind :: QUESTION2 } ; [?.] => { $ crate :: JsSyntaxKind :: QUESTIONDOT } ; [&] => { $ crate :: JsSyntaxKind :: AMP } ; [|] => { $ crate :: JsSyntaxKind :: PIPE } ; [+] => { $ crate :: JsSyntaxKind :: PLUS } ; [++] => { $ crate :: JsSyntaxKind :: PLUS2 } ; [*] => { $ crate :: JsSyntaxKind :: STAR } ; [**] => { $ crate :: JsSyntaxKind :: STAR2 } ; [/] => { $ crate :: JsSyntaxKind :: SLASH } ; [^] => { $ crate :: JsSyntaxKind :: CARET } ; [%] => { $ crate :: JsSyntaxKind :: PERCENT } ; [.] => { $ crate :: JsSyntaxKind :: DOT } ; [...] => { $ crate :: JsSyntaxKind :: DOT3 } ; [:] => { $ crate :: JsSyntaxKind :: COLON } ; [=] => { $ crate :: JsSyntaxKind :: EQ } ; [==] => { $ crate :: JsSyntaxKind :: EQ2 } ; [===] => { $ crate :: JsSyntaxKind :: EQ3 } ; [=>] => { $ crate :: JsSyntaxKind :: FAT_ARROW } ; [!] => { $ crate :: JsSyntaxKind :: BANG } ; [!=] => { $ crate :: JsSyntaxKind :: NEQ } ; [!==] => { $ crate :: JsSyntaxKind :: NEQ2 } ; [-] => { $ crate :: JsSyntaxKind :: MINUS } ; [--] => { $ crate :: JsSyntaxKind :: MINUS2 } ; [<=] => { $ crate :: JsSyntaxKind :: LTEQ } ; [>=] => { $ crate :: JsSyntaxKind :: GTEQ } ; [+=] => { $ crate :: JsSyntaxKind :: PLUSEQ } ; [-=] => { $ crate :: JsSyntaxKind :: MINUSEQ } ; [|=] => { $ crate :: JsSyntaxKind :: PIPEEQ } ; [&=] => { $ crate :: JsSyntaxKind :: AMPEQ } ; [^=] => { $ crate :: JsSyntaxKind :: CARETEQ } ; [/=] => { $ crate :: JsSyntaxKind :: SLASHEQ } ; [*=] => { $ crate :: JsSyntaxKind :: STAREQ } ; [%=] => { $ crate :: JsSyntaxKind :: PERCENTEQ } ; [&&] => { $ crate :: JsSyntaxKind :: AMP2 } ; [||] => { $ crate :: JsSyntaxKind :: PIPE2 } ; [<<] => { $ crate :: JsSyntaxKind :: SHL } ; [>>] => { $ crate :: JsSyntaxKind :: SHR } ; [>>>] => { $ crate :: JsSyntaxKind :: USHR } ; [<<=] => { $ crate :: JsSyntaxKind :: SHLEQ } ; [>>=] => { $ crate :: JsSyntaxKind :: SHREQ } ; [>>>=] => { $ crate :: JsSyntaxKind :: USHREQ } ; [&&=] => { $ crate :: JsSyntaxKind :: AMP2EQ } ; [||=] => { $ crate :: JsSyntaxKind :: PIPE2EQ } ; [**=] => { $ crate :: JsSyntaxKind :: STAR2EQ } ; [??=] => { $ crate :: JsSyntaxKind :: QUESTION2EQ } ; [@] => { $ crate :: JsSyntaxKind :: AT } ; ['`'] => { $ crate :: JsSyntaxKind :: BACKTICK } ; [break] => { $ crate :: JsSyntaxKind :: BREAK_KW } ; [case] => { $ crate :: JsSyntaxKind :: CASE_KW } ; [catch] => { $ crate :: JsSyntaxKind :: CATCH_KW } ; [class] => { $ crate :: JsSyntaxKind :: CLASS_KW } ; [const] => { $ crate :: JsSyntaxKind :: CONST_KW } ; [continue] => { $ crate :: JsSyntaxKind :: CONTINUE_KW } ; [debugger] => { $ crate :: JsSyntaxKind :: DEBUGGER_KW } ; [default] => { $ crate :: JsSyntaxKind :: DEFAULT_KW } ; [delete] => { $ crate :: JsSyntaxKind :: DELETE_KW } ; [do] => { $ crate :: JsSyntaxKind :: DO_KW } ; [else] => { $ crate :: JsSyntaxKind :: ELSE_KW } ; [enum] => { $ crate :: JsSyntaxKind :: ENUM_KW } ; [export] => { $ crate :: JsSyntaxKind :: EXPORT_KW } ; [extends] => { $ crate :: JsSyntaxKind :: EXTENDS_KW } ; [false] => { $ crate :: JsSyntaxKind :: FALSE_KW } ; [finally] => { $ crate :: JsSyntaxKind :: FINALLY_KW } ; [for] => { $ crate :: JsSyntaxKind :: FOR_KW } ; [function] => { $ crate :: JsSyntaxKind :: FUNCTION_KW } ; [if] => { $ crate :: JsSyntaxKind :: IF_KW } ; [in] => { $ crate :: JsSyntaxKind :: IN_KW } ; [instanceof] => { $ crate :: JsSyntaxKind :: INSTANCEOF_KW } ; [import] => { $ crate :: JsSyntaxKind :: IMPORT_KW } ; [new] => { $ crate :: JsSyntaxKind :: NEW_KW } ; [null] => { $ crate :: JsSyntaxKind :: NULL_KW } ; [return] => { $ crate :: JsSyntaxKind :: RETURN_KW } ; [super] => { $ crate :: JsSyntaxKind :: SUPER_KW } ; [switch] => { $ crate :: JsSyntaxKind :: SWITCH_KW } ; [this] => { $ crate :: JsSyntaxKind :: THIS_KW } ; [throw] => { $ crate :: JsSyntaxKind :: THROW_KW } ; [try] => { $ crate :: JsSyntaxKind :: TRY_KW } ; [true] => { $ crate :: JsSyntaxKind :: TRUE_KW } ; [typeof] => { $ crate :: JsSyntaxKind :: TYPEOF_KW } ; [var] => { $ crate :: JsSyntaxKind :: VAR_KW } ; [void] => { $ crate :: JsSyntaxKind :: VOID_KW } ; [while] => { $ crate :: JsSyntaxKind :: WHILE_KW } ; [with] => { $ crate :: JsSyntaxKind :: WITH_KW } ; [implements] => { $ crate :: JsSyntaxKind :: IMPLEMENTS_KW } ; [interface] => { $ crate :: JsSyntaxKind :: INTERFACE_KW } ; [let] => { $ crate :: JsSyntaxKind :: LET_KW } ; [package] => { $ crate :: JsSyntaxKind :: PACKAGE_KW } ; [private] => { $ crate :: JsSyntaxKind :: PRIVATE_KW } ; [protected] => { $ crate :: JsSyntaxKind :: PROTECTED_KW } ; [public] => { $ crate :: JsSyntaxKind :: PUBLIC_KW } ; [static] => { $ crate :: JsSyntaxKind :: STATIC_KW } ; [yield] => { $ crate :: JsSyntaxKind :: YIELD_KW } ; [abstract] => { $ crate :: JsSyntaxKind :: ABSTRACT_KW } ; [accessor] => { $ crate :: JsSyntaxKind :: ACCESSOR_KW } ; [as] => { $ crate :: JsSyntaxKind :: AS_KW } ; [satisfies] => { $ crate :: JsSyntaxKind :: SATISFIES_KW } ; [asserts] => { $ crate :: JsSyntaxKind :: ASSERTS_KW } ; [assert] => { $ crate :: JsSyntaxKind :: ASSERT_KW } ; [any] => { $ crate :: JsSyntaxKind :: ANY_KW } ; [async] => { $ crate :: JsSyntaxKind :: ASYNC_KW } ; [await] => { $ crate :: JsSyntaxKind :: AWAIT_KW } ; [boolean] => { $ crate :: JsSyntaxKind :: BOOLEAN_KW } ; [constructor] => { $ crate :: JsSyntaxKind :: CONSTRUCTOR_KW } ; [declare] => { $ crate :: JsSyntaxKind :: DECLARE_KW } ; [get] => { $ crate :: JsSyntaxKind :: GET_KW } ; [infer] => { $ crate :: JsSyntaxKind :: INFER_KW } ; [is] => { $ crate :: JsSyntaxKind :: IS_KW } ; [keyof] => { $ crate :: JsSyntaxKind :: KEYOF_KW } ; [module] => { $ crate :: JsSyntaxKind :: MODULE_KW } ; [namespace] => { $ crate :: JsSyntaxKind :: NAMESPACE_KW } ; [never] => { $ crate :: JsSyntaxKind :: NEVER_KW } ; [readonly] => { $ crate :: JsSyntaxKind :: READONLY_KW } ; [require] => { $ crate :: JsSyntaxKind :: REQUIRE_KW } ; [number] => { $ crate :: JsSyntaxKind :: NUMBER_KW } ; [object] => { $ crate :: JsSyntaxKind :: OBJECT_KW } ; [set] => { $ crate :: JsSyntaxKind :: SET_KW } ; [string] => { $ crate :: JsSyntaxKind :: STRING_KW } ; [symbol] => { $ crate :: JsSyntaxKind :: SYMBOL_KW } ; [type] => { $ crate :: JsSyntaxKind :: TYPE_KW } ; [undefined] => { $ crate :: JsSyntaxKind :: UNDEFINED_KW } ; [unique] => { $ crate :: JsSyntaxKind :: UNIQUE_KW } ; [unknown] => { $ crate :: JsSyntaxKind :: UNKNOWN_KW } ; [from] => { $ crate :: JsSyntaxKind :: FROM_KW } ; [global] => { $ crate :: JsSyntaxKind :: GLOBAL_KW } ; [bigint] => { $ crate :: JsSyntaxKind :: BIGINT_KW } ; [override] => { $ crate :: JsSyntaxKind :: OVERRIDE_KW } ; [of] => { $ crate :: JsSyntaxKind :: OF_KW } ; [out] => { $ crate :: JsSyntaxKind :: OUT_KW } ; [using] => { $ crate :: JsSyntaxKind :: USING_KW } ; [ident] => { $ crate :: JsSyntaxKind :: IDENT } ; [EOF] => { $ crate :: JsSyntaxKind :: EOF } ; [#] => { $ crate :: JsSyntaxKind :: HASH } ; }
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/generated/macros.rs | crates/rome_js_syntax/src/generated/macros.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
#[doc = r" Reconstruct an AstNode from a SyntaxNode"]
#[doc = r""]
#[doc = r" This macros performs a match over the [kind](rome_rowan::SyntaxNode::kind)"]
#[doc = r" of the provided [rome_rowan::SyntaxNode] and constructs the appropriate"]
#[doc = r" AstNode type for it, then execute the provided expression over it."]
#[doc = r""]
#[doc = r" # Examples"]
#[doc = r""]
#[doc = r" ```ignore"]
#[doc = r" map_syntax_node!(syntax_node, node => node.format())"]
#[doc = r" ```"]
#[macro_export]
macro_rules! map_syntax_node {
($ node : expr , $ pattern : pat => $ body : expr) => {
match $node {
node => match $crate::JsSyntaxNode::kind(&node) {
$crate::JsSyntaxKind::JS_ACCESSOR_MODIFIER => {
let $pattern = unsafe { $crate::JsAccessorModifier::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_ARRAY_ASSIGNMENT_PATTERN => {
let $pattern = unsafe { $crate::JsArrayAssignmentPattern::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_ARRAY_ASSIGNMENT_PATTERN_REST_ELEMENT => {
let $pattern =
unsafe { $crate::JsArrayAssignmentPatternRestElement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_ARRAY_BINDING_PATTERN => {
let $pattern = unsafe { $crate::JsArrayBindingPattern::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_ARRAY_BINDING_PATTERN_REST_ELEMENT => {
let $pattern =
unsafe { $crate::JsArrayBindingPatternRestElement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_ARRAY_EXPRESSION => {
let $pattern = unsafe { $crate::JsArrayExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_ARRAY_HOLE => {
let $pattern = unsafe { $crate::JsArrayHole::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_ARROW_FUNCTION_EXPRESSION => {
let $pattern =
unsafe { $crate::JsArrowFunctionExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_ASSIGNMENT_EXPRESSION => {
let $pattern = unsafe { $crate::JsAssignmentExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_ASSIGNMENT_WITH_DEFAULT => {
let $pattern = unsafe { $crate::JsAssignmentWithDefault::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_AWAIT_EXPRESSION => {
let $pattern = unsafe { $crate::JsAwaitExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_BIGINT_LITERAL_EXPRESSION => {
let $pattern =
unsafe { $crate::JsBigintLiteralExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_BINARY_EXPRESSION => {
let $pattern = unsafe { $crate::JsBinaryExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_BINDING_PATTERN_WITH_DEFAULT => {
let $pattern =
unsafe { $crate::JsBindingPatternWithDefault::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_BLOCK_STATEMENT => {
let $pattern = unsafe { $crate::JsBlockStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_BOOLEAN_LITERAL_EXPRESSION => {
let $pattern =
unsafe { $crate::JsBooleanLiteralExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_BREAK_STATEMENT => {
let $pattern = unsafe { $crate::JsBreakStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_CALL_ARGUMENTS => {
let $pattern = unsafe { $crate::JsCallArguments::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_CALL_EXPRESSION => {
let $pattern = unsafe { $crate::JsCallExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_CASE_CLAUSE => {
let $pattern = unsafe { $crate::JsCaseClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_CATCH_CLAUSE => {
let $pattern = unsafe { $crate::JsCatchClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_CATCH_DECLARATION => {
let $pattern = unsafe { $crate::JsCatchDeclaration::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_CLASS_DECLARATION => {
let $pattern = unsafe { $crate::JsClassDeclaration::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_CLASS_EXPORT_DEFAULT_DECLARATION => {
let $pattern =
unsafe { $crate::JsClassExportDefaultDeclaration::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_CLASS_EXPRESSION => {
let $pattern = unsafe { $crate::JsClassExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_COMPUTED_MEMBER_ASSIGNMENT => {
let $pattern =
unsafe { $crate::JsComputedMemberAssignment::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_COMPUTED_MEMBER_EXPRESSION => {
let $pattern =
unsafe { $crate::JsComputedMemberExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_COMPUTED_MEMBER_NAME => {
let $pattern = unsafe { $crate::JsComputedMemberName::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_CONDITIONAL_EXPRESSION => {
let $pattern = unsafe { $crate::JsConditionalExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_CONSTRUCTOR_CLASS_MEMBER => {
let $pattern = unsafe { $crate::JsConstructorClassMember::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_CONSTRUCTOR_PARAMETERS => {
let $pattern = unsafe { $crate::JsConstructorParameters::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_CONTINUE_STATEMENT => {
let $pattern = unsafe { $crate::JsContinueStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_DEBUGGER_STATEMENT => {
let $pattern = unsafe { $crate::JsDebuggerStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_DECORATOR => {
let $pattern = unsafe { $crate::JsDecorator::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_DEFAULT_CLAUSE => {
let $pattern = unsafe { $crate::JsDefaultClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_DEFAULT_IMPORT_SPECIFIER => {
let $pattern = unsafe { $crate::JsDefaultImportSpecifier::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_DIRECTIVE => {
let $pattern = unsafe { $crate::JsDirective::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_DO_WHILE_STATEMENT => {
let $pattern = unsafe { $crate::JsDoWhileStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_ELSE_CLAUSE => {
let $pattern = unsafe { $crate::JsElseClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_EMPTY_CLASS_MEMBER => {
let $pattern = unsafe { $crate::JsEmptyClassMember::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_EMPTY_STATEMENT => {
let $pattern = unsafe { $crate::JsEmptyStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_EXPORT => {
let $pattern = unsafe { $crate::JsExport::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_EXPORT_AS_CLAUSE => {
let $pattern = unsafe { $crate::JsExportAsClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_EXPORT_DEFAULT_DECLARATION_CLAUSE => {
let $pattern =
unsafe { $crate::JsExportDefaultDeclarationClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_EXPORT_DEFAULT_EXPRESSION_CLAUSE => {
let $pattern =
unsafe { $crate::JsExportDefaultExpressionClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_EXPORT_FROM_CLAUSE => {
let $pattern = unsafe { $crate::JsExportFromClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_EXPORT_NAMED_CLAUSE => {
let $pattern = unsafe { $crate::JsExportNamedClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_EXPORT_NAMED_FROM_CLAUSE => {
let $pattern = unsafe { $crate::JsExportNamedFromClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_EXPORT_NAMED_FROM_SPECIFIER => {
let $pattern =
unsafe { $crate::JsExportNamedFromSpecifier::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_EXPORT_NAMED_SHORTHAND_SPECIFIER => {
let $pattern =
unsafe { $crate::JsExportNamedShorthandSpecifier::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_EXPORT_NAMED_SPECIFIER => {
let $pattern = unsafe { $crate::JsExportNamedSpecifier::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_EXPRESSION_SNIPPED => {
let $pattern = unsafe { $crate::JsExpressionSnipped::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_EXPRESSION_STATEMENT => {
let $pattern = unsafe { $crate::JsExpressionStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_EXTENDS_CLAUSE => {
let $pattern = unsafe { $crate::JsExtendsClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_FINALLY_CLAUSE => {
let $pattern = unsafe { $crate::JsFinallyClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_FOR_IN_STATEMENT => {
let $pattern = unsafe { $crate::JsForInStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_FOR_OF_STATEMENT => {
let $pattern = unsafe { $crate::JsForOfStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_FOR_STATEMENT => {
let $pattern = unsafe { $crate::JsForStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_FOR_VARIABLE_DECLARATION => {
let $pattern = unsafe { $crate::JsForVariableDeclaration::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_FORMAL_PARAMETER => {
let $pattern = unsafe { $crate::JsFormalParameter::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_FUNCTION_BODY => {
let $pattern = unsafe { $crate::JsFunctionBody::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_FUNCTION_DECLARATION => {
let $pattern = unsafe { $crate::JsFunctionDeclaration::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_FUNCTION_EXPORT_DEFAULT_DECLARATION => {
let $pattern =
unsafe { $crate::JsFunctionExportDefaultDeclaration::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_FUNCTION_EXPRESSION => {
let $pattern = unsafe { $crate::JsFunctionExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_GETTER_CLASS_MEMBER => {
let $pattern = unsafe { $crate::JsGetterClassMember::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_GETTER_OBJECT_MEMBER => {
let $pattern = unsafe { $crate::JsGetterObjectMember::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_IDENTIFIER_ASSIGNMENT => {
let $pattern = unsafe { $crate::JsIdentifierAssignment::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_IDENTIFIER_BINDING => {
let $pattern = unsafe { $crate::JsIdentifierBinding::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_IDENTIFIER_EXPRESSION => {
let $pattern = unsafe { $crate::JsIdentifierExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_IF_STATEMENT => {
let $pattern = unsafe { $crate::JsIfStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_IMPORT => {
let $pattern = unsafe { $crate::JsImport::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_IMPORT_ASSERTION => {
let $pattern = unsafe { $crate::JsImportAssertion::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_IMPORT_ASSERTION_ENTRY => {
let $pattern = unsafe { $crate::JsImportAssertionEntry::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_IMPORT_BARE_CLAUSE => {
let $pattern = unsafe { $crate::JsImportBareClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_IMPORT_CALL_EXPRESSION => {
let $pattern = unsafe { $crate::JsImportCallExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_IMPORT_DEFAULT_CLAUSE => {
let $pattern = unsafe { $crate::JsImportDefaultClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_IMPORT_META_EXPRESSION => {
let $pattern = unsafe { $crate::JsImportMetaExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_IMPORT_NAMED_CLAUSE => {
let $pattern = unsafe { $crate::JsImportNamedClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_IMPORT_NAMESPACE_CLAUSE => {
let $pattern = unsafe { $crate::JsImportNamespaceClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_IN_EXPRESSION => {
let $pattern = unsafe { $crate::JsInExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_INITIALIZER_CLAUSE => {
let $pattern = unsafe { $crate::JsInitializerClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_INSTANCEOF_EXPRESSION => {
let $pattern = unsafe { $crate::JsInstanceofExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_LABELED_STATEMENT => {
let $pattern = unsafe { $crate::JsLabeledStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_LITERAL_EXPORT_NAME => {
let $pattern = unsafe { $crate::JsLiteralExportName::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_LITERAL_MEMBER_NAME => {
let $pattern = unsafe { $crate::JsLiteralMemberName::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_LOGICAL_EXPRESSION => {
let $pattern = unsafe { $crate::JsLogicalExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_METHOD_CLASS_MEMBER => {
let $pattern = unsafe { $crate::JsMethodClassMember::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_METHOD_OBJECT_MEMBER => {
let $pattern = unsafe { $crate::JsMethodObjectMember::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_MODULE => {
let $pattern = unsafe { $crate::JsModule::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_MODULE_SOURCE => {
let $pattern = unsafe { $crate::JsModuleSource::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_NAME => {
let $pattern = unsafe { $crate::JsName::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_NAMED_IMPORT_SPECIFIER => {
let $pattern = unsafe { $crate::JsNamedImportSpecifier::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_NAMED_IMPORT_SPECIFIERS => {
let $pattern = unsafe { $crate::JsNamedImportSpecifiers::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_NAMESPACE_IMPORT_SPECIFIER => {
let $pattern =
unsafe { $crate::JsNamespaceImportSpecifier::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_NEW_EXPRESSION => {
let $pattern = unsafe { $crate::JsNewExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_NEW_TARGET_EXPRESSION => {
let $pattern = unsafe { $crate::JsNewTargetExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_NULL_LITERAL_EXPRESSION => {
let $pattern = unsafe { $crate::JsNullLiteralExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_NUMBER_LITERAL_EXPRESSION => {
let $pattern =
unsafe { $crate::JsNumberLiteralExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_OBJECT_ASSIGNMENT_PATTERN => {
let $pattern =
unsafe { $crate::JsObjectAssignmentPattern::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_OBJECT_ASSIGNMENT_PATTERN_PROPERTY => {
let $pattern =
unsafe { $crate::JsObjectAssignmentPatternProperty::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_OBJECT_ASSIGNMENT_PATTERN_REST => {
let $pattern =
unsafe { $crate::JsObjectAssignmentPatternRest::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_OBJECT_ASSIGNMENT_PATTERN_SHORTHAND_PROPERTY => {
let $pattern = unsafe {
$crate::JsObjectAssignmentPatternShorthandProperty::new_unchecked(node)
};
$body
}
$crate::JsSyntaxKind::JS_OBJECT_BINDING_PATTERN => {
let $pattern = unsafe { $crate::JsObjectBindingPattern::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_OBJECT_BINDING_PATTERN_PROPERTY => {
let $pattern =
unsafe { $crate::JsObjectBindingPatternProperty::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_OBJECT_BINDING_PATTERN_REST => {
let $pattern =
unsafe { $crate::JsObjectBindingPatternRest::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_OBJECT_BINDING_PATTERN_SHORTHAND_PROPERTY => {
let $pattern = unsafe {
$crate::JsObjectBindingPatternShorthandProperty::new_unchecked(node)
};
$body
}
$crate::JsSyntaxKind::JS_OBJECT_EXPRESSION => {
let $pattern = unsafe { $crate::JsObjectExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_PARAMETERS => {
let $pattern = unsafe { $crate::JsParameters::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_PARENTHESIZED_ASSIGNMENT => {
let $pattern =
unsafe { $crate::JsParenthesizedAssignment::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_PARENTHESIZED_EXPRESSION => {
let $pattern =
unsafe { $crate::JsParenthesizedExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_POST_UPDATE_EXPRESSION => {
let $pattern = unsafe { $crate::JsPostUpdateExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_PRE_UPDATE_EXPRESSION => {
let $pattern = unsafe { $crate::JsPreUpdateExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_PRIVATE_CLASS_MEMBER_NAME => {
let $pattern = unsafe { $crate::JsPrivateClassMemberName::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_PRIVATE_NAME => {
let $pattern = unsafe { $crate::JsPrivateName::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_PROPERTY_CLASS_MEMBER => {
let $pattern = unsafe { $crate::JsPropertyClassMember::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_PROPERTY_OBJECT_MEMBER => {
let $pattern = unsafe { $crate::JsPropertyObjectMember::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_REFERENCE_IDENTIFIER => {
let $pattern = unsafe { $crate::JsReferenceIdentifier::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_REGEX_LITERAL_EXPRESSION => {
let $pattern = unsafe { $crate::JsRegexLiteralExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_REST_PARAMETER => {
let $pattern = unsafe { $crate::JsRestParameter::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_RETURN_STATEMENT => {
let $pattern = unsafe { $crate::JsReturnStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_SCRIPT => {
let $pattern = unsafe { $crate::JsScript::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_SEQUENCE_EXPRESSION => {
let $pattern = unsafe { $crate::JsSequenceExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_SETTER_CLASS_MEMBER => {
let $pattern = unsafe { $crate::JsSetterClassMember::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_SETTER_OBJECT_MEMBER => {
let $pattern = unsafe { $crate::JsSetterObjectMember::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_SHORTHAND_NAMED_IMPORT_SPECIFIER => {
let $pattern =
unsafe { $crate::JsShorthandNamedImportSpecifier::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_SHORTHAND_PROPERTY_OBJECT_MEMBER => {
let $pattern =
unsafe { $crate::JsShorthandPropertyObjectMember::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_SPREAD => {
let $pattern = unsafe { $crate::JsSpread::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_STATIC_INITIALIZATION_BLOCK_CLASS_MEMBER => {
let $pattern = unsafe {
$crate::JsStaticInitializationBlockClassMember::new_unchecked(node)
};
$body
}
$crate::JsSyntaxKind::JS_STATIC_MEMBER_ASSIGNMENT => {
let $pattern = unsafe { $crate::JsStaticMemberAssignment::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_STATIC_MEMBER_EXPRESSION => {
let $pattern = unsafe { $crate::JsStaticMemberExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_STATIC_MODIFIER => {
let $pattern = unsafe { $crate::JsStaticModifier::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_STRING_LITERAL_EXPRESSION => {
let $pattern =
unsafe { $crate::JsStringLiteralExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_SUPER_EXPRESSION => {
let $pattern = unsafe { $crate::JsSuperExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_SWITCH_STATEMENT => {
let $pattern = unsafe { $crate::JsSwitchStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_TEMPLATE_CHUNK_ELEMENT => {
let $pattern = unsafe { $crate::JsTemplateChunkElement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_TEMPLATE_ELEMENT => {
let $pattern = unsafe { $crate::JsTemplateElement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_TEMPLATE_EXPRESSION => {
let $pattern = unsafe { $crate::JsTemplateExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_THIS_EXPRESSION => {
let $pattern = unsafe { $crate::JsThisExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_THROW_STATEMENT => {
let $pattern = unsafe { $crate::JsThrowStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_TRY_FINALLY_STATEMENT => {
let $pattern = unsafe { $crate::JsTryFinallyStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_TRY_STATEMENT => {
let $pattern = unsafe { $crate::JsTryStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_UNARY_EXPRESSION => {
let $pattern = unsafe { $crate::JsUnaryExpression::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_VARIABLE_DECLARATION => {
let $pattern = unsafe { $crate::JsVariableDeclaration::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_VARIABLE_DECLARATION_CLAUSE => {
let $pattern =
unsafe { $crate::JsVariableDeclarationClause::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_VARIABLE_DECLARATOR => {
let $pattern = unsafe { $crate::JsVariableDeclarator::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_VARIABLE_STATEMENT => {
let $pattern = unsafe { $crate::JsVariableStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_WHILE_STATEMENT => {
let $pattern = unsafe { $crate::JsWhileStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_WITH_STATEMENT => {
let $pattern = unsafe { $crate::JsWithStatement::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_YIELD_ARGUMENT => {
let $pattern = unsafe { $crate::JsYieldArgument::new_unchecked(node) };
$body
}
$crate::JsSyntaxKind::JS_YIELD_EXPRESSION => {
let $pattern = unsafe { $crate::JsYieldExpression::new_unchecked(node) };
$body
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_syntax/src/generated/nodes.rs | crates/rome_js_syntax/src/generated/nodes.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
#![allow(clippy::enum_variant_names)]
#![allow(clippy::match_like_matches_macro)]
use crate::{
macros::map_syntax_node,
JsLanguage as Language, JsSyntaxElement as SyntaxElement,
JsSyntaxElementChildren as SyntaxElementChildren,
JsSyntaxKind::{self as SyntaxKind, *},
JsSyntaxList as SyntaxList, JsSyntaxNode as SyntaxNode, JsSyntaxToken as SyntaxToken,
};
use rome_rowan::{support, AstNode, RawSyntaxKind, SyntaxKindSet, SyntaxResult};
#[allow(unused)]
use rome_rowan::{
AstNodeList, AstNodeListIterator, AstSeparatedList, AstSeparatedListNodesIterator,
};
#[cfg(feature = "serde")]
use serde::ser::SerializeSeq;
#[cfg(feature = "serde")]
use serde::{Serialize, Serializer};
use std::fmt::{Debug, Formatter};
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsAccessorModifier {
pub(crate) syntax: SyntaxNode,
}
impl JsAccessorModifier {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsAccessorModifierFields {
JsAccessorModifierFields {
modifier_token: self.modifier_token(),
}
}
pub fn modifier_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 0usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsAccessorModifier {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsAccessorModifierFields {
pub modifier_token: SyntaxResult<SyntaxToken>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsArrayAssignmentPattern {
pub(crate) syntax: SyntaxNode,
}
impl JsArrayAssignmentPattern {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsArrayAssignmentPatternFields {
JsArrayAssignmentPatternFields {
l_brack_token: self.l_brack_token(),
elements: self.elements(),
r_brack_token: self.r_brack_token(),
}
}
pub fn l_brack_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 0usize)
}
pub fn elements(&self) -> JsArrayAssignmentPatternElementList {
support::list(&self.syntax, 1usize)
}
pub fn r_brack_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 2usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsArrayAssignmentPattern {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsArrayAssignmentPatternFields {
pub l_brack_token: SyntaxResult<SyntaxToken>,
pub elements: JsArrayAssignmentPatternElementList,
pub r_brack_token: SyntaxResult<SyntaxToken>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsArrayAssignmentPatternRestElement {
pub(crate) syntax: SyntaxNode,
}
impl JsArrayAssignmentPatternRestElement {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsArrayAssignmentPatternRestElementFields {
JsArrayAssignmentPatternRestElementFields {
dotdotdot_token: self.dotdotdot_token(),
pattern: self.pattern(),
}
}
pub fn dotdotdot_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 0usize)
}
pub fn pattern(&self) -> SyntaxResult<AnyJsAssignmentPattern> {
support::required_node(&self.syntax, 1usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsArrayAssignmentPatternRestElement {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsArrayAssignmentPatternRestElementFields {
pub dotdotdot_token: SyntaxResult<SyntaxToken>,
pub pattern: SyntaxResult<AnyJsAssignmentPattern>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsArrayBindingPattern {
pub(crate) syntax: SyntaxNode,
}
impl JsArrayBindingPattern {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsArrayBindingPatternFields {
JsArrayBindingPatternFields {
l_brack_token: self.l_brack_token(),
elements: self.elements(),
r_brack_token: self.r_brack_token(),
}
}
pub fn l_brack_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 0usize)
}
pub fn elements(&self) -> JsArrayBindingPatternElementList {
support::list(&self.syntax, 1usize)
}
pub fn r_brack_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 2usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsArrayBindingPattern {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsArrayBindingPatternFields {
pub l_brack_token: SyntaxResult<SyntaxToken>,
pub elements: JsArrayBindingPatternElementList,
pub r_brack_token: SyntaxResult<SyntaxToken>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsArrayBindingPatternRestElement {
pub(crate) syntax: SyntaxNode,
}
impl JsArrayBindingPatternRestElement {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsArrayBindingPatternRestElementFields {
JsArrayBindingPatternRestElementFields {
dotdotdot_token: self.dotdotdot_token(),
pattern: self.pattern(),
}
}
pub fn dotdotdot_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 0usize)
}
pub fn pattern(&self) -> SyntaxResult<AnyJsBindingPattern> {
support::required_node(&self.syntax, 1usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsArrayBindingPatternRestElement {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsArrayBindingPatternRestElementFields {
pub dotdotdot_token: SyntaxResult<SyntaxToken>,
pub pattern: SyntaxResult<AnyJsBindingPattern>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsArrayExpression {
pub(crate) syntax: SyntaxNode,
}
impl JsArrayExpression {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsArrayExpressionFields {
JsArrayExpressionFields {
l_brack_token: self.l_brack_token(),
elements: self.elements(),
r_brack_token: self.r_brack_token(),
}
}
pub fn l_brack_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 0usize)
}
pub fn elements(&self) -> JsArrayElementList { support::list(&self.syntax, 1usize) }
pub fn r_brack_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 2usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsArrayExpression {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsArrayExpressionFields {
pub l_brack_token: SyntaxResult<SyntaxToken>,
pub elements: JsArrayElementList,
pub r_brack_token: SyntaxResult<SyntaxToken>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsArrayHole {
pub(crate) syntax: SyntaxNode,
}
impl JsArrayHole {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsArrayHoleFields { JsArrayHoleFields {} }
}
#[cfg(feature = "serde")]
impl Serialize for JsArrayHole {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsArrayHoleFields {}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsArrowFunctionExpression {
pub(crate) syntax: SyntaxNode,
}
impl JsArrowFunctionExpression {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsArrowFunctionExpressionFields {
JsArrowFunctionExpressionFields {
async_token: self.async_token(),
type_parameters: self.type_parameters(),
parameters: self.parameters(),
return_type_annotation: self.return_type_annotation(),
fat_arrow_token: self.fat_arrow_token(),
body: self.body(),
}
}
pub fn async_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, 0usize) }
pub fn type_parameters(&self) -> Option<TsTypeParameters> {
support::node(&self.syntax, 1usize)
}
pub fn parameters(&self) -> SyntaxResult<AnyJsArrowFunctionParameters> {
support::required_node(&self.syntax, 2usize)
}
pub fn return_type_annotation(&self) -> Option<TsReturnTypeAnnotation> {
support::node(&self.syntax, 3usize)
}
pub fn fat_arrow_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 4usize)
}
pub fn body(&self) -> SyntaxResult<AnyJsFunctionBody> {
support::required_node(&self.syntax, 5usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsArrowFunctionExpression {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsArrowFunctionExpressionFields {
pub async_token: Option<SyntaxToken>,
pub type_parameters: Option<TsTypeParameters>,
pub parameters: SyntaxResult<AnyJsArrowFunctionParameters>,
pub return_type_annotation: Option<TsReturnTypeAnnotation>,
pub fat_arrow_token: SyntaxResult<SyntaxToken>,
pub body: SyntaxResult<AnyJsFunctionBody>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsAssignmentExpression {
pub(crate) syntax: SyntaxNode,
}
impl JsAssignmentExpression {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsAssignmentExpressionFields {
JsAssignmentExpressionFields {
left: self.left(),
operator_token: self.operator_token(),
right: self.right(),
}
}
pub fn left(&self) -> SyntaxResult<AnyJsAssignmentPattern> {
support::required_node(&self.syntax, 0usize)
}
pub fn operator_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 1usize)
}
pub fn right(&self) -> SyntaxResult<AnyJsExpression> {
support::required_node(&self.syntax, 2usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsAssignmentExpression {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsAssignmentExpressionFields {
pub left: SyntaxResult<AnyJsAssignmentPattern>,
pub operator_token: SyntaxResult<SyntaxToken>,
pub right: SyntaxResult<AnyJsExpression>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsAssignmentWithDefault {
pub(crate) syntax: SyntaxNode,
}
impl JsAssignmentWithDefault {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsAssignmentWithDefaultFields {
JsAssignmentWithDefaultFields {
pattern: self.pattern(),
eq_token: self.eq_token(),
default: self.default(),
}
}
pub fn pattern(&self) -> SyntaxResult<AnyJsAssignmentPattern> {
support::required_node(&self.syntax, 0usize)
}
pub fn eq_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 1usize)
}
pub fn default(&self) -> SyntaxResult<AnyJsExpression> {
support::required_node(&self.syntax, 2usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsAssignmentWithDefault {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsAssignmentWithDefaultFields {
pub pattern: SyntaxResult<AnyJsAssignmentPattern>,
pub eq_token: SyntaxResult<SyntaxToken>,
pub default: SyntaxResult<AnyJsExpression>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsAwaitExpression {
pub(crate) syntax: SyntaxNode,
}
impl JsAwaitExpression {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsAwaitExpressionFields {
JsAwaitExpressionFields {
await_token: self.await_token(),
argument: self.argument(),
}
}
pub fn await_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 0usize)
}
pub fn argument(&self) -> SyntaxResult<AnyJsExpression> {
support::required_node(&self.syntax, 1usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsAwaitExpression {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsAwaitExpressionFields {
pub await_token: SyntaxResult<SyntaxToken>,
pub argument: SyntaxResult<AnyJsExpression>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsBigintLiteralExpression {
pub(crate) syntax: SyntaxNode,
}
impl JsBigintLiteralExpression {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsBigintLiteralExpressionFields {
JsBigintLiteralExpressionFields {
value_token: self.value_token(),
}
}
pub fn value_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 0usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsBigintLiteralExpression {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsBigintLiteralExpressionFields {
pub value_token: SyntaxResult<SyntaxToken>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsBinaryExpression {
pub(crate) syntax: SyntaxNode,
}
impl JsBinaryExpression {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsBinaryExpressionFields {
JsBinaryExpressionFields {
left: self.left(),
operator_token: self.operator_token(),
right: self.right(),
}
}
pub fn left(&self) -> SyntaxResult<AnyJsExpression> {
support::required_node(&self.syntax, 0usize)
}
pub fn operator_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 1usize)
}
pub fn right(&self) -> SyntaxResult<AnyJsExpression> {
support::required_node(&self.syntax, 2usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsBinaryExpression {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsBinaryExpressionFields {
pub left: SyntaxResult<AnyJsExpression>,
pub operator_token: SyntaxResult<SyntaxToken>,
pub right: SyntaxResult<AnyJsExpression>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsBindingPatternWithDefault {
pub(crate) syntax: SyntaxNode,
}
impl JsBindingPatternWithDefault {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsBindingPatternWithDefaultFields {
JsBindingPatternWithDefaultFields {
pattern: self.pattern(),
eq_token: self.eq_token(),
default: self.default(),
}
}
pub fn pattern(&self) -> SyntaxResult<AnyJsBindingPattern> {
support::required_node(&self.syntax, 0usize)
}
pub fn eq_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 1usize)
}
pub fn default(&self) -> SyntaxResult<AnyJsExpression> {
support::required_node(&self.syntax, 2usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsBindingPatternWithDefault {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsBindingPatternWithDefaultFields {
pub pattern: SyntaxResult<AnyJsBindingPattern>,
pub eq_token: SyntaxResult<SyntaxToken>,
pub default: SyntaxResult<AnyJsExpression>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsBlockStatement {
pub(crate) syntax: SyntaxNode,
}
impl JsBlockStatement {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsBlockStatementFields {
JsBlockStatementFields {
l_curly_token: self.l_curly_token(),
statements: self.statements(),
r_curly_token: self.r_curly_token(),
}
}
pub fn l_curly_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 0usize)
}
pub fn statements(&self) -> JsStatementList { support::list(&self.syntax, 1usize) }
pub fn r_curly_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 2usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsBlockStatement {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsBlockStatementFields {
pub l_curly_token: SyntaxResult<SyntaxToken>,
pub statements: JsStatementList,
pub r_curly_token: SyntaxResult<SyntaxToken>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsBooleanLiteralExpression {
pub(crate) syntax: SyntaxNode,
}
impl JsBooleanLiteralExpression {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsBooleanLiteralExpressionFields {
JsBooleanLiteralExpressionFields {
value_token: self.value_token(),
}
}
pub fn value_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 0usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsBooleanLiteralExpression {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsBooleanLiteralExpressionFields {
pub value_token: SyntaxResult<SyntaxToken>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsBreakStatement {
pub(crate) syntax: SyntaxNode,
}
impl JsBreakStatement {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsBreakStatementFields {
JsBreakStatementFields {
break_token: self.break_token(),
label_token: self.label_token(),
semicolon_token: self.semicolon_token(),
}
}
pub fn break_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 0usize)
}
pub fn label_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, 1usize) }
pub fn semicolon_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, 2usize) }
}
#[cfg(feature = "serde")]
impl Serialize for JsBreakStatement {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsBreakStatementFields {
pub break_token: SyntaxResult<SyntaxToken>,
pub label_token: Option<SyntaxToken>,
pub semicolon_token: Option<SyntaxToken>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsCallArguments {
pub(crate) syntax: SyntaxNode,
}
impl JsCallArguments {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsCallArgumentsFields {
JsCallArgumentsFields {
l_paren_token: self.l_paren_token(),
args: self.args(),
r_paren_token: self.r_paren_token(),
}
}
pub fn l_paren_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 0usize)
}
pub fn args(&self) -> JsCallArgumentList { support::list(&self.syntax, 1usize) }
pub fn r_paren_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 2usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsCallArguments {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsCallArgumentsFields {
pub l_paren_token: SyntaxResult<SyntaxToken>,
pub args: JsCallArgumentList,
pub r_paren_token: SyntaxResult<SyntaxToken>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsCallExpression {
pub(crate) syntax: SyntaxNode,
}
impl JsCallExpression {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsCallExpressionFields {
JsCallExpressionFields {
callee: self.callee(),
optional_chain_token: self.optional_chain_token(),
type_arguments: self.type_arguments(),
arguments: self.arguments(),
}
}
pub fn callee(&self) -> SyntaxResult<AnyJsExpression> {
support::required_node(&self.syntax, 0usize)
}
pub fn optional_chain_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, 1usize)
}
pub fn type_arguments(&self) -> Option<TsTypeArguments> { support::node(&self.syntax, 2usize) }
pub fn arguments(&self) -> SyntaxResult<JsCallArguments> {
support::required_node(&self.syntax, 3usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsCallExpression {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsCallExpressionFields {
pub callee: SyntaxResult<AnyJsExpression>,
pub optional_chain_token: Option<SyntaxToken>,
pub type_arguments: Option<TsTypeArguments>,
pub arguments: SyntaxResult<JsCallArguments>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsCaseClause {
pub(crate) syntax: SyntaxNode,
}
impl JsCaseClause {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsCaseClauseFields {
JsCaseClauseFields {
case_token: self.case_token(),
test: self.test(),
colon_token: self.colon_token(),
consequent: self.consequent(),
}
}
pub fn case_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 0usize)
}
pub fn test(&self) -> SyntaxResult<AnyJsExpression> {
support::required_node(&self.syntax, 1usize)
}
pub fn colon_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 2usize)
}
pub fn consequent(&self) -> JsStatementList { support::list(&self.syntax, 3usize) }
}
#[cfg(feature = "serde")]
impl Serialize for JsCaseClause {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsCaseClauseFields {
pub case_token: SyntaxResult<SyntaxToken>,
pub test: SyntaxResult<AnyJsExpression>,
pub colon_token: SyntaxResult<SyntaxToken>,
pub consequent: JsStatementList,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsCatchClause {
pub(crate) syntax: SyntaxNode,
}
impl JsCatchClause {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsCatchClauseFields {
JsCatchClauseFields {
catch_token: self.catch_token(),
declaration: self.declaration(),
body: self.body(),
}
}
pub fn catch_token(&self) -> SyntaxResult<SyntaxToken> {
support::required_token(&self.syntax, 0usize)
}
pub fn declaration(&self) -> Option<JsCatchDeclaration> { support::node(&self.syntax, 1usize) }
pub fn body(&self) -> SyntaxResult<JsBlockStatement> {
support::required_node(&self.syntax, 2usize)
}
}
#[cfg(feature = "serde")]
impl Serialize for JsCatchClause {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_fields().serialize(serializer)
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct JsCatchClauseFields {
pub catch_token: SyntaxResult<SyntaxToken>,
pub declaration: Option<JsCatchDeclaration>,
pub body: SyntaxResult<JsBlockStatement>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsCatchDeclaration {
pub(crate) syntax: SyntaxNode,
}
impl JsCatchDeclaration {
#[doc = r" Create an AstNode from a SyntaxNode without checking its kind"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r" This function must be guarded with a call to [AstNode::can_cast]"]
#[doc = r" or a match on [SyntaxNode::kind]"]
#[inline]
pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } }
pub fn as_fields(&self) -> JsCatchDeclarationFields {
JsCatchDeclarationFields {
l_paren_token: self.l_paren_token(),
binding: self.binding(),
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_factory/src/lib.rs | crates/rome_css_factory/src/lib.rs | pub use crate::generated::CssSyntaxFactory;
use rome_css_syntax::CssLanguage;
use rome_rowan::TreeBuilder;
mod generated;
// Re-exported for tests
#[doc(hidden)]
pub use rome_css_syntax as syntax;
pub type CssSyntaxTreeBuilder = TreeBuilder<'static, CssLanguage, CssSyntaxFactory>;
pub use generated::node_factory as make;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_factory/src/generated.rs | crates/rome_css_factory/src/generated.rs | #[rustfmt::skip]
pub(super) mod syntax_factory;
#[rustfmt::skip]
pub mod node_factory;
pub use syntax_factory::CssSyntaxFactory;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_factory/src/generated/syntax_factory.rs | crates/rome_css_factory/src/generated/syntax_factory.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use rome_css_syntax::{CssSyntaxKind, CssSyntaxKind::*, T, *};
use rome_rowan::{AstNode, ParsedChildren, RawNodeSlots, RawSyntaxNode, SyntaxFactory, SyntaxKind};
#[derive(Debug)]
pub struct CssSyntaxFactory;
impl SyntaxFactory for CssSyntaxFactory {
type Kind = CssSyntaxKind;
#[allow(unused_mut)]
fn make_syntax(
kind: Self::Kind,
children: ParsedChildren<Self::Kind>,
) -> RawSyntaxNode<Self::Kind> {
match kind {
CSS_BOGUS => RawSyntaxNode::new(kind, children.into_iter().map(Some)),
CSS_ANY_FUNCTION => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<1usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if CssSimpleFunction::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_ANY_FUNCTION.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_ANY_FUNCTION, children)
}
CSS_AT_KEYFRAMES => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<5usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T ! [@] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T![keyframes] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssIdentifier::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssString::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssAtKeyframesBody::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_AT_KEYFRAMES.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_AT_KEYFRAMES, children)
}
CSS_AT_KEYFRAMES_BODY => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T!['{'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssAtKeyframesItemList::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T!['}'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_AT_KEYFRAMES_BODY.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_AT_KEYFRAMES_BODY, children)
}
CSS_AT_MEDIA => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<6usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T ! [@] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T![media] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssAtMediaQueryList::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T!['{'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyCssRule::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T!['}'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_AT_MEDIA.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_AT_MEDIA, children)
}
CSS_AT_MEDIA_QUERY => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<5usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T![not] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T![or] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T![only] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyCssAtMediaQueryType::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssAtMediaQueryConsequent::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_AT_MEDIA_QUERY.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_AT_MEDIA_QUERY, children)
}
CSS_AT_MEDIA_QUERY_CONSEQUENT => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T![and] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T![not] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyCssAtMediaQueryType::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_AT_MEDIA_QUERY_CONSEQUENT.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_AT_MEDIA_QUERY_CONSEQUENT, children)
}
CSS_AT_MEDIA_QUERY_FEATURE => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T!['('] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyCssAtMediaQueryFeatureType::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T![')'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_AT_MEDIA_QUERY_FEATURE.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_AT_MEDIA_QUERY_FEATURE, children)
}
CSS_AT_MEDIA_QUERY_FEATURE_BOOLEAN => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<1usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if CssIdentifier::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_AT_MEDIA_QUERY_FEATURE_BOOLEAN.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_AT_MEDIA_QUERY_FEATURE_BOOLEAN, children)
}
CSS_AT_MEDIA_QUERY_FEATURE_COMPARE => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if CssIdentifier::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssAtMediaQueryRange::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyCssValue::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_AT_MEDIA_QUERY_FEATURE_COMPARE.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_AT_MEDIA_QUERY_FEATURE_COMPARE, children)
}
CSS_AT_MEDIA_QUERY_FEATURE_PLAIN => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if CssIdentifier::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [:] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyCssValue::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_AT_MEDIA_QUERY_FEATURE_PLAIN.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_AT_MEDIA_QUERY_FEATURE_PLAIN, children)
}
CSS_AT_MEDIA_QUERY_FEATURE_RANGE => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<5usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if AnyCssValue::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssAtMediaQueryRange::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssIdentifier::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyCssValue::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssAtMediaQueryRange::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_AT_MEDIA_QUERY_FEATURE_RANGE.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_AT_MEDIA_QUERY_FEATURE_RANGE, children)
}
CSS_AT_MEDIA_QUERY_RANGE => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<4usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T ! [>] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [<] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [>=] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [<=] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_AT_MEDIA_QUERY_RANGE.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_AT_MEDIA_QUERY_RANGE, children)
}
CSS_ATTRIBUTE => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<4usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T!['['] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssAttributeName::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssAttributeMeta::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T![']'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_ATTRIBUTE.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_ATTRIBUTE, children)
}
CSS_ATTRIBUTE_MATCHER => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<8usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T ! [~=] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [|=] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [^=] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T!["$="] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [*=] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [=] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssString::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssIdentifier::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_ATTRIBUTE_MATCHER.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_ATTRIBUTE_MATCHER, children)
}
CSS_ATTRIBUTE_META => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<2usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if CssAttributeMatcher::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssAttributeModifier::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_ATTRIBUTE_META.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_ATTRIBUTE_META, children)
}
CSS_ATTRIBUTE_MODIFIER => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<1usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T![i] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_ATTRIBUTE_MODIFIER.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_ATTRIBUTE_MODIFIER, children)
}
CSS_ATTRIBUTE_NAME => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<1usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if CssString::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_ATTRIBUTE_NAME.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_ATTRIBUTE_NAME, children)
}
CSS_ATTRIBUTE_SELECTOR_PATTERN => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<2usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if CssIdentifier::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssAttributeList::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_ATTRIBUTE_SELECTOR_PATTERN.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_ATTRIBUTE_SELECTOR_PATTERN, children)
}
CSS_BLOCK => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T!['{'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssDeclarationList::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T!['}'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_BLOCK.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_BLOCK, children)
}
CSS_CLASS_SELECTOR_PATTERN => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<2usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T ! [.] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if CssIdentifier::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
CSS_CLASS_SELECTOR_PATTERN.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(CSS_CLASS_SELECTOR_PATTERN, children)
}
CSS_COMBINATOR_SELECTOR_PATTERN => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<6usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if AnyCssSelectorPattern::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [>] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [+] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [~] {
slots.mark_present();
current_element = elements.next();
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_factory/src/generated/node_factory.rs | crates/rome_css_factory/src/generated/node_factory.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
#![allow(clippy::redundant_closure)]
#![allow(clippy::too_many_arguments)]
use rome_css_syntax::{
CssSyntaxElement as SyntaxElement, CssSyntaxNode as SyntaxNode, CssSyntaxToken as SyntaxToken,
*,
};
use rome_rowan::AstNode;
pub fn css_any_function(css_simple_function: CssSimpleFunction) -> CssAnyFunction {
CssAnyFunction::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_ANY_FUNCTION,
[Some(SyntaxElement::Node(css_simple_function.into_syntax()))],
))
}
pub fn css_at_keyframes(
at_token: SyntaxToken,
keyframes_token: SyntaxToken,
name: CssIdentifier,
css_string: CssString,
body: CssAtKeyframesBody,
) -> CssAtKeyframes {
CssAtKeyframes::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_AT_KEYFRAMES,
[
Some(SyntaxElement::Token(at_token)),
Some(SyntaxElement::Token(keyframes_token)),
Some(SyntaxElement::Node(name.into_syntax())),
Some(SyntaxElement::Node(css_string.into_syntax())),
Some(SyntaxElement::Node(body.into_syntax())),
],
))
}
pub fn css_at_keyframes_body(
l_curly_token: SyntaxToken,
items: CssAtKeyframesItemList,
r_curly_token: SyntaxToken,
) -> CssAtKeyframesBody {
CssAtKeyframesBody::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_AT_KEYFRAMES_BODY,
[
Some(SyntaxElement::Token(l_curly_token)),
Some(SyntaxElement::Node(items.into_syntax())),
Some(SyntaxElement::Token(r_curly_token)),
],
))
}
pub fn css_at_media(
at_token: SyntaxToken,
media_token: SyntaxToken,
query_list: CssAtMediaQueryList,
l_curly_token: SyntaxToken,
body: AnyCssRule,
r_curly_token: SyntaxToken,
) -> CssAtMedia {
CssAtMedia::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_AT_MEDIA,
[
Some(SyntaxElement::Token(at_token)),
Some(SyntaxElement::Token(media_token)),
Some(SyntaxElement::Node(query_list.into_syntax())),
Some(SyntaxElement::Token(l_curly_token)),
Some(SyntaxElement::Node(body.into_syntax())),
Some(SyntaxElement::Token(r_curly_token)),
],
))
}
pub fn css_at_media_query(
condition_token: SyntaxToken,
or_token: SyntaxToken,
ty: AnyCssAtMediaQueryType,
) -> CssAtMediaQueryBuilder {
CssAtMediaQueryBuilder {
condition_token,
or_token,
ty,
only_token: None,
consequent: None,
}
}
pub struct CssAtMediaQueryBuilder {
condition_token: SyntaxToken,
or_token: SyntaxToken,
ty: AnyCssAtMediaQueryType,
only_token: Option<SyntaxToken>,
consequent: Option<CssAtMediaQueryConsequent>,
}
impl CssAtMediaQueryBuilder {
pub fn with_only_token(mut self, only_token: SyntaxToken) -> Self {
self.only_token = Some(only_token);
self
}
pub fn with_consequent(mut self, consequent: CssAtMediaQueryConsequent) -> Self {
self.consequent = Some(consequent);
self
}
pub fn build(self) -> CssAtMediaQuery {
CssAtMediaQuery::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_AT_MEDIA_QUERY,
[
Some(SyntaxElement::Token(self.condition_token)),
Some(SyntaxElement::Token(self.or_token)),
self.only_token.map(|token| SyntaxElement::Token(token)),
Some(SyntaxElement::Node(self.ty.into_syntax())),
self.consequent
.map(|token| SyntaxElement::Node(token.into_syntax())),
],
))
}
}
pub fn css_at_media_query_consequent(
and_token: SyntaxToken,
ty: AnyCssAtMediaQueryType,
) -> CssAtMediaQueryConsequentBuilder {
CssAtMediaQueryConsequentBuilder {
and_token,
ty,
condition_token: None,
}
}
pub struct CssAtMediaQueryConsequentBuilder {
and_token: SyntaxToken,
ty: AnyCssAtMediaQueryType,
condition_token: Option<SyntaxToken>,
}
impl CssAtMediaQueryConsequentBuilder {
pub fn with_condition_token(mut self, condition_token: SyntaxToken) -> Self {
self.condition_token = Some(condition_token);
self
}
pub fn build(self) -> CssAtMediaQueryConsequent {
CssAtMediaQueryConsequent::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_AT_MEDIA_QUERY_CONSEQUENT,
[
Some(SyntaxElement::Token(self.and_token)),
self.condition_token
.map(|token| SyntaxElement::Token(token)),
Some(SyntaxElement::Node(self.ty.into_syntax())),
],
))
}
}
pub fn css_at_media_query_feature(
l_paren_token: SyntaxToken,
feature: AnyCssAtMediaQueryFeatureType,
r_paren_token: SyntaxToken,
) -> CssAtMediaQueryFeature {
CssAtMediaQueryFeature::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_AT_MEDIA_QUERY_FEATURE,
[
Some(SyntaxElement::Token(l_paren_token)),
Some(SyntaxElement::Node(feature.into_syntax())),
Some(SyntaxElement::Token(r_paren_token)),
],
))
}
pub fn css_at_media_query_feature_boolean(
css_identifier: CssIdentifier,
) -> CssAtMediaQueryFeatureBoolean {
CssAtMediaQueryFeatureBoolean::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_AT_MEDIA_QUERY_FEATURE_BOOLEAN,
[Some(SyntaxElement::Node(css_identifier.into_syntax()))],
))
}
pub fn css_at_media_query_feature_compare(
name: CssIdentifier,
range: CssAtMediaQueryRange,
value: AnyCssValue,
) -> CssAtMediaQueryFeatureCompare {
CssAtMediaQueryFeatureCompare::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_AT_MEDIA_QUERY_FEATURE_COMPARE,
[
Some(SyntaxElement::Node(name.into_syntax())),
Some(SyntaxElement::Node(range.into_syntax())),
Some(SyntaxElement::Node(value.into_syntax())),
],
))
}
pub fn css_at_media_query_feature_plain(
name: CssIdentifier,
colon_token: SyntaxToken,
value: AnyCssValue,
) -> CssAtMediaQueryFeaturePlain {
CssAtMediaQueryFeaturePlain::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_AT_MEDIA_QUERY_FEATURE_PLAIN,
[
Some(SyntaxElement::Node(name.into_syntax())),
Some(SyntaxElement::Token(colon_token)),
Some(SyntaxElement::Node(value.into_syntax())),
],
))
}
pub fn css_at_media_query_feature_range(
first_value: AnyCssValue,
first_range: CssAtMediaQueryRange,
name: CssIdentifier,
second_value: AnyCssValue,
second_range: CssAtMediaQueryRange,
) -> CssAtMediaQueryFeatureRange {
CssAtMediaQueryFeatureRange::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_AT_MEDIA_QUERY_FEATURE_RANGE,
[
Some(SyntaxElement::Node(first_value.into_syntax())),
Some(SyntaxElement::Node(first_range.into_syntax())),
Some(SyntaxElement::Node(name.into_syntax())),
Some(SyntaxElement::Node(second_value.into_syntax())),
Some(SyntaxElement::Node(second_range.into_syntax())),
],
))
}
pub fn css_at_media_query_range(
r_angle_token: SyntaxToken,
l_angle_token: SyntaxToken,
greater_than_equal_token: SyntaxToken,
less_than_equal_token: SyntaxToken,
) -> CssAtMediaQueryRange {
CssAtMediaQueryRange::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_AT_MEDIA_QUERY_RANGE,
[
Some(SyntaxElement::Token(r_angle_token)),
Some(SyntaxElement::Token(l_angle_token)),
Some(SyntaxElement::Token(greater_than_equal_token)),
Some(SyntaxElement::Token(less_than_equal_token)),
],
))
}
pub fn css_attribute(
l_brack_token: SyntaxToken,
attribute_name: CssAttributeName,
r_brack_token: SyntaxToken,
) -> CssAttributeBuilder {
CssAttributeBuilder {
l_brack_token,
attribute_name,
r_brack_token,
attribute_meta: None,
}
}
pub struct CssAttributeBuilder {
l_brack_token: SyntaxToken,
attribute_name: CssAttributeName,
r_brack_token: SyntaxToken,
attribute_meta: Option<CssAttributeMeta>,
}
impl CssAttributeBuilder {
pub fn with_attribute_meta(mut self, attribute_meta: CssAttributeMeta) -> Self {
self.attribute_meta = Some(attribute_meta);
self
}
pub fn build(self) -> CssAttribute {
CssAttribute::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_ATTRIBUTE,
[
Some(SyntaxElement::Token(self.l_brack_token)),
Some(SyntaxElement::Node(self.attribute_name.into_syntax())),
self.attribute_meta
.map(|token| SyntaxElement::Node(token.into_syntax())),
Some(SyntaxElement::Token(self.r_brack_token)),
],
))
}
}
pub fn css_attribute_matcher(
matcher_type_token: SyntaxToken,
exactly_or_hyphen_token: SyntaxToken,
prefix_token: SyntaxToken,
suffix_token: SyntaxToken,
times_assign_token: SyntaxToken,
eq_token: SyntaxToken,
matcher_name: CssString,
css_identifier: CssIdentifier,
) -> CssAttributeMatcher {
CssAttributeMatcher::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_ATTRIBUTE_MATCHER,
[
Some(SyntaxElement::Token(matcher_type_token)),
Some(SyntaxElement::Token(exactly_or_hyphen_token)),
Some(SyntaxElement::Token(prefix_token)),
Some(SyntaxElement::Token(suffix_token)),
Some(SyntaxElement::Token(times_assign_token)),
Some(SyntaxElement::Token(eq_token)),
Some(SyntaxElement::Node(matcher_name.into_syntax())),
Some(SyntaxElement::Node(css_identifier.into_syntax())),
],
))
}
pub fn css_attribute_meta() -> CssAttributeMetaBuilder {
CssAttributeMetaBuilder {
attribute_matcher: None,
attribute_modifier: None,
}
}
pub struct CssAttributeMetaBuilder {
attribute_matcher: Option<CssAttributeMatcher>,
attribute_modifier: Option<CssAttributeModifier>,
}
impl CssAttributeMetaBuilder {
pub fn with_attribute_matcher(mut self, attribute_matcher: CssAttributeMatcher) -> Self {
self.attribute_matcher = Some(attribute_matcher);
self
}
pub fn with_attribute_modifier(mut self, attribute_modifier: CssAttributeModifier) -> Self {
self.attribute_modifier = Some(attribute_modifier);
self
}
pub fn build(self) -> CssAttributeMeta {
CssAttributeMeta::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_ATTRIBUTE_META,
[
self.attribute_matcher
.map(|token| SyntaxElement::Node(token.into_syntax())),
self.attribute_modifier
.map(|token| SyntaxElement::Node(token.into_syntax())),
],
))
}
}
pub fn css_attribute_modifier(i_token: SyntaxToken) -> CssAttributeModifier {
CssAttributeModifier::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_ATTRIBUTE_MODIFIER,
[Some(SyntaxElement::Token(i_token))],
))
}
pub fn css_attribute_name(css_string: CssString) -> CssAttributeName {
CssAttributeName::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_ATTRIBUTE_NAME,
[Some(SyntaxElement::Node(css_string.into_syntax()))],
))
}
pub fn css_attribute_selector_pattern(
name: CssIdentifier,
attribute_list: CssAttributeList,
) -> CssAttributeSelectorPattern {
CssAttributeSelectorPattern::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_ATTRIBUTE_SELECTOR_PATTERN,
[
Some(SyntaxElement::Node(name.into_syntax())),
Some(SyntaxElement::Node(attribute_list.into_syntax())),
],
))
}
pub fn css_block(
l_curly_token: SyntaxToken,
declaration_list: CssDeclarationList,
r_curly_token: SyntaxToken,
) -> CssBlock {
CssBlock::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_BLOCK,
[
Some(SyntaxElement::Token(l_curly_token)),
Some(SyntaxElement::Node(declaration_list.into_syntax())),
Some(SyntaxElement::Token(r_curly_token)),
],
))
}
pub fn css_class_selector_pattern(
dot_token: SyntaxToken,
name: CssIdentifier,
) -> CssClassSelectorPattern {
CssClassSelectorPattern::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_CLASS_SELECTOR_PATTERN,
[
Some(SyntaxElement::Token(dot_token)),
Some(SyntaxElement::Node(name.into_syntax())),
],
))
}
pub fn css_combinator_selector_pattern(
left: AnyCssSelectorPattern,
combinator_token: SyntaxToken,
plus_token: SyntaxToken,
bitwise_not_token: SyntaxToken,
css_space_literal_token: SyntaxToken,
right: AnyCssSelectorPattern,
) -> CssCombinatorSelectorPattern {
CssCombinatorSelectorPattern::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_COMBINATOR_SELECTOR_PATTERN,
[
Some(SyntaxElement::Node(left.into_syntax())),
Some(SyntaxElement::Token(combinator_token)),
Some(SyntaxElement::Token(plus_token)),
Some(SyntaxElement::Token(bitwise_not_token)),
Some(SyntaxElement::Token(css_space_literal_token)),
Some(SyntaxElement::Node(right.into_syntax())),
],
))
}
pub fn css_custom_property(value_token: SyntaxToken) -> CssCustomProperty {
CssCustomProperty::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_CUSTOM_PROPERTY,
[Some(SyntaxElement::Token(value_token))],
))
}
pub fn css_declaration(
name: CssIdentifier,
css_custom_property: CssCustomProperty,
colon_token: SyntaxToken,
value: AnyCssValue,
) -> CssDeclarationBuilder {
CssDeclarationBuilder {
name,
css_custom_property,
colon_token,
value,
important: None,
}
}
pub struct CssDeclarationBuilder {
name: CssIdentifier,
css_custom_property: CssCustomProperty,
colon_token: SyntaxToken,
value: AnyCssValue,
important: Option<CssDeclarationImportant>,
}
impl CssDeclarationBuilder {
pub fn with_important(mut self, important: CssDeclarationImportant) -> Self {
self.important = Some(important);
self
}
pub fn build(self) -> CssDeclaration {
CssDeclaration::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_DECLARATION,
[
Some(SyntaxElement::Node(self.name.into_syntax())),
Some(SyntaxElement::Node(self.css_custom_property.into_syntax())),
Some(SyntaxElement::Token(self.colon_token)),
Some(SyntaxElement::Node(self.value.into_syntax())),
self.important
.map(|token| SyntaxElement::Node(token.into_syntax())),
],
))
}
}
pub fn css_declaration_important(
excl_token: SyntaxToken,
important_token: SyntaxToken,
) -> CssDeclarationImportant {
CssDeclarationImportant::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_DECLARATION_IMPORTANT,
[
Some(SyntaxElement::Token(excl_token)),
Some(SyntaxElement::Token(important_token)),
],
))
}
pub fn css_dimension(value: CssNumber, unit: CssIdentifier) -> CssDimension {
CssDimension::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_DIMENSION,
[
Some(SyntaxElement::Node(value.into_syntax())),
Some(SyntaxElement::Node(unit.into_syntax())),
],
))
}
pub fn css_id_selector_pattern(
hash_token: SyntaxToken,
name: CssIdentifier,
) -> CssIdSelectorPattern {
CssIdSelectorPattern::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_ID_SELECTOR_PATTERN,
[
Some(SyntaxElement::Token(hash_token)),
Some(SyntaxElement::Node(name.into_syntax())),
],
))
}
pub fn css_identifier(value_token: SyntaxToken) -> CssIdentifier {
CssIdentifier::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_IDENTIFIER,
[Some(SyntaxElement::Token(value_token))],
))
}
pub fn css_keyframes_block(
selectors: CssKeyframesSelectorList,
l_curly_token: SyntaxToken,
declarations: CssDeclarationList,
r_curly_token: SyntaxToken,
) -> CssKeyframesBlock {
CssKeyframesBlock::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_KEYFRAMES_BLOCK,
[
Some(SyntaxElement::Node(selectors.into_syntax())),
Some(SyntaxElement::Token(l_curly_token)),
Some(SyntaxElement::Node(declarations.into_syntax())),
Some(SyntaxElement::Token(r_curly_token)),
],
))
}
pub fn css_keyframes_selector(
from_token: SyntaxToken,
to_token: SyntaxToken,
css_percentage: CssPercentage,
) -> CssKeyframesSelector {
CssKeyframesSelector::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_KEYFRAMES_SELECTOR,
[
Some(SyntaxElement::Token(from_token)),
Some(SyntaxElement::Token(to_token)),
Some(SyntaxElement::Node(css_percentage.into_syntax())),
],
))
}
pub fn css_number(value_token: SyntaxToken) -> CssNumber {
CssNumber::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_NUMBER,
[Some(SyntaxElement::Token(value_token))],
))
}
pub fn css_parameter(any_css_value: AnyCssValue) -> CssParameter {
CssParameter::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_PARAMETER,
[Some(SyntaxElement::Node(any_css_value.into_syntax()))],
))
}
pub fn css_percentage(value: CssNumber, reminder_token: SyntaxToken) -> CssPercentage {
CssPercentage::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_PERCENTAGE,
[
Some(SyntaxElement::Node(value.into_syntax())),
Some(SyntaxElement::Token(reminder_token)),
],
))
}
pub fn css_pseudo_class_selector_pattern(
colon_token: SyntaxToken,
name: CssIdentifier,
) -> CssPseudoClassSelectorPatternBuilder {
CssPseudoClassSelectorPatternBuilder {
colon_token,
name,
parameters: None,
}
}
pub struct CssPseudoClassSelectorPatternBuilder {
colon_token: SyntaxToken,
name: CssIdentifier,
parameters: Option<CssPseudoClassSelectorPatternParameters>,
}
impl CssPseudoClassSelectorPatternBuilder {
pub fn with_parameters(mut self, parameters: CssPseudoClassSelectorPatternParameters) -> Self {
self.parameters = Some(parameters);
self
}
pub fn build(self) -> CssPseudoClassSelectorPattern {
CssPseudoClassSelectorPattern::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_PSEUDO_CLASS_SELECTOR_PATTERN,
[
Some(SyntaxElement::Token(self.colon_token)),
Some(SyntaxElement::Node(self.name.into_syntax())),
self.parameters
.map(|token| SyntaxElement::Node(token.into_syntax())),
],
))
}
}
pub fn css_pseudo_class_selector_pattern_parameters(
l_paren_token: SyntaxToken,
parameter: AnyCssValue,
r_paren_token: SyntaxToken,
) -> CssPseudoClassSelectorPatternParameters {
CssPseudoClassSelectorPatternParameters::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_PSEUDO_CLASS_SELECTOR_PATTERN_PARAMETERS,
[
Some(SyntaxElement::Token(l_paren_token)),
Some(SyntaxElement::Node(parameter.into_syntax())),
Some(SyntaxElement::Token(r_paren_token)),
],
))
}
pub fn css_ratio(numerator: CssNumber, denominator: CssNumber) -> CssRatio {
CssRatio::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_RATIO,
[
Some(SyntaxElement::Node(numerator.into_syntax())),
Some(SyntaxElement::Node(denominator.into_syntax())),
],
))
}
pub fn css_root(rules: CssRuleList, eof_token: SyntaxToken) -> CssRoot {
CssRoot::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_ROOT,
[
Some(SyntaxElement::Node(rules.into_syntax())),
Some(SyntaxElement::Token(eof_token)),
],
))
}
pub fn css_rule(prelude: CssSelectorList, block: CssBlock) -> CssRule {
CssRule::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_RULE,
[
Some(SyntaxElement::Node(prelude.into_syntax())),
Some(SyntaxElement::Node(block.into_syntax())),
],
))
}
pub fn css_selector(pattern_list: CssAnySelectorPatternList) -> CssSelector {
CssSelector::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_SELECTOR,
[Some(SyntaxElement::Node(pattern_list.into_syntax()))],
))
}
pub fn css_simple_function(
name: CssIdentifier,
l_paren_token: SyntaxToken,
items: CssParameterList,
r_paren_token: SyntaxToken,
) -> CssSimpleFunction {
CssSimpleFunction::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_SIMPLE_FUNCTION,
[
Some(SyntaxElement::Node(name.into_syntax())),
Some(SyntaxElement::Token(l_paren_token)),
Some(SyntaxElement::Node(items.into_syntax())),
Some(SyntaxElement::Token(r_paren_token)),
],
))
}
pub fn css_string(value_token: SyntaxToken) -> CssString {
CssString::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_STRING,
[Some(SyntaxElement::Token(value_token))],
))
}
pub fn css_type_selector_pattern(ident: CssIdentifier) -> CssTypeSelectorPattern {
CssTypeSelectorPattern::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_TYPE_SELECTOR_PATTERN,
[Some(SyntaxElement::Node(ident.into_syntax()))],
))
}
pub fn css_universal_selector_pattern(star_token: SyntaxToken) -> CssUniversalSelectorPattern {
CssUniversalSelectorPattern::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_UNIVERSAL_SELECTOR_PATTERN,
[Some(SyntaxElement::Token(star_token))],
))
}
pub fn css_var_function(
var_token: SyntaxToken,
l_paren_token: SyntaxToken,
property: CssCustomProperty,
r_paren_token: SyntaxToken,
) -> CssVarFunctionBuilder {
CssVarFunctionBuilder {
var_token,
l_paren_token,
property,
r_paren_token,
value: None,
}
}
pub struct CssVarFunctionBuilder {
var_token: SyntaxToken,
l_paren_token: SyntaxToken,
property: CssCustomProperty,
r_paren_token: SyntaxToken,
value: Option<CssVarFunctionValue>,
}
impl CssVarFunctionBuilder {
pub fn with_value(mut self, value: CssVarFunctionValue) -> Self {
self.value = Some(value);
self
}
pub fn build(self) -> CssVarFunction {
CssVarFunction::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_VAR_FUNCTION,
[
Some(SyntaxElement::Token(self.var_token)),
Some(SyntaxElement::Token(self.l_paren_token)),
Some(SyntaxElement::Node(self.property.into_syntax())),
self.value
.map(|token| SyntaxElement::Node(token.into_syntax())),
Some(SyntaxElement::Token(self.r_paren_token)),
],
))
}
}
pub fn css_var_function_value(
comma_token: SyntaxToken,
value: CssIdentifier,
) -> CssVarFunctionValue {
CssVarFunctionValue::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_VAR_FUNCTION_VALUE,
[
Some(SyntaxElement::Token(comma_token)),
Some(SyntaxElement::Node(value.into_syntax())),
],
))
}
pub fn css_any_selector_pattern_list<I>(items: I) -> CssAnySelectorPatternList
where
I: IntoIterator<Item = AnyCssSelectorPattern>,
I::IntoIter: ExactSizeIterator,
{
CssAnySelectorPatternList::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_ANY_SELECTOR_PATTERN_LIST,
items
.into_iter()
.map(|item| Some(item.into_syntax().into())),
))
}
pub fn css_at_keyframes_item_list<I>(items: I) -> CssAtKeyframesItemList
where
I: IntoIterator<Item = CssKeyframesBlock>,
I::IntoIter: ExactSizeIterator,
{
CssAtKeyframesItemList::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_AT_KEYFRAMES_ITEM_LIST,
items
.into_iter()
.map(|item| Some(item.into_syntax().into())),
))
}
pub fn css_at_media_query_list<I, S>(items: I, separators: S) -> CssAtMediaQueryList
where
I: IntoIterator<Item = CssAtMediaQuery>,
I::IntoIter: ExactSizeIterator,
S: IntoIterator<Item = CssSyntaxToken>,
S::IntoIter: ExactSizeIterator,
{
let mut items = items.into_iter();
let mut separators = separators.into_iter();
let length = items.len() + separators.len();
CssAtMediaQueryList::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_AT_MEDIA_QUERY_LIST,
(0..length).map(|index| {
if index % 2 == 0 {
Some(items.next()?.into_syntax().into())
} else {
Some(separators.next()?.into())
}
}),
))
}
pub fn css_attribute_list<I>(items: I) -> CssAttributeList
where
I: IntoIterator<Item = CssAttribute>,
I::IntoIter: ExactSizeIterator,
{
CssAttributeList::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_ATTRIBUTE_LIST,
items
.into_iter()
.map(|item| Some(item.into_syntax().into())),
))
}
pub fn css_declaration_list<I>(items: I) -> CssDeclarationList
where
I: IntoIterator<Item = CssDeclaration>,
I::IntoIter: ExactSizeIterator,
{
CssDeclarationList::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_DECLARATION_LIST,
items
.into_iter()
.map(|item| Some(item.into_syntax().into())),
))
}
pub fn css_keyframes_selector_list<I, S>(items: I, separators: S) -> CssKeyframesSelectorList
where
I: IntoIterator<Item = CssKeyframesSelector>,
I::IntoIter: ExactSizeIterator,
S: IntoIterator<Item = CssSyntaxToken>,
S::IntoIter: ExactSizeIterator,
{
let mut items = items.into_iter();
let mut separators = separators.into_iter();
let length = items.len() + separators.len();
CssKeyframesSelectorList::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_KEYFRAMES_SELECTOR_LIST,
(0..length).map(|index| {
if index % 2 == 0 {
Some(items.next()?.into_syntax().into())
} else {
Some(separators.next()?.into())
}
}),
))
}
pub fn css_parameter_list<I>(items: I) -> CssParameterList
where
I: IntoIterator<Item = CssParameter>,
I::IntoIter: ExactSizeIterator,
{
CssParameterList::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_PARAMETER_LIST,
items
.into_iter()
.map(|item| Some(item.into_syntax().into())),
))
}
pub fn css_rule_list<I>(items: I) -> CssRuleList
where
I: IntoIterator<Item = AnyCssRule>,
I::IntoIter: ExactSizeIterator,
{
CssRuleList::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_RULE_LIST,
items
.into_iter()
.map(|item| Some(item.into_syntax().into())),
))
}
pub fn css_selector_list<I, S>(items: I, separators: S) -> CssSelectorList
where
I: IntoIterator<Item = CssSelector>,
I::IntoIter: ExactSizeIterator,
S: IntoIterator<Item = CssSyntaxToken>,
S::IntoIter: ExactSizeIterator,
{
let mut items = items.into_iter();
let mut separators = separators.into_iter();
let length = items.len() + separators.len();
CssSelectorList::unwrap_cast(SyntaxNode::new_detached(
CssSyntaxKind::CSS_SELECTOR_LIST,
(0..length).map(|index| {
if index % 2 == 0 {
Some(items.next()?.into_syntax().into())
} else {
Some(separators.next()?.into())
}
}),
))
}
pub fn css_bogus<I>(slots: I) -> CssBogus
where
I: IntoIterator<Item = Option<SyntaxElement>>,
I::IntoIter: ExactSizeIterator,
{
CssBogus::unwrap_cast(SyntaxNode::new_detached(CssSyntaxKind::CSS_BOGUS, slots))
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/prelude.rs | crates/rome_json_formatter/src/prelude.rs | //! This module provides important and useful traits to help to format tokens and nodes
//! when implementing the [crate::FormatNodeRule] trait.
#[allow(unused_imports)]
pub(crate) use crate::{
AsFormat, FormatNodeRule, FormattedIterExt as _, IntoFormat, JsonFormatContext, JsonFormatter,
};
pub(crate) use rome_formatter::prelude::*;
#[allow(unused_imports)]
pub(crate) use rome_rowan::{AstNode as _, AstNodeList as _, AstSeparatedList as _};
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/lib.rs | crates/rome_json_formatter/src/lib.rs | mod comments;
pub mod context;
mod cst;
mod format_string;
mod generated;
mod json;
mod prelude;
mod separated;
use crate::comments::JsonCommentStyle;
pub(crate) use crate::context::JsonFormatContext;
use crate::context::JsonFormatOptions;
use crate::cst::FormatJsonSyntaxNode;
use rome_formatter::comments::Comments;
use rome_formatter::prelude::*;
use rome_formatter::{
write, CstFormatContext, FormatContext, FormatLanguage, FormatOwnedWithRule, FormatRefWithRule,
FormatToken, TransformSourceMap,
};
use rome_formatter::{Formatted, Printed};
use rome_json_syntax::{AnyJsonValue, JsonLanguage, JsonSyntaxNode, JsonSyntaxToken};
use rome_rowan::{AstNode, SyntaxNode, TextRange};
/// Used to get an object that knows how to format this object.
pub(crate) trait AsFormat<Context> {
type Format<'a>: rome_formatter::Format<Context>
where
Self: 'a;
/// Returns an object that is able to format this object.
fn format(&self) -> Self::Format<'_>;
}
/// Implement [AsFormat] for references to types that implement [AsFormat].
impl<T, C> AsFormat<C> for &T
where
T: AsFormat<C>,
{
type Format<'a> = T::Format<'a> where Self: 'a;
fn format(&self) -> Self::Format<'_> {
AsFormat::format(&**self)
}
}
/// Implement [AsFormat] for [SyntaxResult] where `T` implements [AsFormat].
///
/// Useful to format mandatory AST fields without having to unwrap the value first.
impl<T, C> AsFormat<C> for rome_rowan::SyntaxResult<T>
where
T: AsFormat<C>,
{
type Format<'a> = rome_rowan::SyntaxResult<T::Format<'a>> where Self: 'a;
fn format(&self) -> Self::Format<'_> {
match self {
Ok(value) => Ok(value.format()),
Err(err) => Err(*err),
}
}
}
/// Implement [AsFormat] for [Option] when `T` implements [AsFormat]
///
/// Allows to call format on optional AST fields without having to unwrap the field first.
impl<T, C> AsFormat<C> for Option<T>
where
T: AsFormat<C>,
{
type Format<'a> = Option<T::Format<'a>> where Self: 'a;
fn format(&self) -> Self::Format<'_> {
self.as_ref().map(|value| value.format())
}
}
/// Used to convert this object into an object that can be formatted.
///
/// The difference to [AsFormat] is that this trait takes ownership of `self`.
pub(crate) trait IntoFormat<Context> {
type Format: rome_formatter::Format<Context>;
fn into_format(self) -> Self::Format;
}
impl<T, Context> IntoFormat<Context> for rome_rowan::SyntaxResult<T>
where
T: IntoFormat<Context>,
{
type Format = rome_rowan::SyntaxResult<T::Format>;
fn into_format(self) -> Self::Format {
self.map(IntoFormat::into_format)
}
}
/// Implement [IntoFormat] for [Option] when `T` implements [IntoFormat]
///
/// Allows to call format on optional AST fields without having to unwrap the field first.
impl<T, Context> IntoFormat<Context> for Option<T>
where
T: IntoFormat<Context>,
{
type Format = Option<T::Format>;
fn into_format(self) -> Self::Format {
self.map(IntoFormat::into_format)
}
}
/// Formatting specific [Iterator] extensions
pub(crate) trait FormattedIterExt {
/// Converts every item to an object that knows how to format it.
fn formatted<Context>(self) -> FormattedIter<Self, Self::Item, Context>
where
Self: Iterator + Sized,
Self::Item: IntoFormat<Context>,
{
FormattedIter {
inner: self,
options: std::marker::PhantomData,
}
}
}
impl<I> FormattedIterExt for I where I: std::iter::Iterator {}
pub(crate) struct FormattedIter<Iter, Item, Context>
where
Iter: Iterator<Item = Item>,
{
inner: Iter,
options: std::marker::PhantomData<Context>,
}
impl<Iter, Item, Context> std::iter::Iterator for FormattedIter<Iter, Item, Context>
where
Iter: Iterator<Item = Item>,
Item: IntoFormat<Context>,
{
type Item = Item::Format;
fn next(&mut self) -> Option<Self::Item> {
Some(self.inner.next()?.into_format())
}
}
impl<Iter, Item, Context> std::iter::FusedIterator for FormattedIter<Iter, Item, Context>
where
Iter: std::iter::FusedIterator<Item = Item>,
Item: IntoFormat<Context>,
{
}
impl<Iter, Item, Context> std::iter::ExactSizeIterator for FormattedIter<Iter, Item, Context>
where
Iter: Iterator<Item = Item> + std::iter::ExactSizeIterator,
Item: IntoFormat<Context>,
{
}
pub(crate) type JsonFormatter<'buf> = Formatter<'buf, JsonFormatContext>;
/// Format a [JsonSyntaxNode]
pub(crate) trait FormatNodeRule<N>
where
N: AstNode<Language = JsonLanguage>,
{
fn fmt(&self, node: &N, f: &mut JsonFormatter) -> FormatResult<()> {
if self.is_suppressed(node, f) {
return write!(f, [format_suppressed_node(node.syntax())]);
}
self.fmt_leading_comments(node, f)?;
self.fmt_fields(node, f)?;
self.fmt_dangling_comments(node, f)?;
self.fmt_trailing_comments(node, f)
}
fn fmt_fields(&self, node: &N, f: &mut JsonFormatter) -> FormatResult<()>;
/// Returns `true` if the node has a suppression comment and should use the same formatting as in the source document.
fn is_suppressed(&self, node: &N, f: &JsonFormatter) -> bool {
f.context().comments().is_suppressed(node.syntax())
}
/// Formats the [leading comments](rome_formatter::comments#leading-comments) of the node.
///
/// You may want to override this method if you want to manually handle the formatting of comments
/// inside of the `fmt_fields` method or customize the formatting of the leading comments.
fn fmt_leading_comments(&self, node: &N, f: &mut JsonFormatter) -> FormatResult<()> {
format_leading_comments(node.syntax()).fmt(f)
}
/// Formats the [dangling comments](rome_formatter::comments#dangling-comments) of the node.
///
/// You should override this method if the node handled by this rule can have dangling comments because the
/// default implementation formats the dangling comments at the end of the node, which isn't ideal but ensures that
/// no comments are dropped.
///
/// A node can have dangling comments if all its children are tokens or if all node childrens are optional.
fn fmt_dangling_comments(&self, node: &N, f: &mut JsonFormatter) -> FormatResult<()> {
format_dangling_comments(node.syntax())
.with_soft_block_indent()
.fmt(f)
}
/// Formats the [trailing comments](rome_formatter::comments#trailing-comments) of the node.
///
/// You may want to override this method if you want to manually handle the formatting of comments
/// inside of the `fmt_fields` method or customize the formatting of the trailing comments.
fn fmt_trailing_comments(&self, node: &N, f: &mut JsonFormatter) -> FormatResult<()> {
format_trailing_comments(node.syntax()).fmt(f)
}
}
/// Rule for formatting an bogus nodes.
pub(crate) trait FormatBogusNodeRule<N>
where
N: AstNode<Language = JsonLanguage>,
{
fn fmt(&self, node: &N, f: &mut JsonFormatter) -> FormatResult<()> {
format_bogus_node(node.syntax()).fmt(f)
}
}
#[derive(Debug, Default, Clone)]
pub struct JsonFormatLanguage {
options: JsonFormatOptions,
}
impl JsonFormatLanguage {
pub fn new(options: JsonFormatOptions) -> Self {
Self { options }
}
}
impl FormatLanguage for JsonFormatLanguage {
type SyntaxLanguage = JsonLanguage;
type Context = JsonFormatContext;
type FormatRule = FormatJsonSyntaxNode;
fn is_range_formatting_node(&self, node: &SyntaxNode<Self::SyntaxLanguage>) -> bool {
AnyJsonValue::can_cast(node.kind())
}
fn options(&self) -> &<Self::Context as FormatContext>::Options {
&self.options
}
fn create_context(
self,
root: &JsonSyntaxNode,
source_map: Option<TransformSourceMap>,
) -> Self::Context {
let comments = Comments::from_node(root, &JsonCommentStyle, source_map.as_ref());
JsonFormatContext::new(self.options, comments).with_source_map(source_map)
}
}
/// Format implementation specific to JavaScript tokens.
pub(crate) type FormatJsonSyntaxToken = FormatToken<JsonFormatContext>;
impl AsFormat<JsonFormatContext> for JsonSyntaxToken {
type Format<'a> = FormatRefWithRule<'a, JsonSyntaxToken, FormatJsonSyntaxToken>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(self, FormatJsonSyntaxToken::default())
}
}
impl IntoFormat<JsonFormatContext> for JsonSyntaxToken {
type Format = FormatOwnedWithRule<JsonSyntaxToken, FormatJsonSyntaxToken>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(self, FormatJsonSyntaxToken::default())
}
}
/// Formats a range within a file, supported by Rome
///
/// This runs a simple heuristic to determine the initial indentation
/// level of the node based on the provided [JsonFormatOptions], which
/// must match currently the current initial of the file. Additionally,
/// because the reformatting happens only locally the resulting code
/// will be indented with the same level as the original selection,
/// even if it's a mismatch from the rest of the block the selection is in
///
/// It returns a [Printed] result with a range corresponding to the
/// range of the input that was effectively overwritten by the formatter
pub fn format_range(
options: JsonFormatOptions,
root: &JsonSyntaxNode,
range: TextRange,
) -> FormatResult<Printed> {
rome_formatter::format_range(root, range, JsonFormatLanguage::new(options))
}
/// Formats a JSON syntax tree.
///
/// It returns the [Formatted] document that can be printed to a string.
pub fn format_node(
options: JsonFormatOptions,
root: &JsonSyntaxNode,
) -> FormatResult<Formatted<JsonFormatContext>> {
rome_formatter::format_node(root, JsonFormatLanguage::new(options))
}
/// Formats a single node within a file, supported by Rome.
///
/// This runs a simple heuristic to determine the initial indentation
/// level of the node based on the provided [JsonFormatOptions], which
/// must match currently the current initial of the file. Additionally,
/// because the reformatting happens only locally the resulting code
/// will be indented with the same level as the original selection,
/// even if it's a mismatch from the rest of the block the selection is in
///
/// Returns the [Printed] code.
pub fn format_sub_tree(options: JsonFormatOptions, root: &JsonSyntaxNode) -> FormatResult<Printed> {
rome_formatter::format_sub_tree(root, JsonFormatLanguage::new(options))
}
#[cfg(test)]
mod tests {
use crate::context::JsonFormatOptions;
use crate::format_node;
use rome_json_parser::{parse_json, JsonParserOptions};
#[test]
fn smoke_test() {
let src = r#"
{
"a": 5,
"b": [1, 2, 3, 4],
"c": null,
"d": true,
"e": false
}
"#;
let parse = parse_json(src, JsonParserOptions::default());
let options = JsonFormatOptions::default();
let formatted = format_node(options, &parse.syntax()).unwrap();
assert_eq!(
formatted.print().unwrap().as_code(),
"{\n\t\"a\": 5,\n\t\"b\": [1, 2, 3, 4],\n\t\"c\": null,\n\t\"d\": true,\n\t\"e\": false\n}\n"
);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/comments.rs | crates/rome_json_formatter/src/comments.rs | use crate::prelude::*;
use rome_diagnostics::category;
use rome_formatter::comments::{
is_doc_comment, CommentKind, CommentStyle, Comments, SourceComment,
};
use rome_formatter::formatter::Formatter;
use rome_formatter::{write, FormatResult, FormatRule};
use rome_json_syntax::{JsonLanguage, TextLen};
use rome_rowan::SyntaxTriviaPieceComments;
use rome_suppression::parse_suppression_comment;
pub type JsonComments = Comments<JsonLanguage>;
#[derive(Default)]
pub struct FormatJsonLeadingComment;
impl FormatRule<SourceComment<JsonLanguage>> for FormatJsonLeadingComment {
type Context = JsonFormatContext;
fn fmt(
&self,
comment: &SourceComment<JsonLanguage>,
f: &mut Formatter<Self::Context>,
) -> FormatResult<()> {
if is_doc_comment(comment.piece()) {
let mut source_offset = comment.piece().text_range().start();
let mut lines = comment.piece().text().lines();
// SAFETY: Safe, `is_doc_comment` only returns `true` for multiline comments
let first_line = lines.next().unwrap();
write!(f, [dynamic_text(first_line.trim_end(), source_offset)])?;
source_offset += first_line.text_len();
// Indent the remaining lines by one space so that all `*` are aligned.
write!(
f,
[align(
1,
&format_once(|f| {
for line in lines {
write!(
f,
[hard_line_break(), dynamic_text(line.trim(), source_offset)]
)?;
source_offset += line.text_len();
}
Ok(())
})
)]
)
} else {
write!(f, [comment.piece().as_piece()])
}
}
}
#[derive(Eq, PartialEq, Copy, Clone, Debug, Default)]
pub struct JsonCommentStyle;
impl CommentStyle for JsonCommentStyle {
type Language = JsonLanguage;
fn is_suppression(text: &str) -> bool {
parse_suppression_comment(text)
.filter_map(Result::ok)
.flat_map(|suppression| suppression.categories)
.any(|(key, _)| key == category!("format"))
}
fn get_comment_kind(comment: &SyntaxTriviaPieceComments<Self::Language>) -> CommentKind {
if comment.text().starts_with("/*") {
if comment.has_newline() {
CommentKind::Block
} else {
CommentKind::InlineBlock
}
} else {
CommentKind::Line
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/format_string.rs | crates/rome_json_formatter/src/format_string.rs | use crate::prelude::*;
use rome_formatter::token::string::{normalize_string, Quote};
use rome_json_syntax::JsonSyntaxToken;
use std::borrow::Cow;
pub(crate) fn format_string_token(token: &JsonSyntaxToken) -> CleanedStringLiteralText {
CleanedStringLiteralText { token }
}
pub(crate) struct CleanedStringLiteralText<'token> {
token: &'token JsonSyntaxToken,
}
impl Format<JsonFormatContext> for CleanedStringLiteralText<'_> {
fn fmt(&self, f: &mut Formatter<JsonFormatContext>) -> FormatResult<()> {
let content = self.token.text_trimmed();
let raw_content = &content[1..content.len() - 1];
let text = match normalize_string(raw_content, Quote::Double) {
Cow::Borrowed(_) => Cow::Borrowed(content),
Cow::Owned(raw_content) => Cow::Owned(std::format!(
"{}{}{}",
Quote::Double.as_char(),
raw_content,
Quote::Double.as_char()
)),
};
format_replaced(
self.token,
&syntax_token_cow_slice(text, self.token, self.token.text_trimmed_range().start()),
)
.fmt(f)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/cst.rs | crates/rome_json_formatter/src/cst.rs | use crate::prelude::*;
use rome_formatter::{FormatOwnedWithRule, FormatRefWithRule, FormatResult};
use rome_json_syntax::{map_syntax_node, JsonSyntaxNode};
#[derive(Debug, Copy, Clone, Default)]
pub struct FormatJsonSyntaxNode;
impl FormatRule<JsonSyntaxNode> for FormatJsonSyntaxNode {
type Context = JsonFormatContext;
fn fmt(&self, node: &JsonSyntaxNode, f: &mut JsonFormatter) -> FormatResult<()> {
map_syntax_node!(node.clone(), node => node.format().fmt(f))
}
}
impl AsFormat<JsonFormatContext> for JsonSyntaxNode {
type Format<'a> = FormatRefWithRule<'a, JsonSyntaxNode, FormatJsonSyntaxNode>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(self, FormatJsonSyntaxNode)
}
}
impl IntoFormat<JsonFormatContext> for JsonSyntaxNode {
type Format = FormatOwnedWithRule<JsonSyntaxNode, FormatJsonSyntaxNode>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(self, FormatJsonSyntaxNode)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/context.rs | crates/rome_json_formatter/src/context.rs | use crate::JsonCommentStyle;
use rome_formatter::prelude::*;
use rome_formatter::{
CstFormatContext, FormatContext, FormatOptions, IndentStyle, LineWidth, TransformSourceMap,
};
use crate::comments::{FormatJsonLeadingComment, JsonComments};
use rome_json_syntax::JsonLanguage;
use std::fmt;
use std::rc::Rc;
#[derive(Debug)]
pub struct JsonFormatContext {
options: JsonFormatOptions,
/// The comments of the nodes and tokens in the program.
comments: Rc<JsonComments>,
source_map: Option<TransformSourceMap>,
}
impl JsonFormatContext {
pub fn new(options: JsonFormatOptions, comments: JsonComments) -> Self {
Self {
options,
comments: Rc::new(comments),
source_map: None,
}
}
pub fn with_source_map(mut self, source_map: Option<TransformSourceMap>) -> Self {
self.source_map = source_map;
self
}
}
impl FormatContext for JsonFormatContext {
type Options = JsonFormatOptions;
fn options(&self) -> &Self::Options {
&self.options
}
fn source_map(&self) -> Option<&TransformSourceMap> {
None
}
}
impl CstFormatContext for JsonFormatContext {
type Language = JsonLanguage;
type Style = JsonCommentStyle;
type CommentRule = FormatJsonLeadingComment;
fn comments(&self) -> &JsonComments {
&self.comments
}
}
#[derive(Debug, Default, Clone)]
pub struct JsonFormatOptions {
indent_style: IndentStyle,
line_width: LineWidth,
}
impl JsonFormatOptions {
pub fn with_indent_style(mut self, indent_style: IndentStyle) -> Self {
self.indent_style = indent_style;
self
}
pub fn with_line_width(mut self, line_width: LineWidth) -> Self {
self.line_width = line_width;
self
}
}
impl FormatOptions for JsonFormatOptions {
fn indent_style(&self) -> IndentStyle {
self.indent_style
}
fn line_width(&self) -> LineWidth {
self.line_width
}
fn as_print_options(&self) -> PrinterOptions {
PrinterOptions::from(self)
}
}
impl fmt::Display for JsonFormatOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "Indent style: {}", self.indent_style)?;
writeln!(f, "Line width: {}", self.line_width.value())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/separated.rs | crates/rome_json_formatter/src/separated.rs | use crate::prelude::*;
use crate::FormatJsonSyntaxToken;
use rome_formatter::separated::{
FormatSeparatedElementRule, FormatSeparatedIter, TrailingSeparator,
};
use rome_formatter::FormatRefWithRule;
use rome_json_syntax::{JsonLanguage, JsonSyntaxToken};
use rome_rowan::{AstNode, AstSeparatedList, AstSeparatedListElementsIterator};
use std::marker::PhantomData;
#[derive(Clone)]
pub(crate) struct JsonFormatSeparatedElementRule<N> {
node: PhantomData<N>,
}
impl<N> FormatSeparatedElementRule<N> for JsonFormatSeparatedElementRule<N>
where
N: AstNode<Language = JsonLanguage> + AsFormat<JsonFormatContext> + 'static,
{
type Context = JsonFormatContext;
type FormatNode<'a> = N::Format<'a>;
type FormatSeparator<'a> = FormatRefWithRule<'a, JsonSyntaxToken, FormatJsonSyntaxToken>;
fn format_node<'a>(&self, node: &'a N) -> Self::FormatNode<'a> {
node.format()
}
fn format_separator<'a>(&self, separator: &'a JsonSyntaxToken) -> Self::FormatSeparator<'a> {
separator.format()
}
}
type JsonFormatSeparatedIter<Node> = FormatSeparatedIter<
AstSeparatedListElementsIterator<JsonLanguage, Node>,
Node,
JsonFormatSeparatedElementRule<Node>,
>;
/// AST Separated list formatting extension methods
pub(crate) trait FormatAstSeparatedListExtension:
AstSeparatedList<Language = JsonLanguage>
{
/// Prints a separated list of nodes
///
/// Trailing separators will be reused from the original list or
/// created by calling the `separator_factory` function.
/// The last trailing separator in the list will only be printed
/// if the outer group breaks.
fn format_separated(&self, separator: &'static str) -> JsonFormatSeparatedIter<Self::Node> {
JsonFormatSeparatedIter::new(
self.elements(),
separator,
JsonFormatSeparatedElementRule { node: PhantomData },
)
.with_trailing_separator(TrailingSeparator::Disallowed)
}
}
impl<T> FormatAstSeparatedListExtension for T where T: AstSeparatedList<Language = JsonLanguage> {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/generated.rs | crates/rome_json_formatter/src/generated.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
use crate::{
AsFormat, FormatBogusNodeRule, FormatNodeRule, IntoFormat, JsonFormatContext, JsonFormatter,
};
use rome_formatter::{FormatOwnedWithRule, FormatRefWithRule, FormatResult, FormatRule};
impl FormatRule<rome_json_syntax::JsonRoot> for crate::json::auxiliary::root::FormatJsonRoot {
type Context = JsonFormatContext;
#[inline(always)]
fn fmt(&self, node: &rome_json_syntax::JsonRoot, f: &mut JsonFormatter) -> FormatResult<()> {
FormatNodeRule::<rome_json_syntax::JsonRoot>::fmt(self, node, f)
}
}
impl AsFormat<JsonFormatContext> for rome_json_syntax::JsonRoot {
type Format<'a> = FormatRefWithRule<
'a,
rome_json_syntax::JsonRoot,
crate::json::auxiliary::root::FormatJsonRoot,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::json::auxiliary::root::FormatJsonRoot::default(),
)
}
}
impl IntoFormat<JsonFormatContext> for rome_json_syntax::JsonRoot {
type Format = FormatOwnedWithRule<
rome_json_syntax::JsonRoot,
crate::json::auxiliary::root::FormatJsonRoot,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::json::auxiliary::root::FormatJsonRoot::default(),
)
}
}
impl FormatRule<rome_json_syntax::JsonStringValue>
for crate::json::value::string_value::FormatJsonStringValue
{
type Context = JsonFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_json_syntax::JsonStringValue,
f: &mut JsonFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_json_syntax::JsonStringValue>::fmt(self, node, f)
}
}
impl AsFormat<JsonFormatContext> for rome_json_syntax::JsonStringValue {
type Format<'a> = FormatRefWithRule<
'a,
rome_json_syntax::JsonStringValue,
crate::json::value::string_value::FormatJsonStringValue,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::json::value::string_value::FormatJsonStringValue::default(),
)
}
}
impl IntoFormat<JsonFormatContext> for rome_json_syntax::JsonStringValue {
type Format = FormatOwnedWithRule<
rome_json_syntax::JsonStringValue,
crate::json::value::string_value::FormatJsonStringValue,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::json::value::string_value::FormatJsonStringValue::default(),
)
}
}
impl FormatRule<rome_json_syntax::JsonBooleanValue>
for crate::json::value::boolean_value::FormatJsonBooleanValue
{
type Context = JsonFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_json_syntax::JsonBooleanValue,
f: &mut JsonFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_json_syntax::JsonBooleanValue>::fmt(self, node, f)
}
}
impl AsFormat<JsonFormatContext> for rome_json_syntax::JsonBooleanValue {
type Format<'a> = FormatRefWithRule<
'a,
rome_json_syntax::JsonBooleanValue,
crate::json::value::boolean_value::FormatJsonBooleanValue,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::json::value::boolean_value::FormatJsonBooleanValue::default(),
)
}
}
impl IntoFormat<JsonFormatContext> for rome_json_syntax::JsonBooleanValue {
type Format = FormatOwnedWithRule<
rome_json_syntax::JsonBooleanValue,
crate::json::value::boolean_value::FormatJsonBooleanValue,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::json::value::boolean_value::FormatJsonBooleanValue::default(),
)
}
}
impl FormatRule<rome_json_syntax::JsonNullValue>
for crate::json::value::null_value::FormatJsonNullValue
{
type Context = JsonFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_json_syntax::JsonNullValue,
f: &mut JsonFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_json_syntax::JsonNullValue>::fmt(self, node, f)
}
}
impl AsFormat<JsonFormatContext> for rome_json_syntax::JsonNullValue {
type Format<'a> = FormatRefWithRule<
'a,
rome_json_syntax::JsonNullValue,
crate::json::value::null_value::FormatJsonNullValue,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::json::value::null_value::FormatJsonNullValue::default(),
)
}
}
impl IntoFormat<JsonFormatContext> for rome_json_syntax::JsonNullValue {
type Format = FormatOwnedWithRule<
rome_json_syntax::JsonNullValue,
crate::json::value::null_value::FormatJsonNullValue,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::json::value::null_value::FormatJsonNullValue::default(),
)
}
}
impl FormatRule<rome_json_syntax::JsonNumberValue>
for crate::json::value::number_value::FormatJsonNumberValue
{
type Context = JsonFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_json_syntax::JsonNumberValue,
f: &mut JsonFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_json_syntax::JsonNumberValue>::fmt(self, node, f)
}
}
impl AsFormat<JsonFormatContext> for rome_json_syntax::JsonNumberValue {
type Format<'a> = FormatRefWithRule<
'a,
rome_json_syntax::JsonNumberValue,
crate::json::value::number_value::FormatJsonNumberValue,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::json::value::number_value::FormatJsonNumberValue::default(),
)
}
}
impl IntoFormat<JsonFormatContext> for rome_json_syntax::JsonNumberValue {
type Format = FormatOwnedWithRule<
rome_json_syntax::JsonNumberValue,
crate::json::value::number_value::FormatJsonNumberValue,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::json::value::number_value::FormatJsonNumberValue::default(),
)
}
}
impl FormatRule<rome_json_syntax::JsonArrayValue>
for crate::json::value::array_value::FormatJsonArrayValue
{
type Context = JsonFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_json_syntax::JsonArrayValue,
f: &mut JsonFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_json_syntax::JsonArrayValue>::fmt(self, node, f)
}
}
impl AsFormat<JsonFormatContext> for rome_json_syntax::JsonArrayValue {
type Format<'a> = FormatRefWithRule<
'a,
rome_json_syntax::JsonArrayValue,
crate::json::value::array_value::FormatJsonArrayValue,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::json::value::array_value::FormatJsonArrayValue::default(),
)
}
}
impl IntoFormat<JsonFormatContext> for rome_json_syntax::JsonArrayValue {
type Format = FormatOwnedWithRule<
rome_json_syntax::JsonArrayValue,
crate::json::value::array_value::FormatJsonArrayValue,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::json::value::array_value::FormatJsonArrayValue::default(),
)
}
}
impl FormatRule<rome_json_syntax::JsonObjectValue>
for crate::json::value::object_value::FormatJsonObjectValue
{
type Context = JsonFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_json_syntax::JsonObjectValue,
f: &mut JsonFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_json_syntax::JsonObjectValue>::fmt(self, node, f)
}
}
impl AsFormat<JsonFormatContext> for rome_json_syntax::JsonObjectValue {
type Format<'a> = FormatRefWithRule<
'a,
rome_json_syntax::JsonObjectValue,
crate::json::value::object_value::FormatJsonObjectValue,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::json::value::object_value::FormatJsonObjectValue::default(),
)
}
}
impl IntoFormat<JsonFormatContext> for rome_json_syntax::JsonObjectValue {
type Format = FormatOwnedWithRule<
rome_json_syntax::JsonObjectValue,
crate::json::value::object_value::FormatJsonObjectValue,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::json::value::object_value::FormatJsonObjectValue::default(),
)
}
}
impl FormatRule<rome_json_syntax::JsonMember> for crate::json::auxiliary::member::FormatJsonMember {
type Context = JsonFormatContext;
#[inline(always)]
fn fmt(&self, node: &rome_json_syntax::JsonMember, f: &mut JsonFormatter) -> FormatResult<()> {
FormatNodeRule::<rome_json_syntax::JsonMember>::fmt(self, node, f)
}
}
impl AsFormat<JsonFormatContext> for rome_json_syntax::JsonMember {
type Format<'a> = FormatRefWithRule<
'a,
rome_json_syntax::JsonMember,
crate::json::auxiliary::member::FormatJsonMember,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::json::auxiliary::member::FormatJsonMember::default(),
)
}
}
impl IntoFormat<JsonFormatContext> for rome_json_syntax::JsonMember {
type Format = FormatOwnedWithRule<
rome_json_syntax::JsonMember,
crate::json::auxiliary::member::FormatJsonMember,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::json::auxiliary::member::FormatJsonMember::default(),
)
}
}
impl FormatRule<rome_json_syntax::JsonMemberName>
for crate::json::auxiliary::member_name::FormatJsonMemberName
{
type Context = JsonFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_json_syntax::JsonMemberName,
f: &mut JsonFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_json_syntax::JsonMemberName>::fmt(self, node, f)
}
}
impl AsFormat<JsonFormatContext> for rome_json_syntax::JsonMemberName {
type Format<'a> = FormatRefWithRule<
'a,
rome_json_syntax::JsonMemberName,
crate::json::auxiliary::member_name::FormatJsonMemberName,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::json::auxiliary::member_name::FormatJsonMemberName::default(),
)
}
}
impl IntoFormat<JsonFormatContext> for rome_json_syntax::JsonMemberName {
type Format = FormatOwnedWithRule<
rome_json_syntax::JsonMemberName,
crate::json::auxiliary::member_name::FormatJsonMemberName,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::json::auxiliary::member_name::FormatJsonMemberName::default(),
)
}
}
impl AsFormat<JsonFormatContext> for rome_json_syntax::JsonArrayElementList {
type Format<'a> = FormatRefWithRule<
'a,
rome_json_syntax::JsonArrayElementList,
crate::json::lists::array_element_list::FormatJsonArrayElementList,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::json::lists::array_element_list::FormatJsonArrayElementList::default(),
)
}
}
impl IntoFormat<JsonFormatContext> for rome_json_syntax::JsonArrayElementList {
type Format = FormatOwnedWithRule<
rome_json_syntax::JsonArrayElementList,
crate::json::lists::array_element_list::FormatJsonArrayElementList,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::json::lists::array_element_list::FormatJsonArrayElementList::default(),
)
}
}
impl AsFormat<JsonFormatContext> for rome_json_syntax::JsonMemberList {
type Format<'a> = FormatRefWithRule<
'a,
rome_json_syntax::JsonMemberList,
crate::json::lists::member_list::FormatJsonMemberList,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::json::lists::member_list::FormatJsonMemberList::default(),
)
}
}
impl IntoFormat<JsonFormatContext> for rome_json_syntax::JsonMemberList {
type Format = FormatOwnedWithRule<
rome_json_syntax::JsonMemberList,
crate::json::lists::member_list::FormatJsonMemberList,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::json::lists::member_list::FormatJsonMemberList::default(),
)
}
}
impl FormatRule<rome_json_syntax::JsonBogus> for crate::json::bogus::bogus::FormatJsonBogus {
type Context = JsonFormatContext;
#[inline(always)]
fn fmt(&self, node: &rome_json_syntax::JsonBogus, f: &mut JsonFormatter) -> FormatResult<()> {
FormatBogusNodeRule::<rome_json_syntax::JsonBogus>::fmt(self, node, f)
}
}
impl AsFormat<JsonFormatContext> for rome_json_syntax::JsonBogus {
type Format<'a> = FormatRefWithRule<
'a,
rome_json_syntax::JsonBogus,
crate::json::bogus::bogus::FormatJsonBogus,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(self, crate::json::bogus::bogus::FormatJsonBogus::default())
}
}
impl IntoFormat<JsonFormatContext> for rome_json_syntax::JsonBogus {
type Format = FormatOwnedWithRule<
rome_json_syntax::JsonBogus,
crate::json::bogus::bogus::FormatJsonBogus,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(self, crate::json::bogus::bogus::FormatJsonBogus::default())
}
}
impl FormatRule<rome_json_syntax::JsonBogusValue>
for crate::json::bogus::bogus_value::FormatJsonBogusValue
{
type Context = JsonFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_json_syntax::JsonBogusValue,
f: &mut JsonFormatter,
) -> FormatResult<()> {
FormatBogusNodeRule::<rome_json_syntax::JsonBogusValue>::fmt(self, node, f)
}
}
impl AsFormat<JsonFormatContext> for rome_json_syntax::JsonBogusValue {
type Format<'a> = FormatRefWithRule<
'a,
rome_json_syntax::JsonBogusValue,
crate::json::bogus::bogus_value::FormatJsonBogusValue,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::json::bogus::bogus_value::FormatJsonBogusValue::default(),
)
}
}
impl IntoFormat<JsonFormatContext> for rome_json_syntax::JsonBogusValue {
type Format = FormatOwnedWithRule<
rome_json_syntax::JsonBogusValue,
crate::json::bogus::bogus_value::FormatJsonBogusValue,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::json::bogus::bogus_value::FormatJsonBogusValue::default(),
)
}
}
impl AsFormat<JsonFormatContext> for rome_json_syntax::AnyJsonValue {
type Format<'a> = FormatRefWithRule<
'a,
rome_json_syntax::AnyJsonValue,
crate::json::any::value::FormatAnyJsonValue,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(self, crate::json::any::value::FormatAnyJsonValue::default())
}
}
impl IntoFormat<JsonFormatContext> for rome_json_syntax::AnyJsonValue {
type Format = FormatOwnedWithRule<
rome_json_syntax::AnyJsonValue,
crate::json::any::value::FormatAnyJsonValue,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(self, crate::json::any::value::FormatAnyJsonValue::default())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/mod.rs | crates/rome_json_formatter/src/json/mod.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
pub(crate) mod any;
pub(crate) mod auxiliary;
pub(crate) mod bogus;
pub(crate) mod lists;
pub(crate) mod value;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/lists/array_element_list.rs | crates/rome_json_formatter/src/json/lists/array_element_list.rs | use crate::prelude::*;
use crate::separated::FormatAstSeparatedListExtension;
use rome_formatter::write;
use rome_json_syntax::{AnyJsonValue, JsonArrayElementList};
use rome_rowan::{AstNode, AstSeparatedList};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsonArrayElementList;
impl FormatRule<JsonArrayElementList> for FormatJsonArrayElementList {
type Context = JsonFormatContext;
fn fmt(&self, node: &JsonArrayElementList, f: &mut JsonFormatter) -> FormatResult<()> {
let layout = if can_concisely_print_array_list(node) {
ArrayLayout::Fill
} else {
ArrayLayout::OnePerLine
};
match layout {
ArrayLayout::Fill => {
let mut filler = f.fill();
for (element, formatted) in node.iter().zip(node.format_separated(",")) {
filler.entry(
&format_once(|f| {
if get_lines_before(element?.syntax()) > 1 {
write!(f, [empty_line()])
} else {
write!(f, [soft_line_break_or_space()])
}
}),
&formatted,
);
}
filler.finish()
}
ArrayLayout::OnePerLine => {
let mut join = f.join_nodes_with_soft_line();
for (element, formatted) in node.elements().zip(node.format_separated(",")) {
join.entry(element.node()?.syntax(), &formatted);
}
join.finish()
}
}
}
}
#[derive(Copy, Clone, Debug)]
enum ArrayLayout {
/// Tries to fit as many array elements on a single line as possible.
///
/// ```json
/// [
/// 1, 2, 3,
/// 5, 6,
/// ]
/// ```
Fill,
/// Prints every element on a single line if the array exceeds the line width, or any
/// of its elements gets printed in *expanded* mode.
/// ```json
/// [
/// { "a": 3 },
/// 4,
/// 3,
/// ]
/// ```
OnePerLine,
}
/// Returns `true` if the array can be "fill-printed" instead of breaking each element on
/// a different line.
///
/// An array can be "fill printed" if it only contains literal elements.
pub(crate) fn can_concisely_print_array_list(list: &JsonArrayElementList) -> bool {
if list.is_empty() {
return false;
}
list.iter()
.all(|node| matches!(node, Ok(AnyJsonValue::JsonNumberValue(_))))
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/lists/mod.rs | crates/rome_json_formatter/src/json/lists/mod.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
pub(crate) mod array_element_list;
pub(crate) mod member_list;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/lists/member_list.rs | crates/rome_json_formatter/src/json/lists/member_list.rs | use crate::prelude::*;
use crate::separated::FormatAstSeparatedListExtension;
use rome_json_syntax::JsonMemberList;
use rome_rowan::{AstNode, AstSeparatedList};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsonMemberList;
impl FormatRule<JsonMemberList> for FormatJsonMemberList {
type Context = JsonFormatContext;
fn fmt(&self, node: &JsonMemberList, f: &mut JsonFormatter) -> FormatResult<()> {
let mut join = f.join_nodes_with_soft_line();
for (element, formatted) in node.elements().zip(node.format_separated(",")) {
join.entry(element.node()?.syntax(), &formatted);
}
join.finish()
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/bogus/bogus_value.rs | crates/rome_json_formatter/src/json/bogus/bogus_value.rs | use crate::FormatBogusNodeRule;
use rome_json_syntax::JsonBogusValue;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsonBogusValue;
impl FormatBogusNodeRule<JsonBogusValue> for FormatJsonBogusValue {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/bogus/mod.rs | crates/rome_json_formatter/src/json/bogus/mod.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
#[allow(clippy::module_inception)]
pub(crate) mod bogus;
pub(crate) mod bogus_value;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/bogus/bogus.rs | crates/rome_json_formatter/src/json/bogus/bogus.rs | use crate::FormatBogusNodeRule;
use rome_json_syntax::JsonBogus;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsonBogus;
impl FormatBogusNodeRule<JsonBogus> for FormatJsonBogus {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/value/boolean_value.rs | crates/rome_json_formatter/src/json/value/boolean_value.rs | use crate::prelude::*;
use rome_json_syntax::JsonBooleanValue;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsonBooleanValue;
impl FormatNodeRule<JsonBooleanValue> for FormatJsonBooleanValue {
fn fmt_fields(&self, node: &JsonBooleanValue, f: &mut JsonFormatter) -> FormatResult<()> {
node.value_token()?.format().fmt(f)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/value/null_value.rs | crates/rome_json_formatter/src/json/value/null_value.rs | use crate::prelude::*;
use rome_json_syntax::JsonNullValue;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsonNullValue;
impl FormatNodeRule<JsonNullValue> for FormatJsonNullValue {
fn fmt_fields(&self, node: &JsonNullValue, f: &mut JsonFormatter) -> FormatResult<()> {
node.value_token()?.format().fmt(f)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/value/string_value.rs | crates/rome_json_formatter/src/json/value/string_value.rs | use crate::format_string::format_string_token;
use crate::prelude::*;
use rome_json_syntax::JsonStringValue;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsonStringValue;
impl FormatNodeRule<JsonStringValue> for FormatJsonStringValue {
fn fmt_fields(&self, node: &JsonStringValue, f: &mut JsonFormatter) -> FormatResult<()> {
format_string_token(&node.value_token()?).fmt(f)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/value/mod.rs | crates/rome_json_formatter/src/json/value/mod.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
pub(crate) mod array_value;
pub(crate) mod boolean_value;
pub(crate) mod null_value;
pub(crate) mod number_value;
pub(crate) mod object_value;
pub(crate) mod string_value;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/value/array_value.rs | crates/rome_json_formatter/src/json/value/array_value.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_json_syntax::JsonArrayValue;
use rome_json_syntax::JsonArrayValueFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsonArrayValue;
impl FormatNodeRule<JsonArrayValue> for FormatJsonArrayValue {
fn fmt_fields(&self, node: &JsonArrayValue, f: &mut JsonFormatter) -> FormatResult<()> {
let JsonArrayValueFields {
l_brack_token,
elements,
r_brack_token,
} = node.as_fields();
write!(
f,
[
l_brack_token.format(),
group(&soft_block_indent(&elements.format())),
r_brack_token.format()
]
)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/value/number_value.rs | crates/rome_json_formatter/src/json/value/number_value.rs | use crate::prelude::*;
use rome_formatter::token::number::format_number_token;
use rome_json_syntax::JsonNumberValue;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsonNumberValue;
impl FormatNodeRule<JsonNumberValue> for FormatJsonNumberValue {
fn fmt_fields(&self, node: &JsonNumberValue, f: &mut JsonFormatter) -> FormatResult<()> {
format_number_token(&node.value_token()?).fmt(f)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/value/object_value.rs | crates/rome_json_formatter/src/json/value/object_value.rs | use crate::prelude::*;
use rome_formatter::{format_args, write};
use rome_json_syntax::JsonObjectValue;
use rome_rowan::AstNode;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsonObjectValue;
impl FormatNodeRule<JsonObjectValue> for FormatJsonObjectValue {
fn fmt_fields(&self, node: &JsonObjectValue, f: &mut JsonFormatter) -> FormatResult<()> {
let should_expand = node.json_member_list().syntax().has_leading_newline();
let list = format_with(|f| {
write!(
f,
[group(&soft_space_or_block_indent(
&node.json_member_list().format()
))
.should_expand(should_expand)]
)
});
if f.comments().has_leading_comments(node.syntax()) {
write!(
f,
[
format_leading_comments(node.syntax()),
group(&format_args![
node.l_curly_token().format(),
list,
node.r_curly_token().format()
]),
]
)
} else {
write!(
f,
[
node.l_curly_token().format(),
list,
node.r_curly_token().format()
]
)
}
}
fn fmt_leading_comments(&self, _: &JsonObjectValue, _: &mut JsonFormatter) -> FormatResult<()> {
// Formatted as part of `fmt_fields`
Ok(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/auxiliary/member_name.rs | crates/rome_json_formatter/src/json/auxiliary/member_name.rs | use crate::format_string::format_string_token;
use crate::prelude::*;
use rome_json_syntax::JsonMemberName;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsonMemberName;
impl FormatNodeRule<JsonMemberName> for FormatJsonMemberName {
fn fmt_fields(&self, node: &JsonMemberName, f: &mut JsonFormatter) -> FormatResult<()> {
format_string_token(&node.value_token()?).fmt(f)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/auxiliary/root.rs | crates/rome_json_formatter/src/json/auxiliary/root.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_json_syntax::{JsonRoot, JsonRootFields};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsonRoot;
impl FormatNodeRule<JsonRoot> for FormatJsonRoot {
fn fmt_fields(&self, node: &JsonRoot, f: &mut JsonFormatter) -> FormatResult<()> {
let JsonRootFields { value, eof_token } = node.as_fields();
match &value {
Ok(value) => {
write!(
f,
[
format_or_verbatim(value.format()),
format_removed(&eof_token?),
hard_line_break()
]
)
}
// Don't fail formatting if the root contains no root value
Err(_) => {
write!(f, [format_verbatim_node(node.syntax())])
}
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/auxiliary/mod.rs | crates/rome_json_formatter/src/json/auxiliary/mod.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
pub(crate) mod member;
pub(crate) mod member_name;
pub(crate) mod root;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/auxiliary/member.rs | crates/rome_json_formatter/src/json/auxiliary/member.rs | use crate::prelude::*;
use rome_formatter::{format_args, write};
use rome_json_syntax::{JsonMember, JsonMemberFields};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsonMember;
impl FormatNodeRule<JsonMember> for FormatJsonMember {
fn fmt_fields(&self, node: &JsonMember, f: &mut JsonFormatter) -> FormatResult<()> {
let JsonMemberFields {
name,
colon_token,
value,
} = node.as_fields();
write!(
f,
[group(&format_args![
&name.format(),
colon_token.format(),
space(),
format_or_verbatim(value?.format())
])]
)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/any/value.rs | crates/rome_json_formatter/src/json/any/value.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
use crate::prelude::*;
use rome_json_syntax::AnyJsonValue;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyJsonValue;
impl FormatRule<AnyJsonValue> for FormatAnyJsonValue {
type Context = JsonFormatContext;
fn fmt(&self, node: &AnyJsonValue, f: &mut JsonFormatter) -> FormatResult<()> {
match node {
AnyJsonValue::JsonStringValue(node) => node.format().fmt(f),
AnyJsonValue::JsonBooleanValue(node) => node.format().fmt(f),
AnyJsonValue::JsonNullValue(node) => node.format().fmt(f),
AnyJsonValue::JsonNumberValue(node) => node.format().fmt(f),
AnyJsonValue::JsonArrayValue(node) => node.format().fmt(f),
AnyJsonValue::JsonObjectValue(node) => node.format().fmt(f),
AnyJsonValue::JsonBogusValue(node) => node.format().fmt(f),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/src/json/any/mod.rs | crates/rome_json_formatter/src/json/any/mod.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
pub(crate) mod value;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/tests/quick_test.rs | crates/rome_json_formatter/tests/quick_test.rs | use rome_formatter_test::check_reformat::CheckReformat;
use rome_json_formatter::context::JsonFormatOptions;
use rome_json_formatter::format_node;
use rome_json_parser::{parse_json, JsonParserOptions};
mod language {
include!("language.rs");
}
#[ignore]
#[test]
// use this test check if your snippet prints as you wish, without using a snapshot
fn quick_test() {
let src = r#"// comment
// comment
{ "test": "test"} /** comment **/
"#;
let parse = parse_json(src, JsonParserOptions::default().with_allow_comments());
let options = JsonFormatOptions::default();
let result = format_node(options.clone(), &parse.syntax())
.unwrap()
.print()
.unwrap();
let root = &parse.syntax();
let language = language::JsonTestFormatLanguage::default();
let check_reformat =
CheckReformat::new(root, result.as_code(), "quick_test", &language, options);
check_reformat.check_reformat();
assert_eq!(
result.as_code(),
r#"// comment
// comment
{ "test": "test"}
// comment
"#
);
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/tests/spec_test.rs | crates/rome_json_formatter/tests/spec_test.rs | use rome_formatter_test::spec::{SpecSnapshot, SpecTestFile};
use rome_json_formatter::context::JsonFormatOptions;
use std::path::Path;
mod language {
include!("language.rs");
}
/// [insta.rs](https://insta.rs/docs) snapshot testing
///
/// For better development workflow, run
/// `cargo watch -i '*.new' -x 'test -p rome_js_formatter formatter'`
///
/// To review and commit the snapshots, `cargo install cargo-insta`, and run
/// `cargo insta review` or `cargo insta accept`
///
/// The input and the expected output are stored as dedicated files in the `tests/specs` directory where
/// the input file name is `{spec_name}.json` and the output file name is `{spec_name}.json.snap`.
///
/// Specs can be grouped in directories by specifying the directory name in the spec name. Examples:
///
/// # Examples
///
/// * `json/null` -> input: `tests/specs/json/null.json`, expected output: `tests/specs/json/null.json.snap`
/// * `null` -> input: `tests/specs/null.json`, expected output: `tests/specs/null.json.snap`
pub fn run(spec_input_file: &str, _expected_file: &str, test_directory: &str, _file_type: &str) {
let root_path = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/specs/"));
let Some(test_file) = SpecTestFile::try_from_file(spec_input_file, root_path) else { return; };
let options = JsonFormatOptions::default();
let language = language::JsonTestFormatLanguage::default();
let snapshot = SpecSnapshot::new(test_file, test_directory, language, options);
snapshot.test()
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/tests/prettier_tests.rs | crates/rome_json_formatter/tests/prettier_tests.rs | use std::{env, path::Path};
use rome_formatter::IndentStyle;
use rome_formatter_test::test_prettier_snapshot::{PrettierSnapshot, PrettierTestFile};
use rome_json_formatter::context::JsonFormatOptions;
#[derive(serde::Serialize)]
struct TestInfo {
test_file: String,
}
mod language;
tests_macros::gen_tests! {"tests/specs/prettier/{json}/**/*.{json}", crate::test_snapshot, ""}
fn test_snapshot(input: &'static str, _: &str, _: &str, _: &str) {
countme::enable(true);
let root_path = Path::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/specs/prettier/"
));
let test_file = PrettierTestFile::new(input, root_path);
let options = JsonFormatOptions::default().with_indent_style(IndentStyle::Space(2));
let language = language::JsonTestFormatLanguage::default();
let snapshot = PrettierSnapshot::new(test_file, language, options);
snapshot.test()
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/tests/spec_tests.rs | crates/rome_json_formatter/tests/spec_tests.rs | mod quick_test;
mod spec_test;
mod formatter {
mod json_module {
tests_macros::gen_tests! {"tests/specs/json/**/*.json", crate::spec_test::run, ""}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_formatter/tests/language.rs | crates/rome_json_formatter/tests/language.rs | use rome_formatter::{FormatContext, FormatResult, Formatted, IndentStyle, LineWidth, Printed};
use rome_formatter_test::TestFormatLanguage;
use rome_json_formatter::context::{JsonFormatContext, JsonFormatOptions};
use rome_json_formatter::{format_node, format_range, JsonFormatLanguage};
use rome_json_parser::{parse_json, JsonParserOptions};
use rome_json_syntax::{JsonFileSource, JsonLanguage};
use rome_parser::AnyParse;
use rome_rowan::{FileSource, SyntaxNode, TextRange};
use serde::{Deserialize, Serialize};
#[derive(Default)]
pub struct JsonTestFormatLanguage {
source_type: JsonFileSource,
}
impl TestFormatLanguage for JsonTestFormatLanguage {
type SyntaxLanguage = JsonLanguage;
type Options = JsonFormatOptions;
type Context = JsonFormatContext;
type FormatLanguage = JsonFormatLanguage;
fn parse(&self, text: &str) -> AnyParse {
let parse = parse_json(text, JsonParserOptions::default().with_allow_comments());
AnyParse::new(
parse.syntax().as_send().unwrap(),
parse.into_diagnostics(),
self.source_type.as_any_file_source(),
)
}
fn deserialize_format_options(
&self,
options: &str,
) -> Vec<<Self::Context as FormatContext>::Options> {
let test_options: TestOptions = serde_json::from_str(options).unwrap();
test_options
.cases
.into_iter()
.map(|case| case.into())
.collect()
}
fn format_node(
&self,
options: Self::Options,
node: &SyntaxNode<Self::SyntaxLanguage>,
) -> FormatResult<Formatted<Self::Context>> {
format_node(options, node)
}
fn format_range(
&self,
options: Self::Options,
node: &SyntaxNode<Self::SyntaxLanguage>,
range: TextRange,
) -> FormatResult<Printed> {
format_range(options, node, range)
}
}
#[derive(Debug, Eq, PartialEq, Clone, Copy, Deserialize, Serialize)]
pub enum JsonSerializableIndentStyle {
/// Tab
Tab,
/// Space, with its quantity
Space(u8),
}
impl From<JsonSerializableIndentStyle> for IndentStyle {
fn from(test: JsonSerializableIndentStyle) -> Self {
match test {
JsonSerializableIndentStyle::Tab => IndentStyle::Tab,
JsonSerializableIndentStyle::Space(spaces) => IndentStyle::Space(spaces),
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone, Copy)]
pub struct JsonSerializableFormatOptions {
/// The indent style.
pub indent_style: Option<JsonSerializableIndentStyle>,
/// What's the max width of a line. Defaults to 80.
pub line_width: Option<u16>,
}
impl From<JsonSerializableFormatOptions> for JsonFormatOptions {
fn from(test: JsonSerializableFormatOptions) -> Self {
JsonFormatOptions::default()
.with_indent_style(
test.indent_style
.map_or_else(|| IndentStyle::Tab, |value| value.into()),
)
.with_line_width(
test.line_width
.and_then(|width| LineWidth::try_from(width).ok())
.unwrap_or_default(),
)
}
}
#[derive(Debug, Deserialize, Serialize)]
struct TestOptions {
cases: Vec<JsonSerializableFormatOptions>,
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_text_edit/src/lib.rs | crates/rome_text_edit/src/lib.rs | //! Representation of a `TextEdit`.
//!
//! This is taken from [rust-analyzer's text_edit crate](https://rust-analyzer.github.io/rust-analyzer/text_edit/index.html)
#![warn(
rust_2018_idioms,
unused_lifetimes,
semicolon_in_expressions_from_macros
)]
use std::{cmp::Ordering, num::NonZeroU32};
use rome_text_size::{TextRange, TextSize};
use serde::{Deserialize, Serialize};
pub use similar::ChangeTag;
use similar::{utils::TextDiffRemapper, TextDiff};
#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct TextEdit {
dictionary: String,
ops: Vec<CompressedOp>,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum CompressedOp {
DiffOp(DiffOp),
EqualLines { line_count: NonZeroU32 },
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum DiffOp {
Equal { range: TextRange },
Insert { range: TextRange },
Delete { range: TextRange },
}
impl DiffOp {
pub fn tag(self) -> ChangeTag {
match self {
DiffOp::Equal { .. } => ChangeTag::Equal,
DiffOp::Insert { .. } => ChangeTag::Insert,
DiffOp::Delete { .. } => ChangeTag::Delete,
}
}
pub fn text(self, diff: &TextEdit) -> &str {
let range = match self {
DiffOp::Equal { range } => range,
DiffOp::Insert { range } => range,
DiffOp::Delete { range } => range,
};
diff.get_text(range)
}
}
#[derive(Debug, Default, Clone)]
pub struct TextEditBuilder {
index: Vec<TextRange>,
edit: TextEdit,
}
impl TextEdit {
/// Convenience method for creating a new [TextEditBuilder]
pub fn builder() -> TextEditBuilder {
TextEditBuilder::default()
}
/// Create a diff of `old` to `new`, tokenized by Unicode words
pub fn from_unicode_words(old: &str, new: &str) -> Self {
let mut builder = Self::builder();
let diff = TextDiff::configure()
.newline_terminated(true)
.diff_unicode_words(old, new);
let remapper = TextDiffRemapper::from_text_diff(&diff, old, new);
for (tag, text) in diff.ops().iter().flat_map(|op| remapper.iter_slices(op)) {
match tag {
ChangeTag::Equal => {
builder.equal(text);
}
ChangeTag::Delete => {
builder.delete(text);
}
ChangeTag::Insert => {
builder.insert(text);
}
}
}
builder.finish()
}
/// Returns the number of [DiffOp] in this [TextEdit]
pub fn len(&self) -> usize {
self.ops.len()
}
/// Return `true` is this [TextEdit] doesn't contain any [DiffOp]
pub fn is_empty(&self) -> bool {
self.ops.is_empty()
}
/// Returns an [Iterator] over the [DiffOp] of this [TextEdit]
pub fn iter(&self) -> std::slice::Iter<'_, CompressedOp> {
self.into_iter()
}
/// Return the text value of range interned in this [TextEdit] dictionnary
pub fn get_text(&self, range: TextRange) -> &str {
&self.dictionary[range]
}
/// Return the content of the "new" revision of the text represented in
/// this [TextEdit]. This methods needs to be provided with the "old"
/// revision of the string since [TextEdit] doesn't store the content of
/// text sections that are equal between revisions
pub fn new_string(&self, old_string: &str) -> String {
let mut output = String::new();
let mut input_position = TextSize::from(0);
for op in &self.ops {
match op {
CompressedOp::DiffOp(DiffOp::Equal { range }) => {
output.push_str(&self.dictionary[*range]);
input_position += range.len();
}
CompressedOp::DiffOp(DiffOp::Insert { range }) => {
output.push_str(&self.dictionary[*range]);
}
CompressedOp::DiffOp(DiffOp::Delete { range }) => {
input_position += range.len();
}
CompressedOp::EqualLines { line_count } => {
let start = u32::from(input_position) as usize;
let input = &old_string[start..];
let line_break_count = line_count.get() as usize + 1;
for line in input.split_inclusive('\n').take(line_break_count) {
output.push_str(line);
input_position += TextSize::of(line);
}
}
}
}
output
}
}
impl IntoIterator for TextEdit {
type Item = CompressedOp;
type IntoIter = std::vec::IntoIter<CompressedOp>;
fn into_iter(self) -> Self::IntoIter {
self.ops.into_iter()
}
}
impl<'a> IntoIterator for &'a TextEdit {
type Item = &'a CompressedOp;
type IntoIter = std::slice::Iter<'a, CompressedOp>;
fn into_iter(self) -> Self::IntoIter {
self.ops.iter()
}
}
impl TextEditBuilder {
pub fn is_empty(&self) -> bool {
self.edit.ops.is_empty()
}
/// Add a piece of string to the dictionnary, returning the corresponding
/// range in the dictionnary string
fn intern(&mut self, value: &str) -> TextRange {
let value_bytes = value.as_bytes();
let value_len = TextSize::of(value);
let index = self.index.binary_search_by(|range| {
let entry = self.edit.dictionary[*range].as_bytes();
for (lhs, rhs) in entry.iter().zip(value_bytes) {
match lhs.cmp(rhs) {
Ordering::Equal => continue,
ordering => return ordering,
}
}
match entry.len().cmp(&value_bytes.len()) {
// If all bytes in the shared sub-slice match, the dictionary
// entry is allowed to be longer than the text being inserted
Ordering::Greater => Ordering::Equal,
ordering => ordering,
}
});
match index {
Ok(index) => {
let range = self.index[index];
let len = value_len.min(range.len());
TextRange::at(range.start(), len)
}
Err(index) => {
let start = TextSize::of(&self.edit.dictionary);
self.edit.dictionary.push_str(value);
let range = TextRange::at(start, value_len);
self.index.insert(index, range);
range
}
}
}
pub fn equal(&mut self, text: &str) {
match compress_equal_op(text) {
Some((start, mid, end)) => {
let start = self.intern(start);
self.edit
.ops
.push(CompressedOp::DiffOp(DiffOp::Equal { range: start }));
self.edit
.ops
.push(CompressedOp::EqualLines { line_count: mid });
let end = self.intern(end);
self.edit
.ops
.push(CompressedOp::DiffOp(DiffOp::Equal { range: end }));
}
None => {
let range = self.intern(text);
self.edit
.ops
.push(CompressedOp::DiffOp(DiffOp::Equal { range }));
}
}
}
pub fn insert(&mut self, text: &str) {
let range = self.intern(text);
self.edit
.ops
.push(CompressedOp::DiffOp(DiffOp::Insert { range }));
}
pub fn delete(&mut self, text: &str) {
let range = self.intern(text);
self.edit
.ops
.push(CompressedOp::DiffOp(DiffOp::Delete { range }));
}
pub fn replace(&mut self, old: &str, new: &str) {
self.delete(old);
self.insert(new);
}
pub fn finish(self) -> TextEdit {
self.edit
}
}
/// Number of lines to keep as [DiffOp::Equal] operations around a
/// [CompressedOp::EqualCompressedLines] operation. This has the effect of
/// making the compressed diff retain a few line of equal content around
/// changes, which is useful for display as it makes it possible to print a few
/// context lines around changes without having to keep the full original text
/// around.
const COMPRESSED_DIFFS_CONTEXT_LINES: usize = 2;
fn compress_equal_op(text: &str) -> Option<(&str, NonZeroU32, &str)> {
let mut iter = text.split('\n');
let mut leading_len = COMPRESSED_DIFFS_CONTEXT_LINES;
for _ in 0..=COMPRESSED_DIFFS_CONTEXT_LINES {
leading_len += iter.next()?.len();
}
let mut trailing_len = COMPRESSED_DIFFS_CONTEXT_LINES;
for _ in 0..=COMPRESSED_DIFFS_CONTEXT_LINES {
trailing_len += iter.next_back()?.len();
}
let mid_count = iter.count();
let mid_count = u32::try_from(mid_count).ok()?;
let mid_count = NonZeroU32::new(mid_count)?;
let trailing_start = text.len().saturating_sub(trailing_len);
Some((&text[..leading_len], mid_count, &text[trailing_start..]))
}
#[cfg(test)]
mod tests {
use std::num::NonZeroU32;
use crate::{compress_equal_op, TextEdit};
#[test]
fn compress_short() {
let output = compress_equal_op(
"
start 1
start 2
end 1
end 2
",
);
assert_eq!(output, None);
}
#[test]
fn compress_long() {
let output = compress_equal_op(
"
start 1
start 2
mid 1
mid 2
mid 3
end 1
end 2
",
);
assert_eq!(
output,
Some((
"\nstart 1\nstart 2",
NonZeroU32::new(3).unwrap(),
"end 1\nend 2\n"
))
);
}
#[test]
fn new_string_compressed() {
const OLD: &str = "line 1 old
line 2
line 3
line 4
line 5
line 6
line 7 old";
const NEW: &str = "line 1 new
line 2
line 3
line 4
line 5
line 6
line 7 new";
let diff = TextEdit::from_unicode_words(OLD, NEW);
let new_string = diff.new_string(OLD);
assert_eq!(new_string, NEW);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/lib.rs | crates/rome_js_semantic/src/lib.rs | mod events;
mod semantic_model;
#[cfg(test)]
mod tests;
pub use events::*;
pub use semantic_model::*;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/events.rs | crates/rome_js_semantic/src/events.rs | //! Events emitted by the [SemanticEventExtractor] which are then constructed into the Semantic Model
use rustc_hash::FxHashMap;
use std::collections::{HashMap, VecDeque};
use rome_js_syntax::{
AnyJsAssignment, AnyJsAssignmentPattern, AnyJsExpression, JsAssignmentExpression,
JsCallExpression, JsForVariableDeclaration, JsIdentifierAssignment, JsIdentifierBinding,
JsLanguage, JsParenthesizedExpression, JsReferenceIdentifier, JsSyntaxKind, JsSyntaxNode,
JsSyntaxToken, JsVariableDeclaration, JsVariableDeclarator, JsVariableDeclaratorList,
JsxReferenceIdentifier, TextRange, TextSize, TsIdentifierBinding, TsTypeParameterName,
};
use rome_rowan::{syntax::Preorder, AstNode, SyntaxNodeCast, SyntaxNodeOptionExt, TokenText};
/// Events emitted by the [SemanticEventExtractor]. These events are later
/// made into the Semantic Model.
#[derive(Debug)]
pub enum SemanticEvent {
/// Tracks where a new symbol declaration is found.
/// Generated for:
/// - Variable Declarations
/// - Import bindings
/// - Functions parameters
DeclarationFound {
range: TextRange,
scope_started_at: TextSize,
scope_id: usize,
hoisted_scope_id: Option<usize>,
name: TokenText,
},
/// Tracks where a symbol is read, but only if its declaration
/// is before this reference.
/// Generated for:
/// - All reference identifiers
Read {
range: TextRange,
declared_at: TextRange,
scope_id: usize,
},
/// Tracks where a symbol is read, but only if its declaration
/// was hoisted. This means that its declaration is after this reference.
/// - All reference identifiers
HoistedRead {
range: TextRange,
declared_at: TextRange,
scope_id: usize,
},
/// Tracks where a symbol is written, but only if its declaration
/// is before this reference.
/// Generated for:
/// - All identifier assignments
Write {
range: TextRange,
declared_at: TextRange,
scope_id: usize,
},
/// Tracks where a symbol is written, but only if its declaration
/// was hoisted. This means that its declaration is after this reference.
/// Generated for:
/// - All identifier assignments
HoistedWrite {
range: TextRange,
declared_at: TextRange,
scope_id: usize,
},
/// Tracks references that do no have any matching binding
/// Generated for:
/// - Unmatched reference identifiers
UnresolvedReference { is_read: bool, range: TextRange },
/// Tracks where a new scope starts
/// Generated for:
/// - Blocks
/// - Function body
ScopeStarted {
range: TextRange,
scope_id: usize,
parent_scope_id: Option<usize>,
is_closure: bool,
},
/// Tracks where a scope ends
/// Generated for:
/// - Blocks
/// - Function body
ScopeEnded {
range: TextRange,
started_at: TextSize,
scope_id: usize,
},
/// Tracks where a symbol is exported.
/// The range points to the binding that
/// is being exported
Exported { range: TextRange },
}
impl SemanticEvent {
pub fn range(&self) -> &TextRange {
match self {
SemanticEvent::DeclarationFound { range, .. } => range,
SemanticEvent::ScopeStarted { range, .. } => range,
SemanticEvent::ScopeEnded { range, .. } => range,
SemanticEvent::Read { range, .. } => range,
SemanticEvent::HoistedRead { range, .. } => range,
SemanticEvent::Write { range, .. } => range,
SemanticEvent::HoistedWrite { range, .. } => range,
SemanticEvent::UnresolvedReference { range, .. } => range,
SemanticEvent::Exported { range } => range,
}
}
pub fn str<'a>(&self, code: &'a str) -> &'a str {
let range = self.range();
let start: u32 = range.start().into();
let end: u32 = range.end().into();
&code[start as usize..end as usize]
}
}
/// Extracts [SemanticEvent] from [SyntaxNode].
///
/// The extraction is not entirely pull based, nor entirely push based.
/// This happens because some nodes can generate multiple events.
/// A hoisted variable declaration like ```var a```, being the more obvious
/// example. As soon ```a``` is hoisted, all references of ```a``` are solved
/// on this node.
///
/// For a simpler way to extract [SemanticEvent] see [semantic_events] or [SemanticEventIterator].
///
/// To use the [SemanticEventExtractor] one must push the current node, following
/// the [PreOrder] of the tree, and must pull events until [Pop] returns [None].
///
/// ```rust
/// use rome_js_parser::*;
/// use rome_js_syntax::*;
/// use rome_js_semantic::*;
/// let tree = parse("let a = 1", JsFileSource::js_script(), JsParserOptions::default());
/// let mut extractor = SemanticEventExtractor::new();
/// for e in tree.syntax().preorder() {
/// match e {
/// WalkEvent::Enter(node) => extractor.enter(&node),
/// WalkEvent::Leave(node) => extractor.leave(&node),
/// _ => {}
/// }
///
/// while let Some(e) = extractor.pop() {
/// dbg!(e);
/// }
/// }
/// ```
#[derive(Default, Debug)]
pub struct SemanticEventExtractor {
stash: VecDeque<SemanticEvent>,
scopes: Vec<Scope>,
next_scope_id: usize,
/// At any point this is the set of available bindings and
/// the range of its declaration
bindings: FxHashMap<TokenText, BindingInfo>,
}
/// Holds the text range of the token when it is bound,
/// along with the kind of declaration
#[derive(Debug)]
struct BindingInfo {
text_range: TextRange,
/// For export determination, it is necessary to provide
/// information on how a specific token is bound
declaration_kind: JsSyntaxKind,
}
#[derive(Debug)]
struct Binding {
name: TokenText,
}
#[derive(Debug)]
enum Reference {
Read { range: TextRange, is_exported: bool },
Write { range: TextRange },
}
impl Reference {
fn is_read(&self) -> bool {
matches!(self, Reference::Read { .. })
}
pub fn range(&self) -> &TextRange {
match self {
Reference::Read { range, .. } => range,
Reference::Write { range } => range,
}
}
}
#[derive(Debug)]
pub enum ScopeHoisting {
DontHoistDeclarationsToParent,
HoistDeclarationsToParent,
}
#[derive(Debug)]
struct Scope {
scope_id: usize,
started_at: TextSize,
/// All bindings declared inside this scope
bindings: Vec<Binding>,
/// References that still needs to be bound and
/// will be solved at the end of the scope
references: HashMap<TokenText, Vec<Reference>>,
/// All bindings that where shadowed and will be
/// restored after this scope ends.
shadowed: Vec<(TokenText, BindingInfo)>,
/// If this scope allows declarations to be hoisted
/// to parent scope or not
hoisting: ScopeHoisting,
}
/// Returns the node that defines the result of the expression
fn result_of(expr: &JsParenthesizedExpression) -> Option<AnyJsExpression> {
let mut expr = Some(AnyJsExpression::JsParenthesizedExpression(expr.clone()));
loop {
match expr {
Some(AnyJsExpression::JsParenthesizedExpression(e)) => {
expr = e.expression().ok();
}
Some(AnyJsExpression::JsSequenceExpression(e)) => {
expr = e.right().ok();
}
Some(AnyJsExpression::JsAssignmentExpression(e)) => {
expr = e.right().ok();
}
Some(expr) => return Some(expr),
None => return None,
}
}
}
impl SemanticEventExtractor {
pub fn new() -> Self {
Self {
stash: VecDeque::new(),
scopes: vec![],
next_scope_id: 0,
bindings: FxHashMap::default(),
}
}
/// See [SemanticEvent] for a more detailed description
/// of which ```SyntaxNode``` generates which events.
#[inline]
pub fn enter(&mut self, node: &JsSyntaxNode) {
use rome_js_syntax::JsSyntaxKind::*;
match node.kind() {
JS_IDENTIFIER_BINDING | TS_IDENTIFIER_BINDING | TS_TYPE_PARAMETER_NAME => {
self.enter_identifier_binding(node);
}
JS_REFERENCE_IDENTIFIER | JSX_REFERENCE_IDENTIFIER => {
self.enter_reference_identifier(node);
}
JS_IDENTIFIER_ASSIGNMENT => {
self.enter_js_identifier_assignment(node);
}
JS_CALL_EXPRESSION => {
self.enter_js_call_expression(node);
}
JS_MODULE | JS_SCRIPT => self.push_scope(
node.text_range(),
ScopeHoisting::DontHoistDeclarationsToParent,
false,
),
JS_FUNCTION_DECLARATION
| JS_FUNCTION_EXPRESSION
| JS_ARROW_FUNCTION_EXPRESSION
| JS_CONSTRUCTOR_CLASS_MEMBER
| JS_METHOD_CLASS_MEMBER
| JS_GETTER_CLASS_MEMBER
| JS_SETTER_CLASS_MEMBER
| JS_METHOD_OBJECT_MEMBER
| JS_GETTER_OBJECT_MEMBER
| JS_SETTER_OBJECT_MEMBER => {
self.push_scope(
node.text_range(),
ScopeHoisting::DontHoistDeclarationsToParent,
true,
);
}
JS_FUNCTION_EXPORT_DEFAULT_DECLARATION
| JS_CLASS_DECLARATION
| JS_CLASS_EXPORT_DEFAULT_DECLARATION
| JS_CLASS_EXPRESSION
| JS_FUNCTION_BODY
| JS_STATIC_INITIALIZATION_BLOCK_CLASS_MEMBER
| TS_MODULE_DECLARATION
| TS_INTERFACE_DECLARATION
| TS_ENUM_DECLARATION
| TS_TYPE_ALIAS_DECLARATION
| TS_FUNCTION_TYPE
| TS_DECLARE_FUNCTION_DECLARATION => {
self.push_scope(
node.text_range(),
ScopeHoisting::DontHoistDeclarationsToParent,
false,
);
}
JS_BLOCK_STATEMENT | JS_FOR_STATEMENT | JS_FOR_OF_STATEMENT | JS_FOR_IN_STATEMENT
| JS_SWITCH_STATEMENT | JS_CATCH_CLAUSE => {
self.push_scope(
node.text_range(),
ScopeHoisting::HoistDeclarationsToParent,
false,
);
}
_ => {}
}
}
fn is_var(binding: &impl AstNode<Language = JsLanguage>) -> Option<bool> {
let declarator = binding.parent::<JsVariableDeclarator>()?;
use JsSyntaxKind::*;
let is_var = match declarator.syntax().parent().kind() {
Some(JS_VARIABLE_DECLARATOR_LIST) => declarator
.parent::<JsVariableDeclaratorList>()?
.parent::<JsVariableDeclaration>()?
.is_var(),
Some(JS_FOR_VARIABLE_DECLARATION) => {
declarator
.parent::<JsForVariableDeclaration>()?
.kind_token()
.ok()?
.kind()
== VAR_KW
}
_ => false,
};
Some(is_var)
}
fn enter_identifier_binding(&mut self, node: &JsSyntaxNode) -> Option<()> {
use JsSyntaxKind::*;
debug_assert!(matches!(
node.kind(),
JS_IDENTIFIER_BINDING | TS_IDENTIFIER_BINDING | TS_TYPE_PARAMETER_NAME
), "specified node is not a identifier binding (JS_IDENTIFIER_BINDING, TS_IDENTIFIER_BINDING, TS_TYPE_PARAMETER)");
let (name_token, is_var) = match node.kind() {
JS_IDENTIFIER_BINDING => {
let binding = node.clone().cast::<JsIdentifierBinding>()?;
let name_token = binding.name_token().ok()?;
let is_var = Self::is_var(&binding);
(name_token, is_var)
}
TS_IDENTIFIER_BINDING => {
let binding = node.clone().cast::<TsIdentifierBinding>()?;
let name_token = binding.name_token().ok()?;
let is_var = Self::is_var(&binding);
(name_token, is_var)
}
TS_TYPE_PARAMETER_NAME => {
let token = node.clone().cast::<TsTypeParameterName>()?;
let name_token = token.ident_token().ok()?;
let is_var = Some(false);
(name_token, is_var)
}
_ => return None,
};
let parent = node.parent()?;
let parent_kind = parent.kind();
match parent_kind {
JS_VARIABLE_DECLARATOR => {
if let Some(true) = is_var {
let hoisted_scope_id = self.scope_index_to_hoist_declarations(0);
self.push_binding_into_scope(hoisted_scope_id, &name_token, &parent_kind);
} else {
self.push_binding_into_scope(None, &name_token, &parent_kind);
};
self.export_variable_declarator(node, &parent);
}
JS_FUNCTION_DECLARATION | JS_FUNCTION_EXPORT_DEFAULT_DECLARATION => {
let hoisted_scope_id = self.scope_index_to_hoist_declarations(1);
self.push_binding_into_scope(hoisted_scope_id, &name_token, &parent_kind);
self.export_function_declaration(node, &parent);
}
JS_CLASS_EXPRESSION | JS_FUNCTION_EXPRESSION => {
self.push_binding_into_scope(None, &name_token, &parent_kind);
self.export_declaration_expression(node, &parent);
}
JS_CLASS_DECLARATION
| JS_CLASS_EXPORT_DEFAULT_DECLARATION
| TS_ENUM_DECLARATION
| TS_INTERFACE_DECLARATION
| TS_MODULE_DECLARATION
| TS_TYPE_ALIAS_DECLARATION => {
let parent_scope = self.scopes.get(self.scopes.len() - 2);
let parent_scope = parent_scope.map(|scope| scope.scope_id);
self.push_binding_into_scope(parent_scope, &name_token, &parent_kind);
self.export_declaration(node, &parent);
}
JS_BINDING_PATTERN_WITH_DEFAULT
| JS_OBJECT_BINDING_PATTERN
| JS_OBJECT_BINDING_PATTERN_REST
| JS_OBJECT_BINDING_PATTERN_PROPERTY
| JS_OBJECT_BINDING_PATTERN_PROPERTY_LIST
| JS_OBJECT_BINDING_PATTERN_SHORTHAND_PROPERTY
| JS_ARRAY_BINDING_PATTERN
| JS_ARRAY_BINDING_PATTERN_ELEMENT_LIST
| JS_ARRAY_BINDING_PATTERN_REST_ELEMENT => {
self.push_binding_into_scope(None, &name_token, &parent_kind);
let possible_declarator = parent.ancestors().find(|x| {
!matches!(
x.kind(),
JS_BINDING_PATTERN_WITH_DEFAULT
| JS_OBJECT_BINDING_PATTERN
| JS_OBJECT_BINDING_PATTERN_REST
| JS_OBJECT_BINDING_PATTERN_PROPERTY
| JS_OBJECT_BINDING_PATTERN_PROPERTY_LIST
| JS_OBJECT_BINDING_PATTERN_SHORTHAND_PROPERTY
| JS_ARRAY_BINDING_PATTERN
| JS_ARRAY_BINDING_PATTERN_ELEMENT_LIST
| JS_ARRAY_BINDING_PATTERN_REST_ELEMENT
)
})?;
if let JS_VARIABLE_DECLARATOR = possible_declarator.kind() {
self.export_variable_declarator(node, &possible_declarator);
}
}
_ => {
self.push_binding_into_scope(None, &name_token, &parent_kind);
}
}
Some(())
}
fn enter_reference_identifier(&mut self, node: &JsSyntaxNode) -> Option<()> {
debug_assert!(
matches!(
node.kind(),
JsSyntaxKind::JS_REFERENCE_IDENTIFIER | JsSyntaxKind::JSX_REFERENCE_IDENTIFIER
),
"specified node is not a reference identifier (JS_REFERENCE_IDENTIFIER, JSX_REFERENCE_IDENTIFIER)"
);
let (name, is_exported) = match node.kind() {
JsSyntaxKind::JS_REFERENCE_IDENTIFIER => {
// SAFETY: kind check above
let reference = JsReferenceIdentifier::unwrap_cast(node.clone());
let name_token = reference.value_token().ok()?;
// skip `this` reference representing the class instance
if name_token.token_text_trimmed() == "this" {
return None;
}
(
name_token.token_text_trimmed(),
self.is_js_reference_identifier_exported(node),
)
}
JsSyntaxKind::JSX_REFERENCE_IDENTIFIER => {
// SAFETY: kind check above
let reference = JsxReferenceIdentifier::unwrap_cast(node.clone());
let name_token = reference.value_token().ok()?;
(name_token.token_text_trimmed(), false)
}
_ => return None,
};
let current_scope = self.current_scope_mut();
let references = current_scope.references.entry(name).or_default();
references.push(Reference::Read {
range: node.text_range(),
is_exported,
});
Some(())
}
fn enter_js_identifier_assignment(&mut self, node: &JsSyntaxNode) -> Option<()> {
debug_assert!(
matches!(node.kind(), JsSyntaxKind::JS_IDENTIFIER_ASSIGNMENT),
"specified node is not a identifier assignment (JS_IDENTIFIER_ASSIGNMENT)"
);
let reference = node.clone().cast::<JsIdentifierAssignment>()?;
let name_token = reference.name_token().ok()?;
let name = name_token.token_text_trimmed();
let current_scope = self.current_scope_mut();
let references = current_scope.references.entry(name).or_default();
references.push(Reference::Write {
range: node.text_range(),
});
Some(())
}
fn enter_js_call_expression(&mut self, node: &JsSyntaxNode) -> Option<()> {
debug_assert!(matches!(node.kind(), JsSyntaxKind::JS_CALL_EXPRESSION));
let call = node.clone().cast::<JsCallExpression>()?;
let callee = call.callee().ok()?;
if let JsSyntaxKind::JS_PARENTHESIZED_EXPRESSION = callee.syntax().kind() {
let expr = callee.as_js_parenthesized_expression()?;
let range = expr.syntax().text_range();
if let Some(AnyJsExpression::JsFunctionExpression(expr)) = result_of(expr) {
let id = expr.id()?;
self.stash.push_back(SemanticEvent::Read {
range,
declared_at: id.syntax().text_range(),
scope_id: self.scopes.last().unwrap().scope_id,
});
}
}
Some(())
}
/// See [SemanticEvent] for a more detailed description
/// of which ```SyntaxNode``` generates which events.
#[inline]
pub fn leave(&mut self, node: &JsSyntaxNode) {
use rome_js_syntax::JsSyntaxKind::*;
match node.kind() {
JS_MODULE | JS_SCRIPT => self.pop_scope(node.text_range()),
JS_FUNCTION_DECLARATION
| JS_FUNCTION_EXPORT_DEFAULT_DECLARATION
| JS_FUNCTION_EXPRESSION
| JS_ARROW_FUNCTION_EXPRESSION
| JS_CLASS_DECLARATION
| JS_CLASS_EXPORT_DEFAULT_DECLARATION
| JS_CLASS_EXPRESSION
| JS_CONSTRUCTOR_CLASS_MEMBER
| JS_METHOD_CLASS_MEMBER
| JS_GETTER_CLASS_MEMBER
| JS_SETTER_CLASS_MEMBER
| JS_METHOD_OBJECT_MEMBER
| JS_GETTER_OBJECT_MEMBER
| JS_SETTER_OBJECT_MEMBER
| JS_FUNCTION_BODY
| JS_BLOCK_STATEMENT
| JS_FOR_STATEMENT
| JS_FOR_OF_STATEMENT
| JS_FOR_IN_STATEMENT
| JS_SWITCH_STATEMENT
| JS_CATCH_CLAUSE
| JS_STATIC_INITIALIZATION_BLOCK_CLASS_MEMBER
| TS_DECLARE_FUNCTION_DECLARATION
| TS_FUNCTION_TYPE
| TS_INTERFACE_DECLARATION
| TS_ENUM_DECLARATION
| TS_TYPE_ALIAS_DECLARATION
| TS_MODULE_DECLARATION => {
self.pop_scope(node.text_range());
}
_ => {}
}
}
/// Return any previous extracted [SemanticEvent].
#[inline]
pub fn pop(&mut self) -> Option<SemanticEvent> {
self.stash.pop_front()
}
fn push_scope(&mut self, range: TextRange, hoisting: ScopeHoisting, is_closure: bool) {
let scope_id = self.next_scope_id;
self.next_scope_id += 1;
let parent_scope_id = self.scopes.iter().last().map(|x| x.scope_id);
self.stash.push_back(SemanticEvent::ScopeStarted {
range,
scope_id,
parent_scope_id,
is_closure,
});
self.scopes.push(Scope {
scope_id,
started_at: range.start(),
bindings: vec![],
references: HashMap::new(),
shadowed: vec![],
hoisting,
});
}
/// When a scope dies we do the following:
/// 1 - Match all references and declarations;
/// 2 - Unmatched references are promoted to its parent scope or become [UnresolvedReference] events;
/// 3 - All declarations of this scope are removed;
/// 4 - All shadowed declarations are restored.
fn pop_scope(&mut self, range: TextRange) {
debug_assert!(!self.scopes.is_empty());
if let Some(scope) = self.scopes.pop() {
// Match references and declarations
for (name, mut references) in scope.references {
// If we know the declaration of these reference push the correct events...
if let Some(declared_binding) = self.bindings.get(&name) {
let declaration_at = declared_binding.text_range;
let declaration_syntax_kind = declared_binding.declaration_kind;
for reference in &references {
let declaration_before_reference =
declaration_at.start() < reference.range().start();
let e = match (declaration_before_reference, &reference) {
(true, Reference::Read { range, .. }) => SemanticEvent::Read {
range: *range,
declared_at: declaration_at,
scope_id: scope.scope_id,
},
(false, Reference::Read { range, .. }) => SemanticEvent::HoistedRead {
range: *range,
declared_at: declaration_at,
scope_id: scope.scope_id,
},
(true, Reference::Write { range }) => SemanticEvent::Write {
range: *range,
declared_at: declaration_at,
scope_id: scope.scope_id,
},
(false, Reference::Write { range }) => SemanticEvent::HoistedWrite {
range: *range,
declared_at: declaration_at,
scope_id: scope.scope_id,
},
};
self.stash.push_back(e);
match reference {
Reference::Read { is_exported, .. } if *is_exported => {
// Check shadowed bindings to find an exportable binding
let find_exportable_binding = scope.shadowed.iter().find_map(
|(shadowed_ident_name, shadowed_binding_info)| {
if shadowed_ident_name != &name {
return None;
}
// The order of interface and other bindings is valid in either order
match (
declaration_syntax_kind,
shadowed_binding_info.declaration_kind,
) {
(
JsSyntaxKind::JS_VARIABLE_DECLARATOR,
JsSyntaxKind::TS_INTERFACE_DECLARATION,
)
| (
JsSyntaxKind::TS_INTERFACE_DECLARATION,
JsSyntaxKind::JS_VARIABLE_DECLARATOR,
)
| (
JsSyntaxKind::JS_CLASS_DECLARATION,
JsSyntaxKind::TS_INTERFACE_DECLARATION,
)
| (
JsSyntaxKind::TS_INTERFACE_DECLARATION,
JsSyntaxKind::JS_CLASS_DECLARATION,
) => Some(shadowed_binding_info),
_ => None,
}
},
);
if let Some(binding_info) = find_exportable_binding {
self.stash.push_back(SemanticEvent::Exported {
range: binding_info.text_range,
});
}
self.stash.push_back(SemanticEvent::Exported {
range: declaration_at,
});
}
_ => {}
}
}
} else if let Some(parent) = self.scopes.last_mut() {
// ... if not, promote these references to the parent scope ...
let parent_references = parent.references.entry(name).or_default();
parent_references.append(&mut references);
} else {
// ... or raise UnresolvedReference if this is the global scope.
for reference in references {
self.stash.push_back(SemanticEvent::UnresolvedReference {
is_read: reference.is_read(),
range: *reference.range(),
});
}
}
}
// Remove all bindings declared in this scope
for binding in scope.bindings {
self.bindings.remove(&binding.name);
}
// Restore shadowed bindings
self.bindings.extend(scope.shadowed);
self.stash.push_back(SemanticEvent::ScopeEnded {
range,
started_at: scope.started_at,
scope_id: scope.scope_id,
});
}
}
fn current_scope_mut(&mut self) -> &mut Scope {
// We should at least have the global scope
debug_assert!(!self.scopes.is_empty());
match self.scopes.last_mut() {
Some(scope) => scope,
None => unreachable!(),
}
}
/// Finds the scope where declarations that are hoisted
/// will be declared at. For example:
///
/// ```js
/// function f() {
/// if (true) {
/// var a;
/// }
/// }
/// ```
///
/// `a` declaration will be hoisted to the scope of
/// function `f`.
///
/// This method when called inside the `f` scope will return
/// the `f` scope index.
fn scope_index_to_hoist_declarations(&mut self, skip: usize) -> Option<usize> {
// We should at least have the global scope
// that do not hoist
debug_assert!(matches!(
self.scopes[0].hoisting,
ScopeHoisting::DontHoistDeclarationsToParent
));
debug_assert!(self.scopes.len() > skip);
let scope_id_hoisted_to = self
.scopes
.iter()
.rev()
.skip(skip)
.find(|scope| matches!(scope.hoisting, ScopeHoisting::DontHoistDeclarationsToParent))
.map(|x| x.scope_id);
let current_scope_id = self.current_scope_mut().scope_id;
match scope_id_hoisted_to {
Some(scope_id) => {
if scope_id == current_scope_id {
None
} else {
Some(scope_id)
}
}
// Worst case this will fallback to the global scope
// which will be idx = 0
None => unreachable!("We must have a least of scope."),
}
}
fn push_binding_into_scope(
&mut self,
hoisted_scope_id: Option<usize>,
name_token: &JsSyntaxToken,
declaration_kind: &JsSyntaxKind,
) {
let name = name_token.token_text_trimmed();
let declaration_range = name_token.text_range();
// insert this name into the list of available names
// and save shadowed names to be used later
let shadowed = self
.bindings
.insert(
name.clone(),
BindingInfo {
text_range: declaration_range,
declaration_kind: *declaration_kind,
},
)
.map(|shadowed_range| (name.clone(), shadowed_range));
let current_scope_id = self.current_scope_mut().scope_id;
let binding_scope_id = hoisted_scope_id.unwrap_or(current_scope_id);
let scope = self
.scopes
.iter_mut()
.rev()
.find(|s| s.scope_id == binding_scope_id);
// A scope will always be found
debug_assert!(scope.is_some());
let scope = scope.unwrap();
scope.bindings.push(Binding { name: name.clone() });
scope.shadowed.extend(shadowed);
let scope_started_at = scope.started_at;
self.stash.push_back(SemanticEvent::DeclarationFound {
range: declaration_range,
scope_started_at,
scope_id: current_scope_id,
hoisted_scope_id,
name,
});
}
// Check if a function is exported and raise the [Exported] event.
fn export_function_declaration(
&mut self,
binding: &JsSyntaxNode,
function_declaration: &JsSyntaxNode,
) {
use JsSyntaxKind::*;
debug_assert!(matches!(
function_declaration.kind(),
JS_FUNCTION_DECLARATION | JS_FUNCTION_EXPORT_DEFAULT_DECLARATION
));
let is_exported = matches!(
function_declaration.parent().kind(),
Some(JS_EXPORT | JS_EXPORT_DEFAULT_DECLARATION_CLAUSE)
);
if is_exported {
self.stash.push_back(SemanticEvent::Exported {
range: binding.text_range(),
});
}
}
// Check if a function or class expression is exported and raise the [Exported] event.
fn export_declaration_expression(
&mut self,
binding: &JsSyntaxNode,
declaration_expression: &JsSyntaxNode,
) {
use JsSyntaxKind::*;
debug_assert!(matches!(
declaration_expression.kind(),
JS_FUNCTION_EXPRESSION | JS_CLASS_EXPRESSION
));
let is_module_exports = declaration_expression
.parent()
.map(|x| self.is_assignment_left_side_module_exports(&x))
.unwrap_or(false);
if is_module_exports {
self.stash.push_back(SemanticEvent::Exported {
range: binding.text_range(),
});
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/semantic_model.rs | crates/rome_js_semantic/src/semantic_model.rs | mod binding;
mod builder;
mod closure;
mod globals;
mod import;
mod is_constant;
mod model;
mod reference;
mod scope;
#[cfg(test)]
mod tests;
use crate::{SemanticEvent, SemanticEventExtractor};
pub use closure::*;
use rome_js_syntax::{
AnyJsExpression, AnyJsRoot, JsIdentifierAssignment, JsIdentifierBinding, JsLanguage,
JsReferenceIdentifier, JsSyntaxKind, JsSyntaxNode, JsxReferenceIdentifier, TextRange, TextSize,
TsIdentifierBinding,
};
use rome_rowan::AstNode;
use rust_lapper::{Interval, Lapper};
use rustc_hash::{FxHashMap, FxHashSet};
use std::{
collections::{BTreeSet, HashSet, VecDeque},
iter::FusedIterator,
sync::Arc,
};
pub use binding::*;
pub use builder::*;
pub use builder::*;
pub use globals::*;
pub use import::*;
pub use is_constant::*;
pub use model::*;
pub use reference::*;
pub use scope::*;
/// Extra options for the [SemanticModel] creation.
#[derive(Default)]
pub struct SemanticModelOptions {
/// All the allowed globals names
pub globals: HashSet<String>,
}
/// Build the complete [SemanticModel] of a parsed file.
/// For a push based model to build the [SemanticModel], see [SemanticModelBuilder].
pub fn semantic_model(root: &AnyJsRoot, options: SemanticModelOptions) -> SemanticModel {
let mut extractor = SemanticEventExtractor::default();
let mut builder = SemanticModelBuilder::new(root.clone());
let SemanticModelOptions { globals } = options;
for global in globals {
builder.push_global(global);
}
let root = root.syntax();
for node in root.preorder() {
match node {
rome_js_syntax::WalkEvent::Enter(node) => {
builder.push_node(&node);
extractor.enter(&node);
}
rome_js_syntax::WalkEvent::Leave(node) => extractor.leave(&node),
}
}
while let Some(e) = extractor.pop() {
builder.push_event(e);
}
builder.build()
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/tests/references.rs | crates/rome_js_semantic/src/tests/references.rs | use crate::assert_semantics;
// Reads
assert_semantics! {
ok_reference_read_global,
"let a/*#A*/ = 1; let b = a/*READ A*/ + 1;",
ok_reference_read_inner_scope,
r#"function f(a/*#A1*/) {
let b = a/*READ A1*/ + 1;
console.log(b);
if (true) {
let a/*#A2*/ = 2;
let b = a/*READ A2*/ + 1;
console.log(b);
}
let c = a/*READ A1*/ + 1;
console.log(b);
}
f(1);"#,
ok_reference_switch,
"let b = 1;
let a/*#A1*/ = 1;
switch (b) {
case 1: let a/*#A2*/ = 2; console.log(1, a/*READ A2*/);
case 2: let c/*#C*/ = 2; console.log(2, a/*READ A2*/, c/*READ C*/);
case 3: { let d/*#D*/ = 2; console.log(3, a/*READ A2*/, c/*READ C*/, d/*READ D*/); }
case 4: console.log(4, a/*READ A2*/, c/*READ C*/, d/*?*/);
}
console.log(5, a/*READ A1*/);",
ok_reference_recursive,
"const fn/*#A*/ = (callback) => { callback(fn/*READ A*/) };",
}
// Read Hoisting
assert_semantics! {
ok_hoisting_read_inside_function, "function f() {
a = 2;
let b = a/*READ A*/ + 1;
console.log(a, b);
var a/*#A*/;
}
f();",
ok_hoisting_read_var_inside_if, r#"function f() {
a = 1;
let b = a/*READ A*/ + 1;
console.log(a, b);
if (true) {
var a/*#A*/;
}
}
f();"#,
ok_hoisting_read_redeclaration_before_use, r#"var a/*#A1*/ = 1;
function f() {
var a/*#A2*/ = 10;
console.log(a/*READ A2*/);
}
f();"#,
ok_hoisting_read_redeclaration_after_use, r#"var a/*#A1*/ = 1;
function f() {
console.log(a/*READ A2*/);
var a/*#A2*/ = 10;
}
f();"#,
ok_hoisting_read_for_of, r#"function f() {
for (var a/*#A*/ of [1,2,3]) {
console.log(a/*READ A*/)
}
console.log(a/*READ A*/);
}
f()"#,
ok_hoisting_read_for_in, r#"function f() {
for (var a/*#A*/ in [1,2,3]) {
console.log(a/*READ A*/)
}
console.log(a/*READ A*/);
}
f()"#,
ok_hoisting_read_let_after_reference_same_scope, r#"var a = 1;
function f() {
console.log(a/*READ A*/);
let a/*#A*/ = 2;
}
f()"#,
ok_hoisting_read_let_after_reference_different_scope, r#"var a/*#A*/ = 1;
function f() {
console.log(a/*READ A*/);
if (true) {
let a = 2;
}
}
f()"#,
ok_hoisting_inside_switch,
"var a/*#A1*/ = 1;
switch (a) {
case 1: var a/*#A2*/ = 2;
};
console.log(a/*READ A2*/);",
}
// Write
assert_semantics! {
ok_reference_write_global, "let a/*#A*/; a/*WRITE A*/ = 1;",
ok_reference_write_inner_scope, r#"function f(a/*#A1*/) {
a/*WRITE A1*/ = 1;
console.log(a);
if (true) {
let a/*#A2*/;
a/*WRITE A2*/ = 2;
console.log(a);
}
a/*WRITE A1*/ = 3;
console.log(3);
}
f(1);"#,
ok_reference_write_expression, "let a/*#A*/ = 1; let b = a/*WRITE A*/ = 2;",
ok_reference_write_object_assignment_pattern,
"let a/*#A*/, b/*#B*/; ({a/*WRITE A*/, b/*WRITE B*/} = obj);",
}
// Write Hoisting
assert_semantics! {
ok_hoisting_write_inside_function, "function f() {
a/*WRITE A*/ = 2;
console.log(a);
var a/*#A*/;
}
f();",
}
// Functions
assert_semantics! {
ok_read_function,
r#"function f/*#F*/() {} console.log(f/*READ F*/);"#,
ok_write_function,
r#"function f/*#F*/() {} f/*WRITE F*/ = null;"#,
ok_read_self_invoking_function,
r#"(function f/*#F*/(){console.log(1)})/*READ F*/()"#,
ok_read_self_invoking_function2,
r#"(1,2,3,function f/*#F*/(){console.log(1)})/*READ F*/()"#,
ok_scope_function_expression_read,
"var f/*#F1*/ = function f/*#F2*/() {console.log(f/*READ F2*/);}; f/*READ F1*/();",
ok_scope_function_expression_read1 ,
"var f/*#F1*/ = function () {console.log(f/*READ F1*/);}",
ok_scope_function_expression_read2,
"let f/*#F1*/ = 1; let g = function f/*#F2*/() {console.log(2, f/*READ F2*/);}; console.log(f/*READ F1*/);",
ok_function_parameter,
"function t({ a/*#A*/ = 0, b/*#B*/ = a/*READ A*/ }, c = a/*READ A*/) { console.log(a/*READ A*/, b/*READ B*/); }",
ok_function_parameter_array,
"let b/*#B*/ = 5;
let c/*#C*/ = 6;
let d/*#D*/ = 7;
function f({a/*#A*/} = {a: [b/*READ B*/,c/*READ C*/,d/*READ D*/]}) {
console.log(a/*READ A*/, b/*READ B*/);
}
f()",
ok_function_parameter_array_with_name_conflict,
"let b/*#B1*/ = 5;
let c/*#C*/ = 6;
let d/*#D*/ = 7;
function f({a/*#A*/} = {a: [b/*READ B2*/,c/*READ C*/,d/*READ D*/]}, b/*#B2*/) {
var b/*#B3*/;
console.log(a/*READ A*/, b/*READ B3*/);
}
f()",
ok_function_overloading,
"function overloaded/*#A*/(): number;
function overloaded/*#B*/(s: string): string;
function overloaded/*#C*/(s?: string) {
return s;
}
overloaded/*READ C*/();",
ok_function_overloading_2,
"function a/*#A*/() {}
a/*READ A*/();
function add(a: string, b: string): string;
console.log(a/*READ A*/);",
}
// Imports
assert_semantics! {
ok_import_used_in_jsx, r#"import A/*#A*/ from 'a.js'; console.log(<A/*READ A*//>);"#,
}
assert_semantics! {
ok_unresolved_reference, r#"a/*?*/"#,
ok_unresolved_function_expression_read,"let f/*#F*/ = function g/*#G*/(){}; g/*?*/();",
ok_unresolved_reference_arguments,
r#"function f() {
console.log(arguments/*?*/);
for(let i = 0;i < arguments/*?*/.length; ++i) {
console.log(arguments/*?*/[i]);
}
}"#,
}
// Exports
assert_semantics! {
ok_export_hoisted_variable,
"var a/*#A1*/ = 2; export {a/*READ A2*/}; var a/*#A2*/ = 1;",
}
// Classes
assert_semantics! {
ok_class_reference,
"class A/*#A*/ {} new A/*READ A*/();",
ok_class_expression_1,
"const A/*#A*/ = class B/*#B*/ {}; console.log(A/*READ A*/, B/*?*/);",
//https://github.com/rome/tools/issues/3779
ok_class_expression_2,
"const A/*#A1*/ = print(class A/*#A2*/ {}); console.log(A/*READ A1*/);",
ok_class_static_init,
"class C { static { () => a/*READ A*/; let a/*#A*/ = 1; } };",
}
// Static Initialization Block
assert_semantics! {
ok_reference_static_initialization_block,
"const a/*#A1*/ = 1;
console.log(a/*READ A1*/);
class A {
static {
console.log(a/*READ A2*/);
const a/*#A2*/ = 2;
console.log(a/*READ A2*/);
}
};
console.log(a/*READ A1*/);",
}
// Typescript types
assert_semantics! {
ok_typescript_function_type,
"function f (a/*#A1*/, b: (a/*#A2*/) => any) { return b(a/*READ A1*/); };",
ok_typescript_type_parameter_name,
"type A = { [key/*#A1*/ in P]: key/*READ A1*/ }",
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/tests/functions.rs | crates/rome_js_semantic/src/tests/functions.rs | use crate::assert_semantics;
// functions
assert_semantics! {
ok_function_declaration, "function f/*#F*/ () {}",
ok_function_call, "function f/*#F*/ () {} f/*READ F*/();",
ok_function_hoisted_call, "function f/*#F*/ () { g/*READ G*/(); } function g/*#G*/() {}",
ok_function_inner_function,
"function b/*#B1*/() { function b/*#B2*/() {console.log(2)}; console.log(1); b/*READ B2*/(); } b/*READ B1*/();",
ok_function_inner_function2,
"function b/*#B1*/(a=b/*READ B1*/()) {
function b/*#B2*/() {console.log(2)}
console.log(a);
}
b(1);
",
ok_function_inner_function3,
"function f() {
if (true) {
function g/*#G*/(){console.log(1)}
}
g/*READ G*/()
}
f()",
}
// modules
assert_semantics! {
ok_function_inside_module,
"declare module M {
function f/*#F*/();
}
console.log(f/*?*/());",
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/tests/mod.rs | crates/rome_js_semantic/src/tests/mod.rs | mod assertions;
pub mod declarations;
mod functions;
mod references;
mod scopes;
#[macro_export]
macro_rules! assert_semantics {
($(#[$attr:meta])* $($name:ident, $code:expr,)*) => {
$(
#[test]
pub fn $name() {
$crate::tests::assertions::assert($code, stringify!($name));
}
)*
};
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/tests/declarations.rs | crates/rome_js_semantic/src/tests/declarations.rs | use crate::assert_semantics;
// Imports
assert_semantics! {
ok_declaration_import, "/*START GLOBAL*/ import a/*#a*//*@GLOBAL*/ from 'a'",
}
// Statements
assert_semantics! {
ok_declaration_if, ";if(true) {/*START A*/ let b/*#b*//*@A*/ = 1; }",
ok_declaration_at_for, ";for/*START A*/ (let a/*#a*//*@A*/;;) {/*START B*/ let b/*#b*//*@B*/ = 1; }",
ok_declaration_at_for_of, ";for/*START A*/ (const a/*#a*//*@A*/ of []) {/*START B*/ let b/*#b*//*@B*/ = 1; }",
ok_declaration_at_for_in, ";for/*START A*/(const a/*#a*//*@A*/ in []) {/*START B*/ let b/*#b*//*@B*/ = 1; }",
ok_declaration_try_catch, ";try {/*START A*/ let a/*#a*//*@A*/ = 1;} catch/*START B*/ (b1/*#b1*//*@B*/) {/*START C*/ let c/*#c*//*@C*/ = 1; }",
ok_declaration_try_catch_finally, ";try {/*START A*/ let a/*#a*//*@A*/ = 1;} catch/*START B*/ (b1/*#b1*//*@B*/) {/*START C*/ let c/*#c*//*@C*/ = 1; } finally {/*START D*/ let d/*#d*//*@D*/ = 1; }",
}
// Functions
assert_semantics! {
ok_declaration_function, ";function/*START A*/ f(a/*#a*//*@A*/) {/*START B*/ let b/*#b*//*@B*/ = 1; }",
ok_declaration_self_invocation, ";(function f/*#F*/() {})();",
ok_declaration_arrow_function, ";(/*START A*/ a/*#a*//*@A*/) => {/*START B*/ let b/*#b*//*@B*/ = 1; }",
}
// Classes
assert_semantics! {
ok_declaration_class_constructor, "class A { constructor/*START A*/ (a/*#a*//*@A*/) {/*START B*/ let b/*#b*//*@B*/ = 1; } }",
ok_declaration_class_getter, "class A { get/*START A*/ name() {/*START B*/ let b/*#b*//*@B*/ = 1;} }",
ok_declaration_class_setter, "class A { set/*START A*/ name(a/*#a*//*@A*/) {/*START B*/ let b/*#b*//*@B*/ = 1;} }",
}
// Others
assert_semantics! {
ok_declaration_at_global_scope, "/*START GLOBAL*/ let b/*#b*//*@GLOBAL*/ = 1;",
ok_declaration_with_inner_scopes, r#";
function f() {/*START SCOPE1*/
let a/*#a1*//*@SCOPE1*/ = 1;
console.log(a);
if (true) {/*START SCOPE2*/
let a/*#a2*//*@SCOPE2*/ = 2;
console.log(a);
}
console.log(a);
}
f();
"#,
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/tests/scopes.rs | crates/rome_js_semantic/src/tests/scopes.rs | use crate::assert_semantics;
// Statements
assert_semantics! {
ok_scope_if, "if(true) {/*START A*/}/*END A*/",
ok_scope_if_no_block, "if(true) ;/*NOEVENT*/;",
ok_scope_if_without_block_else_with_block, "if(true) ;/*NOEVENT*/ else {/*START A*/}/*END A*/;",
ok_scope_if_without_block_else_without_block, "if(true) ;/*NOEVENT*/ else ;/*NOEVENT*/;",
ok_scope_for_with_block, ";for/*START A*/(;;) {/*START B*/}/*END A*//*END B*/;",
ok_scope_for_without_block, "for/*START A*/(;;) ;/*END A*//*UNIQUE*/;",
ok_scope_for_of, "for/*START A*/(const a of []) {/*START B*/}/*END A*//*END B*/;",
ok_scope_for_of_without_block, "for/*START A*/(const a of []) ;/*END A*//*UNIQUE*/;",
ok_scope_for_in, "for/*START A*/(const a in []) {/*START B*/}/*END A*//*END B*/;",
ok_scope_for_in_without_block, "for/*START A*/(const a in []) ;/*END A*//*UNIQUE*/;",
ok_scope_try_catch, "try {/*START A*/}/*END A*/ catch/*START B*/ (e) {}/*END B*/",
ok_scope_try_catch_finally, "try {/*START A*/}/*END A*/ catch/*START B1*/ (e) {/*START B2*/}/*END B1*//*END B2*/ finally {/*START C*/}/*END C*/",
}
// Functions
assert_semantics! {
ok_scope_function, ";function/*START A*/ f() {}/*END A*/",
ok_scope_function_with_export_default, ";export default function/*START A*/ f() {}/*END A*/",
ok_scope_function_expression, ";var a = function/*START A*/ f() {}/*END A*/",
ok_scope_arrow_function, ";(/*START A*/) => {}/*END A*/",
ok_scope_js_function_export_default_declaration, "export default function/*START A*/ () {}/*END A*/",
ok_scope_overloaded_functions, "
function/*START A*/ add(a:string, b:string):string;/*END A*/
function/*START B*/ add(a:number, b:number):number;/*END B*/
function/*START C*/ add(a: any, b:any): any {
return a + b;
}/*END C*/;",
}
// Classes
assert_semantics! {
ok_scope_class_constructor, ";class A { constructor/*START A*/ () {}/*END A*/ }",
ok_scope_class_getter, ";class A { get/*START A*/ name() {}/*END A*/ }",
ok_scope_class_setter, ";class A { set/*START A*/ name(v) {}/*END A*/ }",
}
// Static Initialization Block
assert_semantics! {
ok_scope_static_initialization_block,
"class A {
static/*START A*/ {
const a/*@ A*/ = 2;
}/*END A*/
};",
}
// Type parameters
assert_semantics! {
ok_type_parameter, "export type /*START A*/ EventHandler<Event /*# Event */ /*@ A */ extends string> = `on${ Event /*READ Event */ }` /*END A*/",
ok_type_parameter_with_default, "export type /*START A */ EventHandler<Event /*# Event */ /*@ A */ extends string = 'click'> = `on${ Event /*READ Event */ }` /*END A*/",
ok_type_parameter_multiple_declaration, "
export type /*START ScopeA */ EventHandler<Event /*# EventA */ /*@ ScopeA */ extends string> = `on${ Event /*READ EventA */ }`; /*END ScopeA */
export type /*START ScopeB */ EventHandlerDefault<Event /*# EventB */ /*@ ScopeB */ extends string = 'click'> = `on${ Event /*READ EventB */ }`; /*END ScopeB */
",
ok_type_parameter_interface, "
export interface /*START A*/ EventHandler<Event /*# Event */ /*@ A */ extends string> {
[`on${ Event /*READ Event */ }`]: (event: Event /*READ Event */, data: unknown) => void;
} /*END A*/
",
}
// Modules
assert_semantics! {
ok_scope_module, "module/*START M*/ M {}/*END M*/;",
}
// Others
assert_semantics! {
ok_scope_global, "/*START GLOBAL*//*END GLOBAL*/",
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/tests/assertions.rs | crates/rome_js_semantic/src/tests/assertions.rs | use crate::{semantic_events, SemanticEvent};
use rome_console::{markup, ConsoleExt, EnvConsole};
use rome_diagnostics::location::AsSpan;
use rome_diagnostics::{
Advices, Diagnostic, DiagnosticExt, Location, LogCategory, PrintDiagnostic, Visit,
};
use rome_js_parser::JsParserOptions;
use rome_js_syntax::{AnyJsRoot, JsFileSource, JsSyntaxToken, TextRange, TextSize, WalkEvent};
use rome_rowan::{AstNode, NodeOrToken};
use std::collections::{BTreeMap, HashMap};
/// This method helps testing scope resolution. It does this
/// iterating [SemanticEventIterator] and storing where each scope start and end. Later it iterates
/// the tree looking at tokens with trailing comments following a specifically patterns
/// specifying if a scope has started or ended.
///
/// ### Available Patterns
///
/// #### Declaration Assertion
///
/// Test if the attached token is a declaration.
/// Pattern: ```/*# <LABEL> */
///
/// Every declaration assertion will be tested if it matches a [SemanticEvent::DeclarationFound].
///
/// Example:
/// ```js
/// let a/*#A*/ = 1;
/// ```
///
/// #### Read Assertion
///
/// Test if the attached token is "reading" the value of a symbol.
/// Pattern: ```/*READ <LABEL> */
///
/// /// Example:
/// ```js
/// let a/*#A*/ = 1;
/// let b = a/*READ A*/ + 1;
/// ```
/// #### Write Assertion
///
/// Test if the attached token is "writing" a value to a symbol.
/// Pattern: ```/*WRITE <LABEL> */
///
/// /// Example:
/// ```js
/// let a/*#A*/;
/// a/*WRITE A */ = 1;
/// ```
///
/// #### At Scope Assertion
///
/// Test if the attached token is a declaration that lives inside the specified scope.
/// Pattern: ```/*@ <LABEL> */```
///
/// Every at scope assertion will be tested if it matches the ```scope_started_at``` field of [SemanticEvent::DeclarationFound].
///
/// Example:
/// ```js
/// function f() {/*START A*/ let a/*#a*//*@A*/ = 1; }
/// ```
///
/// #### Scope Start Assertion
///
/// Test if the attached token starts a new scope.
/// Pattern: ```/*START <LABEL>*/```
///
/// Every scope start assertion will be tested if it matches a [SemanticEvent::ScopeStarted].
///
/// Example:
/// ```js
/// function f() {/*START SCOPE1*/ }
/// ```
///
/// #### Scope End Assertion
///
/// Test if the attached token ends a scope.
/// Pattern: ```/*END <LABEL>*/```
///
/// Every scope end assertion will be tested if it matches a [SemanticEvent::ScopeEnded].
/// This assertion also tests if the event and the assertion start scope matches.
///
/// Example:
/// ```js
/// function f() {/*START SCOPE1*/ }/*END SCOPE1*/
/// ```
///
/// #### Unique Assertion
///
/// Test if only one event is attached to the token.
/// Pattern: ```/*UNIQUE*/```
///
/// Example:
/// ```js
/// "for(;;) ;/*UNIQUE*/;"
/// ```
///
/// #### No events Assertion
///
/// Test with there are no events attached to the token.
///
/// Example:
/// ```js
/// if(true) ;/*NOEVENT*/;
/// ```
pub fn assert(code: &str, test_name: &str) {
let r = rome_js_parser::parse(code, JsFileSource::tsx(), JsParserOptions::default());
if r.has_errors() {
let mut console = EnvConsole::default();
for diag in r.into_diagnostics() {
let error = diag
.with_file_path("example.js")
.with_file_source_code(code);
console.log(markup! {
{PrintDiagnostic::verbose(&error)}
});
}
panic!("Compilation error");
}
// Extract semantic events and index by range
let mut events_by_pos: HashMap<TextSize, Vec<SemanticEvent>> = HashMap::new();
for event in semantic_events(r.syntax()) {
let pos = match &event {
SemanticEvent::DeclarationFound { range, .. } => range.start(),
SemanticEvent::ScopeStarted { range, .. } => range.start(),
SemanticEvent::ScopeEnded { range, .. } => range.end(),
SemanticEvent::Read { range, .. } => range.start(),
SemanticEvent::HoistedRead { range, .. } => range.start(),
SemanticEvent::Write { range, .. } => range.start(),
SemanticEvent::HoistedWrite { range, .. } => range.start(),
SemanticEvent::UnresolvedReference { range, .. } => range.start(),
SemanticEvent::Exported { range } => range.start(),
};
let v = events_by_pos.entry(pos).or_default();
v.push(event);
}
let assertions = SemanticAssertions::from_root(r.tree(), code, test_name);
// check
assertions.check(code, test_name, events_by_pos);
}
#[derive(Debug, Diagnostic)]
#[diagnostic(category = "semanticTests")]
struct TestSemanticDiagnostic {
#[message]
#[description]
message: String,
#[location(span)]
span: Option<TextRange>,
#[advice]
advice: TestAdvice,
}
impl TestSemanticDiagnostic {
fn new(message: impl Into<String>, span: impl AsSpan) -> Self {
Self {
message: message.into(),
span: span.as_span(),
advice: TestAdvice::default(),
}
}
fn push_advice(&mut self, range: impl AsSpan, message: impl Into<String>) {
self.advice.advices.push((range.as_span(), message.into()));
}
}
#[derive(Debug, Default)]
struct TestAdvice {
advices: Vec<(Option<TextRange>, String)>,
}
impl Advices for TestAdvice {
fn record(&self, visitor: &mut dyn Visit) -> std::io::Result<()> {
for (span, message) in &self.advices {
let location = Location::builder().span(&span).build();
visitor.record_log(LogCategory::Info, &message)?;
visitor.record_frame(location)?;
}
Ok(())
}
}
#[derive(Clone, Debug)]
struct DeclarationAssertion {
range: TextRange,
declaration_name: String,
}
#[derive(Clone, Debug)]
struct ReadAssertion {
range: TextRange,
declaration_asertion_name: String,
}
#[derive(Clone, Debug)]
struct WriteAssertion {
range: TextRange,
declaration_asertion_name: String,
}
#[derive(Clone, Debug)]
struct AtScopeAssertion {
range: TextRange,
scope_name: String,
}
#[derive(Clone, Debug)]
struct ScopeStartAssertion {
range: TextRange,
scope_name: String,
}
#[derive(Clone, Debug)]
struct ScopeEndAssertion {
range: TextRange,
scope_name: String,
}
#[derive(Clone, Debug)]
struct NoEventAssertion {
range: TextRange,
}
#[derive(Clone, Debug)]
struct UniqueAssertion {
range: TextRange,
}
#[derive(Clone, Debug)]
struct UnresolvedReferenceAssertion {
range: TextRange,
}
#[derive(Clone, Debug)]
enum SemanticAssertion {
Declaration(DeclarationAssertion),
Read(ReadAssertion),
Write(WriteAssertion),
ScopeStart(ScopeStartAssertion),
ScopeEnd(ScopeEndAssertion),
AtScope(AtScopeAssertion),
NoEvent(NoEventAssertion),
Unique(UniqueAssertion),
UnresolvedReference(UnresolvedReferenceAssertion),
}
impl SemanticAssertion {
fn try_from(token: &JsSyntaxToken, assertion_text: &str) -> Option<Self> {
if assertion_text.starts_with("/*#") {
let name = assertion_text
.trim()
.trim_start_matches("/*#")
.trim_end_matches("*/")
.trim()
.to_string();
Some(SemanticAssertion::Declaration(DeclarationAssertion {
range: token.parent().unwrap().text_range(),
declaration_name: name,
}))
} else if assertion_text.starts_with("/*READ ") {
let symbol_name = assertion_text
.trim()
.trim_start_matches("/*READ ")
.trim_end_matches("*/")
.trim()
.to_string();
Some(SemanticAssertion::Read(ReadAssertion {
range: token.parent().unwrap().text_range(),
declaration_asertion_name: symbol_name,
}))
} else if assertion_text.starts_with("/*WRITE ") {
let symbol_name = assertion_text
.trim()
.trim_start_matches("/*WRITE ")
.trim_end_matches("*/")
.trim()
.to_string();
Some(SemanticAssertion::Write(WriteAssertion {
range: token.parent().unwrap().text_range(),
declaration_asertion_name: symbol_name,
}))
} else if assertion_text.contains("/*START") {
let scope_name = assertion_text
.trim()
.trim_start_matches("/*START")
.trim_end_matches("*/")
.trim()
.to_string();
Some(SemanticAssertion::ScopeStart(ScopeStartAssertion {
range: token.parent().unwrap().text_range(),
scope_name,
}))
} else if assertion_text.contains("/*END") {
let scope_name = assertion_text
.trim()
.trim_start_matches("/*END")
.trim_end_matches("*/")
.trim()
.to_string();
Some(SemanticAssertion::ScopeEnd(ScopeEndAssertion {
range: token.parent().unwrap().text_range(),
scope_name,
}))
} else if assertion_text.starts_with("/*@") {
let scope_name = assertion_text
.trim()
.trim_start_matches("/*@")
.trim_end_matches("*/")
.trim()
.to_string();
Some(SemanticAssertion::AtScope(AtScopeAssertion {
range: token.parent().unwrap().text_range(),
scope_name,
}))
} else if assertion_text.contains("/*NOEVENT") {
Some(SemanticAssertion::NoEvent(NoEventAssertion {
range: token.parent().unwrap().text_range(),
}))
} else if assertion_text.contains("/*UNIQUE") {
Some(SemanticAssertion::Unique(UniqueAssertion {
range: token.parent().unwrap().text_range(),
}))
} else if assertion_text.contains("/*?") {
Some(SemanticAssertion::UnresolvedReference(
UnresolvedReferenceAssertion {
range: token.parent().unwrap().text_range(),
},
))
} else {
None
}
}
}
#[derive(Debug)]
struct SemanticAssertions {
declarations_assertions: BTreeMap<String, DeclarationAssertion>,
read_assertions: Vec<ReadAssertion>,
write_assertions: Vec<WriteAssertion>,
at_scope_assertions: Vec<AtScopeAssertion>,
scope_start_assertions: BTreeMap<String, ScopeStartAssertion>,
scope_end_assertions: Vec<ScopeEndAssertion>,
no_events: Vec<NoEventAssertion>,
uniques: Vec<UniqueAssertion>,
unresolved_references: Vec<UnresolvedReferenceAssertion>,
}
impl SemanticAssertions {
fn from_root(root: AnyJsRoot, code: &str, test_name: &str) -> Self {
let mut declarations_assertions: BTreeMap<String, DeclarationAssertion> = BTreeMap::new();
let mut read_assertions = vec![];
let mut write_assertions = vec![];
let mut at_scope_assertions = vec![];
let mut scope_start_assertions: BTreeMap<String, ScopeStartAssertion> = BTreeMap::new();
let mut scope_end_assertions = vec![];
let mut no_events = vec![];
let mut uniques = vec![];
let mut unresolved_references = vec![];
for node in root
.syntax()
.preorder_with_tokens(rome_rowan::Direction::Next)
{
if let WalkEvent::Enter(NodeOrToken::Token(token)) = node {
let pieces = token
.leading_trivia()
.pieces()
.chain(token.trailing_trivia().pieces());
for piece in pieces {
let text = piece.text();
let assertion = SemanticAssertion::try_from(&token, text);
match assertion {
Some(SemanticAssertion::Declaration(assertion)) => {
// Declaration assertions names cannot clash
let old = declarations_assertions
.insert(assertion.declaration_name.clone(), assertion)
.map(|x| x.range);
if let Some(old) = old {
error_assertion_name_clash(&token, code, test_name, old);
}
}
Some(SemanticAssertion::Read(assertion)) => {
read_assertions.push(assertion);
}
Some(SemanticAssertion::Write(assertion)) => {
write_assertions.push(assertion);
}
Some(SemanticAssertion::ScopeStart(assertion)) => {
// Scope start assertions names cannot clash
let old = scope_start_assertions
.insert(assertion.scope_name.clone(), assertion)
.map(|x| x.range);
if let Some(old) = old {
error_assertion_name_clash(&token, code, test_name, old);
}
}
Some(SemanticAssertion::ScopeEnd(assertion)) => {
scope_end_assertions.push(assertion);
}
Some(SemanticAssertion::AtScope(assertion)) => {
at_scope_assertions.push(assertion);
}
Some(SemanticAssertion::NoEvent(assertion)) => {
no_events.push(assertion);
}
Some(SemanticAssertion::Unique(assertion)) => {
uniques.push(assertion);
}
Some(SemanticAssertion::UnresolvedReference(assertion)) => {
unresolved_references.push(assertion);
}
None => {}
};
}
}
}
Self {
declarations_assertions,
read_assertions,
write_assertions,
at_scope_assertions,
scope_start_assertions,
scope_end_assertions,
no_events,
uniques,
unresolved_references,
}
}
fn check(
&self,
code: &str,
test_name: &str,
events_by_pos: HashMap<TextSize, Vec<SemanticEvent>>,
) {
// Check every declaration assertion is ok
for (_, assertion) in self.declarations_assertions.iter() {
if let Some(events) = events_by_pos.get(&assertion.range.start()) {
match &events[0] {
SemanticEvent::DeclarationFound { .. } => {
// OK because we are attached to a declaration
}
_ => {
println!("Assertion: {:?}", assertion);
println!("Events: {:#?}", events_by_pos);
error_assertion_not_attached_to_a_declaration(
code,
assertion.range,
test_name,
)
}
}
} else {
println!("Assertion: {:?}", assertion);
println!("Events: {:#?}", events_by_pos);
error_assertion_not_attached_to_a_declaration(code, assertion.range, test_name);
}
}
// Check every read assertion is ok
let is_read_assertion = |e: &SemanticEvent| matches!(e, SemanticEvent::Read { .. });
for assertion in self.read_assertions.iter() {
let decl = match self
.declarations_assertions
.get(&assertion.declaration_asertion_name)
{
Some(decl) => decl,
None => {
panic!(
"No declaration found with name: {}",
assertion.declaration_asertion_name
);
}
};
let events = match events_by_pos.get(&assertion.range.start()) {
Some(events) => events,
None => {
show_all_events(test_name, code, events_by_pos, is_read_assertion);
show_unmatched_assertion(test_name, code, assertion, assertion.range);
panic!("No read event found at this range");
}
};
let mut unused_match = None;
let at_least_one_match = events.iter().any(|e| {
let declaration_at_range = match &e {
SemanticEvent::Read {
declared_at: declaration_at,
..
} => Some(*declaration_at),
SemanticEvent::HoistedRead {
declared_at: declaration_at,
..
} => Some(*declaration_at),
_ => None,
};
if let Some(declaration_at_range) = declaration_at_range {
unused_match = Some(format!(
"{} != {}",
&code[declaration_at_range], &code[decl.range]
));
code[declaration_at_range] == code[decl.range]
} else {
false
}
});
if !at_least_one_match {
println!("Assertion: {:?}", assertion);
println!("Events: {:#?}", events_by_pos);
if let Some(unused_match) = unused_match {
panic!(
"A read event was found, but was discarded because [{}] when checking {:?}",
unused_match, assertion
);
} else {
panic!(
"No matching read event found at this range when checking {:?}",
assertion
);
}
}
}
// Check every write assertion is ok
for assertion in self.write_assertions.iter() {
let decl = match self
.declarations_assertions
.get(&assertion.declaration_asertion_name)
{
Some(decl) => decl,
None => {
panic!(
"No declaration found with name: {}",
assertion.declaration_asertion_name
);
}
};
let events = match events_by_pos.get(&assertion.range.start()) {
Some(events) => events,
None => {
println!("Assertion: {:?}", assertion);
println!("Events: {:#?}", events_by_pos);
panic!("No write event found at this range");
}
};
let at_least_one_match = events.iter().any(|e| {
let declaration_at_range = match &e {
SemanticEvent::Write {
declared_at: declaration_at,
..
} => Some(*declaration_at),
SemanticEvent::HoistedWrite {
declared_at: declaration_at,
..
} => Some(*declaration_at),
_ => None,
};
if let Some(declaration_at_range) = declaration_at_range {
code[declaration_at_range] == code[decl.range]
} else {
false
}
});
if !at_least_one_match {
println!("Assertion: {:?}", assertion);
println!("Events: {:#?}", events_by_pos);
panic!("No matching write event found at this range");
}
}
let is_scope_event = |e: &SemanticEvent| {
matches!(
e,
SemanticEvent::ScopeStarted { .. } | SemanticEvent::ScopeEnded { .. }
)
};
// Check every at scope assertion is ok
for at_scope_assertion in self.at_scope_assertions.iter() {
if let Some(events) = events_by_pos.get(&at_scope_assertion.range.start()) {
// Needs to be a unique event for now
match &events[0] {
SemanticEvent::DeclarationFound {
scope_started_at, ..
} => match self
.scope_start_assertions
.get(&at_scope_assertion.scope_name)
{
Some(scope_start_assertion) => {
if scope_start_assertion.range.start() != *scope_started_at {
show_all_events(test_name, code, events_by_pos, is_scope_event);
show_unmatched_assertion(
test_name,
code,
at_scope_assertion,
at_scope_assertion.range,
);
panic!("Assertion pointing to a wrong scope");
}
assert_eq!(scope_start_assertion.range.start(), *scope_started_at);
}
None => {
show_all_events(test_name, code, events_by_pos, is_scope_event);
show_unmatched_assertion(
test_name,
code,
at_scope_assertion,
at_scope_assertion.range,
);
panic!("Assertion pointing to a wrong scope");
}
},
_ => {
error_assertion_not_attached_to_a_declaration(
code,
at_scope_assertion.range,
test_name,
);
}
}
}
}
// Check every scope start assertion is ok
for scope_assertion in self.scope_start_assertions.values() {
if let Some(events) = events_by_pos.get(&scope_assertion.range.start()) {
let is_at_least_one_scope_start = events
.iter()
.any(|e| matches!(e, SemanticEvent::ScopeStarted { .. }));
if !is_at_least_one_scope_start {
panic!("error_scope_assertion_not_attached_to_a_scope_event");
}
} else {
show_all_events(test_name, code, events_by_pos, is_scope_event);
show_unmatched_assertion(test_name, code, scope_assertion, scope_assertion.range);
panic!("No scope event found!");
}
}
// Check every scope end assertion is ok
for scope_end_assertion in self.scope_end_assertions.iter() {
// Check we have a scope start with the same label.
let scope_start_assertions_range = match self
.scope_start_assertions
.get(&scope_end_assertion.scope_name)
{
Some(scope_start_assertions) => scope_start_assertions.range,
None => {
error_scope_end_assertion_points_to_non_existing_scope_start_assertion(
code,
&scope_end_assertion.range,
test_name,
);
continue;
}
};
if let Some(events) = events_by_pos.get(&scope_end_assertion.range.end()) {
// At least one of the events should be a scope start starting
// where we expect
let e = events.iter().find(|event| match event {
SemanticEvent::ScopeEnded { started_at, .. } => {
*started_at == scope_start_assertions_range.start()
}
_ => false,
});
if e.is_none() {
error_scope_end_assertion_points_to_the_wrong_scope_start(
code,
&scope_end_assertion.range,
events,
test_name,
);
}
} else {
dbg!(events_by_pos);
panic!("No scope event found. Assertion: {scope_end_assertion:?}");
}
}
// Check every no event assertion
for assertion in self.no_events.iter() {
if events_by_pos.get(&assertion.range.start()).is_some() {
panic!("unexpected event at this position")
}
if events_by_pos.get(&assertion.range.end()).is_some() {
panic!("unexpected event at this position")
}
}
// Check every unique assertion
for unique in self.uniques.iter() {
if let Some(v) = events_by_pos.get(&unique.range.start()) {
if v.len() > 1 {
panic!("unexpected more than one event");
} else if v.is_empty() {
panic!("unexpected no events");
}
}
if let Some(v) = events_by_pos.get(&unique.range.end()) {
if v.len() > 1 {
panic!("unexpected more than one event");
} else if v.is_empty() {
panic!("unexpected no events");
}
}
}
// Check every unresolved_reference assertion
let is_unresolved_reference =
|e: &SemanticEvent| matches!(e, SemanticEvent::UnresolvedReference { .. });
for unresolved_reference in self.unresolved_references.iter() {
match events_by_pos.get(&unresolved_reference.range.start()) {
Some(v) => {
let ok = v
.iter()
.any(|e| matches!(e, SemanticEvent::UnresolvedReference { .. }));
if !ok {
show_all_events(test_name, code, events_by_pos, is_unresolved_reference);
show_unmatched_assertion(
test_name,
code,
unresolved_reference,
unresolved_reference.range,
);
panic!("No UnresolvedReference event found");
}
}
None => {
show_all_events(test_name, code, events_by_pos, is_unresolved_reference);
show_unmatched_assertion(
test_name,
code,
unresolved_reference,
unresolved_reference.range,
);
panic!("No UnresolvedReference event found");
}
}
}
}
}
fn show_unmatched_assertion(
test_name: &str,
code: &str,
assertion: &impl std::fmt::Debug,
assertion_range: TextRange,
) {
let assertion_code = &code[assertion_range];
// eat all trivia at the start
let mut start: usize = assertion_range.start().into();
for chr in assertion_code.chars() {
if chr.is_ascii_whitespace() {
start += chr.len_utf8();
} else {
break;
}
}
// eat all trivia at the end
let mut end: usize = assertion_range.end().into();
for chr in assertion_code.chars().rev() {
if chr.is_ascii_whitespace() {
end -= chr.len_utf8();
} else {
break;
}
}
let diagnostic = TestSemanticDiagnostic::new(
format!("This assertion was not matched: {assertion:?}"),
start..end,
);
let error = diagnostic
.with_file_path(test_name.to_string())
.with_file_source_code(code);
let mut console = EnvConsole::default();
console.log(markup! {
{PrintDiagnostic::verbose(&error)}
});
}
fn show_all_events<F>(
test_name: &str,
code: &str,
events_by_pos: HashMap<TextSize, Vec<SemanticEvent>>,
f: F,
) where
F: Fn(&SemanticEvent) -> bool,
{
let mut console = EnvConsole::default();
let mut all_events = vec![];
for (_, events) in events_by_pos {
for e in events {
if f(&e) {
all_events.push(e);
}
}
}
all_events.sort_by_key(|l| l.range().start());
for e in all_events {
let diagnostic = match e {
SemanticEvent::ScopeStarted { range, .. } => {
let mut start: usize = range.start().into();
let code = &code[range];
for chr in code.chars() {
if chr.is_ascii_whitespace() {
start += chr.len_utf8();
} else {
break;
}
}
TestSemanticDiagnostic::new(format!("{e:?}"), start..start + 1)
}
SemanticEvent::ScopeEnded { range, .. } => {
let mut start: usize = range.end().into();
let code = &code[range];
for chr in code.chars().rev() {
if chr.is_ascii_whitespace() {
start -= chr.len_utf8();
} else {
break;
}
}
TestSemanticDiagnostic::new(format!("{e:?}"), start - 1..start)
}
_ => TestSemanticDiagnostic::new(format!("{e:?}"), e.range()),
};
let error = diagnostic
.with_file_path(test_name.to_string())
.with_file_source_code(code);
console.log(markup! {
{PrintDiagnostic::verbose(&error)}
});
}
}
fn error_assertion_not_attached_to_a_declaration(
code: &str,
assertion_range: TextRange,
test_name: &str,
) {
let diagnostic = TestSemanticDiagnostic::new(
"This assertion must be attached to a SemanticEvent::DeclarationFound.",
assertion_range,
);
let error = diagnostic
.with_file_path(test_name.to_string())
.with_file_source_code(code);
let mut console = EnvConsole::default();
console.log(markup! {
{PrintDiagnostic::verbose(&error)}
});
panic!("This assertion must be attached to a SemanticEvent::DeclarationFound.");
}
fn error_assertion_name_clash(
token: &JsSyntaxToken,
code: &str,
test_name: &str,
old_range: TextRange,
) {
// If there is already an assertion with the same name. Suggest a rename
let mut diagnostic =
TestSemanticDiagnostic::new("Assertion label conflict.", token.text_range());
diagnostic.push_advice(
token.text_range(),
"There is already a assertion with the same name. Consider renaming this one.",
);
diagnostic.push_advice(old_range, "Previous assertion");
let error = diagnostic
.with_file_path(test_name.to_string())
.with_file_source_code(code);
let mut console = EnvConsole::default();
console.log(markup! {
{PrintDiagnostic::verbose(&error)}
});
panic!("Assertion label conflict");
}
fn error_scope_end_assertion_points_to_non_existing_scope_start_assertion(
code: &str,
range: &TextRange,
file_name: &str,
) {
let mut diagnostic = TestSemanticDiagnostic::new("Scope start assertion not found.", range);
diagnostic.push_advice(
range,
"This scope end assertion points to a non-existing scope start assertion.",
);
let error = diagnostic
.with_file_path(file_name.to_string())
.with_file_source_code(code);
let mut console = EnvConsole::default();
console.log(markup! {
{PrintDiagnostic::verbose(&error)}
});
panic!("Scope start assertion not found.");
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/semantic_model/reference.rs | crates/rome_js_semantic/src/semantic_model/reference.rs | use rome_js_syntax::{AnyJsFunction, AnyJsIdentifierUsage, JsCallExpression};
use super::*;
use std::sync::Arc;
/// Provides all information regarding to a specific reference.
#[derive(Debug)]
pub struct Reference {
pub(crate) data: Arc<SemanticModelData>,
pub(crate) index: ReferenceIndex,
}
impl Reference {
pub(crate) fn find_next(&self) -> Option<Reference> {
let reference = self.data.next_reference(self.index)?;
Some(Reference {
data: self.data.clone(),
index: reference.index,
})
}
pub(crate) fn find_next_read(&self) -> Option<Reference> {
let mut index = self.index;
while let Some(reference) = self.data.next_reference(index) {
if reference.is_read() {
return Some(Reference {
data: self.data.clone(),
index: reference.index,
});
} else {
index = reference.index;
}
}
None
}
pub(crate) fn find_next_write(&self) -> Option<Reference> {
let mut index = self.index;
while let Some(reference) = self.data.next_reference(index) {
if reference.is_write() {
return Some(Reference {
data: self.data.clone(),
index: reference.index,
});
} else {
index = reference.index;
}
}
None
}
/// Returns the range of this reference
pub fn range(&self) -> &TextRange {
let reference = self.data.reference(self.index);
&reference.range
}
/// Returns the scope of this reference
pub fn scope(&self) -> Scope {
let id = self.data.scope(self.range());
Scope {
data: self.data.clone(),
id,
}
}
/// Returns the node of this reference
pub fn syntax(&self) -> &JsSyntaxNode {
&self.data.node_by_range[self.range()]
}
/// Returns the binding of this reference
pub fn binding(&self) -> Option<Binding> {
Some(Binding {
data: self.data.clone(),
index: self.index.binding(),
})
}
/// Returns if the declaration of this reference is hoisted or not
pub fn is_using_hoisted_declaration(&self) -> bool {
let reference = &self.data.reference(self.index);
match reference.ty {
SemanticModelReferenceType::Read { hoisted } => hoisted,
SemanticModelReferenceType::Write { hoisted } => hoisted,
}
}
/// Returns if this reference is just reading its binding
pub fn is_read(&self) -> bool {
let reference = self.data.reference(self.index);
matches!(reference.ty, SemanticModelReferenceType::Read { .. })
}
/// Returns if this reference is writing its binding
pub fn is_write(&self) -> bool {
let reference = self.data.reference(self.index);
matches!(reference.ty, SemanticModelReferenceType::Write { .. })
}
/// Returns this reference as a [Call] if possible
pub fn as_call(&self) -> Option<FunctionCall> {
let call = self.syntax().ancestors().find(|x| {
!matches!(
x.kind(),
JsSyntaxKind::JS_REFERENCE_IDENTIFIER | JsSyntaxKind::JS_IDENTIFIER_EXPRESSION
)
});
match call {
Some(node) if node.kind() == JsSyntaxKind::JS_CALL_EXPRESSION => Some(FunctionCall {
data: self.data.clone(),
index: self.index,
}),
_ => None,
}
}
}
/// Provides all information regarding a specific function or method call.
#[derive(Debug)]
pub struct FunctionCall {
pub(crate) data: Arc<SemanticModelData>,
pub(crate) index: ReferenceIndex,
}
impl FunctionCall {
/// Returns the range of this reference
pub fn range(&self) -> &TextRange {
let reference = self.data.reference(self.index);
&reference.range
}
/// Returns the node of this reference
pub fn syntax(&self) -> &JsSyntaxNode {
&self.data.node_by_range[self.range()]
}
/// Returns the typed AST node of this reference
pub fn tree(&self) -> JsCallExpression {
let node = self.syntax();
let call = node.ancestors().find(|x| {
!matches!(
x.kind(),
JsSyntaxKind::JS_REFERENCE_IDENTIFIER | JsSyntaxKind::JS_IDENTIFIER_EXPRESSION
)
});
debug_assert!(matches!(&call,
Some(call) if call.kind() == JsSyntaxKind::JS_CALL_EXPRESSION
));
JsCallExpression::unwrap_cast(call.unwrap())
}
}
pub struct AllCallsIter {
pub(crate) references: AllBindingReadReferencesIter,
}
impl Iterator for AllCallsIter {
type Item = FunctionCall;
fn next(&mut self) -> Option<Self::Item> {
for reference in self.references.by_ref() {
if let Some(call) = reference.as_call() {
return Some(call);
}
}
None
}
}
#[derive(Debug)]
pub struct SemanticModelUnresolvedReference {
pub(crate) range: TextRange,
}
#[derive(Debug)]
pub struct UnresolvedReference {
pub(crate) data: Arc<SemanticModelData>,
pub(crate) id: usize,
}
impl UnresolvedReference {
pub fn syntax(&self) -> &JsSyntaxNode {
let reference = &self.data.unresolved_references[self.id];
&self.data.node_by_range[&reference.range]
}
pub fn tree(&self) -> AnyJsIdentifierUsage {
AnyJsIdentifierUsage::unwrap_cast(self.syntax().clone())
}
pub fn range(&self) -> &TextRange {
let reference = &self.data.unresolved_references[self.id];
&reference.range
}
}
/// Marker trait that groups all "AstNode" that have declarations
pub trait HasDeclarationAstNode: AstNode<Language = JsLanguage> {
#[inline(always)]
fn node(&self) -> &Self {
self
}
}
impl HasDeclarationAstNode for JsReferenceIdentifier {}
impl HasDeclarationAstNode for JsIdentifierAssignment {}
impl HasDeclarationAstNode for JsxReferenceIdentifier {}
/// Extension method to allow any node that is a declaration to easily
/// get all of its references.
pub trait ReferencesExtensions {
fn all_references(&self, model: &SemanticModel) -> AllBindingReferencesIter
where
Self: IsBindingAstNode,
{
model.as_binding(self).all_references()
}
fn all_reads(&self, model: &SemanticModel) -> AllBindingReadReferencesIter
where
Self: IsBindingAstNode,
{
model.as_binding(self).all_reads()
}
fn all_writes(&self, model: &SemanticModel) -> AllBindingWriteReferencesIter
where
Self: IsBindingAstNode,
{
model.as_binding(self).all_writes()
}
}
impl<T: IsBindingAstNode> ReferencesExtensions for T {}
pub trait CallsExtensions {
fn all_calls(&self, model: &SemanticModel) -> Option<AllCallsIter>;
}
impl CallsExtensions for AnyJsFunction {
fn all_calls(&self, model: &SemanticModel) -> Option<AllCallsIter> {
model.all_calls(self)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/semantic_model/builder.rs | crates/rome_js_semantic/src/semantic_model/builder.rs | use super::*;
use rome_js_syntax::{AnyJsRoot, JsSyntaxNode, TextRange};
use rustc_hash::{FxHashMap, FxHashSet};
use std::collections::hash_map::Entry;
/// Builds the [SemanticModel] consuming [SemanticEvent] and [SyntaxNode].
/// For a good example on how to use it see [semantic_model].
///
/// [SemanticModelBuilder] consumes all the [SemanticEvents] and build all the
/// data necessary to build a [SemanticModelData], that is allocated with an [Arc]
/// and stored inside the [SemanticModel].
pub struct SemanticModelBuilder {
root: AnyJsRoot,
node_by_range: FxHashMap<TextRange, JsSyntaxNode>,
globals: Vec<SemanticModelGlobalBindingData>,
globals_by_name: FxHashMap<String, Option<usize>>,
scopes: Vec<SemanticModelScopeData>,
scope_range_by_start: FxHashMap<TextSize, BTreeSet<Interval<usize, usize>>>,
scope_hoisted_to_by_range: FxHashMap<TextSize, usize>,
bindings: Vec<SemanticModelBindingData>,
/// maps a binding range to its index inside SemanticModelBuilder::bindings vec
bindings_by_range: FxHashMap<TextRange, usize>,
/// maps a reference range to its bindings. usize points to SemanticModelBuilder::bindings vec
declared_at_by_range: FxHashMap<TextRange, usize>,
exported: FxHashSet<TextRange>,
unresolved_references: Vec<SemanticModelUnresolvedReference>,
}
impl SemanticModelBuilder {
pub fn new(root: AnyJsRoot) -> Self {
Self {
root,
node_by_range: FxHashMap::default(),
globals: vec![],
globals_by_name: FxHashMap::default(),
scopes: vec![],
scope_range_by_start: FxHashMap::default(),
scope_hoisted_to_by_range: FxHashMap::default(),
bindings: vec![],
bindings_by_range: FxHashMap::default(),
declared_at_by_range: FxHashMap::default(),
exported: FxHashSet::default(),
unresolved_references: Vec::new(),
}
}
#[inline]
pub fn push_node(&mut self, node: &JsSyntaxNode) {
use JsSyntaxKind::*;
match node.kind() {
// Acessible from bindings and references
JS_IDENTIFIER_BINDING
| TS_IDENTIFIER_BINDING
| JS_REFERENCE_IDENTIFIER
| JSX_REFERENCE_IDENTIFIER
| TS_TYPE_PARAMETER_NAME
| JS_IDENTIFIER_ASSIGNMENT => {
self.node_by_range.insert(node.text_range(), node.clone());
}
// Acessible from scopes, closures
JS_MODULE
| JS_SCRIPT
| JS_FUNCTION_DECLARATION
| JS_FUNCTION_EXPRESSION
| JS_ARROW_FUNCTION_EXPRESSION
| JS_CONSTRUCTOR_CLASS_MEMBER
| JS_METHOD_CLASS_MEMBER
| JS_GETTER_CLASS_MEMBER
| JS_SETTER_CLASS_MEMBER
| JS_METHOD_OBJECT_MEMBER
| JS_GETTER_OBJECT_MEMBER
| JS_SETTER_OBJECT_MEMBER
| JS_FUNCTION_EXPORT_DEFAULT_DECLARATION
| JS_CLASS_DECLARATION
| JS_CLASS_EXPORT_DEFAULT_DECLARATION
| JS_CLASS_EXPRESSION
| JS_FUNCTION_BODY
| TS_INTERFACE_DECLARATION
| TS_ENUM_DECLARATION
| TS_TYPE_ALIAS_DECLARATION
| TS_FUNCTION_TYPE
| JS_BLOCK_STATEMENT
| JS_FOR_STATEMENT
| JS_FOR_OF_STATEMENT
| JS_FOR_IN_STATEMENT
| JS_SWITCH_STATEMENT
| JS_CATCH_CLAUSE => {
self.node_by_range.insert(node.text_range(), node.clone());
}
_ => {}
}
}
#[inline]
pub fn push_global(&mut self, name: impl Into<String>) {
self.globals_by_name.insert(name.into(), None);
}
#[inline]
pub fn push_event(&mut self, e: SemanticEvent) {
use SemanticEvent::*;
match e {
ScopeStarted {
range,
parent_scope_id,
scope_id,
is_closure,
} => {
// Scopes will be raised in order
debug_assert!(scope_id == self.scopes.len());
self.scopes.push(SemanticModelScopeData {
range,
parent: parent_scope_id,
children: vec![],
bindings: vec![],
bindings_by_name: FxHashMap::default(),
read_references: vec![],
write_references: vec![],
is_closure,
});
if let Some(parent_scope_id) = parent_scope_id {
self.scopes[parent_scope_id].children.push(scope_id);
}
let start = range.start();
self.scope_range_by_start
.entry(start)
.or_default()
.insert(Interval {
start: start.into(),
stop: range.end().into(),
val: scope_id,
});
}
ScopeEnded { .. } => {}
DeclarationFound {
name,
range,
scope_id,
hoisted_scope_id,
..
} => {
let binding_scope_id = hoisted_scope_id.unwrap_or(scope_id);
// SAFETY: this scope id is guaranteed to exist because they were generated by the
// event extractor
debug_assert!(binding_scope_id < self.scopes.len());
let binding_id = self.bindings.len();
self.bindings.push(SemanticModelBindingData {
id: binding_id.into(),
range,
references: vec![],
});
self.bindings_by_range.insert(range, binding_id);
let scope = self.scopes.get_mut(binding_scope_id).unwrap();
scope.bindings.push(binding_id);
scope.bindings_by_name.insert(name, binding_id);
if let Some(hoisted_scope_id) = hoisted_scope_id {
self.scope_hoisted_to_by_range
.insert(range.start(), hoisted_scope_id);
}
}
Read {
range,
declared_at: declaration_at, //TODO change to binding_id like we do with scope_id
scope_id,
} => {
let binding_id = match self.bindings_by_range.entry(declaration_at) {
Entry::Occupied(entry) => *entry.get(),
Entry::Vacant(entry) => {
let id = self.bindings.len();
self.bindings.push(SemanticModelBindingData {
id: id.into(),
range,
references: vec![],
});
*entry.insert(id)
}
};
let binding = &mut self.bindings[binding_id];
let reference_index = binding.references.len();
binding.references.push(SemanticModelReference {
index: (binding.id, reference_index).into(),
range,
ty: SemanticModelReferenceType::Read { hoisted: false },
});
let scope = &mut self.scopes[scope_id];
scope.read_references.push(SemanticModelScopeReference {
binding_id,
reference_id: reference_index,
});
self.declared_at_by_range.insert(range, binding_id);
}
HoistedRead {
range,
declared_at: declaration_at,
scope_id,
} => {
let binding_id = self.bindings_by_range[&declaration_at];
let binding = &mut self.bindings[binding_id];
let reference_index = binding.references.len();
binding.references.push(SemanticModelReference {
index: (binding.id, reference_index).into(),
range,
ty: SemanticModelReferenceType::Read { hoisted: true },
});
let scope = &mut self.scopes[scope_id];
scope.read_references.push(SemanticModelScopeReference {
binding_id,
reference_id: reference_index,
});
self.declared_at_by_range.insert(range, binding_id);
}
Write {
range,
declared_at: declaration_at,
scope_id,
} => {
let binding_id = self.bindings_by_range[&declaration_at];
let binding = &mut self.bindings[binding_id];
let reference_index = binding.references.len();
binding.references.push(SemanticModelReference {
index: (binding.id, reference_index).into(),
range,
ty: SemanticModelReferenceType::Write { hoisted: false },
});
let scope = &mut self.scopes[scope_id];
scope.read_references.push(SemanticModelScopeReference {
binding_id,
reference_id: reference_index,
});
self.declared_at_by_range.insert(range, binding_id);
}
HoistedWrite {
range,
declared_at: declaration_at,
scope_id,
} => {
let binding_id = self.bindings_by_range[&declaration_at];
let binding = &mut self.bindings[binding_id];
let reference_index = binding.references.len();
binding.references.push(SemanticModelReference {
index: (binding.id, reference_index).into(),
range,
ty: SemanticModelReferenceType::Write { hoisted: true },
});
let scope = &mut self.scopes[scope_id];
scope.read_references.push(SemanticModelScopeReference {
binding_id,
reference_id: reference_index,
});
self.declared_at_by_range.insert(range, binding_id);
}
UnresolvedReference { is_read, range } => {
let ty = if is_read {
SemanticModelReferenceType::Read { hoisted: false }
} else {
SemanticModelReferenceType::Write { hoisted: false }
};
let node = &self.node_by_range[&range];
let name = node.text_trimmed().to_string();
match self.globals_by_name.entry(name) {
Entry::Occupied(mut entry) => {
let entry = entry.get_mut();
match entry {
Some(index) => {
self.globals[*index]
.references
.push(SemanticModelGlobalReferenceData { range, ty });
}
None => {
let id = self.globals.len();
self.globals.push(SemanticModelGlobalBindingData {
references: vec![SemanticModelGlobalReferenceData {
range,
ty,
}],
});
*entry = Some(id);
}
}
}
Entry::Vacant(_) => self
.unresolved_references
.push(SemanticModelUnresolvedReference { range }),
}
}
Exported { range } => {
self.exported.insert(range);
}
}
}
#[inline]
pub fn build(self) -> SemanticModel {
let data = SemanticModelData {
root: self.root,
scopes: self.scopes,
scope_by_range: Lapper::new(
self.scope_range_by_start
.iter()
.flat_map(|(_, scopes)| scopes.iter())
.cloned()
.collect(),
),
scope_hoisted_to_by_range: self.scope_hoisted_to_by_range,
node_by_range: self.node_by_range,
bindings: self.bindings,
bindings_by_range: self.bindings_by_range,
declared_at_by_range: self.declared_at_by_range,
exported: self.exported,
unresolved_references: self.unresolved_references,
globals: self.globals,
};
SemanticModel::new(data)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/semantic_model/tests.rs | crates/rome_js_semantic/src/semantic_model/tests.rs | #[cfg(test)]
mod test {
use crate::{
semantic_model, BindingExtensions, CanBeImportedExported, SemanticModelOptions,
SemanticScopeExtensions,
};
use rome_js_parser::JsParserOptions;
use rome_js_syntax::{
JsFileSource, JsIdentifierAssignment, JsIdentifierBinding, JsReferenceIdentifier,
JsSyntaxKind, TsIdentifierBinding,
};
use rome_rowan::{AstNode, SyntaxNodeCast};
#[test]
pub fn ok_semantic_model() {
let r = rome_js_parser::parse(
"function f(){let a = arguments[0]; let b = a + 1; b = 2; console.log(b)}",
JsFileSource::js_module(),
JsParserOptions::default(),
);
let model = semantic_model(&r.tree(), SemanticModelOptions::default());
let arguments_reference = r
.syntax()
.descendants()
.filter_map(|x| x.cast::<JsReferenceIdentifier>())
.find(|x| x.text() == "arguments")
.unwrap();
let b_from_b_equals_2 = r
.syntax()
.descendants()
.filter_map(|x| x.cast::<JsIdentifierAssignment>())
.find(|x| x.text() == "b")
.unwrap();
// Scope hierarchy navigation
let block_scope = arguments_reference.scope(&model);
let func_scope = block_scope.parent().unwrap();
let global_scope = func_scope.parent().unwrap();
assert!(global_scope.parent().is_none());
assert_eq!(global_scope, model.global_scope());
assert_eq!(block_scope.ancestors().count(), 3);
// Scope equality
assert_eq!(block_scope, block_scope);
assert_eq!(func_scope, func_scope);
assert_eq!(global_scope, global_scope);
assert_ne!(block_scope, func_scope);
assert_ne!(block_scope, global_scope);
// Bindings
// block scope must have two bindings: a and b
let bindings = block_scope.bindings().collect::<Vec<_>>();
match bindings.as_slice() {
[a, b] => {
assert_eq!("a", a.syntax().text_trimmed());
assert_eq!("b", b.syntax().text_trimmed());
}
_ => {
panic!("wrong number of bindings");
}
}
// function scope must have zero bindings
// "f" was actually hoisted to the global scope
let mut bindings = func_scope.bindings();
assert!(bindings.next().is_none());
assert!(global_scope.get_binding("f").is_some());
// Binding by name
let binding = block_scope.get_binding("arguments");
assert!(binding.is_none());
let binding = block_scope.get_binding("a").unwrap();
assert_eq!("a", binding.syntax().text_trimmed());
// Declaration (from Read reference)
let arguments_declaration = arguments_reference.binding(&model);
assert!(arguments_declaration.is_none());
let a_from_a_plus_1 = r
.syntax()
.descendants()
.filter_map(|x| x.cast::<JsReferenceIdentifier>())
.find(|x| x.text() == "a")
.unwrap();
let a_declaration = a_from_a_plus_1.binding(&model).unwrap();
assert_eq!("a", a_declaration.syntax().text_trimmed());
// Declarations (from Write reference)
let b_declaration = b_from_b_equals_2.binding(&model).unwrap();
assert_eq!("b", b_declaration.syntax().text_trimmed());
// All references
assert_eq!(1, a_declaration.all_references().count());
assert_eq!(1, a_declaration.all_reads().count());
assert!(a_declaration.all_reads().all(|r| r.is_read()));
assert!(a_declaration.all_writes().all(|r| r.is_write()));
assert_eq!(2, b_declaration.all_references().count());
assert_eq!(1, b_declaration.all_reads().count());
assert_eq!(1, b_declaration.all_writes().count());
assert!(b_declaration.all_reads().all(|r| r.is_read()));
assert!(b_declaration.all_writes().all(|r| r.is_write()));
}
#[test]
pub fn ok_semantic_model_function_scope() {
let r = rome_js_parser::parse(
"function f() {} function g() {}",
JsFileSource::js_module(),
JsParserOptions::default(),
);
let model = semantic_model(&r.tree(), SemanticModelOptions::default());
let function_f = r
.syntax()
.descendants()
.filter_map(|x| x.cast::<JsIdentifierBinding>())
.find(|x| x.text() == "f")
.unwrap();
let function_g = r
.syntax()
.descendants()
.filter_map(|x| x.cast::<JsIdentifierBinding>())
.find(|x| x.text() == "g")
.unwrap();
// "f" and "g" tokens are not in the same scope, because
// the keyword "function" starts a new scope
// but they are both hoisted to the same scope
assert_ne!(function_f.scope(&model), function_g.scope(&model));
assert_eq!(
function_f.scope_hoisted_to(&model),
function_g.scope_hoisted_to(&model)
);
// they are hoisted to the global scope
let global_scope = model.global_scope();
assert_eq!(function_f.scope_hoisted_to(&model).unwrap(), global_scope);
assert_eq!(function_g.scope_hoisted_to(&model).unwrap(), global_scope);
// And we can find their binding inside the global scope
assert!(global_scope.get_binding("g").is_some());
assert!(global_scope.get_binding("f").is_some());
}
/// Finds the last time a token named "name" is used and see if its node is marked as exported
fn assert_is_exported(is_exported: bool, name: &str, code: &str) {
let r = rome_js_parser::parse(code, JsFileSource::tsx(), JsParserOptions::default());
let model = semantic_model(&r.tree(), SemanticModelOptions::default());
let node = r
.syntax()
.descendants()
.filter(|x| x.text_trimmed() == name)
.last()
.unwrap();
match node.kind() {
JsSyntaxKind::JS_IDENTIFIER_BINDING => {
let binding = JsIdentifierBinding::cast(node).unwrap();
// These do the same thing, but with different APIs
assert!(
is_exported == model.is_exported(&binding),
"at \"{}\"",
code
);
assert!(
is_exported == binding.is_exported(&model),
"at \"{}\"",
code
);
}
JsSyntaxKind::TS_IDENTIFIER_BINDING => {
let binding = TsIdentifierBinding::cast(node).unwrap();
// These do the same thing, but with different APIs
assert!(
is_exported == model.is_exported(&binding),
"at \"{}\"",
code
);
assert!(
is_exported == binding.is_exported(&model),
"at \"{}\"",
code
);
}
JsSyntaxKind::JS_REFERENCE_IDENTIFIER => {
let reference = JsReferenceIdentifier::cast(node).unwrap();
// These do the same thing, but with different APIs
assert!(
is_exported == model.is_exported(&reference).unwrap(),
"at \"{}\"",
code
);
assert!(
is_exported == reference.is_exported(&model).unwrap(),
"at \"{}\"",
code
);
}
x => {
panic!("This node cannot be exported! {:?}", x);
}
};
}
#[test]
pub fn ok_semantic_model_is_exported() {
// Variables
assert_is_exported(false, "A", "const A = 1");
assert_is_exported(true, "A", "export const A = 1");
assert_is_exported(true, "A", "const A = 1; export default A");
assert_is_exported(true, "A", "const A = 1; export {A}");
assert_is_exported(true, "A", "const A = 1; module.exports = A;");
assert_is_exported(true, "A", "const A = 1; module.exports = {A};");
assert_is_exported(true, "A", "const A = 1; exports = A;");
assert_is_exported(true, "A", "const A = 1; exports.A = A;");
// Functions
assert_is_exported(false, "f", "function f() {}");
assert_is_exported(true, "f", "export function f() {}");
assert_is_exported(true, "f", "export default function f() {}");
assert_is_exported(true, "f", "function f() {} export default f");
assert_is_exported(true, "f", "function f() {} export {f}");
assert_is_exported(true, "f", "function f() {} export {f as g}");
assert_is_exported(true, "f", "module.exports = function f() {}");
assert_is_exported(true, "f", "exports = function f() {}");
assert_is_exported(true, "f", "exports.f = function f() {}");
assert_is_exported(true, "f", "function f() {} module.exports = f");
assert_is_exported(true, "f", "function f() {} module.exports = {f}");
assert_is_exported(true, "f", "function f() {} exports = f");
assert_is_exported(true, "f", "function f() {} exports.f = f");
// Classess
assert_is_exported(false, "A", "class A{}");
assert_is_exported(true, "A", "export class A{}");
assert_is_exported(true, "A", "export default class A{}");
assert_is_exported(true, "A", "class A{} export default A");
assert_is_exported(true, "A", "class A{} export {A}");
assert_is_exported(true, "A", "class A{} export {A as B}");
assert_is_exported(true, "A", "module.exports = class A{}");
assert_is_exported(true, "A", "exports = class A{}");
assert_is_exported(true, "A", "class A{} module.exports = A");
assert_is_exported(true, "A", "class A{} exports = A");
assert_is_exported(true, "A", "class A{} exports.A = A");
// Interfaces
assert_is_exported(false, "A", "interface A{}");
assert_is_exported(true, "A", "export interface A{}");
assert_is_exported(true, "A", "export default interface A{}");
assert_is_exported(true, "A", "interface A{} export default A");
assert_is_exported(true, "A", "interface A{} export {A}");
assert_is_exported(true, "A", "interface A{} export {A as B}");
assert_is_exported(true, "A", "interface A{} module.exports = A");
assert_is_exported(true, "A", "interface A{} exports = A");
assert_is_exported(true, "A", "interface A{} exports.A = A");
// Type Aliases
assert_is_exported(false, "A", "type A = number;");
assert_is_exported(true, "A", "export type A = number;");
assert_is_exported(true, "A", "type A = number; export default A");
assert_is_exported(true, "A", "type A = number; export {A}");
assert_is_exported(true, "A", "type A = number; export {A as B}");
assert_is_exported(true, "A", "type A = number; module.exports = A");
assert_is_exported(true, "A", "type A = number; exports = A");
assert_is_exported(true, "A", "type A = number; exports.A = A");
// Enums
assert_is_exported(false, "A", "enum A {};");
assert_is_exported(true, "A", "export enum A {};");
assert_is_exported(true, "A", "enum A {}; export default A");
assert_is_exported(true, "A", "enum A {}; export {A}");
assert_is_exported(true, "A", "enum A {}; export {A as B}");
assert_is_exported(true, "A", "enum A {}; module.exports = A");
assert_is_exported(true, "A", "enum A {}; exports = A");
assert_is_exported(true, "A", "enum A {}; exports.A = A");
}
#[test]
pub fn ok_semantic_model_globals() {
let r = rome_js_parser::parse(
"console.log()",
JsFileSource::js_module(),
JsParserOptions::default(),
);
let mut options = SemanticModelOptions::default();
options.globals.insert("console".into());
let model = semantic_model(&r.tree(), options);
let globals: Vec<_> = model.all_global_references().collect();
assert_eq!(globals.len(), 1);
assert!(globals[0].is_read());
assert_eq!(globals[0].syntax().text_trimmed(), "console");
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/semantic_model/is_constant.rs | crates/rome_js_semantic/src/semantic_model/is_constant.rs | use rome_js_syntax::{AnyJsExpression, JsSyntaxKind};
use rome_rowan::AstNode;
pub fn is_constant(expr: &AnyJsExpression) -> bool {
for node in expr.syntax().descendants() {
if matches!(node.kind(), JsSyntaxKind::JS_REFERENCE_IDENTIFIER) {
return false;
}
}
true
}
#[cfg(test)]
mod tests {
use rome_js_parser::JsParserOptions;
use rome_js_syntax::{JsFileSource, JsIdentifierBinding, JsVariableDeclarator};
use crate::{semantic_model, SemanticModelOptions};
fn assert_is_const(code: &str, is_const: bool) {
use rome_rowan::AstNode;
use rome_rowan::SyntaxNodeCast;
let r = rome_js_parser::parse(code, JsFileSource::js_module(), JsParserOptions::default());
let model = semantic_model(&r.tree(), SemanticModelOptions::default());
let a_reference = r
.syntax()
.descendants()
.filter_map(|x| x.cast::<JsIdentifierBinding>())
.find(|x| x.text() == "a")
.unwrap();
let declarator = a_reference.parent::<JsVariableDeclarator>().unwrap();
let initializer = declarator.initializer().unwrap();
let expr = initializer.expression().ok().unwrap();
assert_eq!(model.is_constant(&expr), is_const, "{}", code);
}
#[test]
pub fn ok_semantic_model_is_constant() {
assert_is_const("const a = 1;", true);
assert_is_const("const a = 1 + 1;", true);
assert_is_const("const a = \"a\";", true);
assert_is_const("const a = b = 1;", true);
assert_is_const("const a = 1 + f();", false);
assert_is_const("const a = `${a}`;", false);
assert_is_const("const a = b = 1 + f();", false);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/semantic_model/globals.rs | crates/rome_js_semantic/src/semantic_model/globals.rs | use super::*;
use rome_js_syntax::{JsSyntaxNode, TextRange};
use std::sync::Arc;
#[derive(Debug)]
pub struct SemanticModelGlobalBindingData {
pub(crate) references: Vec<SemanticModelGlobalReferenceData>,
}
#[derive(Debug)]
pub struct SemanticModelGlobalReferenceData {
pub(crate) range: TextRange,
pub(crate) ty: SemanticModelReferenceType,
}
pub struct GlobalReference {
pub(crate) data: Arc<SemanticModelData>,
pub(crate) global_id: usize,
pub(crate) id: usize,
}
impl GlobalReference {
pub fn syntax(&self) -> &JsSyntaxNode {
let reference = &self.data.globals[self.global_id].references[self.id];
&self.data.node_by_range[&reference.range]
}
/// Returns if this reference is just reading its binding
pub fn is_read(&self) -> bool {
let reference = &self.data.globals[self.global_id].references[self.id];
matches!(reference.ty, SemanticModelReferenceType::Read { .. })
}
/// Returns if this reference is writing its binding
pub fn is_write(&self) -> bool {
let reference = &self.data.globals[self.global_id].references[self.id];
matches!(reference.ty, SemanticModelReferenceType::Write { .. })
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/semantic_model/scope.rs | crates/rome_js_semantic/src/semantic_model/scope.rs | use super::*;
use rome_js_syntax::TextRange;
use rome_rowan::TokenText;
use rustc_hash::FxHashMap;
use std::sync::Arc;
#[derive(Debug)]
pub(crate) struct SemanticModelScopeData {
// The scope range
pub(crate) range: TextRange,
// The parent scope of this scope
pub(crate) parent: Option<usize>,
// All children scope of this scope
pub(crate) children: Vec<usize>,
// All bindings of this scope (points to SemanticModelData::bindings)
pub(crate) bindings: Vec<usize>,
// Map pointing to the [bindings] vec of each bindings by its name
pub(crate) bindings_by_name: FxHashMap<TokenText, usize>,
// All read references of a scope
pub(crate) read_references: Vec<SemanticModelScopeReference>,
// All write references of a scope
pub(crate) write_references: Vec<SemanticModelScopeReference>,
// Identify if this scope is from a closure or not
pub(crate) is_closure: bool,
}
/// Provides all information regarding a specific scope.
/// Allows navigation to parent and children scope and binding information.
#[derive(Clone, Debug)]
pub struct Scope {
pub(crate) data: Arc<SemanticModelData>,
pub(crate) id: usize,
}
impl PartialEq for Scope {
fn eq(&self, other: &Self) -> bool {
self.id == other.id && self.data == other.data
}
}
impl Eq for Scope {}
impl Scope {
/// Returns all parents of this scope. Starting with the current
/// [Scope].
pub fn ancestors(&self) -> impl Iterator<Item = Scope> {
std::iter::successors(Some(self.clone()), |scope| scope.parent())
}
/// Returns all descendents of this scope in breadth-first order. Starting with the current
/// [Scope].
pub fn descendents(&self) -> impl Iterator<Item = Scope> {
let mut q = VecDeque::new();
q.push_back(self.id);
ScopeDescendentsIter {
data: self.data.clone(),
q,
}
}
/// Returns this scope parent.
pub fn parent(&self) -> Option<Scope> {
// id will always be a valid scope because
// it was created by [SemanticModel::scope] method.
debug_assert!(self.id < self.data.scopes.len());
let parent = self.data.scopes[self.id].parent?;
Some(Scope {
data: self.data.clone(),
id: parent,
})
}
/// Returns all bindings that were bound in this scope. It **does
/// not** returns bindings of parent scopes.
pub fn bindings(&self) -> ScopeBindingsIter {
ScopeBindingsIter {
data: self.data.clone(),
scope_id: self.id,
binding_index: 0,
}
}
/// Returns a binding by its name, like it appears on code. It **does
/// not** returns bindings of parent scopes.
pub fn get_binding(&self, name: impl AsRef<str>) -> Option<Binding> {
let data = &self.data.scopes[self.id];
let name = name.as_ref();
let id = data.bindings_by_name.get(name)?;
Some(Binding {
data: self.data.clone(),
index: (*id).into(),
})
}
/// Checks if the current scope is one of the ancestor of "other". Given
/// that [ancestors] return "self" as the first scope,
/// this function returns true for:
///
/// ```rust,ignore
/// assert!(scope.is_ancestor_of(scope));
/// ```
pub fn is_ancestor_of(&self, other: &Scope) -> bool {
other.ancestors().any(|s| s == *self)
}
pub fn range(&self) -> &TextRange {
&self.data.scopes[self.id].range
}
pub fn syntax(&self) -> &JsSyntaxNode {
&self.data.node_by_range[self.range()]
}
/// Return the [Closure] associated with this scope if
/// it has one, otherwise returns None.
/// See [HasClosureAstNode] for nodes that have closure.
pub fn closure(&self) -> Option<Closure> {
Closure::from_scope(self.data.clone(), self.id, self.range())
}
}
/// Represents a refererence inside a scope.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub(crate) struct SemanticModelScopeReference {
// Points to [SemanticModel]::bindings vec
pub(crate) binding_id: usize,
// Points do [SemanticModelBinding]::references vec
pub(crate) reference_id: usize,
}
/// Iterate all descendents scopes of the specified scope in breadth-first order.
pub struct ScopeDescendentsIter {
data: Arc<SemanticModelData>,
q: VecDeque<usize>,
}
impl Iterator for ScopeDescendentsIter {
type Item = Scope;
fn next(&mut self) -> Option<Self::Item> {
if let Some(id) = self.q.pop_front() {
let scope = &self.data.scopes[id];
self.q.extend(scope.children.iter());
Some(Scope {
data: self.data.clone(),
id,
})
} else {
None
}
}
}
impl FusedIterator for ScopeDescendentsIter {}
/// Iterate all bindings that were bound in a given scope. It **does
/// not** Returns bindings of parent scopes.
#[derive(Debug)]
pub struct ScopeBindingsIter {
data: Arc<SemanticModelData>,
scope_id: usize,
binding_index: usize,
}
impl Iterator for ScopeBindingsIter {
type Item = Binding;
fn next(&mut self) -> Option<Self::Item> {
// scope_id will always be a valid scope because
// it was created by [Scope::bindings] method.
debug_assert!(self.scope_id < self.data.scopes.len());
let id = self.data.scopes[self.scope_id]
.bindings
.get(self.binding_index)?;
self.binding_index += 1;
Some(Binding {
data: self.data.clone(),
index: (*id).into(),
})
}
}
impl ExactSizeIterator for ScopeBindingsIter {
fn len(&self) -> usize {
// scope_id will always be a valid scope because
// it was created by [Scope::bindings] method.
debug_assert!(self.scope_id < self.data.scopes.len());
self.data.scopes[self.scope_id].bindings.len()
}
}
impl FusedIterator for ScopeBindingsIter {}
// Extensions
/// Extension method to allow [AstNode] to easily
/// get its [Scope].
pub trait SemanticScopeExtensions {
/// Returns the [Scope] which this object is part of.
/// See [scope](semantic_model::SemanticModel::scope)
fn scope(&self, model: &SemanticModel) -> Scope;
/// Returns the [Scope] which this object was hosted to, if any.
/// See [scope](semantic_model::SemanticModel::scope_hoisted_to)
fn scope_hoisted_to(&self, model: &SemanticModel) -> Option<Scope>;
}
impl<T: AstNode<Language = JsLanguage>> SemanticScopeExtensions for T {
fn scope(&self, model: &SemanticModel) -> Scope {
model.scope(self.syntax())
}
fn scope_hoisted_to(&self, model: &SemanticModel) -> Option<Scope> {
model.scope_hoisted_to(self.syntax())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/semantic_model/closure.rs | crates/rome_js_semantic/src/semantic_model/closure.rs | use super::*;
use rome_js_syntax::{
JsArrowFunctionExpression, JsConstructorClassMember, JsFunctionDeclaration,
JsFunctionExpression, JsGetterClassMember, JsGetterObjectMember, JsLanguage,
JsMethodClassMember, JsMethodObjectMember, JsSetterClassMember, JsSetterObjectMember,
};
use rome_rowan::{AstNode, SyntaxNode, SyntaxNodeCast};
use std::sync::Arc;
/// Marker trait that groups all "AstNode" that have closure
pub trait HasClosureAstNode {
fn node_text_range(&self) -> TextRange;
}
macro_rules! SyntaxTextRangeHasClosureAstNode {
($($kind:tt => $node:tt,)*) => {
$(
impl HasClosureAstNode for $node {
#[inline(always)]
fn node_text_range(&self) -> TextRange {
self.syntax().text_range()
}
}
)*
/// All nodes that have an associated closure
/// and can be used by the [SemanticModel].
pub enum AnyHasClosureNode {
$(
$node($node),
)*
}
impl AnyHasClosureNode {
pub fn from_node(node: &SyntaxNode<JsLanguage>) -> Option<AnyHasClosureNode> {
match node.kind() {
$(
JsSyntaxKind::$kind => node
.clone()
.cast::<$node>()
.map(AnyHasClosureNode::$node),
)*
_ => None,
}
}
}
impl HasClosureAstNode for AnyHasClosureNode {
#[inline(always)]
fn node_text_range(&self) -> TextRange {
match self {
$(
AnyHasClosureNode::$node(node) => node.syntax().text_range(),
)*
}
}
}
};
}
SyntaxTextRangeHasClosureAstNode! {
JS_FUNCTION_DECLARATION => JsFunctionDeclaration,
JS_FUNCTION_EXPRESSION => JsFunctionExpression,
JS_ARROW_FUNCTION_EXPRESSION => JsArrowFunctionExpression,
JS_CONSTRUCTOR_CLASS_MEMBER => JsConstructorClassMember,
JS_METHOD_CLASS_MEMBER => JsMethodClassMember,
JS_GETTER_CLASS_MEMBER => JsGetterClassMember,
JS_SETTER_CLASS_MEMBER => JsSetterClassMember,
JS_METHOD_OBJECT_MEMBER => JsMethodObjectMember,
JS_GETTER_OBJECT_MEMBER => JsGetterObjectMember,
JS_SETTER_OBJECT_MEMBER => JsSetterObjectMember,
}
#[derive(Clone)]
pub enum CaptureType {
ByReference,
Type,
}
/// Provides all information regarding a specific closure capture.
#[derive(Clone)]
pub struct Capture {
data: Arc<SemanticModelData>,
ty: CaptureType,
node: JsSyntaxNode,
binding_id: BindingIndex,
}
impl Capture {
/// Returns if the capture is by reference or just the type of the variable.
pub fn ty(&self) -> &CaptureType {
&self.ty
}
/// Returns the reference node of the capture
pub fn node(&self) -> &SyntaxNode<JsLanguage> {
&self.node
}
/// Returns the binding of this capture
pub fn binding(&self) -> Binding {
Binding {
data: self.data.clone(),
index: self.binding_id,
}
}
/// Returns the non trimmed text range of declaration of this capture.
/// This is equivalent, but faster, to:
///
/// ```rs, ignore
/// self.declaration().text_range()
/// ```
pub fn declaration_range(&self) -> &TextRange {
let binding = self.data.binding(self.binding_id);
&binding.range
}
}
pub struct AllCapturesIter {
data: Arc<SemanticModelData>,
closure_range: TextRange,
scopes: Vec<usize>,
references: Vec<SemanticModelScopeReference>,
}
impl Iterator for AllCapturesIter {
type Item = Capture;
fn next(&mut self) -> Option<Self::Item> {
'references: loop {
while let Some(reference) = self.references.pop() {
let binding = &self.data.bindings[reference.binding_id];
if self.closure_range.intersect(binding.range).is_none() {
let reference = &binding.references[reference.reference_id];
return Some(Capture {
data: self.data.clone(),
node: self.data.node_by_range[&reference.range].clone(), // TODO change node to store the range
ty: CaptureType::ByReference,
binding_id: binding.id,
});
}
}
'scopes: while let Some(scope_id) = self.scopes.pop() {
let scope = &self.data.scopes[scope_id];
if scope.is_closure {
continue 'scopes;
} else {
self.references.clear();
self.references
.extend(scope.read_references.iter().cloned());
self.references
.extend(scope.write_references.iter().cloned());
self.scopes.extend(scope.children.iter());
continue 'references;
}
}
return None;
}
}
}
impl FusedIterator for AllCapturesIter {}
/// Iterate all immediate children closures of a specific closure
pub struct ChildrenIter {
data: Arc<SemanticModelData>,
scopes: Vec<usize>,
}
impl Iterator for ChildrenIter {
type Item = Closure;
fn next(&mut self) -> Option<Self::Item> {
while let Some(scope_id) = self.scopes.pop() {
let scope = &self.data.scopes[scope_id];
if scope.is_closure {
return Some(Closure {
data: self.data.clone(),
scope_id,
closure_range: scope.range,
});
} else {
self.scopes.extend(scope.children.iter());
}
}
None
}
}
impl FusedIterator for ChildrenIter {}
/// Iterate all descendents closures of a specific closure
pub struct DescendentsIter {
data: Arc<SemanticModelData>,
scopes: Vec<usize>,
}
impl Iterator for DescendentsIter {
type Item = Closure;
fn next(&mut self) -> Option<Self::Item> {
while let Some(scope_id) = self.scopes.pop() {
let scope = &self.data.scopes[scope_id];
self.scopes.extend(scope.children.iter());
if scope.is_closure {
return Some(Closure {
data: self.data.clone(),
scope_id,
closure_range: scope.range,
});
}
}
None
}
}
impl FusedIterator for DescendentsIter {}
/// Provides all information regarding a specific closure.
#[derive(Clone)]
pub struct Closure {
data: Arc<SemanticModelData>,
scope_id: usize,
closure_range: TextRange,
}
impl Closure {
pub(super) fn from_node(
data: Arc<SemanticModelData>,
node: &impl HasClosureAstNode,
) -> Closure {
let closure_range = node.node_text_range();
let scope_id = data.scope(&closure_range);
Closure {
data,
scope_id,
closure_range,
}
}
pub(super) fn from_scope(
data: Arc<SemanticModelData>,
scope_id: usize,
closure_range: &TextRange,
) -> Option<Closure> {
let node = &data.node_by_range[closure_range];
match node.kind() {
JsSyntaxKind::JS_FUNCTION_DECLARATION
| JsSyntaxKind::JS_FUNCTION_EXPRESSION
| JsSyntaxKind::JS_ARROW_FUNCTION_EXPRESSION => Some(Closure {
data,
scope_id,
closure_range: *closure_range,
}),
_ => None,
}
}
/// Range of this [Closure]
pub fn closure_range(&self) -> &TextRange {
&self.closure_range
}
/// Return all [Reference] this closure captures, not taking into
/// consideration any capture of children closures
///
/// ```rust,ignore
/// let inner_function = "let a, b;
/// function f(c) {
/// console.log(a);
/// function g() {
/// console.log(b, c);
/// }
/// }";
/// assert!(model.closure(function_f).all_captures(), &["a"]);
/// ```
pub fn all_captures(&self) -> impl Iterator<Item = Capture> {
let scope = &self.data.scopes[self.scope_id];
let scopes = Vec::from_iter(scope.children.iter().cloned());
let mut references = Vec::from_iter(scope.read_references.iter().cloned());
references.extend(scope.write_references.iter().cloned());
AllCapturesIter {
data: self.data.clone(),
closure_range: self.closure_range,
scopes,
references,
}
}
/// Return all immediate children closures of this closure.
///
/// ```rust,ignore
/// let inner_function = "let a, b;
/// function f(c) {
/// console.log(a);
/// function g() {
/// function h() {
/// }
/// console.log(b, c);
/// }
/// }";
/// assert!(model.closure(function_f).children(), &["g"]);
/// ```
pub fn children(&self) -> impl Iterator<Item = Closure> {
let scope = &self.data.scopes[self.scope_id];
let scopes = Vec::from_iter(scope.children.iter().cloned());
ChildrenIter {
data: self.data.clone(),
scopes,
}
}
/// Returns all descendents of this closure in breadth-first order. Starting with the current
/// [Closure].
///
/// ```rust,ignore
/// let inner_function = "let a, b;
/// function f(c) {
/// console.log(a);
/// function g() {
/// function h() {
/// }
/// console.log(b, c);
/// }
/// }";
/// assert!(model.closure(function_f).descendents(), &["f", "g", "h"]);
/// ```
pub fn descendents(&self) -> impl Iterator<Item = Closure> {
let scopes = vec![self.scope_id];
DescendentsIter {
data: self.data.clone(),
scopes,
}
}
}
pub trait ClosureExtensions {
fn closure(&self, model: &SemanticModel) -> Closure
where
Self: HasClosureAstNode + Sized,
{
model.closure(self)
}
}
impl<T: HasClosureAstNode> ClosureExtensions for T {}
#[cfg(test)]
mod test {
use super::*;
use rome_js_parser::JsParserOptions;
use rome_js_syntax::{JsArrowFunctionExpression, JsFileSource, JsSyntaxKind};
use rome_rowan::SyntaxNodeCast;
fn assert_closure(code: &str, name: &str, captures: &[&str]) {
let r = rome_js_parser::parse(code, JsFileSource::tsx(), JsParserOptions::default());
let model = semantic_model(&r.tree(), SemanticModelOptions::default());
let closure = if name != "ARROWFUNCTION" {
let node = r
.syntax()
.descendants()
.filter(|x| x.text_trimmed() == name)
.last()
.unwrap();
let node = node
.parent()
.and_then(|node| AnyHasClosureNode::from_node(&node))
.unwrap();
model.closure(&node)
} else {
let node = r
.syntax()
.descendants()
.filter(|x| x.kind() == JsSyntaxKind::JS_ARROW_FUNCTION_EXPRESSION)
.last()
.unwrap()
.cast::<JsArrowFunctionExpression>()
.unwrap();
model.closure(&node)
};
let expected_captures: BTreeSet<String> = captures.iter().map(|x| x.to_string()).collect();
let all_captures: BTreeSet<String> = closure
.all_captures()
.map(|x| x.node().text_trimmed().to_string())
.collect();
let intersection = expected_captures.intersection(&all_captures);
let intersection_count = intersection.count();
assert_eq!(intersection_count, expected_captures.len());
assert_eq!(intersection_count, all_captures.len());
}
fn get_closure_children(code: &str, name: &str) -> Vec<Closure> {
let r = rome_js_parser::parse(code, JsFileSource::tsx(), JsParserOptions::default());
let model = semantic_model(&r.tree(), SemanticModelOptions::default());
let closure = if name != "ARROWFUNCTION" {
let node = r
.syntax()
.descendants()
.filter(|x| x.text_trimmed() == name)
.last()
.unwrap();
let node = node
.parent()
.and_then(|node| AnyHasClosureNode::from_node(&node))
.unwrap();
model.closure(&node)
} else {
let node = r
.syntax()
.descendants()
.filter(|x| x.kind() == JsSyntaxKind::JS_ARROW_FUNCTION_EXPRESSION)
.last()
.unwrap()
.cast::<JsArrowFunctionExpression>()
.unwrap();
model.closure(&node)
};
closure.children().collect()
}
#[test]
pub fn ok_semantic_model_closure() {
assert_closure("function f() {}", "f", &[]);
let two_captures = "let a, b; function f(c) {console.log(a, b, c)}";
assert_closure(two_captures, "f", &["a", "b"]);
assert_eq!(get_closure_children(two_captures, "f").len(), 0);
let inner_function = "let a, b;
function f(c) {
console.log(a);
function g() {
console.log(b, c);
}
}";
assert_closure(inner_function, "f", &["a"]);
assert_closure(inner_function, "g", &["b", "c"]);
assert_eq!(get_closure_children(inner_function, "f").len(), 1);
assert_eq!(get_closure_children(inner_function, "g").len(), 0);
let arrow_function = "let a, b;
function f(c) {
console.log(a);
c.map(x => x + b + c);
}";
assert_closure(arrow_function, "f", &["a"]);
assert_closure(arrow_function, "ARROWFUNCTION", &["b", "c"]);
assert_eq!(get_closure_children(arrow_function, "f").len(), 1);
assert_eq!(
get_closure_children(arrow_function, "ARROWFUNCTION").len(),
0
);
let writes = "let a;
function f(c) {
a = 1
}";
assert_closure(writes, "f", &["a"]);
let class_callables = "let a;
class A {
constructor() { console.log(a); }
f() { console.log(a); }
get getValue() { console.log(a); }
set setValue(v) { console.log(a); }
}";
assert_closure(class_callables, "constructor", &["a"]);
assert_closure(class_callables, "f", &["a"]);
assert_closure(class_callables, "getValue", &["a"]);
assert_closure(class_callables, "setValue", &["a"]);
let object_callables = "let a;
let a = {
f() { console.log(a); }
get getValue() { console.log(a); }
set setValue(v) { console.log(a); }
}";
assert_closure(object_callables, "f", &["a"]);
assert_closure(object_callables, "getValue", &["a"]);
assert_closure(object_callables, "setValue", &["a"]);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/semantic_model/model.rs | crates/rome_js_semantic/src/semantic_model/model.rs | use super::*;
use rome_js_syntax::{AnyJsFunction, AnyJsRoot, JsInitializerClause, JsVariableDeclarator};
#[derive(Copy, Clone, Debug)]
pub(crate) struct BindingIndex(usize);
impl From<usize> for BindingIndex {
fn from(v: usize) -> Self {
BindingIndex(v)
}
}
#[derive(Copy, Clone, Debug)]
pub(crate) struct ReferenceIndex(usize, usize);
impl ReferenceIndex {
pub(crate) fn binding(&self) -> BindingIndex {
BindingIndex(self.0)
}
}
impl From<(BindingIndex, usize)> for ReferenceIndex {
fn from((binding_index, index): (BindingIndex, usize)) -> Self {
ReferenceIndex(binding_index.0, index)
}
}
/// Contains all the data of the [SemanticModel] and only lives behind an [Arc].
///
/// That allows any returned struct (like [Scope], [Binding])
/// to outlive the [SemanticModel], and to not include lifetimes.
#[derive(Debug)]
pub(crate) struct SemanticModelData {
pub(crate) root: AnyJsRoot,
// All scopes of this model
pub(crate) scopes: Vec<SemanticModelScopeData>,
pub(crate) scope_by_range: rust_lapper::Lapper<usize, usize>,
// Maps the start of a node range to a scope id
pub(crate) scope_hoisted_to_by_range: FxHashMap<TextSize, usize>,
// Map to each by its range
pub(crate) node_by_range: FxHashMap<TextRange, JsSyntaxNode>,
// Maps any range in the code to its bindings (usize points to bindings vec)
pub(crate) declared_at_by_range: FxHashMap<TextRange, usize>,
// List of all the declarations
pub(crate) bindings: Vec<SemanticModelBindingData>,
// Index bindings by range
pub(crate) bindings_by_range: FxHashMap<TextRange, usize>,
// All bindings that were exported
pub(crate) exported: FxHashSet<TextRange>,
/// All references that could not be resolved
pub(crate) unresolved_references: Vec<SemanticModelUnresolvedReference>,
/// All globals references
pub(crate) globals: Vec<SemanticModelGlobalBindingData>,
}
impl SemanticModelData {
pub(crate) fn binding(&self, index: BindingIndex) -> &SemanticModelBindingData {
&self.bindings[index.0]
}
pub(crate) fn reference(&self, index: ReferenceIndex) -> &SemanticModelReference {
let binding = &self.bindings[index.0];
&binding.references[index.1]
}
pub(crate) fn next_reference(&self, index: ReferenceIndex) -> Option<&SemanticModelReference> {
let binding = &self.bindings[index.0];
binding.references.get(index.1 + 1)
}
pub(crate) fn scope(&self, range: &TextRange) -> usize {
let start = range.start().into();
let end = range.end().into();
let scopes = self
.scope_by_range
.find(start, end)
.filter(|x| !(start < x.start || end > x.stop));
// We always want the most tight scope
match scopes.map(|x| x.val).max() {
Some(val) => val,
// We always have at least one scope, the global one.
None => unreachable!("Expected global scope not present"),
}
}
fn scope_hoisted_to(&self, range: &TextRange) -> Option<usize> {
self.scope_hoisted_to_by_range.get(&range.start()).cloned()
}
pub fn is_exported(&self, range: TextRange) -> bool {
self.exported.contains(&range)
}
}
impl PartialEq for SemanticModelData {
fn eq(&self, other: &Self) -> bool {
self.root == other.root
}
}
impl Eq for SemanticModelData {}
/// The façade for all semantic information.
/// - Scope: [scope]
/// - Declarations: [declaration]
///
/// See [SemanticModelData] for more information about the internals.
#[derive(Clone, Debug)]
pub struct SemanticModel {
pub(crate) data: Arc<SemanticModelData>,
}
impl SemanticModel {
pub(crate) fn new(data: SemanticModelData) -> Self {
Self {
data: Arc::new(data),
}
}
/// Iterate all scopes
pub fn scopes(&self) -> impl Iterator<Item = Scope> + '_ {
self.data.scopes.iter().enumerate().map(|(id, _)| Scope {
data: self.data.clone(),
id,
})
}
/// Returns the global scope of the model
pub fn global_scope(&self) -> Scope {
Scope {
data: self.data.clone(),
id: 0,
}
}
/// Returns the [Scope] which the syntax is part of.
/// Can also be called from [AstNode]::scope extension method.
///
/// ```rust
/// use rome_js_parser::JsParserOptions;
/// use rome_rowan::{AstNode, SyntaxNodeCast};
/// use rome_js_syntax::{JsFileSource, JsReferenceIdentifier};
/// use rome_js_semantic::{semantic_model, SemanticModelOptions, SemanticScopeExtensions};
///
/// let r = rome_js_parser::parse("function f(){let a = arguments[0]; let b = a + 1;}", JsFileSource::js_module(), JsParserOptions::default());
/// let model = semantic_model(&r.tree(), SemanticModelOptions::default());
///
/// let arguments_reference = r
/// .syntax()
/// .descendants()
/// .filter_map(|x| x.cast::<JsReferenceIdentifier>())
/// .find(|x| x.text() == "arguments")
/// .unwrap();
///
/// let block_scope = model.scope(&arguments_reference.syntax());
/// // or
/// let block_scope = arguments_reference.scope(&model);
/// ```
pub fn scope(&self, node: &JsSyntaxNode) -> Scope {
let range = node.text_range();
let id = self.data.scope(&range);
Scope {
data: self.data.clone(),
id,
}
}
/// Returns the [Scope] which the specified syntax node was hoisted to, if any.
/// Can also be called from [AstNode]::scope_hoisted_to extension method.
pub fn scope_hoisted_to(&self, node: &JsSyntaxNode) -> Option<Scope> {
let range = node.text_range();
let id = self.data.scope_hoisted_to(&range)?;
Some(Scope {
data: self.data.clone(),
id,
})
}
pub fn all_bindings(&self) -> impl Iterator<Item = Binding> + '_ {
self.data.bindings.iter().map(|x| Binding {
data: self.data.clone(),
index: x.id,
})
}
/// Returns the [Binding] of a reference.
/// Can also be called from "binding" extension method.
///
/// ```rust
/// use rome_js_parser::JsParserOptions;
/// use rome_rowan::{AstNode, SyntaxNodeCast};
/// use rome_js_syntax::{JsFileSource, JsReferenceIdentifier};
/// use rome_js_semantic::{semantic_model, BindingExtensions, SemanticModelOptions};
///
/// let r = rome_js_parser::parse("function f(){let a = arguments[0]; let b = a + 1;}", JsFileSource::js_module(), JsParserOptions::default());
/// let model = semantic_model(&r.tree(), SemanticModelOptions::default());
///
/// let arguments_reference = r
/// .syntax()
/// .descendants()
/// .filter_map(|x| x.cast::<JsReferenceIdentifier>())
/// .find(|x| x.text() == "arguments")
/// .unwrap();
///
/// let arguments_binding = model.binding(&arguments_reference);
/// // or
/// let arguments_binding = arguments_reference.binding(&model);
/// ```
pub fn binding(&self, reference: &impl HasDeclarationAstNode) -> Option<Binding> {
let reference = reference.node();
let range = reference.syntax().text_range();
let id = *self.data.declared_at_by_range.get(&range)?;
Some(Binding {
data: self.data.clone(),
index: id.into(),
})
}
/// Returns an iterator of all the globals references in the program
pub fn all_global_references(
&self,
) -> std::iter::Successors<GlobalReference, fn(&GlobalReference) -> Option<GlobalReference>>
{
let first = self
.data
.globals
.get(0)
.and_then(|global| global.references.get(0))
.map(|_| GlobalReference {
data: self.data.clone(),
global_id: 0,
id: 0,
});
fn succ(current: &GlobalReference) -> Option<GlobalReference> {
let mut global_id = current.global_id;
let mut id = current.id + 1;
while global_id < current.data.globals.len() {
let reference = current
.data
.globals
.get(global_id)
.and_then(|global| global.references.get(id))
.map(|_| GlobalReference {
data: current.data.clone(),
global_id,
id,
});
match reference {
Some(reference) => return Some(reference),
None => {
global_id += 1;
id = 0;
}
}
}
None
}
std::iter::successors(first, succ)
}
/// Returns an iterator of all the unresolved references in the program
pub fn all_unresolved_references(
&self,
) -> std::iter::Successors<
UnresolvedReference,
fn(&UnresolvedReference) -> Option<UnresolvedReference>,
> {
let first = self
.data
.unresolved_references
.get(0)
.map(|_| UnresolvedReference {
data: self.data.clone(),
id: 0,
});
fn succ(current: &UnresolvedReference) -> Option<UnresolvedReference> {
let id = current.id + 1;
current
.data
.unresolved_references
.get(id)
.map(|_| UnresolvedReference {
data: current.data.clone(),
id,
})
}
std::iter::successors(first, succ)
}
/// Returns if the node is exported or is a reference to a binding
/// that is exported.
///
/// When a binding is specified this method returns a bool.
///
/// When a reference is specified this method returns Option<bool>,
/// because there is no guarantee that the corresponding declaration exists.
pub fn is_exported<T>(&self, node: &T) -> T::Result
where
T: CanBeImportedExported,
{
node.is_exported(self)
}
/// Returns if the node is imported or is a reference to a binding
/// that is imported.
///
/// When a binding is specified this method returns a bool.
///
/// When a reference is specified this method returns Option<bool>,
/// because there is no guarantee that the corresponding declaration exists.
pub fn is_imported<T>(&self, node: &T) -> T::Result
where
T: CanBeImportedExported,
{
node.is_imported(self)
}
/// Returns the [Closure] associated with the node.
pub fn closure(&self, node: &impl HasClosureAstNode) -> Closure {
Closure::from_node(self.data.clone(), node)
}
/// Returns true or false if the expression is constant, which
/// means it does not depend on any other variables.
pub fn is_constant(&self, expr: &AnyJsExpression) -> bool {
is_constant::is_constant(expr)
}
pub fn as_binding(&self, binding: &impl IsBindingAstNode) -> Binding {
let range = binding.syntax().text_range();
let id = &self.data.bindings_by_range[&range];
Binding {
data: self.data.clone(),
index: (*id).into(),
}
}
/// Returns all [Call] of a [AnyJsFunction].
///
/// ```rust
/// use rome_js_parser::JsParserOptions;
/// use rome_rowan::{AstNode, SyntaxNodeCast};
/// use rome_js_syntax::{JsFileSource, AnyJsFunction};
/// use rome_js_semantic::{semantic_model, CallsExtensions, SemanticModelOptions};
///
/// let r = rome_js_parser::parse("function f(){} f() f()", JsFileSource::js_module(), JsParserOptions::default());
/// let model = semantic_model(&r.tree(), SemanticModelOptions::default());
///
/// let f_declaration = r
/// .syntax()
/// .descendants()
/// .filter_map(AnyJsFunction::cast)
/// .next()
/// .unwrap();
///
/// let all_calls_to_f = model.all_calls(&f_declaration);
/// assert_eq!(2, all_calls_to_f.unwrap().count());
/// // or
/// let all_calls_to_f = f_declaration.all_calls(&model);
/// assert_eq!(2, all_calls_to_f.unwrap().count());
/// ```
pub fn all_calls(&self, function: &AnyJsFunction) -> Option<AllCallsIter> {
let identifier = match function {
AnyJsFunction::JsFunctionDeclaration(declaration) => declaration.id().ok()?,
AnyJsFunction::JsFunctionExportDefaultDeclaration(declaration) => declaration.id()?,
AnyJsFunction::JsArrowFunctionExpression(_)
| AnyJsFunction::JsFunctionExpression(_) => {
let parent = function
.parent::<JsInitializerClause>()?
.parent::<JsVariableDeclarator>()?;
parent.id().ok()?.as_any_js_binding()?.clone()
}
};
Some(AllCallsIter {
references: identifier.as_js_identifier_binding()?.all_reads(self),
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/semantic_model/binding.rs | crates/rome_js_semantic/src/semantic_model/binding.rs | use super::*;
use rome_js_syntax::{binding_ext::AnyJsIdentifierBinding, TextRange, TsTypeParameterName};
/// Internal type with all the semantic data of a specific binding
#[derive(Debug)]
pub(crate) struct SemanticModelBindingData {
pub id: BindingIndex,
pub range: TextRange,
pub references: Vec<SemanticModelReference>,
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum SemanticModelReferenceType {
Read { hoisted: bool },
Write { hoisted: bool },
}
/// Internal type with all the semantic data of a specific reference
#[derive(Debug)]
pub(crate) struct SemanticModelReference {
pub(crate) index: ReferenceIndex,
pub(crate) range: TextRange,
pub(crate) ty: SemanticModelReferenceType,
}
impl SemanticModelReference {
#[inline(always)]
pub fn is_read(&self) -> bool {
matches!(self.ty, SemanticModelReferenceType::Read { .. })
}
#[inline(always)]
pub fn is_write(&self) -> bool {
matches!(self.ty, SemanticModelReferenceType::Write { .. })
}
}
pub type AllBindingReferencesIter =
std::iter::Successors<Reference, fn(&Reference) -> Option<Reference>>;
pub type AllBindingReadReferencesIter =
std::iter::Successors<Reference, fn(&Reference) -> Option<Reference>>;
pub type AllBindingWriteReferencesIter =
std::iter::Successors<Reference, fn(&Reference) -> Option<Reference>>;
/// Provides access to all semantic data of a specific binding.
pub struct Binding {
pub(crate) data: Arc<SemanticModelData>,
pub(crate) index: BindingIndex,
}
impl std::fmt::Debug for Binding {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Binding").field("id", &self.index).finish()
}
}
impl Binding {
/// Returns the scope of this binding
pub fn scope(&self) -> Scope {
let binding = self.data.binding(self.index);
let id = self.data.scope(&binding.range); //TODO declaration can have its scope id
Scope {
data: self.data.clone(),
id,
}
}
/// Returns the syntax node associated with this binding.
pub fn syntax(&self) -> &JsSyntaxNode {
let binding = self.data.binding(self.index);
&self.data.node_by_range[&binding.range]
}
/// Returns the typed AST node associated with this binding.
pub fn tree(&self) -> AnyJsIdentifierBinding {
let node = self.syntax();
let binding = AnyJsIdentifierBinding::cast_ref(node);
debug_assert!(binding.is_some());
binding.unwrap()
}
/// Returns an iterator to all references of this binding.
pub fn all_references(&self) -> AllBindingReferencesIter {
let binding = self.data.binding(self.index);
let first = binding.references.first().map(|reference| Reference {
data: self.data.clone(),
index: reference.index,
});
std::iter::successors(first, Reference::find_next)
}
/// Returns an iterator to all reads references of this binding.
pub fn all_reads(&self) -> AllBindingReadReferencesIter {
let binding = self.data.binding(self.index);
let first = binding
.references
.iter()
.find(|x| x.is_read())
.map(|reference| Reference {
data: self.data.clone(),
index: reference.index,
});
std::iter::successors(first, Reference::find_next_read)
}
/// Returns an iterator to all write references of this binding.
pub fn all_writes(&self) -> AllBindingWriteReferencesIter {
let binding = self.data.binding(self.index);
let first = binding
.references
.iter()
.find(|x| x.is_write())
.map(|reference| Reference {
data: self.data.clone(),
index: reference.index,
});
std::iter::successors(first, Reference::find_next_write)
}
pub fn is_imported(&self) -> bool {
super::is_imported(self.syntax())
}
}
/// Marker trait that groups all "AstNode" that are bindings
pub trait IsBindingAstNode: AstNode<Language = JsLanguage> {
#[inline(always)]
fn node(&self) -> &Self {
self
}
}
impl IsBindingAstNode for JsIdentifierBinding {}
impl IsBindingAstNode for TsIdentifierBinding {}
impl IsBindingAstNode for AnyJsIdentifierBinding {}
impl IsBindingAstNode for TsTypeParameterName {}
/// Extension method to allow nodes that have declaration to easily
/// get its binding.
pub trait BindingExtensions {
/// Returns the [Binding] that declared the symbol this reference references.
fn binding(&self, model: &SemanticModel) -> Option<Binding>
where
Self: HasDeclarationAstNode,
{
model.binding(self)
}
}
impl<T: HasDeclarationAstNode> BindingExtensions for T {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_semantic/src/semantic_model/import.rs | crates/rome_js_semantic/src/semantic_model/import.rs | use super::*;
use crate::{HasDeclarationAstNode, SemanticModel};
use rome_js_syntax::{
binding_ext::AnyJsIdentifierBinding, JsIdentifierBinding, JsLanguage, JsSyntaxKind,
};
use rome_rowan::AstNode;
pub(crate) fn is_imported(node: &JsSyntaxNode) -> bool {
node.ancestors()
.any(|x| matches!(x.kind(), JsSyntaxKind::JS_IMPORT))
}
/// Marker trait that groups all "AstNode" that can be imported or
/// exported
pub trait CanBeImportedExported: AstNode<Language = JsLanguage> {
type Result;
fn is_exported(&self, model: &SemanticModel) -> Self::Result;
fn is_imported(&self, model: &SemanticModel) -> Self::Result;
}
impl CanBeImportedExported for JsIdentifierBinding {
type Result = bool;
fn is_exported(&self, model: &SemanticModel) -> Self::Result {
let range = self.syntax().text_range();
model.data.is_exported(range)
}
fn is_imported(&self, _: &SemanticModel) -> Self::Result {
is_imported(self.syntax())
}
}
impl CanBeImportedExported for TsIdentifierBinding {
type Result = bool;
fn is_exported(&self, model: &SemanticModel) -> Self::Result {
let range = self.syntax().text_range();
model.data.is_exported(range)
}
fn is_imported(&self, _: &SemanticModel) -> Self::Result {
is_imported(self.syntax())
}
}
impl CanBeImportedExported for AnyJsIdentifierBinding {
type Result = bool;
fn is_exported(&self, model: &SemanticModel) -> Self::Result {
let range = self.syntax().text_range();
model.data.is_exported(range)
}
fn is_imported(&self, _: &SemanticModel) -> Self::Result {
is_imported(self.syntax())
}
}
impl<T: HasDeclarationAstNode> CanBeImportedExported for T {
type Result = Option<bool>;
fn is_exported(&self, model: &SemanticModel) -> Self::Result {
let range = self.binding(model)?.syntax().text_range();
Some(model.data.is_exported(range))
}
fn is_imported(&self, model: &SemanticModel) -> Self::Result {
let binding = self.binding(model)?;
let node = binding.syntax();
Some(is_imported(node))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_aria/src/lib.rs | crates/rome_aria/src/lib.rs | use std::str::FromStr;
pub mod iso;
mod macros;
pub mod properties;
pub mod roles;
pub use properties::AriaProperties;
pub(crate) use roles::AriaRoleDefinition;
pub use roles::AriaRoles;
pub use rome_aria_metadata::{AriaPropertiesEnum, AriaPropertyTypeEnum};
/// It checks if an ARIA property is valid
///
/// ## Examples
///
/// ```
/// use rome_aria::is_aria_property_valid;
///
/// assert!(!is_aria_property_valid("aria-blabla"));
/// assert!(is_aria_property_valid("aria-checked"));
/// ```
pub fn is_aria_property_valid(property: &str) -> bool {
AriaPropertiesEnum::from_str(property).is_ok()
}
/// It checks if an ARIA property type is valid
///
/// ## Examples
///
/// ```
/// use rome_aria::is_aria_property_type_valid;
///
/// assert!(is_aria_property_type_valid("string"));
/// assert!(!is_aria_property_type_valid("bogus"));
/// ```
pub fn is_aria_property_type_valid(property_type: &str) -> bool {
AriaPropertyTypeEnum::from_str(property_type).is_ok()
}
#[cfg(test)]
mod test {
use crate::roles::AriaRoles;
#[test]
fn property_is_required() {
let roles = AriaRoles::default();
let role = roles.get_role("checkbox");
assert!(role.is_some());
let role = role.unwrap();
assert!(role.is_property_required("aria-checked"));
assert!(!role.is_property_required("aria-sort"));
assert!(!role.is_property_required("aria-bnlabla"));
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_aria/src/properties.rs | crates/rome_aria/src/properties.rs | use crate::define_property;
use rome_aria_metadata::AriaPropertyTypeEnum;
use std::fmt::Debug;
use std::slice::Iter;
use std::str::FromStr;
define_property! {
AriaActivedescendant {
PROPERTY_TYPE: "id",
VALUES: [],
}
}
define_property! {
AriaAtomic {
PROPERTY_TYPE: "boolean",
VALUES: [],
}
}
define_property! {
AriaAutocomplete {
PROPERTY_TYPE: "token",
VALUES: ["inline", "list", "both", "none"],
}
}
define_property! {
AriaBusy {
PROPERTY_TYPE: "boolean",
VALUES: [],
}
}
define_property! {
AriaChecked {
PROPERTY_TYPE: "tristate",
VALUES: [],
}
}
define_property! {
AriaColcount {
PROPERTY_TYPE: "integer",
VALUES: [],
}
}
define_property! {
AriaColindex {
PROPERTY_TYPE: "integer",
VALUES: [],
}
}
define_property! {
AriaColspan {
PROPERTY_TYPE: "integer",
VALUES: [],
}
}
define_property! {
AriaControls {
PROPERTY_TYPE: "idlist",
VALUES: [],
}
}
define_property! {
AriaCurrent {
PROPERTY_TYPE: "token",
VALUES: ["page", "step", "location", "date", "time", "true", "false"],
}
}
define_property! {
AriaDescribedby {
PROPERTY_TYPE: "idlist",
VALUES: [],
}
}
define_property! {
AriaDetails {
PROPERTY_TYPE: "id",
VALUES: [],
}
}
define_property! {
AriaDisabled {
PROPERTY_TYPE: "boolean",
VALUES: [],
}
}
define_property! {
AriaDropeffect {
PROPERTY_TYPE: "tokenlist",
VALUES: ["copy", "execute", "link", "move", "none", "popup"],
}
}
define_property! {
AriaErrormessage {
PROPERTY_TYPE: "id",
VALUES: [],
}
}
define_property! {
AriaExpanded {
PROPERTY_TYPE: "boolean",
VALUES: [],
}
}
define_property! {
AriaFlowto {
PROPERTY_TYPE: "idlist",
VALUES: [],
}
}
define_property! {
AriaGrabbed {
PROPERTY_TYPE: "boolean",
VALUES: [],
}
}
define_property! {
AriaHaspopup {
PROPERTY_TYPE: "token",
VALUES: ["false", "true", "menu", "listbox", "tree", "grid", "dialog"],
}
}
define_property! {
AriaHidden {
PROPERTY_TYPE: "boolean",
VALUES: [],
}
}
define_property! {
AriaInvalid {
PROPERTY_TYPE: "token",
VALUES: ["grammar", "false", "spelling", "true"],
}
}
define_property! {
AriaKeyshortcuts {
PROPERTY_TYPE: "string",
VALUES: [],
}
}
define_property! {
AriaLabel {
PROPERTY_TYPE: "string",
VALUES: [],
}
}
define_property! {
AriaLabelledby {
PROPERTY_TYPE: "idlist",
VALUES: [],
}
}
define_property! {
AriaLevel {
PROPERTY_TYPE: "integer",
VALUES: [],
}
}
define_property! {
AriaLive {
PROPERTY_TYPE: "token",
VALUES: ["assertive", "off", "polite"],
}
}
define_property! {
AriaModal {
PROPERTY_TYPE: "boolean",
VALUES: [],
}
}
define_property! {
AriaMultiline {
PROPERTY_TYPE: "boolean",
VALUES: [],
}
}
define_property! {
AriaMultiselectable {
PROPERTY_TYPE: "boolean",
VALUES: [],
}
}
define_property! {
AriaOrientation {
PROPERTY_TYPE: "token",
VALUES: ["vertical", "undefined", "horizontal"],
}
}
define_property! {
AriaOwns {
PROPERTY_TYPE: "idlist",
VALUES: [],
}
}
define_property! {
AriaPlaceholder {
PROPERTY_TYPE: "string",
VALUES: [],
}
}
define_property! {
AriaPosinset {
PROPERTY_TYPE: "integer",
VALUES: [],
}
}
define_property! {
AriaPressed {
PROPERTY_TYPE: "tristate",
VALUES: [],
}
}
define_property! {
AriaReadonly {
PROPERTY_TYPE: "boolean",
VALUES: [],
}
}
define_property! {
AriaRelevant {
PROPERTY_TYPE: "tokenlist",
VALUES: ["additions", "all", "removals", "text"],
}
}
define_property! {
AriaRequired {
PROPERTY_TYPE: "boolean",
VALUES: [],
}
}
define_property! {
AriaRoledescription {
PROPERTY_TYPE: "string",
VALUES: [],
}
}
define_property! {
AriaRowcount {
PROPERTY_TYPE: "integer",
VALUES: [],
}
}
define_property! {
AriaRowindex {
PROPERTY_TYPE: "integer",
VALUES: [],
}
}
define_property! {
AriaRowspan {
PROPERTY_TYPE: "integer",
VALUES: [],
}
}
define_property! {
AriaSelected {
PROPERTY_TYPE: "boolean",
VALUES: [],
}
}
define_property! {
AriaSetsize {
PROPERTY_TYPE: "integer",
VALUES: [],
}
}
define_property! {
AriaSort {
PROPERTY_TYPE: "token",
VALUES: ["ascending", "descending", "none", "other"],
}
}
define_property! {
AriaValuemax {
PROPERTY_TYPE: "number",
VALUES: [],
}
}
define_property! {
AriaValuemin {
PROPERTY_TYPE: "number",
VALUES: [],
}
}
define_property! {
AriaValuenow {
PROPERTY_TYPE: "number",
VALUES: [],
}
}
define_property! {
AriaValuetext {
PROPERTY_TYPE: "string",
VALUES: [],
}
}
/// A collection of ARIA properties with their metadata, necessary to perform various operations.
#[derive(Debug, Default)]
pub struct AriaProperties;
impl AriaProperties {
pub fn get_property<'a>(&self, property_name: &str) -> Option<&'a dyn AriaPropertyDefinition> {
Some(match property_name {
"aria-activedescendant" => &AriaActivedescendant as &dyn AriaPropertyDefinition,
"aria-autocomplete" => &AriaAutocomplete as &dyn AriaPropertyDefinition,
"aria-busy" => &AriaBusy as &dyn AriaPropertyDefinition,
"aria-checked" => &AriaChecked as &dyn AriaPropertyDefinition,
"aria-colcount" => &AriaColcount as &dyn AriaPropertyDefinition,
"aria-colindex" => &AriaColindex as &dyn AriaPropertyDefinition,
"aria-colspan" => &AriaColspan as &dyn AriaPropertyDefinition,
"aria-controls" => &AriaControls as &dyn AriaPropertyDefinition,
"aria-current" => &AriaCurrent as &dyn AriaPropertyDefinition,
"aria-describedby" => &AriaDescribedby as &dyn AriaPropertyDefinition,
"aria-details" => &AriaDetails as &dyn AriaPropertyDefinition,
"aria-disabled" => &AriaDisabled as &dyn AriaPropertyDefinition,
"aria-dropeffect" => &AriaDropeffect as &dyn AriaPropertyDefinition,
"aria-errormessage" => &AriaErrormessage as &dyn AriaPropertyDefinition,
"aria-expanded" => &AriaExpanded as &dyn AriaPropertyDefinition,
"aria-flowto" => &AriaFlowto as &dyn AriaPropertyDefinition,
"aria-grabbed" => &AriaGrabbed as &dyn AriaPropertyDefinition,
"aria-haspopup" => &AriaHaspopup as &dyn AriaPropertyDefinition,
"aria-hidden" => &AriaHidden as &dyn AriaPropertyDefinition,
"aria-invalid" => &AriaInvalid as &dyn AriaPropertyDefinition,
"aria-keyshortcuts" => &AriaKeyshortcuts as &dyn AriaPropertyDefinition,
"aria-label" => &AriaLabel as &dyn AriaPropertyDefinition,
"aria-labelledby" => &AriaLabelledby as &dyn AriaPropertyDefinition,
"aria-level" => &AriaLevel as &dyn AriaPropertyDefinition,
"aria-live" => &AriaLive as &dyn AriaPropertyDefinition,
"aria-modal" => &AriaModal as &dyn AriaPropertyDefinition,
"aria-multiline" => &AriaMultiline as &dyn AriaPropertyDefinition,
"aria-multiselectable" => &AriaMultiselectable as &dyn AriaPropertyDefinition,
"aria-orientation" => &AriaOrientation as &dyn AriaPropertyDefinition,
"aria-owns" => &AriaOwns as &dyn AriaPropertyDefinition,
"aria-placeholder" => &AriaPlaceholder as &dyn AriaPropertyDefinition,
"aria-posinset" => &AriaPosinset as &dyn AriaPropertyDefinition,
"aria-pressed" => &AriaPressed as &dyn AriaPropertyDefinition,
"aria-readonly" => &AriaReadonly as &dyn AriaPropertyDefinition,
"aria-relevant" => &AriaRelevant as &dyn AriaPropertyDefinition,
"aria-required" => &AriaRequired as &dyn AriaPropertyDefinition,
"aria-roledescription" => &AriaRoledescription as &dyn AriaPropertyDefinition,
"aria-rowcount" => &AriaRowcount as &dyn AriaPropertyDefinition,
"aria-rowindex" => &AriaRowindex as &dyn AriaPropertyDefinition,
"aria-rowspan" => &AriaRowspan as &dyn AriaPropertyDefinition,
"aria-selected" => &AriaSelected as &dyn AriaPropertyDefinition,
"aria-setsize" => &AriaSetsize as &dyn AriaPropertyDefinition,
"aria-sort" => &AriaSort as &dyn AriaPropertyDefinition,
"aria-valuemax" => &AriaValuemax as &dyn AriaPropertyDefinition,
"aria-valuemin" => &AriaValuemin as &dyn AriaPropertyDefinition,
"aria-valuenow" => &AriaValuenow as &dyn AriaPropertyDefinition,
"aria-valuetext" => &AriaValuetext as &dyn AriaPropertyDefinition,
_ => return None,
})
}
}
pub trait AriaPropertyDefinition: Debug {
/// Returns the allowed values by this property
fn values(&self) -> Iter<&str>;
/// Returns the property type
fn property_type(&self) -> AriaPropertyTypeEnum;
/// It checks if a value is complaint for the current ARIA property.
///
/// [Source](https://www.w3.org/TR/wai-aria-1.1/#propcharacteristic_value)
///
/// ## Examples
///
/// ```
/// use rome_aria::AriaProperties;
///
/// let aria_properties = AriaProperties::default();
///
/// let aria_current = aria_properties.get_property("aria-current").unwrap();
///
/// assert!(aria_current.contains_correct_value("true"));
/// assert!(aria_current.contains_correct_value("false"));
/// assert!(aria_current.contains_correct_value("step"));
/// assert!(!aria_current.contains_correct_value("something_not_allowed"));
/// ```
fn contains_correct_value(&self, input_value: &str) -> bool {
if input_value.is_empty() {
return false;
}
match self.property_type() {
AriaPropertyTypeEnum::String | AriaPropertyTypeEnum::Id => {
input_value.parse::<f32>().is_err()
}
AriaPropertyTypeEnum::Idlist => input_value
.split(' ')
.any(|piece| piece.parse::<f32>().is_err()),
// A numerical value without a fractional component.
AriaPropertyTypeEnum::Integer => input_value.parse::<u32>().is_ok(),
AriaPropertyTypeEnum::Number => input_value.parse::<f32>().is_ok(),
AriaPropertyTypeEnum::Boolean => {
matches!(input_value, "false" | "true")
}
AriaPropertyTypeEnum::Token => self
.values()
.any(|allowed_token| *allowed_token == input_value),
AriaPropertyTypeEnum::Tokenlist => input_value.split(' ').all(|input_token| {
self.values()
.any(|allowed_token| allowed_token.trim() == input_token)
}),
AriaPropertyTypeEnum::Tristate => {
matches!(input_value, "false" | "true" | "mixed")
}
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_aria/src/macros.rs | crates/rome_aria/src/macros.rs | #[macro_export]
macro_rules! define_role {
( $( #[doc = $doc:literal] )+ $id:ident {
PROPS: $p_value:expr,
ROLES: $r_value:expr,
}) => {
$( #[doc = $doc] )*
#[derive(Debug)]
struct $id;
impl $id {
const PROPS: &[(&'static str, bool)] = &$p_value;
const ROLES: &[&'static str] = &$r_value;
}
impl $crate::AriaRoleDefinition for $id {
fn properties(&self) -> std::slice::Iter<(&str, bool)> {
$id::PROPS.iter()
}
fn roles(&self) -> std::slice::Iter<&str> {
$id::ROLES.iter()
}
}
};
( $( #[doc = $doc:literal] )+ $id:ident {
PROPS: $p_value:expr,
ROLES: $r_value:expr,
CONCEPTS: $c_value:expr,
}) => {
$( #[doc = $doc] )*
#[derive(Debug)]
struct $id;
impl $id {
const PROPS: &[(&'static str, bool)] = &$p_value;
const ROLES: &[&'static str] = &$r_value;
const CONCEPTS: &'static [(&'static str, &'static [(&'static str, &'static str)])] =
$c_value;
}
impl $crate::AriaRoleDefinition for $id {
fn properties(&self) -> std::slice::Iter<(&str, bool)> {
$id::PROPS.iter()
}
fn roles(&self) -> std::slice::Iter<&str> {
$id::ROLES.iter()
}
}
impl AriaRoleDefinitionWithConcepts for $id {
fn concepts_by_element_name<'a>(
&self,
element_name: &str,
) -> ElementsAndAttributes<'a> {
for (concept_name, _attributes) in Self::CONCEPTS {
if *concept_name == element_name {
return Some(Self::CONCEPTS.iter());
}
}
None
}
}
};
}
#[macro_export]
macro_rules! define_property {
( $id:ident {
PROPERTY_TYPE: $property_type:literal,
VALUES: $values:expr,
}) => {
#[derive(Debug)]
struct $id;
impl $id {
const PROPERTY_TYPE: &'static str = &$property_type;
const VALUES: &[&'static str] = &$values;
}
impl AriaPropertyDefinition for $id {
fn values(&self) -> std::slice::Iter<&'static str> {
$id::VALUES.iter()
}
fn property_type(&self) -> $crate::AriaPropertyTypeEnum {
// SAFETY: PROPERTY_TYPE is internal and should not contain extraneous properties
$crate::AriaPropertyTypeEnum::from_str($id::PROPERTY_TYPE).unwrap()
}
}
};
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_aria/src/roles.rs | crates/rome_aria/src/roles.rs | use crate::{define_role, is_aria_property_valid};
use rome_aria_metadata::AriaPropertiesEnum;
use std::collections::HashMap;
use std::fmt::Debug;
use std::slice::Iter;
use std::str::FromStr;
pub trait AriaRoleDefinition: Debug {
/// It returns an iterator over the properties of the current role
///
/// ## Examples
///
/// ```
/// use rome_aria::AriaRoles;
/// let roles = AriaRoles::default();
///
/// let checkbox_role = roles.get_role("checkbox").unwrap();
///
/// let properties = checkbox_role.properties();
/// assert_eq!(properties.len(), 2);
/// ```
fn properties(&self) -> Iter<(&str, bool)>;
/// It returns an iterator over the possible roles of this definition
fn roles(&self) -> Iter<&str>;
/// Given a [aria property](ARIA_PROPERTIES) as input, it checks if it's required
/// for the current role.
///
/// If the property doesn't exist for the current role, [false] is returned.
///
/// ## Examples
///
/// ```
///
/// use rome_aria::AriaRoles;
/// let roles = AriaRoles::default();
///
/// let checkbox_role = roles.get_role("checkbox").unwrap();
///
/// assert_eq!(checkbox_role.is_property_required("aria-readonly"), false);
/// assert_eq!(checkbox_role.is_property_required("aria-checked"), true);
///
/// ```
fn is_property_required(&self, property_to_check: &str) -> bool {
if is_aria_property_valid(property_to_check) {
let property_to_check = AriaPropertiesEnum::from_str(property_to_check);
if let Ok(property_to_check) = property_to_check {
for (property, required) in self.properties() {
let property = AriaPropertiesEnum::from_str(property).unwrap();
if property == property_to_check {
return *required;
}
}
}
}
false
}
/// Whether the current role is interactive
fn is_interactive(&self) -> bool {
self.roles().any(|role| *role == "widget")
}
/// Returns a concrete type name.
fn type_name(&self) -> &'static str {
return std::any::type_name::<Self>();
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#button
ButtonRole {
PROPS: [("aria-expanded", false), ("aria-expanded", false)],
ROLES: ["roletype", "widget", "command"],
CONCEPTS: &[("button", &[]), ("input", &[("type", "button")])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#checkbox
CheckboxRole {
PROPS: [("aria-checked", true), ("aria-readonly", false)],
ROLES: ["switch", "menuitemcheckbox", "widget"],
CONCEPTS: &[("input", &[("type", "checkbox")])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#radio
RadioRole {
PROPS: [("aria-checked", true), ("aria-readonly", false)],
ROLES: ["menuitemradio", "widget"],
CONCEPTS: &[("input", &[("type", "radio")])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#switch
SwitchRole {
PROPS: [("aria-checked", true)],
ROLES: ["checkbox", "widget"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#option
OptionRole {
PROPS: [("aria-selected", true)],
ROLES: ["treeitem", "widget"],
CONCEPTS: &[("option", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#combobox
ComboBoxRole {
PROPS: [("aria-controls", true), ("aria-expanded", true)],
ROLES: ["select", "widget"],
CONCEPTS: &[("select", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#heading
HeadingRole {
PROPS: [("aria-level", true)],
ROLES: ["sectionhead"],
CONCEPTS: &[("h1", &[]), ("h2", &[]), ("h3", &[]), ("h4", &[]), ("h5", &[]), ("h6", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#spinbutton
SpinButtonRole {
PROPS: [
("aria-valuemax", true),
("aria-valuemin", true),
("aria-valuenow", true),
],
ROLES: ["composite", "input", "range", "widget"],
CONCEPTS: &[("hr", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#checkbox
SliderRole {
PROPS: [
("aria-valuemax", true),
("aria-valuemin", true),
("aria-valuenow", true),
],
ROLES: ["input", "range", "widget"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#separator
SeparatorRole {
PROPS: [
("aria-valuemax", true),
("aria-valuemin", true),
("aria-valuenow", true),
],
ROLES: ["structure", "widget"],
CONCEPTS: &[("hr", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#scrollbar
ScollbarRole {
PROPS: [
("aria-valuemax", true),
("aria-valuemin", true),
("aria-valuenow", true),
("aria-orientation", true),
("aria-controls", true),
],
ROLES: ["range", "widget"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#article
ArticleRole {
PROPS: [],
ROLES: ["document"],
CONCEPTS: &[("article", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#dialog
DialogRole {
PROPS: [("aria-label", false), ("aria-labelledby", false)],
ROLES: ["window"],
CONCEPTS: &[("dialog", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#alert
AlertRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("alert", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#alertdialog
AlertDialogRole {
PROPS: [],
ROLES: ["structure"],
CONCEPTS: &[("alert", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#application
ApplicationRole {
PROPS: [],
ROLES: ["alert", "dialog"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#banner
BannerRole {
PROPS: [],
ROLES: ["landmark"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#cell
CellRole {
PROPS: [
("aria-colindex", false),
("aria-colspan", false),
("aria-rowindex", false),
("aria-rowspan", false),
],
ROLES: ["section"],
CONCEPTS: &[("td", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#columnheader
ColumnHeaderRole {
PROPS: [("aria-sort", false)],
ROLES: ["cell", "gridcell", "sectionhead"],
CONCEPTS: &[("th", &[("scope", "col")])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#definition
DefinitionRole {
PROPS: [("aria-labelledby", false)],
ROLES: ["section"],
CONCEPTS: &[("dd", &[]), ("dfn", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#feed
FeedRole {
PROPS: [("aria-labelledby", false), ("aria-setsize", false)],
ROLES: ["section"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#figure
FigureRole {
PROPS: [("aria-label", false), ("aria-labelledby", false)],
ROLES: ["section"],
CONCEPTS: &[("figure", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#form
FormRole {
PROPS: [("aria-label", false), ("aria-labelledby", false)],
ROLES: ["section"],
CONCEPTS: &[("form", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#grid
GridRole {
PROPS: [("aria-level", false), ("aria-multiselectable", false), ("aria-readonly", false)],
ROLES: ["composite", "table"],
CONCEPTS: &[("table", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#gridcell
GridCellRole {
PROPS: [("aria-readonly", false), ("aria-required", false), ("aria-selected", false)],
ROLES: ["cell", "widget"],
CONCEPTS: &[("td", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#group
GroupRole {
PROPS: [("aria-activedescendant", false)],
ROLES: ["row", "select", "toolbar"],
CONCEPTS: &[("fieldset", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#img
ImgRole {
PROPS: [("aria-activedescendant", false)],
ROLES: ["section"],
CONCEPTS: &[("img", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#link
LinkRole {
PROPS: [("aria-expanded", false)],
ROLES: ["command", "widget"],
CONCEPTS: &[("a", &[]), ("link", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#list
ListRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("ol", &[]), ("ul", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#listbox
ListBoxRole {
PROPS: [],
ROLES: ["select", "widget"],
CONCEPTS: &[("select", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#listitem
ListItemRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("li", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#log
LogRole {
PROPS: [],
ROLES: ["section"],
}
}
define_role! {
/// https://w3c.github.io/aria/#main
MainRole {
PROPS: [],
ROLES: ["landmark"],
CONCEPTS: &[("main", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#menubar
MenubarRole {
PROPS: [],
ROLES: ["toolbar"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#menu
MenuRole {
PROPS: [("aria-posinset", false), ("aria-setsize", false)],
ROLES: ["select"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#menuitem
MenuItemRole {
PROPS: [("aria-posinset", false), ("aria-setsize", false)],
ROLES: ["command", "widget"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#menuitemcheckbox
MenuItemCheckboxRole {
PROPS: [("aria-checked", true)],
ROLES: ["checkbox", "menuitem", "widget"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#menuitemradio
MenuItemRadioRole {
PROPS: [("aria-checked", true)],
ROLES: ["radio", "menuitemcheckbox", "widget"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#navigation
NavigationRole {
PROPS: [],
ROLES: ["landmark"],
CONCEPTS: &[("nav", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#progressbar
ProgressBarRole {
PROPS: [("aria-valuenow", true), ("aria-valuemin", true), ("aria-valuemax", true)],
ROLES: ["range", "widget"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#radiogroup
RadiogroupRole {
PROPS: [("aria-readonly", false), ("aria-required", false)],
ROLES: ["range"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#row
RowRole {
PROPS: [("aria-colindex", false), ("aria-level", false), ("aria-rowindex", false), ("aria-selected", false)],
ROLES: ["group", "widget"],
CONCEPTS: &[("tr", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#rowgroup
RowGroupRole {
PROPS: [],
ROLES: ["structure"],
CONCEPTS: &[("tbody", &[]), ("tfoot", &[]), ("thead", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#rowheader
RowHeaderRole {
PROPS: [("aria-sort", false)],
ROLES: ["cell", "gridcell", "sectionhead"],
CONCEPTS: &[("th", &[("scope", "row")])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#searchbox
SearchboxRole {
PROPS: [
("aria-activedescendant", false),
("aria-autocomplete", false),
("aria-multiline", false),
("aria-placeholder", false),
("aria-readonly", false),
("aria-required", false),
],
ROLES: ["textbox", "widget"],
CONCEPTS: &[("input", &[("type", "search")])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#tab
TabRole {
PROPS: [("aria-posinset", false), ("aria-selected", false), ("aria-setsize", false)],
ROLES: ["sectionhead", "widget"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#table
TableRole {
PROPS: [("aria-colcount", false), ("aria-rowcount", false)],
ROLES: ["section"],
CONCEPTS: &[("table", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#tablelist
TableListRole {
PROPS: [("aria-level", false), ("aria-multiselectable", false), ("aria-orientation", false)],
ROLES: ["composite"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#term
TermRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("dt", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#textbox
TextboxRole {
PROPS: [
("aria-activedescendant", false),
("aria-autocomplete", false),
("aria-multiline", false),
("aria-placeholder", false),
("aria-readonly", false),
("aria-required", false),
],
ROLES: ["input", "widget"],
CONCEPTS: &[("textarea", &[]), ("input", &[("type", "search")])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#toolbar
ToolbarRole {
PROPS: [("aria-orientation", false)],
ROLES: ["group"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.1/#tree
TreeRole {
PROPS: [("aria-multiselectable", false), ("aria-required", false)],
ROLES: ["select"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#generic
GenericRole {
PROPS: [],
ROLES: ["structure"],
CONCEPTS: &[("div", &[]), ("span", &[])],
}
}
define_role! {
/// https://w3c.github.io/aria/#complementary
ComplementaryRole {
PROPS: [],
ROLES: ["landmark"],
CONCEPTS: &[("aside", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#blockquote
BlockQuoteRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("blockquote", &[])],
}
}
define_role! {
/// https://w3c.github.io/aria/#caption
CaptionRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("caption", &[]), ("figcaption", &[]), ("legend", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#code
CodeRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("code", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#deletion
DeletionRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("del", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#document
DocumentRole {
PROPS: [],
ROLES: ["structure"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#emphasis
EmphasisRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("em", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#insertion
InsertionRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("ins", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#math
MathRole {
PROPS: [],
ROLES: ["section"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#strong
StrongRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("strong", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#subscript
SubScriptRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("sub", &[]), ("sup", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#superscript
SuperScriptRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("sub", &[]), ("sup", &[])],
}
}
define_role! {
/// https://w3c.github.io/graphics-aria/#graphics-document
GraphicsDocumentRole {
PROPS: [],
ROLES: ["document"],
CONCEPTS: &[("graphics-object", &[]), ("img", &[]), ("article", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#time
TimeRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("time", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#paragraph
ParagraphRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("p", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#status
StatusRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("output", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#meter
MeterRole {
PROPS: [],
ROLES: ["range"],
CONCEPTS: &[("meter", &[])],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#presentation
PresentationRole {
PROPS: [],
ROLES: ["structure"],
}
}
define_role! {
/// https://www.w3.org/TR/wai-aria-1.2/#region
RegionRole {
PROPS: [],
ROLES: ["landmark"],
CONCEPTS: &[("section", &[])],
}
}
define_role! {
/// https://w3c.github.io/aria/#mark
MarkRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("mark", &[])],
}
}
define_role! {
/// https://w3c.github.io/aria/#marquee
MarqueeRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("marquee", &[])],
}
}
define_role! {
/// https://w3c.github.io/aria/#associationlist
AssociationListRole {
PROPS: [],
ROLES: ["section"],
CONCEPTS: &[("dl", &[])],
}
}
define_role! {
/// https://w3c.github.io/aria/#contentinfo
ContentInfoRole {
PROPS: [],
ROLES: ["landmark"],
CONCEPTS: &[("footer", &[])],
}
}
impl<'a> AriaRoles {
/// These are roles that will contain "concepts".
pub(crate) const ROLE_WITH_CONCEPTS: &'a [&'a str] = &[
"checkbox",
"radio",
"option",
"combobox",
"heading",
"separator",
"button",
"article",
"dialog",
"alert",
"alertdialog",
"cell",
"columnheader",
"definition",
"figure",
"form",
"grid",
"gridcell",
"group",
"img",
"link",
"list",
"listbox",
"listitem",
"navigation",
"row",
"rowgroup",
"rowheader",
"searchbox",
"table",
"term",
"textbox",
"generic",
"caption",
"main",
"time",
"p",
"aside",
"blockquote",
"associationlist",
"status",
"contentinfo",
"region",
];
/// It returns the metadata of a role, if it exits.
///
/// ## Examples
///
/// ```
/// use rome_aria::AriaRoles;
/// let roles = AriaRoles::default();
///
///
/// let button_role = roles.get_role("button");
/// let made_up_role = roles.get_role("made-up");
///
/// assert!(button_role.is_some());
/// assert!(made_up_role.is_none());
/// ```
pub fn get_role(&self, role: &str) -> Option<&'static dyn AriaRoleDefinition> {
let result = match role {
"button" => &ButtonRole as &dyn AriaRoleDefinition,
"checkbox" => &CheckboxRole as &dyn AriaRoleDefinition,
"radio" => &RadioRole as &dyn AriaRoleDefinition,
"switch" => &SwitchRole as &dyn AriaRoleDefinition,
"option" => &OptionRole as &dyn AriaRoleDefinition,
"combobox" => &ComboBoxRole as &dyn AriaRoleDefinition,
"heading" => &HeadingRole as &dyn AriaRoleDefinition,
"spinbutton" => &SpinButtonRole as &dyn AriaRoleDefinition,
"slider" => &SliderRole as &dyn AriaRoleDefinition,
"separator" => &SeparatorRole as &dyn AriaRoleDefinition,
"scrollbar" => &ScollbarRole as &dyn AriaRoleDefinition,
"article" => &ArticleRole as &dyn AriaRoleDefinition,
"dialog" => &DialogRole as &dyn AriaRoleDefinition,
"alert" => &AlertRole as &dyn AriaRoleDefinition,
"alertdialog" => &AlertDialogRole as &dyn AriaRoleDefinition,
"application" => &ApplicationRole as &dyn AriaRoleDefinition,
"banner" => &BannerRole as &dyn AriaRoleDefinition,
"cell" => &CellRole as &dyn AriaRoleDefinition,
"columnheader" => &ColumnHeaderRole as &dyn AriaRoleDefinition,
"definition" => &DefinitionRole as &dyn AriaRoleDefinition,
"feed" => &FeedRole as &dyn AriaRoleDefinition,
"figure" => &FigureRole as &dyn AriaRoleDefinition,
"form" => &FormRole as &dyn AriaRoleDefinition,
"grid" => &GridRole as &dyn AriaRoleDefinition,
"gridcell" => &GridCellRole as &dyn AriaRoleDefinition,
"group" => &GroupRole as &dyn AriaRoleDefinition,
"img" => &ImgRole as &dyn AriaRoleDefinition,
"link" => &LinkRole as &dyn AriaRoleDefinition,
"list" => &ListRole as &dyn AriaRoleDefinition,
"listbox" => &ListBoxRole as &dyn AriaRoleDefinition,
"listitem" => &ListItemRole as &dyn AriaRoleDefinition,
"log" => &LogRole as &dyn AriaRoleDefinition,
"main" => &MainRole as &dyn AriaRoleDefinition,
"menubar" => &MenubarRole as &dyn AriaRoleDefinition,
"menu" => &MenuRole as &dyn AriaRoleDefinition,
"menuitem" => &MenuItemRole as &dyn AriaRoleDefinition,
"menuitemcheckbox" => &MenuItemCheckboxRole as &dyn AriaRoleDefinition,
"menuitemradio" => &MenuItemRadioRole as &dyn AriaRoleDefinition,
"navigation" => &NavigationRole as &dyn AriaRoleDefinition,
"progressbar" => &ProgressBarRole as &dyn AriaRoleDefinition,
"radiogroup" => &RadiogroupRole as &dyn AriaRoleDefinition,
"row" => &RowRole as &dyn AriaRoleDefinition,
"rowgroup" => &RowGroupRole as &dyn AriaRoleDefinition,
"rowheader" => &RowHeaderRole as &dyn AriaRoleDefinition,
"searchbox" => &SearchboxRole as &dyn AriaRoleDefinition,
"tab" => &TabRole as &dyn AriaRoleDefinition,
"table" => &TableRole as &dyn AriaRoleDefinition,
"tablelist" => &TableListRole as &dyn AriaRoleDefinition,
"term" => &TermRole as &dyn AriaRoleDefinition,
"textbox" => &TextboxRole as &dyn AriaRoleDefinition,
"toolbar" => &ToolbarRole as &dyn AriaRoleDefinition,
"tree" => &TreeRole as &dyn AriaRoleDefinition,
"region" => &RegionRole as &dyn AriaRoleDefinition,
"presentation" => &PresentationRole as &dyn AriaRoleDefinition,
"document" => &DocumentRole as &dyn AriaRoleDefinition,
"generic" => &GenericRole as &dyn AriaRoleDefinition,
_ => return None,
};
Some(result)
}
/// Given a element and attributes, it returns the metadata of the element's implicit role.
///
/// Check: https://www.w3.org/TR/html-aria/#docconformance
pub fn get_implicit_role(
&self,
element: &str,
// To generate `attributes`, you can use `rome_js_analyze::aria_services::AriaServices::extract_defined_attributes`
attributes: &HashMap<String, Vec<String>>,
) -> Option<&'static dyn AriaRoleDefinition> {
let result = match element {
"article" => &ArticleRole as &dyn AriaRoleDefinition,
"aside" => &ComplementaryRole as &dyn AriaRoleDefinition,
"blockquote" => &BlockQuoteRole as &dyn AriaRoleDefinition,
"button" => &ButtonRole as &dyn AriaRoleDefinition,
"caption" => &CaptionRole as &dyn AriaRoleDefinition,
"code" => &CodeRole as &dyn AriaRoleDefinition,
"datalist" => &ListBoxRole as &dyn AriaRoleDefinition,
"del" => &DeletionRole as &dyn AriaRoleDefinition,
"dfn" => &TermRole as &dyn AriaRoleDefinition,
"dialog" => &DialogRole as &dyn AriaRoleDefinition,
"em" => &EmphasisRole as &dyn AriaRoleDefinition,
"figure" => &FigureRole as &dyn AriaRoleDefinition,
"form" => &FormRole as &dyn AriaRoleDefinition,
"hr" => &SeparatorRole as &dyn AriaRoleDefinition,
"html" => &DocumentRole as &dyn AriaRoleDefinition,
"ins" => &InsertionRole as &dyn AriaRoleDefinition,
"main" => &MainRole as &dyn AriaRoleDefinition,
"math" => &MathRole as &dyn AriaRoleDefinition,
"menu" => &ListRole as &dyn AriaRoleDefinition,
"meter" => &MeterRole as &dyn AriaRoleDefinition,
"nav" => &NavigationRole as &dyn AriaRoleDefinition,
"ul" | "ol" => &ListRole as &dyn AriaRoleDefinition,
"li" => &ListItemRole as &dyn AriaRoleDefinition,
"optgroup" => &GroupRole as &dyn AriaRoleDefinition,
"output" => &StatusRole as &dyn AriaRoleDefinition,
"p" => &ParagraphRole as &dyn AriaRoleDefinition,
"progress" => &ProgressBarRole as &dyn AriaRoleDefinition,
"strong" => &StrongRole as &dyn AriaRoleDefinition,
"sub" => &SubScriptRole as &dyn AriaRoleDefinition,
"sup" => &SuperScriptRole as &dyn AriaRoleDefinition,
"svg" => &GraphicsDocumentRole as &dyn AriaRoleDefinition,
"table" => &TableRole as &dyn AriaRoleDefinition,
"textarea" => &TextboxRole as &dyn AriaRoleDefinition,
"tr" => &RowRole as &dyn AriaRoleDefinition,
"time" => &TimeRole as &dyn AriaRoleDefinition,
"address" | "details" | "fieldset" => &GroupRole as &dyn AriaRoleDefinition,
"h1" | "h2" | "h3" | "h4" | "h5" | "h6" => &HeadingRole as &dyn AriaRoleDefinition,
"tbody" | "tfoot" | "thead" => &RowGroupRole as &dyn AriaRoleDefinition,
"input" => {
let type_values = attributes.get("type")?;
match type_values.first()?.as_str() {
"checkbox" => &CheckboxRole as &dyn AriaRoleDefinition,
"number" => &SpinButtonRole as &dyn AriaRoleDefinition,
"radio" => &RadioRole as &dyn AriaRoleDefinition,
"range" => &SliderRole as &dyn AriaRoleDefinition,
"button" | "image" | "reset" | "submit" => {
&ButtonRole as &dyn AriaRoleDefinition
}
"search" => match attributes.get("list") {
Some(_) => &ComboBoxRole as &dyn AriaRoleDefinition,
_ => &SearchboxRole as &dyn AriaRoleDefinition,
},
"email" | "tel" | "url" => match attributes.get("list") {
Some(_) => &ComboBoxRole as &dyn AriaRoleDefinition,
_ => &TextboxRole as &dyn AriaRoleDefinition,
},
"text" => &TextboxRole as &dyn AriaRoleDefinition,
_ => &TextboxRole as &dyn AriaRoleDefinition,
}
}
"a" | "area" => match attributes.get("href") {
Some(_) => &LinkRole as &dyn AriaRoleDefinition,
_ => &GenericRole as &dyn AriaRoleDefinition,
},
"img" => match attributes.get("alt") {
Some(values) => {
if values.iter().any(|x| !x.is_empty()) {
&ImgRole as &dyn AriaRoleDefinition
} else {
&PresentationRole as &dyn AriaRoleDefinition
}
}
None => &ImgRole as &dyn AriaRoleDefinition,
},
"section" => {
let has_accessible_name = attributes.get("aria-labelledby").is_some()
|| attributes.get("aria-label").is_some()
|| attributes.get("title").is_some();
if has_accessible_name {
&RegionRole as &dyn AriaRoleDefinition
} else {
return None;
}
}
"select" => {
let size = match attributes.get("size") {
Some(size) => size
.first()
.unwrap_or(&"0".to_string())
.parse::<i32>()
.ok()?,
None => 0,
};
let multiple = attributes.get("multiple");
if multiple.is_none() && size <= 1 {
&ComboBoxRole as &dyn AriaRoleDefinition
} else {
&ListBoxRole as &dyn AriaRoleDefinition
}
}
"b" | "bdi" | "bdo" | "body" | "data" | "div" | "hgroup" | "i" | "q" | "samp"
| "small" | "span" | "u" => &GenericRole as &dyn AriaRoleDefinition,
"header" | "footer" => {
// This crate does not support checking a descendant of an element.
// header (maybe BannerRole): https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/examples/banner.html
// footer (maybe ContentInfoRole): https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/examples/contentinfo.html
&GenericRole as &dyn AriaRoleDefinition
}
_ => return None,
};
Some(result)
}
/// Given a role, it returns whether this role is interactive
pub fn is_role_interactive(&self, role: &str) -> bool {
let role = self.get_role(role);
if let Some(role) = role {
role.is_interactive()
} else {
false
}
}
/// Given the name of element, the function tells whether it's interactive
pub fn is_not_interactive_element(
&self,
element_name: &str,
attributes: Option<HashMap<String, Vec<String>>>,
) -> bool {
// <header> elements do not technically have semantics, unless the
// element is a direct descendant of <body>, and this crate cannot
// reliably test that.
//
// Check: https://www.w3.org/TR/wai-aria-practices/examples/landmarks/banner.html
if element_name == "header" {
return false;
}
let elements_no_concept_info = [
"body", "br", "details", "dir", "frame", "iframe", "label", "mark", "marquee", "menu",
"meter", "optgroup", "pre", "progress", "ruby",
];
if elements_no_concept_info.contains(&element_name) {
return true;
}
// <input type="hidden"> is not interactive.
// `type=hidden` is not represented as concept information.
if element_name == "input"
&& attributes
.as_ref()
.and_then(|attributes| attributes.get("type"))
.map_or(false, |values| values.iter().any(|x| x == "hidden"))
{
return true;
}
for element in Self::ROLE_WITH_CONCEPTS {
let role = match *element {
"checkbox" => &CheckboxRole as &dyn AriaRoleDefinitionWithConcepts,
"radio" => &RadioRole as &dyn AriaRoleDefinitionWithConcepts,
"option" => &OptionRole as &dyn AriaRoleDefinitionWithConcepts,
"combobox" => &ComboBoxRole as &dyn AriaRoleDefinitionWithConcepts,
"heading" => &HeadingRole as &dyn AriaRoleDefinitionWithConcepts,
"separator" => &SeparatorRole as &dyn AriaRoleDefinitionWithConcepts,
"button" => &ButtonRole as &dyn AriaRoleDefinitionWithConcepts,
"article" => &ArticleRole as &dyn AriaRoleDefinitionWithConcepts,
"dialog" => &DialogRole as &dyn AriaRoleDefinitionWithConcepts,
"alert" => &AlertRole as &dyn AriaRoleDefinitionWithConcepts,
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_aria/src/iso.rs | crates/rome_aria/src/iso.rs | use rome_aria_metadata::{IsoCountries, IsoLanguages, ISO_COUNTRIES, ISO_LANGUAGES};
use std::str::FromStr;
/// Returns a list of valid ISO countries
pub fn is_valid_country(country: &str) -> bool {
IsoCountries::from_str(country).is_ok()
}
/// Returns a list of valid ISO languages
pub fn is_valid_language(language: &str) -> bool {
IsoLanguages::from_str(language).is_ok()
}
/// An array of all available countries
pub fn countries() -> &'static [&'static str] {
&ISO_COUNTRIES
}
/// An array of all available languages
pub fn languages() -> &'static [&'static str] {
&ISO_LANGUAGES
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_fs/src/path.rs | crates/rome_fs/src/path.rs | //! This module is responsible to manage paths inside Rome.
//! It is a small wrapper around [path::PathBuf] but it is also able to
//! give additional information around the the file that holds:
//! - the [FileHandlers] for the specific file
//! - shortcuts to open/write to the file
use std::fs::read_to_string;
use std::io::Read;
use std::{fs::File, io, io::Write, ops::Deref, path::PathBuf};
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)
)]
pub struct RomePath {
path: PathBuf,
}
impl Deref for RomePath {
type Target = PathBuf;
fn deref(&self) -> &Self::Target {
&self.path
}
}
impl RomePath {
pub fn new(path_to_file: impl Into<PathBuf>) -> Self {
Self {
path: path_to_file.into(),
}
}
// TODO: handle error with diagnostic?
/// Opens a file and returns a [File] in write mode
pub fn open(&self) -> File {
File::open(&self.path).expect("cannot open the file to format")
}
/// Accepts a file opened in read mode and saves into it
pub fn save(&mut self, content: &str) -> Result<(), std::io::Error> {
let mut file_to_write = File::create(&self.path).unwrap();
// TODO: handle error with diagnostic
file_to_write.write_all(content.as_bytes())
}
/// Returns the contents of a file, if it exists
pub fn get_buffer_from_file(&mut self) -> String {
let mut file = self.open();
let mut buffer = String::new();
// we assume we have permissions
file.read_to_string(&mut buffer)
.expect("cannot read the file to format");
buffer
}
/// Small wrapper for [read_to_string]
pub fn read_to_string(&self) -> io::Result<String> {
let path = self.path.as_path();
read_to_string(path)
}
pub fn extension_as_str(&self) -> &str {
self.extension()
.expect("Can't read the file")
.to_str()
.expect("Can't read the file")
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_fs/src/lib.rs | crates/rome_fs/src/lib.rs | mod fs;
mod interner;
mod path;
pub use fs::{
AutoSearchResult, ErrorEntry, File, FileSystem, FileSystemDiagnostic, FileSystemExt,
MemoryFileSystem, OpenOptions, OsFileSystem, TraversalContext, TraversalScope, CONFIG_NAME,
};
pub use interner::PathInterner;
pub use path::RomePath;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_fs/src/interner.rs | crates/rome_fs/src/interner.rs | use crossbeam::channel::{unbounded, Receiver, Sender};
use indexmap::IndexSet;
use std::path::PathBuf;
use std::sync::RwLock;
/// File paths interner cache
///
/// The path interner stores an instance of [PathBuf]
pub struct PathInterner {
storage: RwLock<IndexSet<PathBuf>>,
handler: Sender<PathBuf>,
}
impl PathInterner {
pub fn new() -> (Self, Receiver<PathBuf>) {
let (send, recv) = unbounded();
let interner = Self {
storage: RwLock::new(IndexSet::new()),
handler: send,
};
(interner, recv)
}
/// Insert the path.
pub fn intern_path(&self, path: PathBuf) -> bool {
let (_, result) = self.storage.write().unwrap().insert_full(path.clone());
if result {
self.handler.send(path).ok();
}
result
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_fs/src/fs.rs | crates/rome_fs/src/fs.rs | use crate::{PathInterner, RomePath};
pub use memory::{ErrorEntry, MemoryFileSystem};
pub use os::OsFileSystem;
use rome_diagnostics::{console, Advices, Diagnostic, LogCategory, Visit};
use rome_diagnostics::{Error, Severity};
use serde::{Deserialize, Serialize};
use std::io;
use std::panic::RefUnwindSafe;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tracing::{error, info};
mod memory;
mod os;
pub const CONFIG_NAME: &str = "rome.json";
pub trait FileSystem: Send + Sync + RefUnwindSafe {
/// It opens a file with the given set of options
fn open_with_options(&self, path: &Path, options: OpenOptions) -> io::Result<Box<dyn File>>;
/// Initiate a traversal of the filesystem
///
/// This method creates a new "traversal scope" that can be used to
/// efficiently batch many filesystem read operations
fn traversal<'scope>(&'scope self, func: BoxedTraversal<'_, 'scope>);
/// Returns the name of the main configuration file
fn config_name(&self) -> &str {
CONFIG_NAME
}
/// Return the path to the working directory
fn working_directory(&self) -> Option<PathBuf>;
/// Checks if the given path exists in the file system
fn path_exists(&self, path: &Path) -> bool;
/// Method that takes a path to a folder `file_path`, and a `file_name`. It attempts to find
/// and read the file from that folder and if not found, it reads the parent directories recursively
/// until:
/// - the file is found, then it reads and return its contents
/// - the file is not found
///
/// If `should_error_if_file_not_found` it `true`, it returns an error.
///
/// ## Errors
///
/// - The file can't be read
///
fn auto_search(
&self,
mut file_path: PathBuf,
file_name: &str,
should_error_if_file_not_found: bool,
) -> Result<Option<AutoSearchResult>, FileSystemDiagnostic> {
let mut from_parent = false;
let mut file_directory_path = file_path.join(file_name);
loop {
let options = OpenOptions::default().read(true);
let file = self.open_with_options(&file_directory_path, options);
return match file {
Ok(mut file) => {
let mut buffer = String::new();
file.read_to_string(&mut buffer)
.map_err(|_| FileSystemDiagnostic {
path: file_directory_path.display().to_string(),
severity: Severity::Error,
error_kind: ErrorKind::CantReadFile(
file_directory_path.display().to_string(),
),
})?;
if from_parent {
info!(
"Rome auto discovered the file at following path that wasn't in the working directory: {}",
file_path.display()
);
}
return Ok(Some(AutoSearchResult {
content: buffer,
file_path: file_directory_path,
directory_path: file_path,
}));
}
Err(err) => {
// base paths from users are not eligible for auto discovery
if !should_error_if_file_not_found {
let parent_directory = if let Some(path) = file_path.parent() {
if path.is_dir() {
Some(PathBuf::from(path))
} else {
None
}
} else {
None
};
if let Some(parent_directory) = parent_directory {
file_path = parent_directory;
file_directory_path = file_path.join(file_name);
from_parent = true;
continue;
}
}
// We skip the error when the configuration file is not found.
// Not having a configuration file is only an error when the `base_path` is
// set to `BasePath::FromUser`.
if should_error_if_file_not_found || err.kind() != io::ErrorKind::NotFound {
return Err(FileSystemDiagnostic {
path: file_directory_path.display().to_string(),
severity: Severity::Error,
error_kind: ErrorKind::CantReadFile(
file_directory_path.display().to_string(),
),
});
}
error!(
"Could not read the file from {:?}, reason:\n {}",
file_directory_path.display(),
err
);
Ok(None)
}
};
}
}
}
/// Result of the auto search
pub struct AutoSearchResult {
/// The content of the file
pub content: String,
/// The path of the directory where the file was found
pub directory_path: PathBuf,
/// The path of the file found
pub file_path: PathBuf,
}
pub trait File {
/// Read the content of the file into `buffer`
fn read_to_string(&mut self, buffer: &mut String) -> io::Result<()>;
/// Overwrite the content of the file with the provided bytes
///
/// This will write to the associated memory buffer, as well as flush the
/// new content to the disk if this is a physical file
fn set_content(&mut self, content: &[u8]) -> io::Result<()>;
/// Returns the version of the current file
fn file_version(&self) -> i32;
}
/// This struct is a "mirror" of [std::fs::FileOptions].
/// Refer to their documentation for more details
#[derive(Default, Debug)]
pub struct OpenOptions {
read: bool,
write: bool,
truncate: bool,
create: bool,
create_new: bool,
}
impl OpenOptions {
pub fn read(mut self, read: bool) -> Self {
self.read = read;
self
}
pub fn write(mut self, write: bool) -> Self {
self.write = write;
self
}
pub fn truncate(mut self, truncate: bool) -> Self {
self.truncate = truncate;
self
}
pub fn create(mut self, create: bool) -> Self {
self.create = create;
self
}
pub fn create_new(mut self, create_new: bool) -> Self {
self.create_new = create_new;
self
}
pub fn into_fs_options(self, options: &mut std::fs::OpenOptions) -> &mut std::fs::OpenOptions {
options
.read(self.read)
.write(self.write)
.truncate(self.truncate)
.create(self.create)
.create_new(self.create_new)
}
}
/// Trait that contains additional methods to work with [FileSystem]
pub trait FileSystemExt: FileSystem {
/// Open a file with the `read` option
///
/// Equivalent to [std::fs::File::open]
fn open(&self, path: &Path) -> io::Result<Box<dyn File>> {
self.open_with_options(path, OpenOptions::default().read(true))
}
/// Open a file with the `write` and `create` options
///
/// Equivalent to [std::fs::File::create]
fn create(&self, path: &Path) -> io::Result<Box<dyn File>> {
self.open_with_options(
path,
OpenOptions::default()
.write(true)
.create(true)
.truncate(true),
)
}
/// Opens a file with the `read`, `write` and `create_new` options
///
/// Equivalent to [std::fs::File::create_new]
fn create_new(&self, path: &Path) -> io::Result<Box<dyn File>> {
self.open_with_options(
path,
OpenOptions::default()
.read(true)
.write(true)
.create_new(true),
)
}
}
impl<T: ?Sized> FileSystemExt for T where T: FileSystem {}
type BoxedTraversal<'fs, 'scope> = Box<dyn FnOnce(&dyn TraversalScope<'scope>) + Send + 'fs>;
pub trait TraversalScope<'scope> {
/// Spawn a new filesystem read task
///
/// If the provided path exists and is a file, then the [`handle_file`](TraversalContext::handle_file)
/// method of the provided [TraversalContext] will be called. If it's a
/// directory, it will be recursively traversed and all the files the
/// [`can_handle`](TraversalContext::can_handle) method of the context
/// returns true for will be handled as well
fn spawn(&self, context: &'scope dyn TraversalContext, path: PathBuf);
}
pub trait TraversalContext: Sync {
/// Provides the traversal scope with an instance of [PathInterner], used
/// to emit diagnostics for IO errors that may happen in the traversal process
fn interner(&self) -> &PathInterner;
/// Called by the traversal process to emit an error diagnostic associated
/// with a particular file ID when an IO error happens
fn push_diagnostic(&self, error: Error);
/// Checks if the traversal context can handle a particular path, used as
/// an optimization to bail out of scheduling a file handler if it wouldn't
/// be able to process the file anyway
fn can_handle(&self, path: &RomePath) -> bool;
/// This method will be called by the traversal for each file it finds
/// where [TraversalContext::can_handle] returned true
fn handle_file(&self, path: &Path);
}
impl<T> FileSystem for Arc<T>
where
T: FileSystem + Send,
{
fn open_with_options(&self, path: &Path, options: OpenOptions) -> io::Result<Box<dyn File>> {
T::open_with_options(self, path, options)
}
fn traversal<'scope>(&'scope self, func: BoxedTraversal<'_, 'scope>) {
T::traversal(self, func)
}
fn working_directory(&self) -> Option<PathBuf> {
T::working_directory(self)
}
fn path_exists(&self, path: &Path) -> bool {
T::path_exists(self, path)
}
}
#[derive(Debug, Diagnostic, Deserialize, Serialize)]
#[diagnostic(category = "internalError/fs")]
pub struct FileSystemDiagnostic {
#[severity]
pub severity: Severity,
#[location(resource)]
pub path: String,
#[message]
#[description]
#[advice]
pub error_kind: ErrorKind,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum ErrorKind {
/// File not found
CantReadFile(String),
/// Unknown file type
UnknownFileType,
/// Dereferenced (broken) symbolic link
DereferencedSymlink(String),
/// Too deeply nested symbolic link expansion
DeeplyNestedSymlinkExpansion(String),
}
impl console::fmt::Display for ErrorKind {
fn fmt(&self, fmt: &mut console::fmt::Formatter) -> io::Result<()> {
match self {
ErrorKind::CantReadFile(_) => fmt.write_str("Rome couldn't read the file"),
ErrorKind::UnknownFileType => fmt.write_str("Unknown file type"),
ErrorKind::DereferencedSymlink(_) => fmt.write_str("Dereferenced symlink"),
ErrorKind::DeeplyNestedSymlinkExpansion(_) => {
fmt.write_str("Deeply nested symlink expansion")
}
}
}
}
impl std::fmt::Display for ErrorKind {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ErrorKind::CantReadFile(_) => fmt.write_str("Rome couldn't read the file"),
ErrorKind::UnknownFileType => write!(fmt, "Unknown file type"),
ErrorKind::DereferencedSymlink(_) => write!(fmt, "Dereferenced symlink"),
ErrorKind::DeeplyNestedSymlinkExpansion(_) => {
write!(fmt, "Deeply nested symlink expansion")
}
}
}
}
impl Advices for ErrorKind {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
match self {
ErrorKind::CantReadFile(path) => visitor.record_log(
LogCategory::Error,
&format!("Rome couldn't read the following file, maybe for permissions reasons or it doesn't exists: {}", path)
),
ErrorKind::UnknownFileType => visitor.record_log(
LogCategory::Info,
&"Rome encountered a file system entry that's neither a file, directory or symbolic link",
),
ErrorKind::DereferencedSymlink(path) => visitor.record_log(
LogCategory::Info,
&format!("Rome encountered a file system entry that is a broken symbolic link: {}", path),
),
ErrorKind::DeeplyNestedSymlinkExpansion(path) => visitor.record_log(
LogCategory::Error,
&format!("Rome encountered a file system entry with too many nested symbolic links, possibly forming an infinite cycle: {}", path),
),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_fs/src/fs/os.rs | crates/rome_fs/src/fs/os.rs | //! Implementation of the [FileSystem] and related traits for the underlying OS filesystem
use super::{BoxedTraversal, ErrorKind, File, FileSystemDiagnostic};
use crate::fs::OpenOptions;
use crate::{
fs::{TraversalContext, TraversalScope},
FileSystem, RomePath,
};
use rayon::{scope, Scope};
use rome_diagnostics::{adapters::IoError, DiagnosticExt, Error, Severity};
use std::fs::{DirEntry, FileType};
use std::{
env,
ffi::OsStr,
fs,
io::{self, ErrorKind as IoErrorKind, Read, Seek, Write},
mem,
path::{Path, PathBuf},
};
const MAX_SYMLINK_DEPTH: u8 = 3;
/// Implementation of [FileSystem] that directly calls through to the underlying OS
pub struct OsFileSystem;
impl FileSystem for OsFileSystem {
fn open_with_options(&self, path: &Path, options: OpenOptions) -> io::Result<Box<dyn File>> {
tracing::debug_span!("OsFileSystem::open_with_options", path = ?path, options = ?options)
.in_scope(move || -> io::Result<Box<dyn File>> {
let mut fs_options = fs::File::options();
Ok(Box::new(OsFile {
inner: options.into_fs_options(&mut fs_options).open(path)?,
version: 0,
}))
})
}
fn traversal(&self, func: BoxedTraversal) {
OsTraversalScope::with(move |scope| {
func(scope);
})
}
fn working_directory(&self) -> Option<PathBuf> {
env::current_dir().ok()
}
fn path_exists(&self, path: &Path) -> bool {
path.exists()
}
}
struct OsFile {
inner: fs::File,
version: i32,
}
impl File for OsFile {
fn read_to_string(&mut self, buffer: &mut String) -> io::Result<()> {
tracing::debug_span!("OsFile::read_to_string").in_scope(move || {
// Reset the cursor to the starting position
self.inner.rewind()?;
// Read the file content
self.inner.read_to_string(buffer)?;
Ok(())
})
}
fn set_content(&mut self, content: &[u8]) -> io::Result<()> {
tracing::debug_span!("OsFile::set_content").in_scope(move || {
// Truncate the file
self.inner.set_len(0)?;
// Reset the cursor to the starting position
self.inner.rewind()?;
// Write the byte slice
self.inner.write_all(content)?;
// new version stored
self.version += 1;
Ok(())
})
}
fn file_version(&self) -> i32 {
self.version
}
}
#[repr(transparent)]
pub struct OsTraversalScope<'scope> {
scope: Scope<'scope>,
}
impl<'scope> OsTraversalScope<'scope> {
pub(crate) fn with<F>(func: F)
where
F: FnOnce(&Self) + Send,
{
scope(move |scope| func(Self::from_rayon(scope)))
}
fn from_rayon<'a>(scope: &'a Scope<'scope>) -> &'a Self {
// SAFETY: transmuting from Scope to OsTraversalScope is safe since
// OsTraversalScope has the `repr(transparent)` attribute that
// guarantees its layout is the same as Scope
unsafe { mem::transmute(scope) }
}
}
impl<'scope> TraversalScope<'scope> for OsTraversalScope<'scope> {
fn spawn(&self, ctx: &'scope dyn TraversalContext, mut path: PathBuf) {
let mut file_type = match path.metadata() {
Ok(meta) => meta.file_type(),
Err(err) => {
ctx.push_diagnostic(
IoError::from(err).with_file_path(path.to_string_lossy().to_string()),
);
return;
}
};
if file_type.is_symlink() {
let Ok((target_path, target_file_type)) = expand_symbolic_link(path, ctx) else {
return;
};
path = target_path;
file_type = target_file_type;
}
let _ = ctx.interner().intern_path(path.clone());
if file_type.is_file() {
self.scope.spawn(move |_| {
ctx.handle_file(&path);
});
return;
}
if file_type.is_dir() {
self.scope.spawn(move |scope| {
handle_dir(scope, ctx, &path, None);
});
return;
}
ctx.push_diagnostic(Error::from(FileSystemDiagnostic {
path: path.to_string_lossy().to_string(),
error_kind: ErrorKind::from(file_type),
severity: Severity::Warning,
}));
}
}
/// Default list of ignored directories, in the future will be supplanted by
/// detecting and parsing .ignore files
const DEFAULT_IGNORE: &[&str; 5] = &[".git", ".svn", ".hg", ".yarn", "node_modules"];
/// Traverse a single directory
fn handle_dir<'scope>(
scope: &Scope<'scope>,
ctx: &'scope dyn TraversalContext,
path: &Path,
// The unresolved origin path in case the directory is behind a symbolic link
origin_path: Option<PathBuf>,
) {
if let Some(file_name) = path.file_name().and_then(OsStr::to_str) {
if DEFAULT_IGNORE.contains(&file_name) {
return;
}
}
let iter = match fs::read_dir(path) {
Ok(iter) => iter,
Err(err) => {
ctx.push_diagnostic(IoError::from(err).with_file_path(path.display().to_string()));
return;
}
};
for entry in iter {
match entry {
Ok(entry) => handle_dir_entry(scope, ctx, entry, origin_path.clone()),
Err(err) => {
ctx.push_diagnostic(IoError::from(err).with_file_path(path.display().to_string()));
}
}
}
}
/// Traverse a single directory entry, scheduling any file to execute the context
/// handler and sub-directories for subsequent traversal
fn handle_dir_entry<'scope>(
scope: &Scope<'scope>,
ctx: &'scope dyn TraversalContext,
entry: DirEntry,
// The unresolved origin path in case the directory is behind a symbolic link
mut origin_path: Option<PathBuf>,
) {
let mut path = entry.path();
let mut file_type = match entry.file_type() {
Ok(file_type) => file_type,
Err(err) => {
ctx.push_diagnostic(
IoError::from(err).with_file_path(path.to_string_lossy().to_string()),
);
return;
}
};
if file_type.is_symlink() {
let Ok((target_path, target_file_type)) = expand_symbolic_link(path.clone(), ctx) else {
return;
};
if target_file_type.is_dir() {
// Override the origin path of the symbolic link
origin_path = Some(path);
}
path = target_path;
file_type = target_file_type;
}
let inserted = ctx.interner().intern_path(path.clone());
if !inserted {
// If the path was already inserted, it could have been pointed at by
// multiple symlinks. No need to traverse again.
return;
}
if file_type.is_dir() {
if ctx.can_handle(&RomePath::new(path.clone())) {
scope.spawn(move |scope| {
handle_dir(scope, ctx, &path, origin_path);
});
}
return;
}
if file_type.is_file() {
if matches!(
path.file_name().and_then(OsStr::to_str),
Some("package.json" | "package-lock.json" | "tsconfig.json" | "jsconfig.json")
) {
return;
}
// In case the file is inside a directory that is behind a symbolic link,
// the unresolved origin path is used to construct a new path.
// This is required to support ignore patterns to symbolic links.
let rome_path = if let Some(origin_path) = origin_path {
if let Some(file_name) = path.file_name() {
RomePath::new(origin_path.join(file_name))
} else {
ctx.push_diagnostic(Error::from(FileSystemDiagnostic {
path: path.to_string_lossy().to_string(),
error_kind: ErrorKind::UnknownFileType,
severity: Severity::Warning,
}));
return;
}
} else {
RomePath::new(&path)
};
// Performing this check here let's us skip skip unsupported
// files entirely, as well as silently ignore unsupported files when
// doing a directory traversal, but printing an error message if the
// user explicitly requests an unsupported file to be handled.
// This check also works for symbolic links.
if !ctx.can_handle(&rome_path) {
return;
}
scope.spawn(move |_| {
ctx.handle_file(&path);
});
return;
}
ctx.push_diagnostic(Error::from(FileSystemDiagnostic {
path: path.to_string_lossy().to_string(),
error_kind: ErrorKind::from(file_type),
severity: Severity::Warning,
}));
}
/// Indicates a symbolic link could not be expanded.
///
/// Has no fields, since the diagnostics are already generated inside
/// [follow_symbolic_link()] and the caller doesn't need to do anything except
/// an early return.
struct SymlinkExpansionError;
/// Expands symlinks by recursively following them up to [MAX_SYMLINK_DEPTH].
///
/// ## Returns
///
/// Returns a tuple where the first argument is the target path being pointed to
/// and the second argument is the target file type.
fn expand_symbolic_link(
mut path: PathBuf,
ctx: &dyn TraversalContext,
) -> Result<(PathBuf, FileType), SymlinkExpansionError> {
let mut symlink_depth = 0;
loop {
symlink_depth += 1;
if symlink_depth > MAX_SYMLINK_DEPTH {
let path = path.to_string_lossy().to_string();
ctx.push_diagnostic(Error::from(FileSystemDiagnostic {
path: path.clone(),
error_kind: ErrorKind::DeeplyNestedSymlinkExpansion(path),
severity: Severity::Warning,
}));
return Err(SymlinkExpansionError);
}
let (target_path, target_file_type) = follow_symlink(&path, ctx)?;
if target_file_type.is_symlink() {
path = target_path;
continue;
}
return Ok((target_path, target_file_type));
}
}
fn follow_symlink(
path: &Path,
ctx: &dyn TraversalContext,
) -> Result<(PathBuf, FileType), SymlinkExpansionError> {
tracing::info!("Translating symlink: {path:?}");
let target_path = fs::read_link(path).map_err(|err| {
ctx.push_diagnostic(IoError::from(err).with_file_path(path.to_string_lossy().to_string()));
SymlinkExpansionError
})?;
// Make sure relative symlinks are resolved:
let target_path = path
.parent()
.map(|parent_dir| parent_dir.join(&target_path))
.unwrap_or(target_path);
let target_file_type = match fs::symlink_metadata(&target_path) {
Ok(meta) => meta.file_type(),
Err(err) => {
if err.kind() == IoErrorKind::NotFound {
let path = path.to_string_lossy().to_string();
ctx.push_diagnostic(Error::from(FileSystemDiagnostic {
path: path.clone(),
error_kind: ErrorKind::DereferencedSymlink(path),
severity: Severity::Warning,
}));
} else {
ctx.push_diagnostic(
IoError::from(err).with_file_path(path.to_string_lossy().to_string()),
);
}
return Err(SymlinkExpansionError);
}
};
Ok((target_path, target_file_type))
}
impl From<fs::FileType> for ErrorKind {
fn from(_: fs::FileType) -> Self {
Self::UnknownFileType
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_fs/src/fs/memory.rs | crates/rome_fs/src/fs/memory.rs | use std::collections::hash_map::Entry;
use std::collections::{hash_map::IntoIter, HashMap};
use std::io;
use std::panic::AssertUnwindSafe;
use std::path::{Path, PathBuf};
use std::str;
use std::sync::Arc;
use parking_lot::{lock_api::ArcMutexGuard, Mutex, RawMutex, RwLock};
use rome_diagnostics::{Error, Severity};
use crate::fs::OpenOptions;
use crate::{FileSystem, RomePath, TraversalContext, TraversalScope};
use super::{BoxedTraversal, ErrorKind, File, FileSystemDiagnostic};
/// Fully in-memory file system, stores the content of all known files in a hashmap
pub struct MemoryFileSystem {
files: AssertUnwindSafe<RwLock<HashMap<PathBuf, FileEntry>>>,
errors: HashMap<PathBuf, ErrorEntry>,
allow_write: bool,
}
impl Default for MemoryFileSystem {
fn default() -> Self {
Self {
files: Default::default(),
errors: Default::default(),
allow_write: true,
}
}
}
/// This is what's actually being stored for each file in the filesystem
///
/// To break it down:
/// - `Vec<u8>` is the byte buffer holding the content of the file
/// - `Mutex` lets it safely be read an written concurrently from multiple
/// threads ([FileSystem] is required to be [Sync])
/// - `Arc` allows [MemoryFile] handles to outlive references to the filesystem
/// itself (since [FileSystem::open] returns an owned value)
/// - `AssertUnwindSafe` tells the type system this value can safely be
/// accessed again after being recovered from a panic (using `catch_unwind`),
/// which means the filesystem guarantees a file will never get into an
/// inconsistent state if a thread panics while having a handle open (a read
/// or write either happens or not, but will never panic halfway through)
type FileEntry = Arc<Mutex<Vec<u8>>>;
/// Error entries are special file system entries that cause an error to be
/// emitted when they are reached through a filesystem traversal. This is
/// mainly useful as a mechanism to test the handling of filesystem error in
/// client code.
#[derive(Clone, Debug)]
pub enum ErrorEntry {
UnknownFileType,
DereferencedSymlink(PathBuf),
DeeplyNestedSymlinkExpansion(PathBuf),
}
impl MemoryFileSystem {
/// Create a read-only instance of [MemoryFileSystem]
///
/// This instance will disallow any modification through the [FileSystem]
/// trait, but the content of the filesystem may still be modified using
/// the methods on [MemoryFileSystem] itself.
pub fn new_read_only() -> Self {
Self {
allow_write: false,
..Self::default()
}
}
/// Create or update a file in the filesystem
pub fn insert(&mut self, path: PathBuf, content: impl Into<Vec<u8>>) {
let files = self.files.0.get_mut();
files.insert(path, Arc::new(Mutex::new(content.into())));
}
/// Create or update an error in the filesystem
pub fn insert_error(&mut self, path: PathBuf, kind: ErrorEntry) {
self.errors.insert(path, kind);
}
/// Remove a file from the filesystem
pub fn remove(&mut self, path: &Path) {
self.files.0.write().remove(path);
}
pub fn files(self) -> IntoIter<PathBuf, FileEntry> {
let files = self.files.0.into_inner();
files.into_iter()
}
}
impl FileSystem for MemoryFileSystem {
fn open_with_options(&self, path: &Path, options: OpenOptions) -> io::Result<Box<dyn File>> {
if !self.allow_write
&& (options.create || options.create_new || options.truncate || options.write)
{
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"cannot acquire write access to file in read-only filesystem",
));
}
let mut inner = if options.create || options.create_new {
// Acquire write access to the files map if the file may need to be created
let mut files = self.files.0.write();
match files.entry(PathBuf::from(path)) {
Entry::Vacant(entry) => {
// we create an empty file
let file: FileEntry = Arc::new(Mutex::new(vec![]));
let entry = entry.insert(file);
entry.lock_arc()
}
Entry::Occupied(entry) => {
if options.create {
// If `create` is true, truncate the file
let entry = entry.into_mut();
*entry = Arc::new(Mutex::new(vec![]));
entry.lock_arc()
} else {
// This branch can only be reached if `create_new` was true,
// we should return an error if the file already exists
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!("path {path:?} already exists in memory filesystem"),
));
}
}
}
} else {
let files = self.files.0.read();
let entry = files.get(path).ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("path {path:?} does not exists in memory filesystem"),
)
})?;
entry.lock_arc()
};
if options.truncate {
// Clear the buffer if the file was open with `truncate`
inner.clear();
}
Ok(Box::new(MemoryFile {
inner,
can_read: options.read,
can_write: options.write,
version: 0,
}))
}
fn traversal<'scope>(&'scope self, func: BoxedTraversal<'_, 'scope>) {
func(&MemoryTraversalScope { fs: self })
}
fn working_directory(&self) -> Option<PathBuf> {
None
}
fn path_exists(&self, path: &Path) -> bool {
let files = self.files.0.read();
files.get(path).is_some()
}
}
struct MemoryFile {
inner: ArcMutexGuard<RawMutex, Vec<u8>>,
can_read: bool,
can_write: bool,
version: i32,
}
impl File for MemoryFile {
fn read_to_string(&mut self, buffer: &mut String) -> io::Result<()> {
if !self.can_read {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"this file wasn't open with read access",
));
}
// Verify the stored byte content is valid UTF-8
let content = str::from_utf8(&self.inner)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
// Append the content of the file to the buffer
buffer.push_str(content);
Ok(())
}
fn set_content(&mut self, content: &[u8]) -> io::Result<()> {
if !self.can_write {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"this file wasn't open with write access",
));
}
// Resize the memory buffer to fit the new content
self.inner.resize(content.len(), 0);
// Copy the new content into the memory buffer
self.inner.copy_from_slice(content);
// we increase its version
self.version += 1;
Ok(())
}
fn file_version(&self) -> i32 {
self.version
}
}
pub struct MemoryTraversalScope<'scope> {
fs: &'scope MemoryFileSystem,
}
impl<'scope> TraversalScope<'scope> for MemoryTraversalScope<'scope> {
fn spawn(&self, ctx: &'scope dyn TraversalContext, base: PathBuf) {
// Traversal is implemented by iterating on all keys, and matching on
// those that are prefixed with the provided `base` path
{
let files = &self.fs.files.0.read();
for path in files.keys() {
let should_process_file = if base.starts_with(".") || base.starts_with("./") {
// we simulate absolute paths, so we can correctly strips out the base path from the path
let absolute_base = PathBuf::from("/").join(&base);
let absolute_path = Path::new("/").join(path);
absolute_path.strip_prefix(&absolute_base).is_ok()
} else {
path.strip_prefix(&base).is_ok()
};
if should_process_file {
let _ = ctx.interner().intern_path(path.into());
let rome_path = RomePath::new(path);
if !ctx.can_handle(&rome_path) {
continue;
}
ctx.handle_file(path);
}
}
}
for (path, entry) in &self.fs.errors {
if path.strip_prefix(&base).is_ok() {
ctx.push_diagnostic(Error::from(FileSystemDiagnostic {
path: path.to_string_lossy().to_string(),
error_kind: match entry {
ErrorEntry::UnknownFileType => ErrorKind::UnknownFileType,
ErrorEntry::DereferencedSymlink(path) => {
ErrorKind::DereferencedSymlink(path.to_string_lossy().to_string())
}
ErrorEntry::DeeplyNestedSymlinkExpansion(path) => {
ErrorKind::DeeplyNestedSymlinkExpansion(
path.to_string_lossy().to_string(),
)
}
},
severity: Severity::Warning,
}));
}
}
}
}
#[cfg(test)]
mod tests {
use std::{
io,
mem::swap,
path::{Path, PathBuf},
};
use parking_lot::Mutex;
use rome_diagnostics::Error;
use crate::{fs::FileSystemExt, OpenOptions};
use crate::{FileSystem, MemoryFileSystem, PathInterner, RomePath, TraversalContext};
#[test]
fn fs_read_only() {
let mut fs = MemoryFileSystem::new_read_only();
let path = Path::new("file.js");
fs.insert(path.into(), *b"content");
assert!(fs.open(path).is_ok());
match fs.create(path) {
Ok(_) => panic!("fs.create() for a read-only filesystem should return an error"),
Err(error) => {
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
}
}
match fs.create_new(path) {
Ok(_) => panic!("fs.create() for a read-only filesystem should return an error"),
Err(error) => {
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
}
}
match fs.open_with_options(path, OpenOptions::default().read(true).write(true)) {
Ok(_) => panic!("fs.open_with_options(read + write) for a read-only filesystem should return an error"),
Err(error) => {
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
}
}
}
#[test]
fn file_read_write() {
let mut fs = MemoryFileSystem::default();
let path = Path::new("file.js");
let content_1 = "content 1";
let content_2 = "content 2";
fs.insert(path.into(), content_1.as_bytes());
let mut file = fs
.open_with_options(path, OpenOptions::default().read(true).write(true))
.expect("the file should exist in the memory file system");
let mut buffer = String::new();
file.read_to_string(&mut buffer)
.expect("the file should be read without error");
assert_eq!(buffer, content_1);
file.set_content(content_2.as_bytes())
.expect("the file should be written without error");
let mut buffer = String::new();
file.read_to_string(&mut buffer)
.expect("the file should be read without error");
assert_eq!(buffer, content_2);
}
#[test]
fn file_create() {
let fs = MemoryFileSystem::default();
let path = Path::new("file.js");
let mut file = fs.create(path).expect("the file should not fail to open");
file.set_content(b"content".as_slice())
.expect("the file should be written without error");
}
#[test]
fn file_create_truncate() {
let mut fs = MemoryFileSystem::default();
let path = Path::new("file.js");
fs.insert(path.into(), b"content".as_slice());
let file = fs.create(path).expect("the file should not fail to create");
drop(file);
let mut file = fs.open(path).expect("the file should not fail to open");
let mut buffer = String::new();
file.read_to_string(&mut buffer)
.expect("the file should be read without error");
assert!(
buffer.is_empty(),
"fs.create() should truncate the file content"
);
}
#[test]
fn file_create_new() {
let fs = MemoryFileSystem::default();
let path = Path::new("file.js");
let content = "content";
let mut file = fs
.create_new(path)
.expect("the file should not fail to create");
file.set_content(content.as_bytes())
.expect("the file should be written without error");
drop(file);
let mut file = fs.open(path).expect("the file should not fail to open");
let mut buffer = String::new();
file.read_to_string(&mut buffer)
.expect("the file should be read without error");
assert_eq!(buffer, content);
}
#[test]
fn file_create_new_exists() {
let mut fs = MemoryFileSystem::default();
let path = Path::new("file.js");
fs.insert(path.into(), b"content".as_slice());
let result = fs.create_new(path);
match result {
Ok(_) => panic!("fs.create_new() for an existing file should return an error"),
Err(error) => {
assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
}
}
}
#[test]
fn missing_file() {
let fs = MemoryFileSystem::default();
let result = fs.open(Path::new("non_existing"));
match result {
Ok(_) => panic!("opening a non-existing file should return an error"),
Err(error) => {
assert_eq!(error.kind(), io::ErrorKind::NotFound);
}
}
}
#[test]
fn traversal() {
let mut fs = MemoryFileSystem::default();
fs.insert(PathBuf::from("dir1/file1"), "dir1/file1".as_bytes());
fs.insert(PathBuf::from("dir1/file2"), "dir1/file1".as_bytes());
fs.insert(PathBuf::from("dir2/file1"), "dir2/file1".as_bytes());
fs.insert(PathBuf::from("dir2/file2"), "dir2/file1".as_bytes());
struct TestContext {
interner: PathInterner,
visited: Mutex<Vec<PathBuf>>,
}
impl TraversalContext for TestContext {
fn interner(&self) -> &PathInterner {
&self.interner
}
fn push_diagnostic(&self, err: Error) {
panic!("unexpected error {err:?}")
}
fn can_handle(&self, _: &RomePath) -> bool {
true
}
fn handle_file(&self, path: &Path) {
self.visited.lock().push(path.into())
}
}
let (interner, _) = PathInterner::new();
let mut ctx = TestContext {
interner,
visited: Mutex::default(),
};
// Traverse a directory
fs.traversal(Box::new(|scope| {
scope.spawn(&ctx, PathBuf::from("dir1"));
}));
let mut visited = Vec::new();
swap(&mut visited, ctx.visited.get_mut());
assert_eq!(visited.len(), 2);
assert!(visited.contains(&PathBuf::from("dir1/file1")));
assert!(visited.contains(&PathBuf::from("dir1/file2")));
// Traverse a single file
fs.traversal(Box::new(|scope| {
scope.spawn(&ctx, PathBuf::from("dir2/file2"));
}));
let mut visited = Vec::new();
swap(&mut visited, ctx.visited.get_mut());
assert_eq!(visited.len(), 1);
assert!(visited.contains(&PathBuf::from("dir2/file2")));
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_aria_metadata/build.rs | crates/rome_aria_metadata/build.rs | //! Metadata of:
//! - ARIA properties
//! - ARIA property types
//! - ARIA roles
use case::CaseExt;
use proc_macro2::{Ident, Literal, Span, TokenStream};
use quote::quote;
use std::path::PathBuf;
use std::{env, fs, io};
pub const ARIA_PROPERTIES: [&str; 48] = [
"aria-activedescendant",
"aria-atomic",
"aria-autocomplete",
"aria-busy",
"aria-checked",
"aria-colcount",
"aria-colindex",
"aria-colspan",
"aria-controls",
"aria-current",
"aria-describedby",
"aria-details",
"aria-disabled",
"aria-dropeffect",
"aria-errormessage",
"aria-expanded",
"aria-flowto",
"aria-grabbed",
"aria-haspopup",
"aria-hidden",
"aria-invalid",
"aria-keyshortcuts",
"aria-label",
"aria-labelledby",
"aria-level",
"aria-live",
"aria-modal",
"aria-multiline",
"aria-multiselectable",
"aria-orientation",
"aria-owns",
"aria-placeholder",
"aria-posinset",
"aria-pressed",
"aria-readonly",
"aria-relevant",
"aria-required",
"aria-roledescription",
"aria-rowcount",
"aria-rowindex",
"aria-rowspan",
"aria-selected",
"aria-setsize",
"aria-sort",
"aria-valuemax",
"aria-valuemin",
"aria-valuenow",
"aria-valuetext",
];
pub const ARIA_PROPERTY_TYPE: [&str; 9] = [
"boolean",
"id",
"idlist",
"integer",
"number",
"string",
"token",
"tokenlist",
"tristate",
];
pub const ARIA_WIDGET_ROLES: [&str; 27] = [
"alert",
"alertdialog",
"button",
"checkbox",
"dialog",
"gridcell",
"link",
"log",
"marquee",
"menuitem",
"menuitemcheckbox",
"menuitemradio",
"option",
"progressbar",
"radio",
"scrollbar",
"searchbox",
"slider",
"spinbutton",
"status",
"switch",
"tab",
"tabpanel",
"textbox",
"timer",
"tooltip",
"treeitem",
];
pub const ARIA_ABSTRACT_ROLES: [&str; 12] = [
"command",
"composite",
"input",
"landmark",
"range",
"roletype",
"section",
"sectionhead",
"select",
"structure",
"widget",
"window",
];
pub const ARIA_DOCUMENT_STRUCTURE_ROLES: [&str; 25] = [
"article",
"cell",
"columnheader",
"definition",
"directory",
"document",
"feed",
"figure",
"group",
"heading",
"img",
"list",
"listitem",
"math",
"none",
"note",
"presentation",
"region",
"row",
"rowgroup",
"rowheader",
"separator",
"table",
"term",
"toolbar",
];
const ISO_COUNTRIES: [&str; 233] = [
"AF", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS",
"BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BR", "IO", "VG", "BN",
"BG", "BF", "MM", "BI", "KH", "CM", "CA", "CV", "KY", "CF", "TD", "CL", "CN", "CX", "CC", "CO",
"KM", "CK", "CR", "HR", "CU", "CY", "CZ", "CD", "DK", "DJ", "DM", "DO", "EC", "EG", "SV", "GQ",
"ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "PF", "GA", "GM", "GE", "DE", "GH", "GI", "GR",
"GL", "GD", "GU", "GT", "GN", "GW", "GY", "HT", "VA", "HN", "HK", "HU", "IS", "IN", "ID", "IR",
"IQ", "IE", "IM", "IL", "IT", "CI", "JM", "JP", "JE", "JO", "KZ", "KE", "KI", "KW", "KG", "LA",
"LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MY", "MV", "ML", "MT",
"MH", "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "ME", "MS", "MA", "MZ", "NA", "NR", "NP",
"NL", "AN", "NC", "NZ", "NI", "NE", "NG", "NU", "KP", "MP", "NO", "OM", "PK", "PW", "PA", "PG",
"PY", "PE", "PH", "PN", "PL", "PT", "PR", "QA", "CG", "RO", "RU", "RW", "BL", "SH", "KN", "LC",
"MF", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "RS", "SC", "SL", "SG", "SK", "SI", "SB", "SO",
"ZA", "KR", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "TL",
"TG", "TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UY", "VI",
"UZ", "VU", "VE", "VN", "WF", "EH", "YE", "ZM", "ZW",
];
const ISO_LANGUAGES: [&str; 150] = [
"ab", "aa", "af", "sq", "am", "ar", "an", "hy", "as", "ay", "az", "ba", "eu", "bn", "dz", "bh",
"bi", "br", "bg", "my", "be", "km", "ca", "zh", "zh-Hans", "zh-Hant", "co", "hr", "cs", "da",
"nl", "en", "eo", "et", "fo", "fa", "fj", "fi", "fr", "fy", "gl", "gd", "gv", "ka", "de", "el",
"kl", "gn", "gu", "ht", "ha", "he", "iw", "hi", "hu", "is", "io", "id", "in", "ia", "ie", "iu",
"ik", "ga", "it", "ja", "jv", "kn", "ks", "kk", "rw", "ky", "rn", "ko", "ku", "lo", "la", "lv",
"li", "ln", "lt", "mk", "mg", "ms", "ml", "mt", "mi", "mr", "mo", "mn", "na", "ne", "no", "oc",
"or", "om", "ps", "pl", "pt", "pa", "qu", "rm", "ro", "ru", "sm", "sg", "sa", "sr", "sh", "st",
"tn", "sn", "ii", "sd", "si", "ss", "sk", "sl", "so", "es", "su", "sw", "sv", "tl", "tg", "ta",
"tt", "te", "th", "bo", "ti", "to", "ts", "tr", "tk", "tw", "ug", "uk", "ur", "uz", "vi", "vo",
"wa", "cy", "wo", "xh", "yi", "ji", "yo", "zu",
];
fn main() -> io::Result<()> {
let aria_properties = generate_properties();
let aria_roles = generate_roles();
let tokens = quote! {
use std::str::FromStr;
#aria_properties
#aria_roles
};
let ast = tokens.to_string();
let out_dir = env::var("OUT_DIR").unwrap();
fs::write(PathBuf::from(out_dir).join("roles_and_properties.rs"), ast)?;
Ok(())
}
fn generate_properties() -> TokenStream {
let properties = generate_enums(
ARIA_PROPERTIES.len(),
ARIA_PROPERTIES.iter(),
"AriaPropertiesEnum",
);
let property_types = generate_enums(
ARIA_PROPERTY_TYPE.len(),
ARIA_PROPERTY_TYPE.iter(),
"AriaPropertyTypeEnum",
);
quote! {
#properties
#property_types
}
}
fn generate_roles() -> TokenStream {
let widget_roles = generate_enums(
ARIA_WIDGET_ROLES.len(),
ARIA_WIDGET_ROLES.iter(),
"AriaWidgetRolesEnum",
);
let abstract_roles = generate_enums(
ARIA_ABSTRACT_ROLES.len(),
ARIA_ABSTRACT_ROLES.iter(),
"AriaAbstractRolesEnum",
);
let document_structure_roles = generate_enums(
ARIA_DOCUMENT_STRUCTURE_ROLES.len(),
ARIA_DOCUMENT_STRUCTURE_ROLES.iter(),
"AriaDocumentStructureRolesEnum",
);
let iso_countries = generate_enums(ISO_COUNTRIES.len(), ISO_COUNTRIES.iter(), "IsoCountries");
let iso_languages = generate_enums(ISO_LANGUAGES.len(), ISO_LANGUAGES.iter(), "IsoLanguages");
quote! {
#widget_roles
#abstract_roles
#document_structure_roles
#iso_countries
#iso_languages
}
}
fn generate_enums(len: usize, array: std::slice::Iter<&str>, enum_name: &str) -> TokenStream {
let enum_name = Ident::new(enum_name, Span::call_site());
let mut enum_metadata = Vec::with_capacity(len);
let mut from_enum_metadata = Vec::with_capacity(len);
let mut from_string_metadata = Vec::with_capacity(len);
for property in array {
let name = Ident::new(&property.replace('-', "_").to_camel(), Span::call_site());
let property = Literal::string(property);
from_enum_metadata.push(quote! {
#enum_name::#name => #property
});
from_string_metadata.push(quote! {
#property => Ok(#enum_name::#name)
});
enum_metadata.push(name);
}
from_string_metadata.push(quote! {
_ => Err("aria property not implemented".to_string())
});
quote! {
#[derive(Debug, Eq, PartialEq)]
pub enum #enum_name {
#( #enum_metadata ),*
}
impl From<#enum_name> for &str {
fn from(property: #enum_name) -> Self {
match property {
#( #from_enum_metadata ),*
}
}
}
impl FromStr for #enum_name {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
#( #from_string_metadata ),*
}
}
}
impl #enum_name {
pub fn as_str(&self) -> &str {
match self {
#( #from_enum_metadata ),*
}
}
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_aria_metadata/src/lib.rs | crates/rome_aria_metadata/src/lib.rs | include!(concat!(env!("OUT_DIR"), "/roles_and_properties.rs"));
pub const ISO_COUNTRIES: [&str; 233] = [
"AF", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS",
"BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BR", "IO", "VG", "BN",
"BG", "BF", "MM", "BI", "KH", "CM", "CA", "CV", "KY", "CF", "TD", "CL", "CN", "CX", "CC", "CO",
"KM", "CK", "CR", "HR", "CU", "CY", "CZ", "CD", "DK", "DJ", "DM", "DO", "EC", "EG", "SV", "GQ",
"ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "PF", "GA", "GM", "GE", "DE", "GH", "GI", "GR",
"GL", "GD", "GU", "GT", "GN", "GW", "GY", "HT", "VA", "HN", "HK", "HU", "IS", "IN", "ID", "IR",
"IQ", "IE", "IM", "IL", "IT", "CI", "JM", "JP", "JE", "JO", "KZ", "KE", "KI", "KW", "KG", "LA",
"LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MY", "MV", "ML", "MT",
"MH", "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "ME", "MS", "MA", "MZ", "NA", "NR", "NP",
"NL", "AN", "NC", "NZ", "NI", "NE", "NG", "NU", "KP", "MP", "NO", "OM", "PK", "PW", "PA", "PG",
"PY", "PE", "PH", "PN", "PL", "PT", "PR", "QA", "CG", "RO", "RU", "RW", "BL", "SH", "KN", "LC",
"MF", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "RS", "SC", "SL", "SG", "SK", "SI", "SB", "SO",
"ZA", "KR", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "TL",
"TG", "TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UY", "VI",
"UZ", "VU", "VE", "VN", "WF", "EH", "YE", "ZM", "ZW",
];
pub const ISO_LANGUAGES: [&str; 150] = [
"ab", "aa", "af", "sq", "am", "ar", "an", "hy", "as", "ay", "az", "ba", "eu", "bn", "dz", "bh",
"bi", "br", "bg", "my", "be", "km", "ca", "zh", "zh-Hans", "zh-Hant", "co", "hr", "cs", "da",
"nl", "en", "eo", "et", "fo", "fa", "fj", "fi", "fr", "fy", "gl", "gd", "gv", "ka", "de", "el",
"kl", "gn", "gu", "ht", "ha", "he", "iw", "hi", "hu", "is", "io", "id", "in", "ia", "ie", "iu",
"ik", "ga", "it", "ja", "jv", "kn", "ks", "kk", "rw", "ky", "rn", "ko", "ku", "lo", "la", "lv",
"li", "ln", "lt", "mk", "mg", "ms", "ml", "mt", "mi", "mr", "mo", "mn", "na", "ne", "no", "oc",
"or", "om", "ps", "pl", "pt", "pa", "qu", "rm", "ro", "ru", "sm", "sg", "sa", "sr", "sh", "st",
"tn", "sn", "ii", "sd", "si", "ss", "sk", "sl", "so", "es", "su", "sw", "sv", "tl", "tg", "ta",
"tt", "te", "th", "bo", "ti", "to", "ts", "tr", "tk", "tw", "ug", "uk", "ur", "uz", "vi", "vo",
"wa", "cy", "wo", "xh", "yi", "ji", "yo", "zu",
];
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/src/markup.rs | crates/rome_console/src/markup.rs | use std::{
borrow::Cow,
fmt::{self, Debug},
io,
};
use rome_text_size::TextSize;
use termcolor::{Color, ColorSpec};
use crate::fmt::{Display, Formatter, MarkupElements, Write};
/// Enumeration of all the supported markup elements
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)
)]
pub enum MarkupElement<'fmt> {
Emphasis,
Dim,
Italic,
Underline,
Error,
Success,
Warn,
Info,
Inverse,
Hyperlink { href: Cow<'fmt, str> },
}
impl fmt::Display for MarkupElement<'_> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Self::Hyperlink { href } = self {
if fmt.alternate() {
write!(fmt, "Hyperlink href={:?}", href.as_ref())
} else {
fmt.write_str("Hyperlink")
}
} else {
write!(fmt, "{self:?}")
}
}
}
impl<'fmt> MarkupElement<'fmt> {
/// Mutate a [ColorSpec] object in place to apply this element's associated
/// style to it
pub(crate) fn update_color(&self, color: &mut ColorSpec) {
match self {
// Text Styles
MarkupElement::Emphasis => {
color.set_bold(true);
}
MarkupElement::Dim => {
color.set_dimmed(true);
}
MarkupElement::Italic => {
color.set_italic(true);
}
MarkupElement::Underline => {
color.set_underline(true);
}
// Text Colors
MarkupElement::Error => {
color.set_fg(Some(Color::Red));
}
MarkupElement::Success => {
color.set_fg(Some(Color::Green));
}
MarkupElement::Warn => {
color.set_fg(Some(Color::Yellow));
}
MarkupElement::Info => {
// Blue is really difficult to see on the standard windows command line
#[cfg(windows)]
const BLUE: Color = Color::Cyan;
#[cfg(not(windows))]
const BLUE: Color = Color::Blue;
color.set_fg(Some(BLUE));
}
MarkupElement::Inverse | MarkupElement::Hyperlink { .. } => {}
}
}
fn to_owned(&self) -> MarkupElement<'static> {
match self {
MarkupElement::Emphasis => MarkupElement::Emphasis,
MarkupElement::Dim => MarkupElement::Dim,
MarkupElement::Italic => MarkupElement::Italic,
MarkupElement::Underline => MarkupElement::Underline,
MarkupElement::Error => MarkupElement::Error,
MarkupElement::Success => MarkupElement::Success,
MarkupElement::Warn => MarkupElement::Warn,
MarkupElement::Info => MarkupElement::Info,
MarkupElement::Inverse => MarkupElement::Inverse,
MarkupElement::Hyperlink { href } => MarkupElement::Hyperlink {
href: Cow::Owned(match href {
Cow::Borrowed(href) => href.to_string(),
Cow::Owned(href) => href.clone(),
}),
},
}
}
}
/// Implementation of a single "markup node": a piece of text with a number of
/// associated styles applied to it
#[derive(Copy, Clone)]
pub struct MarkupNode<'fmt> {
pub elements: &'fmt [MarkupElement<'fmt>],
pub content: &'fmt dyn Display,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)
)]
pub struct MarkupNodeBuf {
pub elements: Vec<MarkupElement<'static>>,
pub content: String,
}
impl Debug for MarkupNodeBuf {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
for element in &self.elements {
write!(fmt, "<{element:#}>")?;
}
if fmt.alternate() {
let mut content = self.content.as_str();
while let Some(index) = content.find('\n') {
let (before, after) = content.split_at(index + 1);
if !before.is_empty() {
writeln!(fmt, "{before:?}")?;
}
content = after;
}
if !content.is_empty() {
write!(fmt, "{content:?}")?;
}
} else {
write!(fmt, "{:?}", self.content)?;
}
for element in self.elements.iter().rev() {
write!(fmt, "</{element}>")?;
}
Ok(())
}
}
/// Root type returned by the `markup` macro: this is simply a container for a
/// list of markup nodes
///
/// Text nodes are formatted lazily by storing an [fmt::Arguments] struct, this
/// means [Markup] shares the same restriction as the values returned by
/// [format_args] and can't be stored in a `let` binding for instance
#[derive(Copy, Clone)]
pub struct Markup<'fmt>(pub &'fmt [MarkupNode<'fmt>]);
impl<'fmt> Markup<'fmt> {
pub fn to_owned(&self) -> MarkupBuf {
let mut result = MarkupBuf(Vec::new());
// SAFETY: The implementation of Write for MarkupBuf below always returns Ok
Formatter::new(&mut result).write_markup(*self).unwrap();
result
}
}
#[derive(Clone, Default, PartialEq, Eq, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)
)]
pub struct MarkupBuf(pub Vec<MarkupNodeBuf>);
impl MarkupBuf {
pub fn is_empty(&self) -> bool {
self.0.iter().all(|node| node.content.is_empty())
}
pub fn len(&self) -> TextSize {
self.0.iter().map(|node| TextSize::of(&node.content)).sum()
}
}
impl Write for MarkupBuf {
fn write_str(&mut self, elements: &MarkupElements, content: &str) -> io::Result<()> {
let mut styles = Vec::new();
elements.for_each(&mut |elements| {
styles.extend(elements.iter().map(MarkupElement::to_owned));
Ok(())
})?;
if let Some(last) = self.0.last_mut() {
if last.elements == styles {
last.content.push_str(content);
return Ok(());
}
}
self.0.push(MarkupNodeBuf {
elements: styles,
content: content.into(),
});
Ok(())
}
fn write_fmt(&mut self, elements: &MarkupElements, content: fmt::Arguments) -> io::Result<()> {
let mut styles = Vec::new();
elements.for_each(&mut |elements| {
styles.extend(elements.iter().map(MarkupElement::to_owned));
Ok(())
})?;
if let Some(last) = self.0.last_mut() {
if last.elements == styles {
last.content.push_str(&content.to_string());
return Ok(());
}
}
self.0.push(MarkupNodeBuf {
elements: styles,
content: content.to_string(),
});
Ok(())
}
}
impl Display for MarkupBuf {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
let nodes: Vec<_> = self
.0
.iter()
.map(|node| MarkupNode {
elements: &node.elements,
content: &node.content,
})
.collect();
fmt.write_markup(Markup(&nodes))
}
}
impl Debug for MarkupBuf {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
for node in &self.0 {
Debug::fmt(node, fmt)?;
}
Ok(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/src/lib.rs | crates/rome_console/src/lib.rs | use atty::Stream;
use std::io;
use std::io::{Read, Stdin, Write};
use std::panic::RefUnwindSafe;
use termcolor::{ColorChoice, StandardStream};
use write::Termcolor;
pub mod fmt;
mod markup;
mod write;
pub use self::markup::{Markup, MarkupBuf, MarkupElement, MarkupNode};
use crate::fmt::Formatter;
pub use rome_markup::markup;
/// Determines the "output stream" a message should get printed to
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LogLevel {
/// Print the message to the `Error` stream of the console, for instance
/// "stderr" for the [EnvConsole]
Error,
/// Print the message to the `Log` stream of the console, for instance
/// "stdout" for the [EnvConsole]
Log,
}
/// Generic abstraction over printing markup and diagnostics to an output,
/// which can be a terminal, a file, a memory buffer ...
pub trait Console: Send + Sync + RefUnwindSafe {
/// Prints a message (formatted using [markup!]) to the console.
///
/// It adds a new line at the end.
fn println(&mut self, level: LogLevel, args: Markup);
/// Prints a message (formatted using [markup!]) to the console.
fn print(&mut self, level: LogLevel, args: Markup);
/// It reads from a source, and if this source contains something, it's converted into a [String]
fn read(&mut self) -> Option<String>;
}
/// Extension trait for [Console] providing convenience printing methods
pub trait ConsoleExt: Console {
/// Prints a piece of markup with level [LogLevel::Error]
fn error(&mut self, args: Markup);
/// Prints a piece of markup with level [LogLevel::Log]
///
/// Logs a message, adds a new line at the end.
fn log(&mut self, args: Markup);
/// Prints a piece of markup with level [LogLevel::Log]
///
/// It doesn't add any line
fn append(&mut self, args: Markup);
}
impl<T: Console + ?Sized> ConsoleExt for T {
fn error(&mut self, args: Markup) {
self.println(LogLevel::Error, args);
}
fn log(&mut self, args: Markup) {
self.println(LogLevel::Log, args);
}
fn append(&mut self, args: Markup) {
self.print(LogLevel::Log, args);
}
}
/// Implementation of [Console] printing messages to the standard output and standard error
pub struct EnvConsole {
/// Channel to print messages
out: StandardStream,
/// Channel to print errors
err: StandardStream,
/// Channel to read arbitrary input
r#in: Stdin,
}
#[derive(Debug, Clone)]
pub enum ColorMode {
/// Always print color using either ANSI or the Windows Console API
Enabled,
/// Never print colors
Disabled,
/// Print colors if stdout / stderr are determined to be TTY / Console
/// streams, and the `TERM=dumb` and `NO_COLOR` environment variables are
/// not set
Auto,
}
impl EnvConsole {
fn compute_color(colors: ColorMode) -> (ColorChoice, ColorChoice) {
match colors {
ColorMode::Enabled => (ColorChoice::Always, ColorChoice::Always),
ColorMode::Disabled => (ColorChoice::Never, ColorChoice::Never),
ColorMode::Auto => {
let stdout = if atty::is(atty::Stream::Stdout) {
ColorChoice::Auto
} else {
ColorChoice::Never
};
let stderr = if atty::is(atty::Stream::Stderr) {
ColorChoice::Auto
} else {
ColorChoice::Never
};
(stdout, stderr)
}
}
}
pub fn new(colors: ColorMode) -> Self {
let (out_mode, err_mode) = Self::compute_color(colors);
Self {
out: StandardStream::stdout(out_mode),
err: StandardStream::stderr(err_mode),
r#in: io::stdin(),
}
}
pub fn set_color(&mut self, colors: ColorMode) {
let (out_mode, err_mode) = Self::compute_color(colors);
self.out = StandardStream::stdout(out_mode);
self.err = StandardStream::stderr(err_mode);
}
}
impl Default for EnvConsole {
fn default() -> Self {
Self::new(ColorMode::Auto)
}
}
impl Console for EnvConsole {
fn println(&mut self, level: LogLevel, args: Markup) {
let mut out = match level {
LogLevel::Error => self.err.lock(),
LogLevel::Log => self.out.lock(),
};
fmt::Formatter::new(&mut Termcolor(&mut out))
.write_markup(args)
.unwrap();
writeln!(out).unwrap();
}
fn print(&mut self, level: LogLevel, args: Markup) {
let mut out = match level {
LogLevel::Error => self.err.lock(),
LogLevel::Log => self.out.lock(),
};
fmt::Formatter::new(&mut Termcolor(&mut out))
.write_markup(args)
.unwrap();
write!(out, "").unwrap();
}
fn read(&mut self) -> Option<String> {
// Here we check if stdin is redirected. If not, we bail.
//
// Doing this check allows us to pipe stdin to rome, without expecting
// user content when we call `read_to_string`
if atty::is(Stream::Stdin) {
return None;
}
let mut handle = self.r#in.lock();
let mut buffer = String::new();
let result = handle.read_to_string(&mut buffer);
// Skipping the error for now
if result.is_ok() {
Some(buffer)
} else {
None
}
}
}
/// Implementation of [Console] storing all printed messages to a memory buffer
#[derive(Default, Debug)]
pub struct BufferConsole {
pub out_buffer: Vec<Message>,
pub in_buffer: Vec<String>,
}
/// Individual message entry printed to a [BufferConsole]
#[derive(Debug)]
pub struct Message {
pub level: LogLevel,
pub content: MarkupBuf,
}
impl Console for BufferConsole {
fn println(&mut self, level: LogLevel, args: Markup) {
self.out_buffer.push(Message {
level,
content: args.to_owned(),
});
}
fn print(&mut self, level: LogLevel, args: Markup) {
self.out_buffer.push(Message {
level,
content: args.to_owned(),
});
}
fn read(&mut self) -> Option<String> {
if self.in_buffer.is_empty() {
None
} else {
// for the time being we simple return the first message, as we don't
// particular use case for multiple prompts
Some(self.in_buffer[0].clone())
}
}
}
/// A horizontal line with the given print width
pub struct HorizontalLine {
width: usize,
}
impl HorizontalLine {
pub fn new(width: usize) -> Self {
Self { width }
}
}
impl fmt::Display for HorizontalLine {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
fmt.write_str(&"\u{2501}".repeat(self.width))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/src/write.rs | crates/rome_console/src/write.rs | mod html;
mod termcolor;
use std::{fmt, io};
use crate::fmt::MarkupElements;
pub use self::{html::HTML, termcolor::Termcolor};
pub trait Write {
fn write_str(&mut self, elements: &MarkupElements, content: &str) -> io::Result<()>;
fn write_fmt(&mut self, elements: &MarkupElements, content: fmt::Arguments) -> io::Result<()>;
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/src/fmt.rs | crates/rome_console/src/fmt.rs | use std::{borrow::Cow, fmt, io, time::Duration};
pub use crate::write::{Termcolor, Write, HTML};
use crate::{markup, Markup, MarkupElement};
/// A stack-allocated linked-list of [MarkupElement] slices
#[derive(Clone, Copy)]
pub enum MarkupElements<'a> {
Root,
Node(&'a Self, &'a [MarkupElement<'a>]),
}
impl<'a> MarkupElements<'a> {
/// Iterates on all the element slices depth-first
pub fn for_each(
&self,
func: &mut impl FnMut(&'a [MarkupElement]) -> io::Result<()>,
) -> io::Result<()> {
if let Self::Node(parent, elem) = self {
parent.for_each(func)?;
func(elem)?;
}
Ok(())
}
/// Iterates on all the element slices breadth-first
pub fn for_each_rev(
&self,
func: &mut impl FnMut(&'a [MarkupElement]) -> io::Result<()>,
) -> io::Result<()> {
if let Self::Node(parent, elem) = self {
func(elem)?;
parent.for_each(func)?;
}
Ok(())
}
}
/// The [Formatter] is the `rome_console` equivalent to [std::fmt::Formatter]:
/// it's never constructed directly by consumers, and can only be used through
/// the mutable reference passed to implementations of the [Display] trait).
/// It manages the state of the markup to print, and implementations of
/// [Display] can call into its methods to append content into the current
/// printing session
pub struct Formatter<'fmt> {
/// Stack of markup elements currently applied to the text being printed
state: MarkupElements<'fmt>,
/// Inner IO writer this [Formatter] will print text into
writer: &'fmt mut dyn Write,
}
impl<'fmt> Formatter<'fmt> {
/// Create a new instance of the [Formatter] using the provided `writer` for printing
pub fn new(writer: &'fmt mut dyn Write) -> Self {
Self {
state: MarkupElements::Root,
writer,
}
}
pub fn wrap_writer<'b: 'c, 'c>(
&'b mut self,
wrap: impl FnOnce(&'b mut dyn Write) -> &'c mut dyn Write,
) -> Formatter<'c> {
Formatter {
state: self.state,
writer: wrap(self.writer),
}
}
/// Return a new instance of the [Formatter] with `elements` appended to its element stack
fn with_elements<'b>(&'b mut self, elements: &'b [MarkupElement]) -> Formatter<'b> {
Formatter {
state: MarkupElements::Node(&self.state, elements),
writer: self.writer,
}
}
/// Write a piece of markup into this formatter
pub fn write_markup(&mut self, markup: Markup) -> io::Result<()> {
for node in markup.0 {
let mut fmt = self.with_elements(node.elements);
node.content.fmt(&mut fmt)?;
}
Ok(())
}
/// Write a slice of text into this formatter
pub fn write_str(&mut self, content: &str) -> io::Result<()> {
self.writer.write_str(&self.state, content)
}
/// Write formatted text into this formatter
pub fn write_fmt(&mut self, content: fmt::Arguments) -> io::Result<()> {
self.writer.write_fmt(&self.state, content)
}
}
/// Formatting trait for types to be displayed as markup, the `rome_console`
/// equivalent to [std::fmt::Display]
///
/// # Example
/// Implementing `Display` on a custom struct
/// ```
/// use rome_console::{
/// fmt::{Display, Formatter},
/// markup,
/// };
/// use std::io;
///
/// struct Warning(String);
///
/// impl Display for Warning {
/// fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
/// fmt.write_markup(markup! {
/// <Warn>{self.0}</Warn>
/// })
/// }
/// }
///
/// let warning = Warning(String::from("content"));
/// markup! {
/// <Emphasis>{warning}</Emphasis>
/// };
/// ```
pub trait Display {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()>;
}
// Blanket implementations of Display for reference types
impl<'a, T> Display for &'a T
where
T: Display + ?Sized,
{
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
T::fmt(self, fmt)
}
}
impl<'a, T> Display for Cow<'a, T>
where
T: Display + ToOwned + ?Sized,
{
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
T::fmt(self, fmt)
}
}
// Simple implementations of Display calling through to write_str for types
// that implement Deref<str>
impl Display for str {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
fmt.write_str(self)
}
}
impl Display for String {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
fmt.write_str(self)
}
}
// Implement Display for Markup and Rust format Arguments
impl<'a> Display for Markup<'a> {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
fmt.write_markup(*self)
}
}
impl<'a> Display for std::fmt::Arguments<'a> {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
fmt.write_fmt(*self)
}
}
/// Implement [Display] for types that implement [std::fmt::Display] by calling
/// through to [Formatter::write_fmt]
macro_rules! impl_std_display {
($ty:ty) => {
impl Display for $ty {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
write!(fmt, "{self}")
}
}
};
}
impl_std_display!(char);
impl_std_display!(i8);
impl_std_display!(i16);
impl_std_display!(i32);
impl_std_display!(i64);
impl_std_display!(i128);
impl_std_display!(isize);
impl_std_display!(u8);
impl_std_display!(u16);
impl_std_display!(u32);
impl_std_display!(u64);
impl_std_display!(u128);
impl_std_display!(usize);
impl Display for Duration {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
use crate as rome_console;
let secs = self.as_secs();
if secs > 1 {
return fmt.write_markup(markup! {
{secs}<Dim>"s"</Dim>
});
}
let millis = self.as_millis();
if millis > 1 {
return fmt.write_markup(markup! {
{millis}<Dim>"ms"</Dim>
});
}
let micros = self.as_micros();
if micros > 1 {
return fmt.write_markup(markup! {
{micros}<Dim>"µs"</Dim>
});
}
let nanos = self.as_nanos();
fmt.write_markup(markup! {
{nanos}<Dim>"ns"</Dim>
})
}
}
#[repr(transparent)]
#[derive(Clone, Copy, Debug)]
pub struct Bytes(pub usize);
impl std::fmt::Display for Bytes {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self(mut value) = *self;
if value < 1024 {
return write!(fmt, "{value} B");
}
const PREFIX: [char; 4] = ['K', 'M', 'G', 'T'];
let prefix = PREFIX
.into_iter()
.find(|_| {
let next_value = value / 1024;
if next_value < 1024 {
return true;
}
value = next_value;
false
})
.unwrap_or('T');
write!(fmt, "{:.1} {prefix}iB", value as f32 / 1024.0)
}
}
impl Display for Bytes {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
write!(fmt, "{self}")
}
}
#[cfg(test)]
mod tests {
use crate::fmt::Bytes;
#[test]
fn display_bytes() {
// Examples taken from https://stackoverflow.com/a/3758880
assert_eq!(Bytes(0).to_string(), "0 B");
assert_eq!(Bytes(27).to_string(), "27 B");
assert_eq!(Bytes(999).to_string(), "999 B");
assert_eq!(Bytes(1_000).to_string(), "1000 B");
assert_eq!(Bytes(1_023).to_string(), "1023 B");
assert_eq!(Bytes(1_024).to_string(), "1.0 KiB");
assert_eq!(Bytes(1_728).to_string(), "1.7 KiB");
assert_eq!(Bytes(110_592).to_string(), "108.0 KiB");
assert_eq!(Bytes(999_999).to_string(), "976.6 KiB");
assert_eq!(Bytes(7_077_888).to_string(), "6.8 MiB");
assert_eq!(Bytes(452_984_832).to_string(), "432.0 MiB");
assert_eq!(Bytes(28_991_029_248).to_string(), "27.0 GiB");
assert_eq!(Bytes(1_855_425_871_872).to_string(), "1.7 TiB");
#[cfg(target_pointer_width = "32")]
assert_eq!(Bytes(usize::MAX).to_string(), "4.0 GiB");
#[cfg(target_pointer_width = "64")]
assert_eq!(Bytes(usize::MAX).to_string(), "16384.0 TiB");
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/src/write/html.rs | crates/rome_console/src/write/html.rs | use std::{
fmt,
io::{self, Write as _},
};
use crate::{fmt::MarkupElements, MarkupElement};
use super::Write;
/// Adapter struct implementing [Write] over types implementing [io::Write],
/// renders markup as UTF-8 strings of HTML code
pub struct HTML<W>(pub W);
impl<W> Write for HTML<W>
where
W: io::Write,
{
fn write_str(&mut self, elements: &MarkupElements, content: &str) -> io::Result<()> {
push_styles(&mut self.0, elements)?;
EscapeAdapter(&mut self.0).write_all(content.as_bytes())?;
pop_styles(&mut self.0, elements)
}
fn write_fmt(&mut self, elements: &MarkupElements, content: fmt::Arguments) -> io::Result<()> {
push_styles(&mut self.0, elements)?;
EscapeAdapter(&mut self.0).write_fmt(content)?;
pop_styles(&mut self.0, elements)
}
}
fn push_styles<W: io::Write>(fmt: &mut W, elements: &MarkupElements) -> io::Result<()> {
elements.for_each(&mut |styles| {
for style in styles {
match style {
MarkupElement::Emphasis => write!(fmt, "<strong>")?,
MarkupElement::Dim => write!(fmt, "<span style=\"opacity: 0.8;\">")?,
MarkupElement::Italic => write!(fmt, "<i>")?,
MarkupElement::Underline => write!(fmt, "<u>")?,
MarkupElement::Error => write!(fmt, "<span style=\"color: Tomato;\">")?,
MarkupElement::Success => write!(fmt, "<span style=\"color: MediumSeaGreen;\">")?,
MarkupElement::Warn => write!(fmt, "<span style=\"color: Orange;\">")?,
MarkupElement::Info => write!(fmt, "<span style=\"color: rgb(38, 148, 255);\">")?,
MarkupElement::Inverse => {
write!(fmt, "<span style=\"color: #000; background-color: #ddd;\">")?
}
MarkupElement::Hyperlink { href } => write!(fmt, "<a href=\"{href}\">")?,
}
}
Ok(())
})
}
fn pop_styles<W: io::Write>(fmt: &mut W, elements: &MarkupElements) -> io::Result<()> {
elements.for_each_rev(&mut |styles| {
for style in styles.iter().rev() {
match style {
MarkupElement::Emphasis => write!(fmt, "</strong>")?,
MarkupElement::Italic => write!(fmt, "</i>")?,
MarkupElement::Underline => write!(fmt, "</u>")?,
MarkupElement::Dim
| MarkupElement::Error
| MarkupElement::Success
| MarkupElement::Warn
| MarkupElement::Info
| MarkupElement::Inverse => write!(fmt, "</span>")?,
MarkupElement::Hyperlink { .. } => write!(fmt, "</a>")?,
}
}
Ok(())
})
}
/// Adapter wrapping a type implementing [io::Write] and adding HTML special
/// characters escaping to the written byte sequence
struct EscapeAdapter<W>(W);
impl<W: io::Write> io::Write for EscapeAdapter<W> {
fn write(&mut self, mut buf: &[u8]) -> io::Result<usize> {
let mut bytes = 0;
const HTML_ESCAPES: [u8; 4] = [b'"', b'&', b'<', b'>'];
while let Some(idx) = buf.iter().position(|b| HTML_ESCAPES.contains(b)) {
let (before, after) = buf.split_at(idx);
self.0.write_all(before)?;
bytes += before.len();
// SAFETY: Because of the above `position` match we know the buffer
// contains at least the matching byte
let (byte, after) = after.split_first().unwrap();
match *byte {
b'"' => self.0.write_all(b""")?,
b'&' => self.0.write_all(b"&")?,
b'<' => self.0.write_all(b"<")?,
b'>' => self.0.write_all(b">")?,
_ => unreachable!(),
}
// Only 1 byte of the input was written
bytes += 1;
buf = after;
}
self.0.write_all(buf)?;
bytes += buf.len();
Ok(bytes)
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/src/write/termcolor.rs | crates/rome_console/src/write/termcolor.rs | use std::{
fmt::{self, Write as _},
io,
};
use termcolor::{Color, ColorSpec, WriteColor};
use unicode_width::UnicodeWidthChar;
use crate::{fmt::MarkupElements, MarkupElement};
use super::Write;
/// Adapter struct implementing [Write] over types implementing [WriteColor]
pub struct Termcolor<W>(pub W);
impl<W> Write for Termcolor<W>
where
W: WriteColor,
{
fn write_str(&mut self, elements: &MarkupElements, content: &str) -> io::Result<()> {
with_format(&mut self.0, elements, |writer| {
let mut adapter = SanitizeAdapter {
writer,
error: Ok(()),
};
match adapter.write_str(content) {
Ok(()) => Ok(()),
Err(..) => {
if adapter.error.is_err() {
adapter.error
} else {
// SanitizeAdapter can only fail if the underlying
// writer returns an error
unreachable!()
}
}
}
})
}
fn write_fmt(&mut self, elements: &MarkupElements, content: fmt::Arguments) -> io::Result<()> {
with_format(&mut self.0, elements, |writer| {
let mut adapter = SanitizeAdapter {
writer,
error: Ok(()),
};
match adapter.write_fmt(content) {
Ok(()) => Ok(()),
Err(..) => {
if adapter.error.is_err() {
adapter.error
} else {
Err(io::Error::new(
io::ErrorKind::Other,
"a Display formatter returned an error",
))
}
}
}
})
}
}
/// Applies the current format in `state` to `writer`, calls `func` to
/// print a piece of text, then reset the printing format
fn with_format<W>(
writer: &mut W,
state: &MarkupElements,
func: impl FnOnce(&mut W) -> io::Result<()>,
) -> io::Result<()>
where
W: WriteColor,
{
let mut color = ColorSpec::new();
let mut link = None;
let mut inverse = false;
state.for_each(&mut |elements| {
for element in elements {
match element {
MarkupElement::Inverse => {
inverse = !inverse;
}
MarkupElement::Hyperlink { href } => {
link = Some(href);
}
_ => {
element.update_color(&mut color);
}
}
}
Ok(())
})?;
if inverse {
let fg = color.fg().map_or(Color::White, |c| *c);
let bg = color.bg().map_or(Color::Black, |c| *c);
color.set_bg(Some(fg));
color.set_fg(Some(bg));
}
if let Err(err) = writer.set_color(&color) {
writer.reset()?;
return Err(err);
}
let mut reset_link = false;
if let Some(href) = link {
// `is_synchronous` is used to check if the underlying writer
// is using the Windows Console API, that does not support ANSI
// escape codes. Generally this would only be true when running
// in the legacy `cmd.exe` terminal emulator, since in modern
// clients like the Windows Terminal ANSI is used instead
if writer.supports_color() && !writer.is_synchronous() {
write!(writer, "\x1b]8;;{href}\x1b\\")?;
reset_link = true;
}
}
let result = func(writer);
if reset_link {
write!(writer, "\x1b]8;;\x1b\\")?;
}
writer.reset()?;
result
}
/// Adapter [fmt::Write] calls to [io::Write] with sanitization,
/// implemented as an internal struct to avoid exposing [fmt::Write] on
/// [Termcolor]
struct SanitizeAdapter<W> {
writer: W,
error: io::Result<()>,
}
impl<W> fmt::Write for SanitizeAdapter<W>
where
W: WriteColor,
{
fn write_str(&mut self, content: &str) -> fmt::Result {
let mut buffer = [0; 4];
for item in content.chars() {
// Replace non-whitespace, zero-width characters with the Unicode replacement character
let is_whitespace = item.is_whitespace();
let is_zero_width = UnicodeWidthChar::width(item).map_or(true, |width| width == 0);
let item = if !is_whitespace && is_zero_width {
char::REPLACEMENT_CHARACTER
} else if cfg!(windows) || !self.writer.supports_color() {
// Unicode is currently poorly supported on most Windows
// terminal clients, so we always strip emojis in Windows
unicode_to_ascii(item)
} else {
item
};
item.encode_utf8(&mut buffer);
if let Err(err) = self.writer.write_all(&buffer[..item.len_utf8()]) {
self.error = Err(err);
return Err(fmt::Error);
}
}
Ok(())
}
}
/// Replace emoji characters with similar but more widely supported ASCII
/// characters
fn unicode_to_ascii(c: char) -> char {
match c {
'\u{2714}' => '\u{221a}',
'\u{2139}' => 'i',
'\u{26a0}' => '!',
'\u{2716}' => '\u{00d7}',
_ => c,
}
}
#[cfg(test)]
mod tests {
use std::{fmt::Write, str::from_utf8};
use rome_markup::markup;
use termcolor::Ansi;
use crate as rome_console;
use crate::fmt::Formatter;
use super::{SanitizeAdapter, Termcolor};
#[test]
fn test_sanitize() {
// Sanitization should leave whitespace control characters (space,
// tabs, newline, ...) and non-ASCII unicode characters as-is but
// redact zero-width characters (RTL override, null character, bell,
// zero-width space, ...)
const INPUT: &str = "t\tes t\r\n\u{202D}t\0es\x07t\u{202E}\nt\u{200B}es🐛t";
const OUTPUT: &str = "t\tes t\r\n\u{FFFD}t\u{FFFD}es\u{FFFD}t\u{FFFD}\nt\u{FFFD}es🐛t";
let mut buffer = Vec::new();
{
let writer = termcolor::Ansi::new(&mut buffer);
let mut adapter = SanitizeAdapter {
writer,
error: Ok(()),
};
adapter.write_str(INPUT).unwrap();
adapter.error.unwrap();
}
assert_eq!(from_utf8(&buffer).unwrap(), OUTPUT);
}
#[test]
fn test_hyperlink() {
const OUTPUT: &str = "\x1b[0m\x1b]8;;https://rome.tools/\x1b\\link\x1b]8;;\x1b\\\x1b[0m";
let mut buffer = Vec::new();
let mut writer = Termcolor(Ansi::new(&mut buffer));
let mut formatter = Formatter::new(&mut writer);
formatter
.write_markup(markup! {
<Hyperlink href="https://rome.tools/">"link"</Hyperlink>
})
.unwrap();
assert_eq!(from_utf8(&buffer).unwrap(), OUTPUT);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/macro.rs | crates/rome_console/tests/macro.rs | use rome_console::{Markup, MarkupElement};
#[test]
fn test_macro() {
let category = "test";
match
// Due to how MarkupNode is implemented, the result of the markup macro
// cannot be stored in a binding and must be matched upon immediately
rome_markup::markup! {
<Info><Emphasis>{category}</Emphasis>" Commands"</Info>
}
{
Markup(markup) => {
let node_0 = &markup[0];
assert_eq!(&node_0.elements, &[MarkupElement::Info, MarkupElement::Emphasis]);
// assert_eq!(node_0.content.to_string(), category.to_string());
let node_1 = &markup[1];
assert_eq!(&node_1.elements, &[MarkupElement::Info]);
// assert_eq!(node_1.content.to_string(), " Commands".to_string());
}
}
}
#[test]
fn test_macro_attributes() {
rome_markup::markup! {
<Hyperlink href="https://rome.tools/">"link"</Hyperlink>
};
}
#[test]
fn test_macro_errors() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/markup/*.rs");
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/markup/open_element_unfinished_4.rs | crates/rome_console/tests/markup/open_element_unfinished_4.rs | fn main() {
rome_console::markup! {
<Emphasis prop
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/markup/open_element_unfinished_3.rs | crates/rome_console/tests/markup/open_element_unfinished_3.rs | fn main() {
rome_console::markup! {
<Emphasis /
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/markup/unclosed_element.rs | crates/rome_console/tests/markup/unclosed_element.rs | fn main() {
rome_console::markup! {
<Emphasis>
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/markup/open_element_unfinished_2.rs | crates/rome_console/tests/markup/open_element_unfinished_2.rs | fn main() {
rome_console::markup! {
<Emphasis
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/markup/open_element_improper_prop_value.rs | crates/rome_console/tests/markup/open_element_improper_prop_value.rs | fn main() {
rome_console::markup! {
<Emphasis property=ident />
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/markup/open_element_improper_close_2.rs | crates/rome_console/tests/markup/open_element_improper_close_2.rs | fn main() {
rome_console::markup! {
<Emphasis /"Literal"
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/markup/open_element_unfinished_5.rs | crates/rome_console/tests/markup/open_element_unfinished_5.rs | fn main() {
rome_console::markup! {
<Emphasis prop=
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/markup/open_element_improper_close_1.rs | crates/rome_console/tests/markup/open_element_improper_close_1.rs | fn main() {
rome_console::markup! {
<Emphasis /<
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/markup/open_element_unfinished_6.rs | crates/rome_console/tests/markup/open_element_unfinished_6.rs | fn main() {
rome_console::markup! {
<Emphasis prop={}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/markup/element_non_ident_name.rs | crates/rome_console/tests/markup/element_non_ident_name.rs | fn main() {
rome_console::markup! {
<"Literal" />
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/markup/invalid_group.rs | crates/rome_console/tests/markup/invalid_group.rs | fn main() {
rome_console::markup! {
[]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.