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_formatter/src/ts/any/type_member.rs | crates/rome_js_formatter/src/ts/any/type_member.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_js_syntax::AnyTsTypeMember;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyTsTypeMember;
impl FormatRule<AnyTsTypeMember> for FormatAnyTsTypeMember {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyTsTypeMember, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyTsTypeMember::TsCallSignatureTypeMember(node) => node.format().fmt(f),
AnyTsTypeMember::TsPropertySignatureTypeMember(node) => node.format().fmt(f),
AnyTsTypeMember::TsConstructSignatureTypeMember(node) => node.format().fmt(f),
AnyTsTypeMember::TsMethodSignatureTypeMember(node) => node.format().fmt(f),
AnyTsTypeMember::TsGetterSignatureTypeMember(node) => node.format().fmt(f),
AnyTsTypeMember::TsSetterSignatureTypeMember(node) => node.format().fmt(f),
AnyTsTypeMember::TsIndexSignatureTypeMember(node) => node.format().fmt(f),
AnyTsTypeMember::JsBogusMember(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_js_formatter/src/ts/any/property_signature_annotation.rs | crates/rome_js_formatter/src/ts/any/property_signature_annotation.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_js_syntax::AnyTsPropertySignatureAnnotation;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyTsPropertySignatureAnnotation;
impl FormatRule<AnyTsPropertySignatureAnnotation> for FormatAnyTsPropertySignatureAnnotation {
type Context = JsFormatContext;
fn fmt(
&self,
node: &AnyTsPropertySignatureAnnotation,
f: &mut JsFormatter,
) -> FormatResult<()> {
match node {
AnyTsPropertySignatureAnnotation::TsTypeAnnotation(node) => node.format().fmt(f),
AnyTsPropertySignatureAnnotation::TsOptionalPropertyAnnotation(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_js_formatter/src/ts/any/method_signature_modifier.rs | crates/rome_js_formatter/src/ts/any/method_signature_modifier.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_js_syntax::AnyTsMethodSignatureModifier;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyTsMethodSignatureModifier;
impl FormatRule<AnyTsMethodSignatureModifier> for FormatAnyTsMethodSignatureModifier {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyTsMethodSignatureModifier, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyTsMethodSignatureModifier::TsAccessibilityModifier(node) => node.format().fmt(f),
AnyTsMethodSignatureModifier::JsDecorator(node) => node.format().fmt(f),
AnyTsMethodSignatureModifier::JsStaticModifier(node) => node.format().fmt(f),
AnyTsMethodSignatureModifier::TsOverrideModifier(node) => node.format().fmt(f),
AnyTsMethodSignatureModifier::TsAbstractModifier(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_js_formatter/src/ts/any/template_element.rs | crates/rome_js_formatter/src/ts/any/template_element.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_js_syntax::AnyTsTemplateElement;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyTsTemplateElement;
impl FormatRule<AnyTsTemplateElement> for FormatAnyTsTemplateElement {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyTsTemplateElement, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyTsTemplateElement::TsTemplateChunkElement(node) => node.format().fmt(f),
AnyTsTemplateElement::TsTemplateElement(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_js_formatter/src/ts/any/property_signature_modifier.rs | crates/rome_js_formatter/src/ts/any/property_signature_modifier.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_js_syntax::AnyTsPropertySignatureModifier;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyTsPropertySignatureModifier;
impl FormatRule<AnyTsPropertySignatureModifier> for FormatAnyTsPropertySignatureModifier {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyTsPropertySignatureModifier, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyTsPropertySignatureModifier::TsDeclareModifier(node) => node.format().fmt(f),
AnyTsPropertySignatureModifier::TsAccessibilityModifier(node) => node.format().fmt(f),
AnyTsPropertySignatureModifier::JsStaticModifier(node) => node.format().fmt(f),
AnyTsPropertySignatureModifier::JsDecorator(node) => node.format().fmt(f),
AnyTsPropertySignatureModifier::JsAccessorModifier(node) => node.format().fmt(f),
AnyTsPropertySignatureModifier::TsReadonlyModifier(node) => node.format().fmt(f),
AnyTsPropertySignatureModifier::TsOverrideModifier(node) => node.format().fmt(f),
AnyTsPropertySignatureModifier::TsAbstractModifier(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_js_formatter/src/ts/any/type_predicate_parameter_name.rs | crates/rome_js_formatter/src/ts/any/type_predicate_parameter_name.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_js_syntax::AnyTsTypePredicateParameterName;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyTsTypePredicateParameterName;
impl FormatRule<AnyTsTypePredicateParameterName> for FormatAnyTsTypePredicateParameterName {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyTsTypePredicateParameterName, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyTsTypePredicateParameterName::JsReferenceIdentifier(node) => node.format().fmt(f),
AnyTsTypePredicateParameterName::TsThisType(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_js_formatter/src/ts/any/ts_type.rs | crates/rome_js_formatter/src/ts/any/ts_type.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_js_syntax::AnyTsType;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyTsType;
impl FormatRule<AnyTsType> for FormatAnyTsType {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyTsType, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyTsType::TsAnyType(node) => node.format().fmt(f),
AnyTsType::TsUnknownType(node) => node.format().fmt(f),
AnyTsType::TsNumberType(node) => node.format().fmt(f),
AnyTsType::TsBooleanType(node) => node.format().fmt(f),
AnyTsType::TsBigintType(node) => node.format().fmt(f),
AnyTsType::TsStringType(node) => node.format().fmt(f),
AnyTsType::TsSymbolType(node) => node.format().fmt(f),
AnyTsType::TsVoidType(node) => node.format().fmt(f),
AnyTsType::TsUndefinedType(node) => node.format().fmt(f),
AnyTsType::TsNeverType(node) => node.format().fmt(f),
AnyTsType::TsParenthesizedType(node) => node.format().fmt(f),
AnyTsType::TsReferenceType(node) => node.format().fmt(f),
AnyTsType::TsArrayType(node) => node.format().fmt(f),
AnyTsType::TsTupleType(node) => node.format().fmt(f),
AnyTsType::TsTypeofType(node) => node.format().fmt(f),
AnyTsType::TsImportType(node) => node.format().fmt(f),
AnyTsType::TsTypeOperatorType(node) => node.format().fmt(f),
AnyTsType::TsIndexedAccessType(node) => node.format().fmt(f),
AnyTsType::TsMappedType(node) => node.format().fmt(f),
AnyTsType::TsObjectType(node) => node.format().fmt(f),
AnyTsType::TsNonPrimitiveType(node) => node.format().fmt(f),
AnyTsType::TsThisType(node) => node.format().fmt(f),
AnyTsType::TsNumberLiteralType(node) => node.format().fmt(f),
AnyTsType::TsBigintLiteralType(node) => node.format().fmt(f),
AnyTsType::TsStringLiteralType(node) => node.format().fmt(f),
AnyTsType::TsNullLiteralType(node) => node.format().fmt(f),
AnyTsType::TsBooleanLiteralType(node) => node.format().fmt(f),
AnyTsType::TsTemplateLiteralType(node) => node.format().fmt(f),
AnyTsType::TsInferType(node) => node.format().fmt(f),
AnyTsType::TsIntersectionType(node) => node.format().fmt(f),
AnyTsType::TsUnionType(node) => node.format().fmt(f),
AnyTsType::TsFunctionType(node) => node.format().fmt(f),
AnyTsType::TsConstructorType(node) => node.format().fmt(f),
AnyTsType::TsConditionalType(node) => node.format().fmt(f),
AnyTsType::TsBogusType(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_js_formatter/src/ts/any/variable_annotation.rs | crates/rome_js_formatter/src/ts/any/variable_annotation.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_js_syntax::AnyTsVariableAnnotation;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyTsVariableAnnotation;
impl FormatRule<AnyTsVariableAnnotation> for FormatAnyTsVariableAnnotation {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyTsVariableAnnotation, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyTsVariableAnnotation::TsTypeAnnotation(node) => node.format().fmt(f),
AnyTsVariableAnnotation::TsDefiniteVariableAnnotation(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_js_formatter/src/ts/any/mod.rs | crates/rome_js_formatter/src/ts/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 external_module_declaration_body;
pub(crate) mod index_signature_modifier;
pub(crate) mod method_signature_modifier;
pub(crate) mod module_name;
pub(crate) mod module_reference;
pub(crate) mod name;
pub(crate) mod property_annotation;
pub(crate) mod property_parameter_modifier;
pub(crate) mod property_signature_annotation;
pub(crate) mod property_signature_modifier;
pub(crate) mod return_type;
pub(crate) mod template_element;
pub(crate) mod ts_type;
pub(crate) mod tuple_type_element;
pub(crate) mod type_member;
pub(crate) mod type_parameter_modifier;
pub(crate) mod type_predicate_parameter_name;
pub(crate) mod variable_annotation;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/ts/any/tuple_type_element.rs | crates/rome_js_formatter/src/ts/any/tuple_type_element.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_js_syntax::AnyTsTupleTypeElement;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyTsTupleTypeElement;
impl FormatRule<AnyTsTupleTypeElement> for FormatAnyTsTupleTypeElement {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyTsTupleTypeElement, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyTsTupleTypeElement::TsNamedTupleTypeElement(node) => node.format().fmt(f),
AnyTsTupleTypeElement::AnyTsType(node) => node.format().fmt(f),
AnyTsTupleTypeElement::TsRestTupleTypeElement(node) => node.format().fmt(f),
AnyTsTupleTypeElement::TsOptionalTupleTypeElement(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_js_formatter/src/ts/any/name.rs | crates/rome_js_formatter/src/ts/any/name.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_js_syntax::AnyTsName;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyTsName;
impl FormatRule<AnyTsName> for FormatAnyTsName {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyTsName, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyTsName::JsReferenceIdentifier(node) => node.format().fmt(f),
AnyTsName::TsQualifiedName(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_js_formatter/src/ts/any/module_reference.rs | crates/rome_js_formatter/src/ts/any/module_reference.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_js_syntax::AnyTsModuleReference;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyTsModuleReference;
impl FormatRule<AnyTsModuleReference> for FormatAnyTsModuleReference {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyTsModuleReference, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyTsModuleReference::AnyTsName(node) => node.format().fmt(f),
AnyTsModuleReference::TsExternalModuleReference(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_js_formatter/src/ts/any/property_annotation.rs | crates/rome_js_formatter/src/ts/any/property_annotation.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_js_syntax::AnyTsPropertyAnnotation;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyTsPropertyAnnotation;
impl FormatRule<AnyTsPropertyAnnotation> for FormatAnyTsPropertyAnnotation {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyTsPropertyAnnotation, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyTsPropertyAnnotation::TsTypeAnnotation(node) => node.format().fmt(f),
AnyTsPropertyAnnotation::TsOptionalPropertyAnnotation(node) => node.format().fmt(f),
AnyTsPropertyAnnotation::TsDefinitePropertyAnnotation(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_js_formatter/src/ts/any/type_parameter_modifier.rs | crates/rome_js_formatter/src/ts/any/type_parameter_modifier.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_js_syntax::AnyTsTypeParameterModifier;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyTsTypeParameterModifier;
impl FormatRule<AnyTsTypeParameterModifier> for FormatAnyTsTypeParameterModifier {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyTsTypeParameterModifier, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyTsTypeParameterModifier::TsConstModifier(node) => node.format().fmt(f),
AnyTsTypeParameterModifier::TsInModifier(node) => node.format().fmt(f),
AnyTsTypeParameterModifier::TsOutModifier(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_js_formatter/src/ts/any/return_type.rs | crates/rome_js_formatter/src/ts/any/return_type.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_js_syntax::AnyTsReturnType;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyTsReturnType;
impl FormatRule<AnyTsReturnType> for FormatAnyTsReturnType {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyTsReturnType, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyTsReturnType::AnyTsType(node) => node.format().fmt(f),
AnyTsReturnType::TsPredicateReturnType(node) => node.format().fmt(f),
AnyTsReturnType::TsAssertsReturnType(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_js_formatter/src/ts/any/property_parameter_modifier.rs | crates/rome_js_formatter/src/ts/any/property_parameter_modifier.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_js_syntax::AnyTsPropertyParameterModifier;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyTsPropertyParameterModifier;
impl FormatRule<AnyTsPropertyParameterModifier> for FormatAnyTsPropertyParameterModifier {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyTsPropertyParameterModifier, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyTsPropertyParameterModifier::TsAccessibilityModifier(node) => node.format().fmt(f),
AnyTsPropertyParameterModifier::TsReadonlyModifier(node) => node.format().fmt(f),
AnyTsPropertyParameterModifier::TsOverrideModifier(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_js_formatter/src/context/trailing_comma.rs | crates/rome_js_formatter/src/context/trailing_comma.rs | use crate::prelude::*;
use crate::{JsFormatContext, JsFormatOptions};
use rome_deserialize::json::with_only_known_variants;
use rome_deserialize::{DeserializationDiagnostic, VisitNode};
use rome_formatter::formatter::Formatter;
use rome_formatter::prelude::{if_group_breaks, text};
use rome_formatter::write;
use rome_formatter::{Format, FormatResult};
use rome_json_syntax::JsonLanguage;
use rome_rowan::SyntaxNode;
use std::fmt;
use std::str::FromStr;
/// This enum is used within formatting functions to print or omit trailing comma.
#[derive(Debug, Copy, Clone)]
pub(crate) enum FormatTrailingComma {
/// Print trailing comma if the option is [TrailingComma::All].
All,
/// Print trailing comma if the option is [TrailingComma::All] or [TrailingComma::Es5].
ES5,
}
impl FormatTrailingComma {
/// This function returns corresponding [TrailingSeparator] for [format_separated] function.
pub fn trailing_separator(&self, options: &JsFormatOptions) -> TrailingSeparator {
if options.trailing_comma.is_none() {
return TrailingSeparator::Omit;
}
match self {
FormatTrailingComma::All => {
if options.trailing_comma.is_all() {
TrailingSeparator::Allowed
} else {
TrailingSeparator::Omit
}
}
FormatTrailingComma::ES5 => TrailingSeparator::Allowed,
}
}
}
impl Format<JsFormatContext> for FormatTrailingComma {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
if f.options().trailing_comma.is_none() {
return Ok(());
}
if matches!(self, FormatTrailingComma::ES5) || f.options().trailing_comma().is_all() {
write!(f, [if_group_breaks(&text(","))])?
}
Ok(())
}
}
/// Print trailing commas wherever possible in multi-line comma-separated syntactic structures.
#[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema),
serde(rename_all = "camelCase")
)]
pub enum TrailingComma {
/// Trailing commas wherever possible (including function parameters and calls).
#[default]
All,
/// Trailing commas where valid in ES5 (objects, arrays, etc.). No trailing commas in type parameters in TypeScript.
Es5,
/// No trailing commas.
None,
}
impl TrailingComma {
pub(crate) const KNOWN_VALUES: &'static [&'static str] = &["all", "es5", "none"];
pub const fn is_es5(&self) -> bool {
matches!(self, TrailingComma::Es5)
}
pub const fn is_all(&self) -> bool {
matches!(self, TrailingComma::All)
}
pub const fn is_none(&self) -> bool {
matches!(self, TrailingComma::None)
}
}
impl FromStr for TrailingComma {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"es5" | "ES5" => Ok(Self::Es5),
"all" | "All" => Ok(Self::All),
"none" | "None" => Ok(Self::None),
// TODO: replace this error with a diagnostic
_ => Err("Value not supported for TrailingComma"),
}
}
}
impl fmt::Display for TrailingComma {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TrailingComma::Es5 => std::write!(f, "ES5"),
TrailingComma::All => std::write!(f, "All"),
TrailingComma::None => std::write!(f, "None"),
}
}
}
impl VisitNode<JsonLanguage> for TrailingComma {
fn visit_member_value(
&mut self,
node: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let node = with_only_known_variants(node, TrailingComma::KNOWN_VALUES, diagnostics)?;
match node.inner_string_text().ok()?.text() {
"all" => {
*self = TrailingComma::All;
}
"es5" => {
*self = TrailingComma::Es5;
}
"none" => {
*self = TrailingComma::None;
}
_ => {}
}
Some(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/tests/quick_test.rs | crates/rome_js_formatter/tests/quick_test.rs | use rome_formatter_test::check_reformat::CheckReformat;
use rome_js_formatter::context::{ArrowParentheses, JsFormatOptions, QuoteStyle, Semicolons};
use rome_js_formatter::format_node;
use rome_js_parser::{parse, JsParserOptions};
use rome_js_syntax::JsFileSource;
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#"
(action: h) => {}
(action?) => {}
(action
// yes
) => {}
({ action }) => {}
([ action ]) => {}
(...action) => {}
(action = 1) => {}
"#;
let syntax = JsFileSource::tsx();
let tree = parse(
src,
syntax,
JsParserOptions::default().with_parse_class_parameter_decorators(),
);
let options = JsFormatOptions::new(syntax)
.with_semicolons(Semicolons::Always)
.with_quote_style(QuoteStyle::Double)
.with_jsx_quote_style(QuoteStyle::Single)
.with_arrow_parentheses(ArrowParentheses::AsNeeded);
let result = format_node(options.clone(), &tree.syntax())
.unwrap()
.print()
.unwrap();
let root = &tree.syntax();
let language = language::JsTestFormatLanguage::new(JsFileSource::tsx());
let check_reformat =
CheckReformat::new(root, result.as_code(), "quick_test", &language, options);
check_reformat.check_reformat();
// I don't know why semicolons are added there, but it's not related to my code changes so ¯\_(ツ)_/¯
assert_eq!(
result.as_code(),
r#"(action: h) => {};
(action?) => {};
(
action,
// yes
) => {};
({ action }) => {};
([action]) => {};
(...action) => {};
(action = 1) => {};
"#
);
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/tests/spec_test.rs | crates/rome_js_formatter/tests/spec_test.rs | use rome_formatter_test::spec::{SpecSnapshot, SpecTestFile};
use rome_js_formatter::context::JsFormatOptions;
use rome_js_syntax::{JsFileSource, ModuleKind};
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 mut source_type: JsFileSource = test_file.input_file().as_path().try_into().unwrap();
if file_type != "module" {
source_type = source_type.with_module_kind(ModuleKind::Script);
}
let options = JsFormatOptions::new(source_type);
let language = language::JsTestFormatLanguage::new(source_type);
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_js_formatter/tests/prettier_tests.rs | crates/rome_js_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_js_formatter::context::JsFormatOptions;
use rome_js_syntax::JsFileSource;
mod language;
tests_macros::gen_tests! {"tests/specs/prettier/{js,typescript,jsx}/**/*.{js,ts,jsx,tsx}", crate::test_snapshot, "script"}
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 source_type = {
// Prettier testing suite uses JSX tags inside JS files.
// As there's no way to know in advance which files have JSX syntax, we
// change the source type only here
if test_file.file_extension() == "js" {
JsFileSource::jsx()
} else if test_file.file_name().contains("jsx") && test_file.file_extension() == "ts" {
JsFileSource::tsx()
} else {
test_file.input_file().try_into().unwrap()
}
};
let options = JsFormatOptions::new(source_type).with_indent_style(IndentStyle::Space(2));
let language = language::JsTestFormatLanguage::new(source_type);
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_js_formatter/tests/spec_tests.rs | crates/rome_js_formatter/tests/spec_tests.rs | mod quick_test;
mod spec_test;
mod formatter {
mod js_module {
tests_macros::gen_tests! {"tests/specs/js/module/**/*.js", crate::spec_test::run, "module"}
}
mod js_script {
tests_macros::gen_tests! {"tests/specs/js/script/**/*.js", crate::spec_test::run, "script"}
}
mod ts_module {
tests_macros::gen_tests! {"tests/specs/ts/**/*.ts", crate::spec_test::run, "module"}
}
mod jsx_module {
tests_macros::gen_tests! {"tests/specs/jsx/**/*.jsx", crate::spec_test::run, "module"}
}
mod tsx_module {
tests_macros::gen_tests! {"tests/specs/tsx/**/*.tsx", crate::spec_test::run, "module"}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/tests/language.rs | crates/rome_js_formatter/tests/language.rs | use rome_formatter::{FormatContext, FormatResult, Formatted, IndentStyle, LineWidth, Printed};
use rome_formatter_test::TestFormatLanguage;
use rome_js_formatter::context::trailing_comma::TrailingComma;
use rome_js_formatter::context::{
ArrowParentheses, JsFormatContext, JsFormatOptions, QuoteProperties, QuoteStyle, Semicolons,
};
use rome_js_formatter::{format_node, format_range, JsFormatLanguage};
use rome_js_parser::{parse, JsParserOptions};
use rome_js_syntax::{JsFileSource, JsLanguage};
use rome_parser::AnyParse;
use rome_rowan::{FileSource, SyntaxNode};
use rome_text_size::TextRange;
use serde::{Deserialize, Serialize};
pub struct JsTestFormatLanguage {
source_type: JsFileSource,
}
impl JsTestFormatLanguage {
pub fn new(source_type: JsFileSource) -> Self {
JsTestFormatLanguage { source_type }
}
}
impl TestFormatLanguage for JsTestFormatLanguage {
type SyntaxLanguage = JsLanguage;
type Options = JsFormatOptions;
type Context = JsFormatContext;
type FormatLanguage = JsFormatLanguage;
fn parse(&self, text: &str) -> AnyParse {
let parse = parse(
text,
self.source_type,
JsParserOptions::default().with_parse_class_parameter_decorators(),
);
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_format_options(self.source_type))
.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 JsSerializableIndentStyle {
/// Tab
Tab,
/// Space, with its quantity
Space(u8),
}
impl From<JsSerializableIndentStyle> for IndentStyle {
fn from(test: JsSerializableIndentStyle) -> Self {
match test {
JsSerializableIndentStyle::Tab => IndentStyle::Tab,
JsSerializableIndentStyle::Space(spaces) => IndentStyle::Space(spaces),
}
}
}
#[derive(Debug, Eq, PartialEq, Clone, Copy, Deserialize, Serialize)]
pub enum JsSerializableQuoteStyle {
Double,
Single,
}
impl From<JsSerializableQuoteStyle> for QuoteStyle {
fn from(test: JsSerializableQuoteStyle) -> Self {
match test {
JsSerializableQuoteStyle::Double => QuoteStyle::Double,
JsSerializableQuoteStyle::Single => QuoteStyle::Single,
}
}
}
#[derive(Debug, Eq, PartialEq, Clone, Copy, Deserialize, Serialize)]
pub enum JsSerializableQuoteProperties {
AsNeeded,
Preserve,
}
impl From<JsSerializableQuoteProperties> for QuoteProperties {
fn from(test: JsSerializableQuoteProperties) -> Self {
match test {
JsSerializableQuoteProperties::AsNeeded => QuoteProperties::AsNeeded,
JsSerializableQuoteProperties::Preserve => QuoteProperties::Preserve,
}
}
}
#[derive(Debug, Eq, PartialEq, Clone, Copy, Deserialize, Serialize)]
pub enum JsSerializableTrailingComma {
All,
ES5,
None,
}
impl From<JsSerializableTrailingComma> for TrailingComma {
fn from(test: JsSerializableTrailingComma) -> Self {
match test {
JsSerializableTrailingComma::All => TrailingComma::All,
JsSerializableTrailingComma::ES5 => TrailingComma::Es5,
JsSerializableTrailingComma::None => TrailingComma::None,
}
}
}
#[derive(Debug, Eq, PartialEq, Clone, Copy, Deserialize, Serialize)]
pub enum JsSerializableSemicolons {
Always,
AsNeeded,
}
impl From<JsSerializableSemicolons> for Semicolons {
fn from(test: JsSerializableSemicolons) -> Self {
match test {
JsSerializableSemicolons::Always => Semicolons::Always,
JsSerializableSemicolons::AsNeeded => Semicolons::AsNeeded,
}
}
}
#[derive(Debug, Eq, PartialEq, Clone, Copy, Deserialize, Serialize)]
pub enum JsSerializableArrowParentheses {
Always,
AsNeeded,
}
impl From<JsSerializableArrowParentheses> for ArrowParentheses {
fn from(test: JsSerializableArrowParentheses) -> Self {
match test {
JsSerializableArrowParentheses::Always => ArrowParentheses::Always,
JsSerializableArrowParentheses::AsNeeded => ArrowParentheses::AsNeeded,
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone, Copy)]
pub struct JsSerializableFormatOptions {
/// The indent style.
pub indent_style: Option<JsSerializableIndentStyle>,
/// What's the max width of a line. Defaults to 80.
pub line_width: Option<u16>,
/// The style for quotes. Defaults to double.
pub quote_style: Option<JsSerializableQuoteStyle>,
/// The style for JSX quotes. Defaults to double.
pub jsx_quote_style: Option<JsSerializableQuoteStyle>,
/// When properties in objects are quoted. Defaults to as-needed.
pub quote_properties: Option<JsSerializableQuoteProperties>,
/// Print trailing commas wherever possible in multi-line comma-separated syntactic structures. Defaults to "all".
pub trailing_comma: Option<JsSerializableTrailingComma>,
/// Whether the formatter prints semicolons for all statements or only in for statements where it is necessary because of ASI.
pub semicolons: Option<JsSerializableSemicolons>,
/// Whether to add non-necessary parentheses to arrow functions. Defaults to "always".
pub arrow_parentheses: Option<JsSerializableArrowParentheses>,
}
impl JsSerializableFormatOptions {
fn into_format_options(self, source_type: JsFileSource) -> JsFormatOptions {
JsFormatOptions::new(source_type)
.with_indent_style(
self.indent_style
.map_or_else(|| IndentStyle::Tab, |value| value.into()),
)
.with_line_width(
self.line_width
.and_then(|width| LineWidth::try_from(width).ok())
.unwrap_or_default(),
)
.with_jsx_quote_style(
self.jsx_quote_style
.map_or_else(|| QuoteStyle::Double, |value| value.into()),
)
.with_quote_style(
self.quote_style
.map_or_else(|| QuoteStyle::Double, |value| value.into()),
)
.with_quote_properties(
self.quote_properties
.map_or_else(|| QuoteProperties::AsNeeded, |value| value.into()),
)
.with_trailing_comma(
self.trailing_comma
.map_or_else(|| TrailingComma::All, |value| value.into()),
)
.with_semicolons(
self.semicolons
.map_or_else(|| Semicolons::Always, |value| value.into()),
)
.with_arrow_parentheses(
self.arrow_parentheses
.map_or_else(|| ArrowParentheses::Always, |value| value.into()),
)
}
}
#[derive(Debug, Deserialize, Serialize)]
struct TestOptions {
cases: Vec<JsSerializableFormatOptions>,
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/benches/iai.rs | crates/rome_js_formatter/benches/iai.rs | use rome_formatter::token::string::ToAsciiLowercaseCow;
fn to_ascii_lowercase() {
let _ = str::to_ascii_lowercase(iai::black_box("lowercase"));
let _ = str::to_ascii_lowercase(iai::black_box("upperCASE"));
}
fn to_ascii_lowercase_cow() {
let _ = str::to_ascii_lowercase_cow(iai::black_box("lowercase"));
let _ = str::to_ascii_lowercase_cow(iai::black_box("upperCASE"));
}
iai::main!(to_ascii_lowercase, to_ascii_lowercase_cow);
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_markup/src/lib.rs | crates/rome_markup/src/lib.rs | use proc_macro2::{Delimiter, Group, Ident, TokenStream, TokenTree};
use proc_macro_error::*;
use quote::{quote, ToTokens};
struct StackEntry {
name: Ident,
attributes: Vec<(Ident, TokenTree)>,
}
impl ToTokens for StackEntry {
fn to_tokens(&self, tokens: &mut TokenStream) {
let name = &self.name;
tokens.extend(quote! {
rome_console::MarkupElement::#name
});
if !self.attributes.is_empty() {
let attributes: Vec<_> = self
.attributes
.iter()
.map(|(key, value)| quote! { #key: (#value).into() })
.collect();
tokens.extend(quote! { { #( #attributes ),* } })
}
}
}
#[proc_macro]
#[proc_macro_error]
pub fn markup(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let mut input = TokenStream::from(input).into_iter().peekable();
let mut stack = Vec::new();
let mut output = Vec::new();
while let Some(token) = input.next() {
match token {
TokenTree::Punct(punct) => match punct.as_char() {
'<' => {
let is_closing_element = match input.peek() {
Some(TokenTree::Punct(punct)) if punct.as_char() == '/' => {
// SAFETY: Guarded by above call to peek
input.next().unwrap();
true
}
_ => false,
};
let name = match input.next() {
Some(TokenTree::Ident(ident)) => ident,
Some(token) => abort!(token.span(), "unexpected token"),
None => abort_call_site!("unexpected end of input"),
};
let mut attributes = Vec::new();
while let Some(TokenTree::Ident(_)) = input.peek() {
// SAFETY: these panics are checked by the above call to peek
let attr = match input.next().unwrap() {
TokenTree::Ident(attr) => attr,
_ => unreachable!(),
};
match input.next() {
Some(TokenTree::Punct(punct)) => {
if punct.as_char() != '=' {
abort!(punct.span(), "unexpected token");
}
}
Some(token) => abort!(token.span(), "unexpected token"),
None => abort_call_site!("unexpected end of input"),
}
let value = match input.next() {
Some(TokenTree::Literal(value)) => TokenTree::Literal(value),
Some(TokenTree::Group(group)) => {
TokenTree::Group(Group::new(Delimiter::None, group.stream()))
}
Some(token) => abort!(token.span(), "unexpected token"),
None => abort_call_site!("unexpected end of input"),
};
attributes.push((attr, value));
}
let is_self_closing = match input.next() {
Some(TokenTree::Punct(punct)) => match punct.as_char() {
'>' => false,
'/' if !is_closing_element => {
match input.next() {
Some(TokenTree::Punct(punct)) if punct.as_char() == '>' => {}
Some(token) => abort!(token.span(), "unexpected token"),
None => abort_call_site!("unexpected end of input"),
}
true
}
_ => abort!(punct.span(), "unexpected token"),
},
Some(token) => abort!(token.span(), "unexpected token"),
None => abort_call_site!("unexpected end of input"),
};
if !is_closing_element {
stack.push(StackEntry {
name: name.clone(),
attributes: attributes.clone(),
});
} else if let Some(top) = stack.last() {
// Only verify the coherence of the top element on the
// stack with a closing element, skip over the check if
// the stack is empty as that error will be handled
// when the top element gets popped off the stack later
let name_str = name.to_string();
let top_str = top.name.to_string();
if name_str != top_str {
abort!(
name.span(), "closing element mismatch";
close = "found closing element {}", name_str;
open = top.name.span() => "expected {}", top_str
);
}
}
if (is_closing_element || is_self_closing) && stack.pop().is_none() {
abort!(name.span(), "unexpected closing element");
}
}
_ => {
abort!(punct.span(), "unexpected token");
}
},
TokenTree::Literal(literal) => {
let elements: Vec<_> = stack
.iter()
.map(|entry| {
quote! { #entry }
})
.collect();
output.push(quote! {
rome_console::MarkupNode {
elements: &[ #( #elements ),* ],
content: &(#literal),
}
});
}
TokenTree::Group(group) => match group.delimiter() {
Delimiter::Brace => {
let elements: Vec<_> = stack.iter().map(|entry| quote! { #entry }).collect();
let body = group.stream();
output.push(quote! {
rome_console::MarkupNode {
elements: &[ #( #elements ),* ],
content: &(#body) as &dyn rome_console::fmt::Display,
}
});
}
_ => abort!(group.span(), "unexpected token"),
},
_ => abort!(token.span(), "unexpected token"),
}
}
if let Some(top) = stack.pop() {
abort!(top.name.span(), "unclosed element");
}
quote! { rome_console::Markup(&[ #( #output ),* ]) }.into()
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/utility_types.rs | crates/rome_rowan/src/utility_types.rs | use std::{fmt, ops::Deref};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum NodeOrToken<N, T> {
Node(N),
Token(T),
}
impl<N, T> NodeOrToken<N, T> {
pub fn into_node(self) -> Option<N> {
match self {
NodeOrToken::Node(node) => Some(node),
NodeOrToken::Token(_) => None,
}
}
pub fn into_token(self) -> Option<T> {
match self {
NodeOrToken::Node(_) => None,
NodeOrToken::Token(token) => Some(token),
}
}
pub fn as_node(&self) -> Option<&N> {
match self {
NodeOrToken::Node(node) => Some(node),
NodeOrToken::Token(_) => None,
}
}
pub fn as_token(&self) -> Option<&T> {
match self {
NodeOrToken::Node(_) => None,
NodeOrToken::Token(token) => Some(token),
}
}
}
impl<N: Deref, T: Deref> NodeOrToken<N, T> {
pub(crate) fn as_deref(&self) -> NodeOrToken<&N::Target, &T::Target> {
match self {
NodeOrToken::Node(node) => NodeOrToken::Node(&**node),
NodeOrToken::Token(token) => NodeOrToken::Token(&**token),
}
}
}
impl<N: fmt::Display, T: fmt::Display> fmt::Display for NodeOrToken<N, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
NodeOrToken::Node(node) => fmt::Display::fmt(node, f),
NodeOrToken::Token(token) => fmt::Display::fmt(token, f),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Direction {
Next,
Prev,
}
/// `WalkEvent` describes tree walking process.
#[derive(Debug, Copy, Clone)]
pub enum WalkEvent<T> {
/// Fired before traversing the node.
Enter(T),
/// Fired after the node is traversed.
Leave(T),
}
impl<T> WalkEvent<T> {
pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> WalkEvent<U> {
match self {
WalkEvent::Enter(it) => WalkEvent::Enter(f(it)),
WalkEvent::Leave(it) => WalkEvent::Leave(f(it)),
}
}
}
/// There might be zero, one or two leaves at a given offset.
#[derive(Clone, Debug)]
pub enum TokenAtOffset<T> {
/// No leaves at offset -- possible for the empty file.
None,
/// Only a single leaf at offset.
Single(T),
/// Offset is exactly between two leaves.
Between(T, T),
}
impl<T> TokenAtOffset<T> {
pub fn map<F: Fn(T) -> U, U>(self, f: F) -> TokenAtOffset<U> {
match self {
TokenAtOffset::None => TokenAtOffset::None,
TokenAtOffset::Single(it) => TokenAtOffset::Single(f(it)),
TokenAtOffset::Between(l, r) => TokenAtOffset::Between(f(l), f(r)),
}
}
/// Convert to option, preferring the right leaf in case of a tie.
pub fn right_biased(self) -> Option<T> {
match self {
TokenAtOffset::None => None,
TokenAtOffset::Single(node) => Some(node),
TokenAtOffset::Between(_, right) => Some(right),
}
}
/// Convert to option, preferring the left leaf in case of a tie.
pub fn left_biased(self) -> Option<T> {
match self {
TokenAtOffset::None => None,
TokenAtOffset::Single(node) => Some(node),
TokenAtOffset::Between(left, _) => Some(left),
}
}
}
impl<T> Iterator for TokenAtOffset<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
match std::mem::replace(self, TokenAtOffset::None) {
TokenAtOffset::None => None,
TokenAtOffset::Single(node) => {
*self = TokenAtOffset::None;
Some(node)
}
TokenAtOffset::Between(left, right) => {
*self = TokenAtOffset::Single(right);
Some(left)
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self {
TokenAtOffset::None => (0, Some(0)),
TokenAtOffset::Single(_) => (1, Some(1)),
TokenAtOffset::Between(_, _) => (2, Some(2)),
}
}
}
impl<T> ExactSizeIterator for TokenAtOffset<T> {}
#[cfg(target_pointer_width = "64")]
#[macro_export]
macro_rules! static_assert {
($expr:expr) => {
const _: i32 = 0 / $expr as i32;
};
}
#[cfg(target_pointer_width = "64")]
pub use static_assert;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/cursor.rs | crates/rome_rowan/src/cursor.rs | //! Implementation of the cursors -- API for convenient access to syntax trees.
//!
//! Functional programmers will recognize that this module implements a zipper
//! for a purely functional (green) tree.
//!
//! A cursor node (`SyntaxNode`) points to a `GreenNode` and a parent
//! `SyntaxNode`. This allows cursor to provide iteration over both ancestors
//! and descendants, as well as a cheep access to absolute offset of the node in
//! file.
//!
// Implementation notes:
//
// The implementation is utterly and horribly unsafe. This whole module is an
// unsafety boundary. It is believed that the API here is, in principle, sound,
// but the implementation might have bugs.
//
// The core type is `NodeData` -- a heap-allocated reference counted object,
// which points to a green node or a green token, and to the parent `NodeData`.
// Publicly-exposed `SyntaxNode` and `SyntaxToken` own a reference to
// `NodeData`.
//
// `NodeData`s are transient, and are created and destroyed during tree
// traversals. In general, only currently referenced nodes and their ancestors
// are alive at any given moment.
//
// More specifically, `NodeData`'s ref count is equal to the number of
// outstanding `SyntaxNode` and `SyntaxToken` plus the number of children with
// non-zero ref counts. For example, if the user has only a single `SyntaxNode`
// pointing somewhere in the middle of the tree, then all `NodeData` on the path
// from that point towards the root have ref count equal to one.
//
// `NodeData` which doesn't have a parent (is a root) owns the corresponding
// green node or token, and is responsible for freeing it. For child `NodeData`
// however since they hold a strong reference to their parent node and thus
// to the root, their corresponding green node is guaranteed to be alive as
// a reference cycle to is know to exist (child `NodeData` -> root `NodeData`
// -> root `GreenNode` -> child `GreenNode`) and they can safely use a "weak
// reference" (raw pointer) to the corresponding green node as an optimization
// to avoid having to track atomic references on the traversal hot path
mod element;
mod node;
mod token;
mod trivia;
use std::{iter, ops};
use std::{ptr, rc::Rc};
use countme::Count;
pub(crate) use trivia::{SyntaxTrivia, SyntaxTriviaPiecesIterator};
use crate::cursor::node::Siblings;
pub(crate) use crate::cursor::token::SyntaxToken;
use crate::green::{self, GreenElement, GreenNodeData, GreenTokenData};
use crate::{
green::{GreenElementRef, RawSyntaxKind},
NodeOrToken, TextRange, TextSize,
};
pub(crate) use element::SyntaxElement;
pub(crate) use node::{
Preorder, PreorderWithTokens, SyntaxElementChildren, SyntaxNode, SyntaxNodeChildren,
SyntaxSlot, SyntaxSlots,
};
#[derive(Debug)]
struct _SyntaxElement;
pub(crate) fn has_live() -> bool {
countme::get::<_SyntaxElement>().live > 0
}
#[derive(Debug)]
struct NodeData {
_c: Count<_SyntaxElement>,
kind: NodeKind,
slot: u32,
/// Absolute offset for immutable nodes, unused for mutable nodes.
offset: TextSize,
}
/// A single NodeData (red node) is either a "root node" (no parent node and
/// holds a strong reference to the root of the green tree) or a "child node"
/// (holds a strong reference to its parent red node and a weak reference to its
/// counterpart green node)
#[derive(Debug)]
enum NodeKind {
Root {
green: GreenElement,
},
Child {
green: WeakGreenElement,
parent: Rc<NodeData>,
},
}
/// Child SyntaxNodes use "unsafe" weak pointers to refer to their green node.
/// Unlike the safe [std::sync::Weak] these are just a raw pointer: the
/// corresponding [ThinArc](crate::arc::ThinArc) doesn't keep a counter of
/// outstanding weak references or defer the release of the underlying memory
/// until the last `Weak` is dropped. On the other hand, a weak reference to a
/// released green node points to deallocated memory and it is undefined
/// behavior to dereference it, but in the context of `NodeData` this is
/// statically known to never happen
#[derive(Debug, Clone)]
enum WeakGreenElement {
Node { ptr: ptr::NonNull<GreenNodeData> },
Token { ptr: ptr::NonNull<GreenTokenData> },
}
impl WeakGreenElement {
fn new(green: GreenElementRef) -> Self {
match green {
NodeOrToken::Node(ptr) => Self::Node {
ptr: ptr::NonNull::from(ptr),
},
NodeOrToken::Token(ptr) => Self::Token {
ptr: ptr::NonNull::from(ptr),
},
}
}
fn as_deref(&self) -> GreenElementRef {
match self {
WeakGreenElement::Node { ptr } => GreenElementRef::Node(unsafe { ptr.as_ref() }),
WeakGreenElement::Token { ptr } => GreenElementRef::Token(unsafe { ptr.as_ref() }),
}
}
fn to_owned(&self) -> GreenElement {
match self {
WeakGreenElement::Node { ptr } => {
GreenElement::Node(unsafe { ptr.as_ref().to_owned() })
}
WeakGreenElement::Token { ptr } => {
GreenElement::Token(unsafe { ptr.as_ref().to_owned() })
}
}
}
}
impl NodeData {
#[inline]
fn new(kind: NodeKind, slot: u32, offset: TextSize) -> Rc<NodeData> {
let res = NodeData {
_c: Count::new(),
kind,
slot,
offset,
};
Rc::new(res)
}
#[inline]
fn key(&self) -> (ptr::NonNull<()>, TextSize) {
let weak = match &self.kind {
NodeKind::Root { green } => WeakGreenElement::new(green.as_deref()),
NodeKind::Child { green, .. } => green.clone(),
};
let ptr = match weak {
WeakGreenElement::Node { ptr } => ptr.cast(),
WeakGreenElement::Token { ptr } => ptr.cast(),
};
(ptr, self.offset())
}
#[inline]
fn parent_node(&self) -> Option<SyntaxNode> {
debug_assert!(matches!(
self.parent()?.green(),
GreenElementRef::Node { .. }
));
match &self.kind {
NodeKind::Child { parent, .. } => Some(SyntaxNode {
ptr: parent.clone(),
}),
NodeKind::Root { .. } => None,
}
}
#[inline]
fn parent(&self) -> Option<&NodeData> {
match &self.kind {
NodeKind::Child { parent, .. } => Some(&**parent),
NodeKind::Root { .. } => None,
}
}
#[inline]
fn green(&self) -> GreenElementRef<'_> {
match &self.kind {
NodeKind::Root { green } => green.as_deref(),
NodeKind::Child { green, .. } => green.as_deref(),
}
}
/// Returns an iterator over the siblings of this node. The iterator is positioned at the current node.
#[inline]
fn green_siblings(&self) -> Option<Siblings> {
match &self.parent()?.green() {
GreenElementRef::Node(ptr) => Some(Siblings::new(ptr, self.slot())),
GreenElementRef::Token(_) => {
debug_assert!(
false,
"A token should never be a parent of a token or node."
);
None
}
}
}
#[inline]
fn slot(&self) -> u32 {
self.slot
}
#[inline]
fn offset(&self) -> TextSize {
self.offset
}
#[inline]
fn text_range(&self) -> TextRange {
let offset = self.offset();
let len = self.green().text_len();
TextRange::at(offset, len)
}
#[inline]
fn kind(&self) -> RawSyntaxKind {
self.green().kind()
}
fn next_sibling(&self) -> Option<SyntaxNode> {
let siblings = self.green_siblings()?;
siblings.following().find_map(|child| {
child.element().into_node().and_then(|green| {
let parent = self.parent_node()?;
let offset = parent.offset() + child.rel_offset();
Some(SyntaxNode::new_child(green, parent, child.slot(), offset))
})
})
}
fn prev_sibling(&self) -> Option<SyntaxNode> {
let siblings = self.green_siblings()?;
siblings.previous().find_map(|child| {
child.element().into_node().and_then(|green| {
let parent = self.parent_node()?;
let offset = parent.offset() + child.rel_offset();
Some(SyntaxNode::new_child(green, parent, child.slot(), offset))
})
})
}
fn next_sibling_or_token(&self) -> Option<SyntaxElement> {
let siblings = self.green_siblings()?;
siblings.following().next().and_then(|child| {
let parent = self.parent_node()?;
let offset = parent.offset() + child.rel_offset();
Some(SyntaxElement::new(
child.element(),
parent,
child.slot(),
offset,
))
})
}
fn prev_sibling_or_token(&self) -> Option<SyntaxElement> {
let siblings = self.green_siblings()?;
siblings.previous().next().and_then(|child| {
let parent = self.parent_node()?;
let offset = parent.offset() + child.rel_offset();
Some(SyntaxElement::new(
child.element(),
parent,
child.slot(),
offset,
))
})
}
fn into_green(self: Rc<Self>) -> GreenElement {
match Rc::try_unwrap(self) {
Ok(data) => match data.kind {
NodeKind::Root { green } => green,
NodeKind::Child { green, .. } => green.to_owned(),
},
Err(ptr) => ptr.green().to_owned(),
}
}
/// Return a clone of this subtree detached from its parent
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
fn detach(self: Rc<Self>) -> Rc<Self> {
match &self.kind {
NodeKind::Child { green, .. } => Self::new(
NodeKind::Root {
green: green.to_owned(),
},
0,
0.into(),
),
// If this node is already detached, increment the reference count and return a clone
NodeKind::Root { .. } => self.clone(),
}
}
/// Return a clone of this node with the specified range of slots replaced
/// with the elements of the provided iterator
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
fn splice_slots<R, I>(mut self: Rc<Self>, range: R, replace_with: I) -> Rc<Self>
where
R: ops::RangeBounds<usize>,
I: Iterator<Item = Option<green::GreenElement>>,
{
let green = match self.green() {
NodeOrToken::Node(green) => green.splice_slots(range, replace_with).into(),
NodeOrToken::Token(_) => panic!("called splice_slots on a token node"),
};
// Try to reuse the underlying memory allocation if self is the only
// outstanding reference to this NodeData
match Rc::get_mut(&mut self) {
Some(node) => {
node.kind = NodeKind::Root { green };
node.slot = 0;
node.offset = TextSize::from(0);
self
}
None => Self::new(NodeKind::Root { green }, 0, 0.into()),
}
}
/// Return a new version of this node with the element `prev_elem` replaced with `next_elem`
///
/// `prev_elem` can be a direct child of this node, or an indirect child through any descendant node
///
/// Returns `None` if `prev_elem` is not a descendant of this node
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
fn replace_child(
mut self: Rc<Self>,
prev_elem: SyntaxElement,
next_elem: SyntaxElement,
) -> Option<Rc<Self>> {
let mut green = next_elem.into_green();
let mut elem = prev_elem;
loop {
let node = elem.parent()?;
let is_self = node.key() == self.key();
let index = elem.index();
let range = index..=index;
let replace_with = iter::once(Some(green));
green = node.green().splice_slots(range, replace_with).into();
elem = node.into();
if is_self {
break;
}
}
// Try to reuse the underlying memory allocation if self is the only
// outstanding reference to this NodeData
let result = match Rc::get_mut(&mut self) {
Some(node) => {
node.kind = NodeKind::Root { green };
node.slot = 0;
node.offset = TextSize::from(0);
self
}
None => Self::new(NodeKind::Root { green }, 0, 0.into()),
};
Some(result)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/green.rs | crates/rome_rowan/src/green.rs | mod element;
mod node;
mod node_cache;
mod token;
mod trivia;
pub(crate) use self::{
element::{GreenElement, GreenElementRef},
node::{Child, Children, GreenNode, GreenNodeData, Slot},
token::{GreenToken, GreenTokenData},
trivia::GreenTrivia,
};
pub use self::node_cache::NodeCache;
pub(crate) use self::node_cache::NodeCacheNodeEntryMut;
/// RawSyntaxKind is a type tag for each token or node.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RawSyntaxKind(pub u16);
pub(crate) fn has_live() -> bool {
node::has_live() || token::has_live() || trivia::has_live()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::green::trivia::GreenTrivia;
#[test]
fn assert_send_sync() {
fn f<T: Send + Sync>() {}
f::<GreenNode>();
f::<GreenToken>();
f::<GreenElement>();
}
#[test]
fn test_size_of() {
use std::mem::size_of;
assert_eq!(8, size_of::<GreenNode>());
assert_eq!(8, size_of::<GreenToken>());
assert_eq!(8, size_of::<GreenTrivia>());
assert_eq!(16, size_of::<GreenElement>());
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/lib.rs | crates/rome_rowan/src/lib.rs | //! A generic library for lossless syntax trees.
//! See `examples/s_expressions.rs` for a tutorial.
#![forbid(
// missing_debug_implementations,
unconditional_recursion,
future_incompatible,
// missing_docs,
)]
#![deny(unsafe_code)]
#![deny(rustdoc::broken_intra_doc_links)]
#[doc(hidden)]
pub mod macros;
#[allow(unsafe_code)]
pub mod cursor;
#[allow(unsafe_code)]
mod green;
pub mod syntax;
mod syntax_node_text;
mod utility_types;
#[allow(unsafe_code)]
mod arc;
mod ast;
mod cow_mut;
mod file_source;
pub mod raw_language;
#[cfg(feature = "serde")]
mod serde_impls;
mod syntax_factory;
mod token_text;
mod tree_builder;
pub use rome_text_size::{TextLen, TextRange, TextSize};
pub use crate::{
ast::*,
file_source::{AnyFileSource, FileSource, FileSourceError},
green::{NodeCache, RawSyntaxKind},
syntax::{
chain_trivia_pieces, trim_leading_trivia_pieces, trim_trailing_trivia_pieces,
ChainTriviaPiecesIterator, Language, SendNode, SyntaxElement, SyntaxElementChildren,
SyntaxKind, SyntaxList, SyntaxNode, SyntaxNodeChildren, SyntaxNodeOptionExt,
SyntaxRewriter, SyntaxSlot, SyntaxToken, SyntaxTriviaPiece, SyntaxTriviaPieceComments,
TriviaPiece, TriviaPieceKind, VisitNodeSignal,
},
syntax_factory::*,
syntax_node_text::SyntaxNodeText,
token_text::TokenText,
tree_builder::{Checkpoint, TreeBuilder},
utility_types::{Direction, NodeOrToken, TokenAtOffset, WalkEvent},
};
pub(crate) use crate::green::{GreenNode, GreenNodeData, GreenToken, GreenTokenData};
pub fn check_live() -> Option<String> {
if cursor::has_live() || green::has_live() {
Some(countme::get_all().to_string())
} else {
None
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/syntax_node_text.rs | crates/rome_rowan/src/syntax_node_text.rs | use crate::{
cursor::{SyntaxNode, SyntaxToken},
TextRange, TextSize, TokenAtOffset,
};
use rome_text_size::TextLen;
use std::fmt;
use std::iter::FusedIterator;
#[derive(Clone)]
pub struct SyntaxNodeText {
node: SyntaxNode,
range: TextRange,
}
impl SyntaxNodeText {
pub(crate) fn new(node: SyntaxNode) -> SyntaxNodeText {
let range = node.text_range();
SyntaxNodeText { node, range }
}
pub(crate) fn with_range(node: SyntaxNode, range: TextRange) -> SyntaxNodeText {
SyntaxNodeText { node, range }
}
pub fn len(&self) -> TextSize {
self.range.len()
}
pub fn is_empty(&self) -> bool {
self.range.is_empty()
}
pub fn contains_char(&self, c: char) -> bool {
self.try_for_each_chunk(|chunk| if chunk.contains(c) { Err(()) } else { Ok(()) })
.is_err()
}
pub fn find_char(&self, c: char) -> Option<TextSize> {
let mut acc: TextSize = 0.into();
let res = self.try_for_each_chunk(|chunk| {
if let Some(pos) = chunk.find(c) {
let pos: TextSize = (pos as u32).into();
return Err(acc + pos);
}
acc += TextSize::of(chunk);
Ok(())
});
found(res)
}
pub fn char_at(&self, offset: TextSize) -> Option<char> {
let mut start: TextSize = 0.into();
let res = self.try_for_each_chunk(|chunk| {
let end = start + TextSize::of(chunk);
if start <= offset && offset < end {
let off: usize = u32::from(offset - start) as usize;
return Err(chunk[off..].chars().next().unwrap());
}
start = end;
Ok(())
});
found(res)
}
pub fn slice<R: private::SyntaxTextRange>(&self, range: R) -> SyntaxNodeText {
let start = range.start().unwrap_or_default();
let end = range.end().unwrap_or_else(|| self.len());
assert!(start <= end);
let len = end - start;
let start = self.range.start() + start;
let end = start + len;
assert!(
start <= end,
"invalid slice, range: {:?}, slice: {:?}",
self.range,
(range.start(), range.end()),
);
let range = TextRange::new(start, end);
assert!(
self.range.contains_range(range),
"invalid slice, range: {:?}, slice: {:?}",
self.range,
range,
);
SyntaxNodeText {
node: self.node.clone(),
range,
}
}
pub fn try_fold_chunks<T, F, E>(&self, init: T, mut f: F) -> Result<T, E>
where
F: FnMut(T, &str) -> Result<T, E>,
{
self.tokens_with_ranges()
.try_fold(init, move |acc, (token, range)| {
f(acc, &token.text()[range])
})
}
pub fn try_for_each_chunk<F: FnMut(&str) -> Result<(), E>, E>(
&self,
mut f: F,
) -> Result<(), E> {
self.try_fold_chunks((), move |(), chunk| f(chunk))
}
pub fn for_each_chunk<F: FnMut(&str)>(&self, mut f: F) {
enum Void {}
match self.try_for_each_chunk(|chunk| {
f(chunk);
Ok::<(), Void>(())
}) {
Ok(()) => (),
Err(void) => match void {},
}
}
fn tokens_with_ranges(&self) -> impl Iterator<Item = (SyntaxToken, TextRange)> + FusedIterator {
SyntaxNodeTokenWithRanges::new(self)
}
pub fn chars(&self) -> impl Iterator<Item = char> + FusedIterator {
SyntaxNodeTextChars::new(self)
}
}
#[derive(Clone)]
struct SyntaxNodeTokenWithRanges {
text_range: TextRange,
next_token: Option<(SyntaxToken, TextRange)>,
}
impl SyntaxNodeTokenWithRanges {
fn new(text: &SyntaxNodeText) -> Self {
let text_range = text.range;
let token = match text.node.token_at_offset(text_range.start()) {
TokenAtOffset::None => None,
TokenAtOffset::Single(token) => Some(token),
TokenAtOffset::Between(_, next) => Some(next),
};
Self {
next_token: token.and_then(|token| Self::with_intersecting_range(token, text_range)),
text_range,
}
}
fn with_intersecting_range(
token: SyntaxToken,
text_range: TextRange,
) -> Option<(SyntaxToken, TextRange)> {
let token_range = token.text_range();
let range = text_range.intersect(token_range)?;
Some((token, range - token_range.start()))
}
}
impl Iterator for SyntaxNodeTokenWithRanges {
type Item = (SyntaxToken, TextRange);
fn next(&mut self) -> Option<Self::Item> {
let (token, range) = self.next_token.take()?;
self.next_token = token
.next_token()
.and_then(|token| Self::with_intersecting_range(token, self.text_range));
Some((token, range))
}
}
impl FusedIterator for SyntaxNodeTokenWithRanges {}
#[derive(Clone)]
struct SyntaxNodeTextChars {
head: Option<(SyntaxToken, TextRange)>,
tail: SyntaxNodeTokenWithRanges,
index: TextSize,
}
impl SyntaxNodeTextChars {
fn new(text: &SyntaxNodeText) -> Self {
let mut chunks = SyntaxNodeTokenWithRanges::new(text);
Self {
head: chunks.next(),
tail: chunks,
index: TextSize::default(),
}
}
}
impl Iterator for SyntaxNodeTextChars {
type Item = char;
fn next(&mut self) -> Option<Self::Item> {
loop {
let (token, range) = self.head.as_ref()?;
if self.index >= range.end() {
self.head = self.tail.next();
self.index = TextSize::default();
continue;
}
let text = token.text();
// SAFETY: Index check above guarantees that there's at least some text left
let next_char = text[TextRange::new(self.index, range.end())]
.chars()
.next()
.unwrap();
self.index += next_char.text_len();
break Some(next_char);
}
}
}
impl FusedIterator for SyntaxNodeTextChars {}
fn found<T>(res: Result<(), T>) -> Option<T> {
match res {
Ok(()) => None,
Err(it) => Some(it),
}
}
impl fmt::Debug for SyntaxNodeText {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.to_string(), f)
}
}
impl fmt::Display for SyntaxNodeText {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.try_for_each_chunk(|chunk| fmt::Display::fmt(chunk, f))
}
}
impl From<SyntaxNodeText> for String {
fn from(text: SyntaxNodeText) -> String {
text.to_string()
}
}
impl PartialEq<str> for SyntaxNodeText {
fn eq(&self, mut rhs: &str) -> bool {
self.try_for_each_chunk(|chunk| {
if !rhs.starts_with(chunk) {
return Err(());
}
rhs = &rhs[chunk.len()..];
Ok(())
})
.is_ok()
&& rhs.is_empty()
}
}
impl PartialEq<SyntaxNodeText> for str {
fn eq(&self, rhs: &SyntaxNodeText) -> bool {
rhs == self
}
}
impl PartialEq<&'_ str> for SyntaxNodeText {
fn eq(&self, rhs: &&str) -> bool {
self == *rhs
}
}
impl PartialEq<SyntaxNodeText> for &'_ str {
fn eq(&self, rhs: &SyntaxNodeText) -> bool {
rhs == self
}
}
impl PartialEq for SyntaxNodeText {
fn eq(&self, other: &SyntaxNodeText) -> bool {
if self.range.len() != other.range.len() {
return false;
}
let mut lhs = self.tokens_with_ranges();
let mut rhs = other.tokens_with_ranges();
zip_texts(&mut lhs, &mut rhs).is_none()
&& lhs.all(|it| it.1.is_empty())
&& rhs.all(|it| it.1.is_empty())
}
}
fn zip_texts<I: Iterator<Item = (SyntaxToken, TextRange)>>(xs: &mut I, ys: &mut I) -> Option<()> {
let mut x = xs.next()?;
let mut y = ys.next()?;
loop {
while x.1.is_empty() {
x = xs.next()?;
}
while y.1.is_empty() {
y = ys.next()?;
}
let x_text = &x.0.text()[x.1];
let y_text = &y.0.text()[y.1];
if !(x_text.starts_with(y_text) || y_text.starts_with(x_text)) {
return Some(());
}
let advance = std::cmp::min(x.1.len(), y.1.len());
x.1 = TextRange::new(x.1.start() + advance, x.1.end());
y.1 = TextRange::new(y.1.start() + advance, y.1.end());
}
}
impl Eq for SyntaxNodeText {}
mod private {
use std::ops;
use crate::{TextRange, TextSize};
pub trait SyntaxTextRange {
fn start(&self) -> Option<TextSize>;
fn end(&self) -> Option<TextSize>;
}
impl SyntaxTextRange for TextRange {
fn start(&self) -> Option<TextSize> {
Some(TextRange::start(*self))
}
fn end(&self) -> Option<TextSize> {
Some(TextRange::end(*self))
}
}
impl SyntaxTextRange for ops::Range<TextSize> {
fn start(&self) -> Option<TextSize> {
Some(self.start)
}
fn end(&self) -> Option<TextSize> {
Some(self.end)
}
}
impl SyntaxTextRange for ops::RangeFrom<TextSize> {
fn start(&self) -> Option<TextSize> {
Some(self.start)
}
fn end(&self) -> Option<TextSize> {
None
}
}
impl SyntaxTextRange for ops::RangeTo<TextSize> {
fn start(&self) -> Option<TextSize> {
None
}
fn end(&self) -> Option<TextSize> {
Some(self.end)
}
}
impl SyntaxTextRange for ops::RangeFull {
fn start(&self) -> Option<TextSize> {
None
}
fn end(&self) -> Option<TextSize> {
None
}
}
}
#[cfg(test)]
mod tests {
use crate::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
use crate::SyntaxNode;
fn build_tree(chunks: &[&str]) -> SyntaxNode<RawLanguage> {
let mut builder = RawSyntaxTreeBuilder::new();
builder.start_node(RawLanguageKind::ROOT);
for &chunk in chunks.iter() {
builder.token(RawLanguageKind::STRING_TOKEN, chunk);
}
builder.finish_node();
builder.finish()
}
#[test]
fn test_text_equality() {
fn do_check(t1: &[&str], t2: &[&str]) {
let t1 = build_tree(t1).text();
let t2 = build_tree(t2).text();
let expected = t1.to_string() == t2.to_string();
let actual = t1 == t2;
assert_eq!(
expected, actual,
"`{}` (SyntaxText) `{}` (SyntaxText)",
t1, t2
);
let actual = t1 == *t2.to_string();
assert_eq!(expected, actual, "`{}` (SyntaxText) `{}` (&str)", t1, t2);
}
fn check(t1: &[&str], t2: &[&str]) {
do_check(t1, t2);
do_check(t2, t1)
}
check(&[""], &[""]);
check(&["a"], &[""]);
check(&["a"], &["a"]);
check(&["abc"], &["def"]);
check(&["hello", "world"], &["hello", "world"]);
check(&["hellowo", "rld"], &["hell", "oworld"]);
check(&["hel", "lowo", "rld"], &["helloworld"]);
check(&["{", "abc", "}"], &["{", "123", "}"]);
check(&["{", "abc", "}", "{"], &["{", "123", "}"]);
check(&["{", "abc", "}"], &["{", "123", "}", "{"]);
check(&["{", "abc", "}ab"], &["{", "abc", "}", "ab"]);
}
#[test]
fn test_chars() {
fn check(t1: &[&str], expected: &str) {
let t1 = build_tree(t1).text();
let actual = t1.chars().collect::<String>();
assert_eq!(
expected, &actual,
"`{}` (SyntaxText) `{}` (SyntaxText)",
actual, expected
);
}
check(&[""], "");
check(&["a"], "a");
check(&["hello", "world"], "helloworld");
check(&["hellowo", "rld"], "helloworld");
check(&["hel", "lowo", "rld"], "helloworld");
check(&["{", "abc", "}"], "{abc}");
check(&["{", "abc", "}", "{"], "{abc}{");
check(&["{", "abc", "}ab"], "{abc}ab");
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/syntax.rs | crates/rome_rowan/src/syntax.rs | mod element;
mod node;
mod rewriter;
mod token;
mod trivia;
use crate::{AstNode, RawSyntaxKind};
pub use element::{SyntaxElement, SyntaxElementKey};
pub(crate) use node::SyntaxSlots;
pub use node::{
Preorder, PreorderWithTokens, SendNode, SyntaxElementChildren, SyntaxNode, SyntaxNodeChildren,
SyntaxNodeOptionExt, SyntaxSlot,
};
pub use rewriter::{SyntaxRewriter, VisitNodeSignal};
use std::fmt;
use std::fmt::Debug;
pub use token::SyntaxToken;
pub use trivia::{
chain_trivia_pieces, trim_leading_trivia_pieces, trim_trailing_trivia_pieces,
ChainTriviaPiecesIterator, SyntaxTrivia, SyntaxTriviaPiece, SyntaxTriviaPieceComments,
SyntaxTriviaPieceNewline, SyntaxTriviaPieceSkipped, SyntaxTriviaPieceWhitespace,
SyntaxTriviaPiecesIterator, TriviaPiece, TriviaPieceKind,
};
/// Type tag for each node or token of a language
pub trait SyntaxKind: fmt::Debug + PartialEq + Copy {
const TOMBSTONE: Self;
const EOF: Self;
/// Returns `true` if this is a kind of a bogus node.
fn is_bogus(&self) -> bool;
/// Converts this into to the best matching bogus node kind.
fn to_bogus(&self) -> Self;
/// Converts this kind to a raw syntax kind.
fn to_raw(&self) -> RawSyntaxKind;
/// Creates a syntax kind from a raw kind.
fn from_raw(raw: RawSyntaxKind) -> Self;
/// Returns `true` if this kind is for a root node.
fn is_root(&self) -> bool;
/// Returns `true` if this kind is a list node.
fn is_list(&self) -> bool;
/// Returns a string for keywords and punctuation tokens or `None` otherwise.
fn to_string(&self) -> Option<&'static str>;
}
pub trait Language: Sized + Clone + Copy + fmt::Debug + Eq + Ord + std::hash::Hash {
type Kind: SyntaxKind;
type Root: AstNode<Language = Self> + Clone + Eq + fmt::Debug;
}
/// A list of `SyntaxNode`s and/or `SyntaxToken`s
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct SyntaxList<L: Language> {
list: SyntaxNode<L>,
}
impl<L: Language> SyntaxList<L> {
/// Creates a new list wrapping a List `SyntaxNode`
fn new(node: SyntaxNode<L>) -> Self {
Self { list: node }
}
/// Iterates over the elements in the list.
pub fn iter(&self) -> SyntaxSlots<L> {
self.list.slots()
}
/// Returns the number of items in this list
pub fn len(&self) -> usize {
self.list.slots().len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn first(&self) -> Option<SyntaxSlot<L>> {
self.list.slots().next()
}
pub fn last(&self) -> Option<SyntaxSlot<L>> {
self.list.slots().last()
}
pub fn node(&self) -> &SyntaxNode<L> {
&self.list
}
pub fn into_node(self) -> SyntaxNode<L> {
self.list
}
}
impl<L: Language> IntoIterator for &SyntaxList<L> {
type Item = SyntaxSlot<L>;
type IntoIter = SyntaxSlots<L>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<L: Language> IntoIterator for SyntaxList<L> {
type Item = SyntaxSlot<L>;
type IntoIter = SyntaxSlots<L>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[cfg(test)]
mod tests {
use rome_text_size::TextRange;
use crate::raw_language::{RawLanguageKind, RawSyntaxTreeBuilder};
use crate::syntax::TriviaPiece;
use crate::Direction;
#[test]
fn empty_list() {
let mut builder: RawSyntaxTreeBuilder = RawSyntaxTreeBuilder::new();
builder.start_node(RawLanguageKind::EXPRESSION_LIST);
builder.finish_node();
let list = builder.finish().into_list();
assert!(list.is_empty());
assert_eq!(list.len(), 0);
assert_eq!(list.first(), None);
assert_eq!(list.last(), None);
assert_eq!(list.iter().collect::<Vec<_>>(), Vec::default());
}
#[test]
fn node_list() {
let mut builder = RawSyntaxTreeBuilder::new();
builder.start_node(RawLanguageKind::EXPRESSION_LIST);
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::NUMBER_TOKEN, "1");
builder.finish_node();
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::NUMBER_TOKEN, "2");
builder.finish_node();
builder.finish_node();
let node = builder.finish();
let list = node.into_list();
assert!(!list.is_empty());
assert_eq!(list.len(), 2);
let first = list.first().and_then(|e| e.into_node()).unwrap();
assert_eq!(first.kind(), RawLanguageKind::LITERAL_EXPRESSION);
assert_eq!(first.text(), "1");
let last = list.last().and_then(|e| e.into_node()).unwrap();
assert_eq!(last.kind(), RawLanguageKind::LITERAL_EXPRESSION);
assert_eq!(last.text(), "2");
let node_texts: Vec<_> = list
.iter()
.map(|e| e.into_node().map(|n| n.text().to_string()))
.collect();
assert_eq!(
node_texts,
vec![Some(String::from("1")), Some(String::from("2"))]
)
}
#[test]
fn node_or_token_list() {
let mut builder = RawSyntaxTreeBuilder::new();
builder.start_node(RawLanguageKind::SEPARATED_EXPRESSION_LIST);
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::NUMBER_TOKEN, "1");
builder.finish_node();
builder.token(RawLanguageKind::NUMBER_TOKEN, ",");
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::NUMBER_TOKEN, "2");
builder.finish_node();
builder.finish_node();
let node = builder.finish();
let list = node.into_list();
assert!(!list.is_empty());
assert_eq!(list.len(), 3);
let first = list.first().and_then(|e| e.into_node()).unwrap();
assert_eq!(first.kind(), RawLanguageKind::LITERAL_EXPRESSION);
assert_eq!(first.text(), "1");
let last = list.last().and_then(|e| e.into_node()).unwrap();
assert_eq!(last.kind(), RawLanguageKind::LITERAL_EXPRESSION);
assert_eq!(last.text(), "2");
let kinds: Vec<_> = list.iter().map(|e| e.kind()).collect();
assert_eq!(
kinds,
vec![
Some(RawLanguageKind::LITERAL_EXPRESSION),
Some(RawLanguageKind::NUMBER_TOKEN),
Some(RawLanguageKind::LITERAL_EXPRESSION)
]
)
}
#[test]
fn siblings() {
let mut builder = RawSyntaxTreeBuilder::new();
// list
builder.start_node(RawLanguageKind::SEPARATED_EXPRESSION_LIST);
// element 1
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::NUMBER_TOKEN, "a");
builder.finish_node();
// element 2
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::NUMBER_TOKEN, "b");
builder.finish_node();
// Missing ,
// element 3
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::NUMBER_TOKEN, "c");
builder.finish_node();
builder.finish_node();
let root = builder.finish();
let first = root.children().next().unwrap();
assert_eq!(first.text().to_string(), "a");
assert_eq!(
first.next_sibling().map(|e| e.text().to_string()),
Some(String::from("b"))
);
let second = root.children().nth(1).unwrap();
assert_eq!(second.text().to_string(), "b");
// Skips the missing element
assert_eq!(
second.next_sibling().map(|e| e.text().to_string()),
Some(String::from("c"))
);
assert_eq!(
second.prev_sibling().map(|e| e.text().to_string()),
Some(String::from("a"))
);
let last = root.children().last().unwrap();
assert_eq!(last.text(), "c");
assert_eq!(last.next_sibling(), None);
assert_eq!(
last.prev_sibling().map(|e| e.text().to_string()),
Some(String::from("b"))
);
assert_eq!(
first
.siblings(Direction::Next)
.map(|s| s.text().to_string())
.collect::<Vec<_>>(),
vec!["a", "b", "c"]
);
assert_eq!(
last.siblings(Direction::Prev)
.map(|s| s.text().to_string())
.collect::<Vec<_>>(),
vec!["c", "b", "a"]
);
}
#[test]
fn siblings_with_tokens() {
let mut builder = RawSyntaxTreeBuilder::new();
builder.start_node(RawLanguageKind::ROOT);
builder.token(RawLanguageKind::FOR_KW, "for");
builder.token(RawLanguageKind::L_PAREN_TOKEN, "(");
builder.token(RawLanguageKind::SEMICOLON_TOKEN, ";");
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::STRING_TOKEN, "x");
builder.finish_node();
builder.token(RawLanguageKind::SEMICOLON_TOKEN, ";");
builder.token(RawLanguageKind::R_PAREN_TOKEN, ")");
builder.finish_node();
let root = builder.finish();
let first_semicolon = root
.children_with_tokens()
.nth(2)
.and_then(|e| e.into_token())
.unwrap();
assert_eq!(first_semicolon.text(), ";");
assert_eq!(
first_semicolon
.siblings_with_tokens(Direction::Next)
.map(|e| e.to_string())
.collect::<Vec<_>>(),
vec!["x", ";", ")"]
);
assert_eq!(
first_semicolon.next_sibling_or_token(),
first_semicolon.siblings_with_tokens(Direction::Next).next()
);
assert_eq!(
first_semicolon.prev_sibling_or_token(),
first_semicolon.siblings_with_tokens(Direction::Prev).next()
);
}
#[test]
pub fn syntax_text_and_len() {
let mut builder = RawSyntaxTreeBuilder::new();
builder.start_node(RawLanguageKind::ROOT);
builder.token_with_trivia(
RawLanguageKind::LET_TOKEN,
"\n\t let \t\t",
&[TriviaPiece::whitespace(3)],
&[TriviaPiece::whitespace(3)],
);
builder.finish_node();
// // Node texts
let node = builder.finish();
assert_eq!("\n\t let \t\t", node.text());
assert_eq!("let", node.text_trimmed());
assert_eq!("\n\t ", node.first_leading_trivia().unwrap().text());
assert_eq!(" \t\t", node.last_trailing_trivia().unwrap().text());
// Token texts
let token = node.first_token().unwrap();
assert_eq!("\n\t let \t\t", token.text());
assert_eq!("let", token.text_trimmed());
assert_eq!("\n\t ", token.leading_trivia().text());
assert_eq!(" \t\t", token.trailing_trivia().text());
}
#[test]
pub fn syntax_range() {
let mut builder = RawSyntaxTreeBuilder::new();
builder.start_node(RawLanguageKind::ROOT);
builder.token_with_trivia(
RawLanguageKind::LET_TOKEN,
"\n\t let \t\t",
&[TriviaPiece::whitespace(3)],
&[TriviaPiece::whitespace(3)],
);
builder.token_with_trivia(
RawLanguageKind::LET_TOKEN,
"a ",
&[TriviaPiece::whitespace(0)],
&[TriviaPiece::whitespace(1)],
);
builder.token_with_trivia(
RawLanguageKind::EQUAL_TOKEN,
"\n=\n",
&[TriviaPiece::whitespace(1)],
&[TriviaPiece::whitespace(1)],
);
builder.token(RawLanguageKind::NUMBER_TOKEN, "1");
builder.token_with_trivia(
RawLanguageKind::SEMICOLON_TOKEN,
";\t\t",
&[],
&[TriviaPiece::whitespace(2)],
);
builder.finish_node();
let node = builder.finish();
// Node Ranges
assert_eq!(TextRange::new(0.into(), 18.into()), node.text_range());
assert_eq!(
TextRange::new(3.into(), 16.into()),
node.text_trimmed_range()
);
assert_eq!(
TextRange::new(0.into(), 3.into()),
node.first_leading_trivia().unwrap().text_range()
);
assert_eq!(
TextRange::new(16.into(), 18.into()),
node.last_trailing_trivia().unwrap().text_range()
);
// as NodeOrToken
let eq_token = node
.descendants_with_tokens(Direction::Next)
.find(|x| x.kind() == RawLanguageKind::EQUAL_TOKEN)
.unwrap();
assert_eq!(TextRange::new(11.into(), 14.into()), eq_token.text_range());
assert_eq!(
TextRange::new(12.into(), 13.into()),
eq_token.text_trimmed_range()
);
assert_eq!(
TextRange::new(11.into(), 12.into()),
eq_token.leading_trivia().unwrap().text_range()
);
assert_eq!(
TextRange::new(13.into(), 14.into()),
eq_token.trailing_trivia().unwrap().text_range()
);
// as Token
let eq_token = eq_token.as_token().unwrap();
assert_eq!(TextRange::new(11.into(), 14.into()), eq_token.text_range());
assert_eq!(
TextRange::new(12.into(), 13.into()),
eq_token.text_trimmed_range()
);
assert_eq!(
TextRange::new(11.into(), 12.into()),
eq_token.leading_trivia().text_range()
);
assert_eq!(
TextRange::new(13.into(), 14.into()),
eq_token.trailing_trivia().text_range()
);
}
#[test]
pub fn syntax_trivia_pieces() {
use crate::*;
let node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
builder.token_with_trivia(
RawLanguageKind::LET_TOKEN,
"\n\t /**/let \t\t",
&[
TriviaPiece::whitespace(3),
TriviaPiece::single_line_comment(4),
],
&[TriviaPiece::whitespace(3)],
);
});
let pieces: Vec<_> = node.first_leading_trivia().unwrap().pieces().collect();
assert_eq!(2, pieces.len());
assert_eq!("\n\t ", pieces[0].text());
assert_eq!(TextSize::from(3), pieces[0].text_len());
assert_eq!(TextRange::new(0.into(), 3.into()), pieces[0].text_range());
assert!(pieces[0].is_whitespace());
assert_eq!("/**/", pieces[1].text());
assert_eq!(TextSize::from(4), pieces[1].text_len());
assert_eq!(TextRange::new(3.into(), 7.into()), pieces[1].text_range());
assert!(pieces[1].is_comments());
let pieces_rev: Vec<_> = node
.first_leading_trivia()
.unwrap()
.pieces()
.rev()
.collect();
assert_eq!(2, pieces_rev.len());
assert_eq!("/**/", pieces_rev[0].text());
assert_eq!("\n\t ", pieces_rev[1].text());
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/tree_builder.rs | crates/rome_rowan/src/tree_builder.rs | use crate::{
cow_mut::CowMut,
green::{GreenElement, NodeCache, NodeCacheNodeEntryMut},
syntax::TriviaPiece,
GreenNode, Language, NodeOrToken, ParsedChildren, SyntaxFactory, SyntaxKind, SyntaxNode,
};
use std::marker::PhantomData;
/// A checkpoint for maybe wrapping a node. See `GreenNodeBuilder::checkpoint` for details.
#[derive(Clone, Copy, Debug)]
pub struct Checkpoint(usize);
/// A builder for a syntax tree.
#[derive(Debug)]
pub struct TreeBuilder<'cache, L: Language, S: SyntaxFactory<Kind = L::Kind>> {
cache: CowMut<'cache, NodeCache>,
parents: Vec<(L::Kind, usize)>,
children: Vec<(u64, GreenElement)>,
ph: PhantomData<S>,
}
impl<L: Language, S: SyntaxFactory<Kind = L::Kind>> Default for TreeBuilder<'_, L, S> {
fn default() -> Self {
Self {
cache: CowMut::default(),
parents: Vec::default(),
children: Vec::default(),
ph: PhantomData,
}
}
}
impl<L: Language, S: SyntaxFactory<Kind = L::Kind>> TreeBuilder<'_, L, S> {
/// Creates new builder.
pub fn new() -> TreeBuilder<'static, L, S> {
TreeBuilder::default()
}
/// Reusing `NodeCache` between different [TreeBuilder]s saves memory.
/// It allows to structurally share underlying trees.
pub fn with_cache(cache: &mut NodeCache) -> TreeBuilder<'_, L, S> {
cache.increment_generation();
TreeBuilder {
cache: CowMut::Borrowed(cache),
parents: Vec::new(),
children: Vec::new(),
ph: PhantomData,
}
}
/// Method to quickly wrap a tree with a node.
///
/// ```ignore
/// TreeBuilder::<RawLanguage>::wrap_with_node(RawSyntaxKind(0), |builder| {
/// builder.token(RawSyntaxKind(1), "let");
/// });
/// ```
pub fn wrap_with_node<F>(kind: L::Kind, build: F) -> SyntaxNode<L>
where
F: Fn(&mut Self),
{
let mut builder = TreeBuilder::<L, S>::new();
builder.start_node(kind);
build(&mut builder);
builder.finish_node();
builder.finish()
}
/// Adds new token to the current branch.
#[inline]
pub fn token(&mut self, kind: L::Kind, text: &str) -> &mut Self {
let (hash, token) = self.cache.token(kind.to_raw(), text);
self.children.push((hash, token.into()));
self
}
/// Adds new token to the current branch.
#[inline]
pub fn token_with_trivia(
&mut self,
kind: L::Kind,
text: &str,
leading: &[TriviaPiece],
trailing: &[TriviaPiece],
) {
let (hash, token) = self
.cache
.token_with_trivia(kind.to_raw(), text, leading, trailing);
self.children.push((hash, token.into()));
}
/// Start new node and make it current.
#[inline]
pub fn start_node(&mut self, kind: L::Kind) -> &mut Self {
let len = self.children.len();
self.parents.push((kind, len));
self
}
/// Finish current branch and restore previous
/// branch as current.
#[inline]
pub fn finish_node(&mut self) -> &mut Self {
let (kind, first_child) = self.parents.pop().unwrap();
let raw_kind = kind.to_raw();
let slots = &self.children[first_child..];
let node_entry = self.cache.node(raw_kind, slots);
let mut build_node = || {
let children = ParsedChildren::new(&mut self.children, first_child);
S::make_syntax(kind, children).into_green()
};
let (hash, node) = match node_entry {
NodeCacheNodeEntryMut::NoCache(hash) => (hash, build_node()),
NodeCacheNodeEntryMut::Vacant(entry) => {
let node = build_node();
let hash = entry.cache(node.clone());
(hash, node)
}
NodeCacheNodeEntryMut::Cached(cached) => {
self.children.truncate(first_child);
(cached.hash(), cached.node().to_owned())
}
};
self.children.push((hash, node.into()));
self
}
/// Prepare for maybe wrapping the next node.
/// The way wrapping works is that you first of all get a checkpoint,
/// then you place all tokens you want to wrap, and then *maybe* call
/// `start_node_at`.
/// Example:
/// ```rust
/// # use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// # const PLUS: RawLanguageKind = RawLanguageKind::PLUS_TOKEN;
/// # const OPERATION: RawLanguageKind = RawLanguageKind::ROOT;
/// # struct Parser;
/// # impl Parser {
/// # fn peek(&self) -> Option<RawLanguageKind> { None }
/// # fn parse_expr(&mut self) {}
/// # }
/// # let mut builder = RawSyntaxTreeBuilder::new();
/// # let mut parser = Parser;
/// let checkpoint = builder.checkpoint();
/// parser.parse_expr();
/// if parser.peek() == Some(PLUS) {
/// // 1 + 2 = Add(1, 2)
/// builder.start_node_at(checkpoint, OPERATION);
/// parser.parse_expr();
/// builder.finish_node();
/// }
/// ```
#[inline]
pub fn checkpoint(&self) -> Checkpoint {
Checkpoint(self.children.len())
}
/// Wrap the previous branch marked by `checkpoint` in a new branch and
/// make it current.
#[inline]
pub fn start_node_at(&mut self, checkpoint: Checkpoint, kind: L::Kind) {
let Checkpoint(checkpoint) = checkpoint;
assert!(
checkpoint <= self.children.len(),
"checkpoint no longer valid, was finish_node called early?"
);
if let Some(&(_, first_child)) = self.parents.last() {
assert!(
checkpoint >= first_child,
"checkpoint no longer valid, was an unmatched start_node_at called?"
);
}
self.parents.push((kind, checkpoint));
}
/// Complete tree building. Make sure that
/// `start_node_at` and `finish_node` calls
/// are paired!
#[inline]
#[must_use]
pub fn finish(mut self) -> SyntaxNode<L> {
let root = SyntaxNode::new_root(self.finish_green());
self.cache.sweep_cache();
root
}
// For tests
#[must_use]
pub(crate) fn finish_green(&mut self) -> GreenNode {
assert_eq!(self.children.len(), 1);
match self.children.pop().unwrap().1 {
NodeOrToken::Node(node) => node,
_ => panic!(),
}
}
}
#[cfg(test)]
mod tests {
use crate::green::GreenElementRef;
use crate::raw_language::{RawLanguageKind, RawSyntaxTreeBuilder};
use crate::{GreenNodeData, GreenTokenData, NodeOrToken};
// Builds a "Condition" like structure where the closing ) is missing
fn build_condition_with_missing_closing_parenthesis(builder: &mut RawSyntaxTreeBuilder) {
builder.start_node(RawLanguageKind::CONDITION);
builder.token(RawLanguageKind::L_PAREN_TOKEN, "(");
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::STRING_TOKEN, "a");
builder.finish_node();
// missing )
builder.finish_node();
}
#[test]
fn caches_identical_nodes_with_empty_slots() {
let mut builder = RawSyntaxTreeBuilder::new();
builder.start_node(RawLanguageKind::ROOT); // Root
build_condition_with_missing_closing_parenthesis(&mut builder);
build_condition_with_missing_closing_parenthesis(&mut builder);
builder.finish_node();
let root = builder.finish_green();
let first = root.children().next().unwrap();
let last = root.children().last().unwrap();
assert_eq!(first.element(), last.element());
assert_same_elements(first.element(), last.element());
}
#[test]
fn doesnt_cache_node_if_empty_slots_differ() {
let mut builder = RawSyntaxTreeBuilder::new();
builder.start_node(RawLanguageKind::ROOT); // Root
build_condition_with_missing_closing_parenthesis(&mut builder); // misses the ')'
// Create a well formed condition
builder.start_node(RawLanguageKind::CONDITION);
builder.token(RawLanguageKind::L_PAREN_TOKEN, "(");
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::STRING_TOKEN, "a");
builder.finish_node();
// missing )
builder.token(RawLanguageKind::R_PAREN_TOKEN, ")");
builder.finish_node();
// finish root
builder.finish_node();
let root = builder.finish_green();
let first_condition = root.children().next().unwrap();
let last_condition = root.children().last().unwrap();
assert_ne!(first_condition.element(), last_condition.element());
}
fn assert_same_elements(left: GreenElementRef<'_>, right: GreenElementRef<'_>) {
fn element_id(element: GreenElementRef<'_>) -> *const () {
match element {
NodeOrToken::Node(node) => node as *const GreenNodeData as *const (),
NodeOrToken::Token(token) => token as *const GreenTokenData as *const (),
}
}
assert_eq!(element_id(left), element_id(right),);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/syntax_factory.rs | crates/rome_rowan/src/syntax_factory.rs | mod parsed_children;
mod raw_syntax;
use crate::SyntaxKind;
use std::fmt;
use std::iter::{FusedIterator, Peekable};
pub use self::parsed_children::{
ParsedChildren, ParsedChildrenIntoIterator, ParsedChildrenIterator,
};
pub use self::raw_syntax::{
RawSyntaxElement, RawSyntaxElementRef, RawSyntaxNode, RawSyntaxNodeRef, RawSyntaxToken,
RawSyntaxTokenRef,
};
/// Factory for creating syntax nodes of a particular kind.
pub trait SyntaxFactory: fmt::Debug {
/// The syntax kind used by the nodes constructed by this syntax factory.
type Kind: SyntaxKind;
/// Creates a new syntax node of the passed `kind` with the given children.
///
/// The `children` contains the parsed direct children of the node. There may be fewer children
/// in case there's a syntax error and a required child or an optional child isn't present in the source code.
/// The `make_syntax` implementation must then fill in empty slots to match the slots as they're defined in the grammar.
///
/// The implementation is free to change the `kind` of the node but that has the consequence that
/// such a node will not be cached. The reason for not caching these nodes is that the cache lookup is performed
/// before calling `make_syntax`, thus querying the cache with the old kind.
///
/// It's important that the factory function is idempotent, meaning, calling the function
/// multiple times with the same `kind` and `children` returns syntax nodes with the same structure.
/// This is important because the returned nodes may be cached by `kind` and what `children` are present.
fn make_syntax(
kind: Self::Kind,
children: ParsedChildren<Self::Kind>,
) -> RawSyntaxNode<Self::Kind>;
/// Crates a *node list* syntax node. Validates if all elements are valid and changes the node's kind to
/// [SyntaxKind::to_bogus] if that's not the case.
fn make_node_list_syntax<F>(
kind: Self::Kind,
children: ParsedChildren<Self::Kind>,
can_cast: F,
) -> RawSyntaxNode<Self::Kind>
where
F: Fn(Self::Kind) -> bool,
{
let valid = (&children)
.into_iter()
.all(|element| can_cast(element.kind()));
let kind = if valid { kind } else { kind.to_bogus() };
RawSyntaxNode::new(kind, children.into_iter().map(Some))
}
/// Creates a *separated list* syntax node. Validates if the elements are valid, are correctly
/// separated by the specified separator token.
///
/// It changes the kind of the node to [SyntaxKind::to_bogus] if an element isn't a valid list-node
/// nor separator.
///
/// It inserts empty slots for missing elements or missing markers
fn make_separated_list_syntax<F>(
kind: Self::Kind,
children: ParsedChildren<Self::Kind>,
can_cast: F,
separator: Self::Kind,
allow_trailing: bool,
) -> RawSyntaxNode<Self::Kind>
where
F: Fn(Self::Kind) -> bool,
{
let mut next_node = true;
let mut missing_count = 0;
let mut valid = true;
for child in &children {
let kind = child.kind();
if next_node {
if can_cast(kind) {
next_node = false;
} else if kind == separator {
// a missing element
missing_count += 1;
} else {
// an invalid element
valid = false;
break;
}
} else if kind == separator {
next_node = true;
} else if can_cast(kind) {
// a missing separator
missing_count += 1;
} else {
// something unexpected
valid = false;
}
}
if next_node && !allow_trailing && !children.is_empty() {
// a trailing comma in a list that doesn't support trailing commas
missing_count += 1;
}
if !valid {
RawSyntaxNode::new(kind.to_bogus(), children.into_iter().map(Some))
} else if missing_count > 0 {
RawSyntaxNode::new(
kind,
SeparatedListWithMissingNodesOrSeparatorSlotsIterator {
inner: children.into_iter().peekable(),
missing_count,
next_node: true,
separator,
},
)
} else {
RawSyntaxNode::new(kind, children.into_iter().map(Some))
}
}
}
/// Iterator that "fixes up" a separated list by inserting empty slots for any missing
/// separator or element.
struct SeparatedListWithMissingNodesOrSeparatorSlotsIterator<'a, K: SyntaxKind> {
inner: Peekable<ParsedChildrenIntoIterator<'a, K>>,
missing_count: usize,
next_node: bool,
separator: K,
}
impl<'a, K: SyntaxKind> Iterator for SeparatedListWithMissingNodesOrSeparatorSlotsIterator<'a, K> {
type Item = Option<RawSyntaxElement<K>>;
#[cold]
fn next(&mut self) -> Option<Self::Item> {
let peeked = self.inner.peek();
if let Some(peeked) = peeked {
let is_separator = self.separator == peeked.kind();
if self.next_node {
self.next_node = false;
if !is_separator {
Some(self.inner.next())
} else {
self.missing_count -= 1;
Some(None) // Missing separator
}
} else if is_separator {
self.next_node = true;
Some(self.inner.next())
} else {
// Missing node
self.missing_count -= 1;
self.next_node = true;
Some(None)
}
} else if self.missing_count > 0 {
// at a trailing comma in a list that doesn't allow trailing commas.
self.missing_count -= 1;
Some(None)
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
}
impl<'a, K: SyntaxKind> FusedIterator
for SeparatedListWithMissingNodesOrSeparatorSlotsIterator<'a, K>
{
}
impl<'a, K: SyntaxKind> ExactSizeIterator
for SeparatedListWithMissingNodesOrSeparatorSlotsIterator<'a, K>
{
fn len(&self) -> usize {
self.inner.len() + self.missing_count
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SlotContent {
Present,
Absent,
}
/// Description of the slots of a node in combination with [ParsedChildren].
/// It stores for each slot if the node is present in [ParsedChildren] or not, allowing
/// to generate a node with the right number of empty slots.
#[derive(Debug)]
pub struct RawNodeSlots<const COUNT: usize> {
slots: [SlotContent; COUNT],
current_slot: usize,
}
impl<const COUNT: usize> Default for RawNodeSlots<COUNT> {
fn default() -> Self {
Self {
slots: [SlotContent::Absent; COUNT],
current_slot: 0,
}
}
}
impl<const COUNT: usize> RawNodeSlots<COUNT> {
/// Progresses to the next slot
pub fn next_slot(&mut self) {
debug_assert!(self.current_slot < COUNT);
self.current_slot += 1;
}
/// Marks that the node for the current slot is *present* in the source code.
pub fn mark_present(&mut self) {
debug_assert!(self.current_slot < COUNT);
self.slots[self.current_slot] = SlotContent::Present;
}
/// Creates a node with the kind `kind`, filling in the nodes from the `children`.
pub fn into_node<K: SyntaxKind>(
self,
kind: K,
children: ParsedChildren<K>,
) -> RawSyntaxNode<K> {
debug_assert!(self.current_slot == COUNT, "Missing slots");
RawSyntaxNode::new(
kind,
RawNodeSlotIterator {
children: children.into_iter(),
slots: self.slots.as_slice().iter(),
},
)
}
}
struct RawNodeSlotIterator<'a, K: SyntaxKind> {
children: ParsedChildrenIntoIterator<'a, K>,
slots: std::slice::Iter<'a, SlotContent>,
}
impl<'a, K: SyntaxKind> Iterator for RawNodeSlotIterator<'a, K> {
type Item = Option<RawSyntaxElement<K>>;
fn next(&mut self) -> Option<Self::Item> {
let slot = self.slots.next()?;
match slot {
SlotContent::Present => {
Some(Some(self.children.next().expect(
"Expected a present node according to the slot description",
)))
}
SlotContent::Absent => Some(None),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.slots.len(), Some(self.slots.len()))
}
}
impl<'a, K: SyntaxKind> FusedIterator for RawNodeSlotIterator<'a, K> {}
impl<'a, K: SyntaxKind> ExactSizeIterator for RawNodeSlotIterator<'a, K> {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/cow_mut.rs | crates/rome_rowan/src/cow_mut.rs | #[derive(Debug)]
pub(crate) enum CowMut<'a, T> {
Owned(T),
Borrowed(&'a mut T),
}
impl<T> std::ops::Deref for CowMut<'_, T> {
type Target = T;
fn deref(&self) -> &T {
match self {
CowMut::Owned(it) => it,
CowMut::Borrowed(it) => it,
}
}
}
impl<T> std::ops::DerefMut for CowMut<'_, T> {
fn deref_mut(&mut self) -> &mut T {
match self {
CowMut::Owned(it) => it,
CowMut::Borrowed(it) => it,
}
}
}
impl<T: Default> Default for CowMut<'_, T> {
fn default() -> Self {
CowMut::Owned(T::default())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/file_source.rs | crates/rome_rowan/src/file_source.rs | use crate::Language;
use std::any::TypeId;
use std::fmt::Display;
use std::path::{Path, PathBuf};
/// Errors around the construct of the source type
#[derive(Debug)]
pub enum FileSourceError {
/// The path has no file name
MissingFileName(PathBuf),
/// The path has no file extension
MissingFileExtension(PathBuf),
/// The source type is unknown
UnknownExtension(String, String),
}
impl std::error::Error for FileSourceError {}
impl Display for FileSourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FileSourceError::MissingFileName(path) => {
write!(f, "The path {path:?} has no file name")
}
FileSourceError::MissingFileExtension(path) => {
write!(f, "The path {path:?} has no file extension")
}
FileSourceError::UnknownExtension(_, extension) => {
write!(f, "The parser can't parse the extension '{extension}' yet")
}
}
}
}
/// Generic trait that provides a method to safely create
/// a file source that can be send across thread boundaries.
///
/// When applying this trait, the [TryFrom] trait for [Path] must be implemented.
///
/// ```
/// use std::path::Path;
/// use rome_rowan::{FileSource, FileSourceError};
/// use rome_rowan::raw_language::RawLanguage;
/// struct UnknownFileSource {}
///
/// impl TryFrom<&Path> for UnknownFileSource {
/// type Error = FileSourceError;
///
/// fn try_from(value: &Path) -> Result<Self, Self::Error> {
/// Ok(UnknownFileSource {})
/// }
/// }
/// impl<'a> FileSource<'a, RawLanguage> for UnknownFileSource {}
/// ```
pub trait FileSource<'a, L: Language + 'static>:
TryFrom<&'a Path, Error = FileSourceError>
{
fn as_any_file_source(&self) -> AnyFileSource {
AnyFileSource {
file_source: TypeId::of::<L>(),
}
}
}
/// Generic file source that can be send across thread boundaries
#[derive(Clone)]
pub struct AnyFileSource {
pub(crate) file_source: TypeId,
}
impl AnyFileSource {
/// Attempts to retrieve the original file source of the file
///
/// ## Errors
///
/// The function will panic if:
/// - the original type and given type mismatch
/// - it's possible to retrieve the correct [FileSource] from the given [Path]
pub fn unwrap_cast_from_path<'a, F, L>(&self, path: &'a Path) -> Result<F, FileSourceError>
where
F: FileSource<'a, L> + 'static,
L: Language + 'static,
{
let file_source = TypeId::of::<L>();
if file_source == self.file_source {
F::try_from(path)
} else {
Err(FileSourceError::MissingFileExtension(PathBuf::from(path)))
}
}
}
#[cfg(test)]
mod test {
use crate::file_source::FileSourceError;
use crate::raw_language::RawLanguage;
use crate::FileSource;
use std::path::{Path, PathBuf};
#[test]
fn should_cast_file_source() {
#[derive(Debug, Eq, PartialEq)]
struct Test {
path: String,
}
impl TryFrom<&Path> for Test {
type Error = FileSourceError;
fn try_from(value: &Path) -> Result<Self, Self::Error> {
Ok(Test {
path: value.display().to_string(),
})
}
}
impl<'a> FileSource<'a, RawLanguage> for Test {}
let path = PathBuf::from("test");
let first_test = Test {
path: path.display().to_string(),
};
let send_first = first_test.as_any_file_source();
let cast = send_first.unwrap_cast_from_path::<Test, RawLanguage>(path.as_path());
assert!(cast.is_ok());
let cast = cast.unwrap();
assert_eq!(cast, first_test)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/macros.rs | crates/rome_rowan/src/macros.rs | use crate::{AstNode, Language};
/// Matches a `SyntaxNode` against an `ast` type.
///
/// # Example:
///
/// ```
/// use rome_rowan::{match_ast, AstNode};
/// use rome_rowan::raw_language::{LiteralExpression, RawLanguageRoot, RawLanguageKind, RawSyntaxTreeBuilder};
///
/// let mut builder = RawSyntaxTreeBuilder::new();
/// builder.start_node(RawLanguageKind::ROOT);
/// builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
/// builder.token(RawLanguageKind::NUMBER_TOKEN, "5");
/// builder.finish_node();
/// builder.finish_node();
///
/// let root = builder.finish();
///
/// let text = match_ast! {
/// match &root {
/// RawLanguageRoot(root) => { format!("root: {}", root.text()) },
/// LiteralExpression(literal) => { format!("literal: {}", literal.text()) },
/// _ => {
/// root.text().to_string()
/// }
/// }
/// };
///
/// assert_eq!(text, "root: 5");
/// ```
#[macro_export]
macro_rules! match_ast {
// Necessary because expressions aren't allowed in front of `{`
(match &$node:ident { $($tt:tt)* }) => { match_ast!(match (&$node) { $($tt)* }) };
(match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
(match ($node:expr) {
$( $( $path:ident )::+ ($it:pat) => $res:expr, )*
_ => $catch_all:expr $(,)?
}) => {{
$( if let Some($it) = $($path::)+cast_ref($node) { $res } else )*
{ $catch_all }
}};
}
/// Declares a custom union AstNode type with an ungram-like syntax
///
/// # Example
///
/// ```ignore
/// declare_node_union! {
/// /// Matches an if statement or a conditional expression
/// pub(crate) JsAnyConditional = JsIfStatement | JsConditionalExpression
/// }
/// ```
#[macro_export]
macro_rules! declare_node_union {
(@merge_kind $head:ident ) => {
$head::KIND_SET
};
(@merge_kind $head:ident $( $rest:ident )* ) => {
$head::KIND_SET.union($crate::declare_node_union!( @merge_kind $( $rest )* ))
};
( $( #[$attr:meta] )* $vis:vis $name:ident = $( $variant:ident )|* ) => {
$( #[$attr] )*
#[allow(clippy::enum_variant_names)]
#[derive(Clone, PartialEq, Eq, Hash)]
$vis enum $name {
$( $variant($variant), )*
}
impl $crate::AstNode for $name {
type Language = <( $( $variant, )* ) as $crate::macros::UnionLanguage>::Language;
const KIND_SET: $crate::SyntaxKindSet<Self::Language> = $crate::declare_node_union!( @merge_kind $( $variant )* );
fn can_cast(kind: <Self::Language as $crate::Language>::Kind) -> bool {
$( $variant::can_cast(kind) )||*
}
fn cast(syntax: $crate::SyntaxNode<Self::Language>) -> Option<Self>
where
Self: Sized,
{
$( if $variant::can_cast(syntax.kind()) {
return Some(Self::$variant($variant::unwrap_cast(syntax)));
} )*
None
}
fn syntax(&self) -> &$crate::SyntaxNode<Self::Language> {
match self {
$( Self::$variant(node) => node.syntax() ),*
}
}
fn into_syntax(self) -> $crate::SyntaxNode<Self::Language> {
match self {
$( Self::$variant(node) => node.into_syntax() ),*
}
}
}
impl std::fmt::Debug for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
$( Self::$variant(it) => std::fmt::Debug::fmt(it, f), )*
}
}
}
impl std::fmt::Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt($crate::AstNode::syntax(self), f)
}
}
$( impl From<$variant> for $name {
fn from(node: $variant) -> Self {
Self::$variant(node)
}
} )*
impl From<$name> for $crate::SyntaxNode<<$name as $crate::AstNode>::Language> {
fn from(n: $name) -> $crate::SyntaxNode<<$name as $crate::AstNode>::Language> {
match n {
$( $name::$variant(it) => it.into(), )*
}
}
}
impl From<$name> for $crate::SyntaxElement<<$name as $crate::AstNode>::Language> {
fn from(n: $name) -> $crate::SyntaxElement<<$name as $crate::AstNode>::Language> {
$crate::SyntaxNode::<<$name as $crate::AstNode>::Language>::from(n).into()
}
}
};
}
/// This trait is implemented for tuples of AstNode types of size 1 to 12 if
/// all node types share the same associated language (which is then aliased as
/// the `Language` associated type on [UnionLanguage] itself)
pub trait UnionLanguage {
type Language: Language;
}
macro_rules! impl_union_language {
( $head:ident $( , $rest:ident )* ) => {
impl<$head $( , $rest )*> UnionLanguage for ($head, $( $rest ),*)
where
$head: AstNode $( , $rest: AstNode<Language = <$head as AstNode>::Language> )*
{
type Language = <$head as AstNode>::Language;
}
impl_union_language!( $( $rest ),* );
};
() => {};
}
impl_union_language!(
T00, T01, T02, T03, T04, T05, T06, T07, T08, T09, T10, T11, T12, T13, T14, T15, T16, T17, T18,
T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29
);
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/token_text.rs | crates/rome_rowan/src/token_text.rs | use crate::GreenToken;
use rome_text_size::{TextRange, TextSize};
use std::ops::Deref;
use std::{borrow::Borrow, fmt::Formatter};
/// Reference to the text of a SyntaxToken without having to worry about the lifetime of `&str`.
#[derive(Eq, Clone)]
pub struct TokenText {
// Using a green token to ensure this type is Send + Sync.
token: GreenToken,
/// Relative range of the "selected" token text.
range: TextRange,
}
impl std::hash::Hash for TokenText {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.text().hash(state);
}
}
impl TokenText {
pub(crate) fn new(token: GreenToken) -> TokenText {
let range = TextRange::at(TextSize::default(), token.text_len());
Self { token, range }
}
pub(crate) fn with_range(token: GreenToken, range: TextRange) -> TokenText {
debug_assert!(range.end() <= token.text_len());
Self { token, range }
}
/// Returns the length of the text
pub fn len(&self) -> TextSize {
self.range.len()
}
/// Returns `true` if the text is empty
pub fn is_empty(&self) -> bool {
self.range.is_empty()
}
/// Returns a subslice of the text.
/// `range.end()` must be lower or equal to `self.len()`
pub fn slice(mut self, range: TextRange) -> TokenText {
assert!(
range.end() <= self.len(),
"Range {range:?} exceeds the text length {:?}",
self.len()
);
self.range = range + self.range.start();
self
}
pub fn text(&self) -> &str {
&self.token.text()[self.range]
}
}
impl Deref for TokenText {
type Target = str;
fn deref(&self) -> &Self::Target {
self.text()
}
}
impl std::fmt::Display for TokenText {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.text())
}
}
impl std::fmt::Debug for TokenText {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.text())
}
}
impl PartialEq for TokenText {
fn eq(&self, other: &Self) -> bool {
**self == **other
}
}
impl PartialEq<&'_ str> for TokenText {
fn eq(&self, rhs: &&'_ str) -> bool {
**self == **rhs
}
}
impl PartialEq<TokenText> for &'_ str {
fn eq(&self, other: &TokenText) -> bool {
**self == **other
}
}
impl Borrow<str> for TokenText {
fn borrow(&self) -> &str {
self.text()
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/serde_impls.rs | crates/rome_rowan/src/serde_impls.rs | use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer};
use std::fmt;
use crate::{
syntax::{Language, SyntaxNode, SyntaxToken},
NodeOrToken,
};
struct SerDisplay<T>(T);
impl<T: fmt::Display> Serialize for SerDisplay<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_str(&self.0)
}
}
struct DisplayDebug<T>(T);
impl<T: fmt::Debug> fmt::Display for DisplayDebug<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl<L: Language> Serialize for SyntaxNode<L> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_map(Some(3))?;
state.serialize_entry("kind", &SerDisplay(DisplayDebug(self.kind())))?;
state.serialize_entry("text_range", &self.text_range())?;
state.serialize_entry("children", &Children(self))?;
state.end()
}
}
impl<L: Language> Serialize for SyntaxToken<L> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_map(Some(3))?;
state.serialize_entry("kind", &SerDisplay(DisplayDebug(self.kind())))?;
state.serialize_entry("text_range", &self.text_range())?;
state.serialize_entry("text", &self.text())?;
// To implement this, SyntaxTrivia will need to expose the kind and the length of each trivia
// state.serialize_entry("leading", &self.leading())?;
// state.serialize_entry("trailing", &self.trailing())?;
state.end()
}
}
struct Children<T>(T);
impl<L: Language> Serialize for Children<&'_ SyntaxNode<L>> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_seq(None)?;
self.0
.children_with_tokens()
.try_for_each(|element| match element {
NodeOrToken::Node(it) => state.serialize_element(&it),
NodeOrToken::Token(it) => state.serialize_element(&it),
})?;
state.end()
}
}
#[cfg(test)]
mod test {
use crate::raw_language::{RawLanguage, RawLanguageKind, RawLanguageSyntaxFactory};
#[test]
pub fn serialization() {
let mut builder: crate::TreeBuilder<RawLanguage, RawLanguageSyntaxFactory> =
crate::TreeBuilder::new();
builder.start_node(RawLanguageKind::ROOT);
builder.token(RawLanguageKind::LET_TOKEN, "\n\tlet ");
builder.finish_node();
let root = builder.finish();
assert!(serde_json::to_string(&root).is_ok());
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/raw_language.rs | crates/rome_rowan/src/raw_language.rs | //! Provides a sample language implementation that is useful in API explanation or tests
use crate::raw_language::RawLanguageKind::{COMMA_TOKEN, LITERAL_EXPRESSION, ROOT};
use crate::{
AstNode, AstSeparatedList, Language, ParsedChildren, RawNodeSlots, RawSyntaxKind,
RawSyntaxNode, SyntaxFactory, SyntaxKind, SyntaxKindSet, SyntaxList, SyntaxNode, TreeBuilder,
};
#[doc(hidden)]
#[derive(Debug, Default, Hash, Copy, Eq, Ord, PartialEq, PartialOrd, Clone)]
pub struct RawLanguage;
impl Language for RawLanguage {
type Kind = RawLanguageKind;
type Root = RawLanguageRoot;
}
#[doc(hidden)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(u16)]
#[allow(bad_style)]
pub enum RawLanguageKind {
ROOT = 0,
EXPRESSION_LIST = 1,
SEPARATED_EXPRESSION_LIST = 2,
COMMA_TOKEN = 3,
STRING_TOKEN = 4,
NUMBER_TOKEN = 5,
LITERAL_EXPRESSION = 6,
BOGUS = 7,
FOR_KW = 8,
L_PAREN_TOKEN = 9,
SEMICOLON_TOKEN = 10,
R_PAREN_TOKEN = 11,
EQUAL_TOKEN = 12,
LET_TOKEN = 13,
CONDITION = 14,
PLUS_TOKEN = 15,
WHITESPACE = 16,
TOMBSTONE = 17,
EOF = 18,
__LAST,
}
impl SyntaxKind for RawLanguageKind {
const TOMBSTONE: Self = RawLanguageKind::TOMBSTONE;
const EOF: Self = RawLanguageKind::EOF;
fn is_bogus(&self) -> bool {
self == &RawLanguageKind::BOGUS
}
fn to_bogus(&self) -> Self {
RawLanguageKind::BOGUS
}
fn to_raw(&self) -> RawSyntaxKind {
RawSyntaxKind(*self as u16)
}
#[allow(unsafe_code)]
fn from_raw(raw: RawSyntaxKind) -> Self {
assert!(raw.0 < RawLanguageKind::__LAST as u16);
unsafe { std::mem::transmute::<u16, RawLanguageKind>(raw.0) }
}
fn is_root(&self) -> bool {
self == &RawLanguageKind::ROOT
}
fn is_list(&self) -> bool {
matches!(
self,
RawLanguageKind::EXPRESSION_LIST | RawLanguageKind::SEPARATED_EXPRESSION_LIST
)
}
fn to_string(&self) -> Option<&'static str> {
let str = match self {
COMMA_TOKEN => ",",
RawLanguageKind::FOR_KW => "for",
RawLanguageKind::L_PAREN_TOKEN => "(",
RawLanguageKind::SEMICOLON_TOKEN => ";",
RawLanguageKind::R_PAREN_TOKEN => ")",
RawLanguageKind::EQUAL_TOKEN => "=",
RawLanguageKind::LET_TOKEN => "let",
RawLanguageKind::PLUS_TOKEN => "+",
_ => return None,
};
Some(str)
}
}
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RawLanguageRoot {
node: SyntaxNode<RawLanguage>,
}
impl AstNode for RawLanguageRoot {
type Language = RawLanguage;
const KIND_SET: SyntaxKindSet<RawLanguage> =
SyntaxKindSet::from_raw(RawSyntaxKind(ROOT as u16));
fn can_cast(kind: RawLanguageKind) -> bool {
kind == ROOT
}
fn cast(syntax: SyntaxNode<RawLanguage>) -> Option<Self>
where
Self: Sized,
{
if syntax.kind() == ROOT {
Some(RawLanguageRoot { node: syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode<RawLanguage> {
&self.node
}
fn into_syntax(self) -> SyntaxNode<RawLanguage> {
self.node
}
}
#[doc(hidden)]
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct LiteralExpression {
node: SyntaxNode<RawLanguage>,
}
impl AstNode for LiteralExpression {
type Language = RawLanguage;
const KIND_SET: SyntaxKindSet<RawLanguage> =
SyntaxKindSet::from_raw(RawSyntaxKind(LITERAL_EXPRESSION as u16));
fn can_cast(kind: RawLanguageKind) -> bool {
kind == LITERAL_EXPRESSION
}
fn cast(syntax: SyntaxNode<RawLanguage>) -> Option<Self>
where
Self: Sized,
{
if syntax.kind() == LITERAL_EXPRESSION {
Some(LiteralExpression { node: syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode<RawLanguage> {
&self.node
}
fn into_syntax(self) -> SyntaxNode<RawLanguage> {
self.node
}
}
#[doc(hidden)]
pub struct SeparatedExpressionList {
syntax_list: SyntaxList<RawLanguage>,
}
impl SeparatedExpressionList {
pub fn new(list: SyntaxList<RawLanguage>) -> Self {
Self { syntax_list: list }
}
}
impl AstSeparatedList for SeparatedExpressionList {
type Language = RawLanguage;
type Node = LiteralExpression;
fn syntax_list(&self) -> &SyntaxList<RawLanguage> {
&self.syntax_list
}
fn into_syntax_list(self) -> SyntaxList<RawLanguage> {
self.syntax_list
}
}
#[doc(hidden)]
#[derive(Debug)]
pub struct RawLanguageSyntaxFactory;
impl SyntaxFactory for RawLanguageSyntaxFactory {
type Kind = RawLanguageKind;
fn make_syntax(
kind: Self::Kind,
children: ParsedChildren<Self::Kind>,
) -> RawSyntaxNode<Self::Kind> {
match kind {
RawLanguageKind::BOGUS | RawLanguageKind::ROOT => {
RawSyntaxNode::new(kind, children.into_iter().map(Some))
}
RawLanguageKind::EXPRESSION_LIST => {
Self::make_node_list_syntax(kind, children, |kind| kind == LITERAL_EXPRESSION)
}
RawLanguageKind::SEPARATED_EXPRESSION_LIST => Self::make_separated_list_syntax(
kind,
children,
|kind| kind == LITERAL_EXPRESSION,
COMMA_TOKEN,
true,
),
RawLanguageKind::LITERAL_EXPRESSION => {
let actual_len = children.len();
if actual_len > 1 {
return RawSyntaxNode::new(kind.to_bogus(), children.into_iter().map(Some));
}
let mut elements = children.into_iter();
let current_element = elements.next();
if let Some(element) = ¤t_element {
if !matches!(
element.kind(),
RawLanguageKind::STRING_TOKEN | RawLanguageKind::NUMBER_TOKEN
) {
return RawSyntaxNode::new(
kind.to_bogus(),
std::iter::once(current_element),
);
}
} else {
return RawSyntaxNode::new(kind, std::iter::once(None));
}
RawSyntaxNode::new(kind, std::iter::once(current_element))
}
RawLanguageKind::CONDITION => {
let mut elements = (&children).into_iter();
let mut current_element = elements.next();
let mut slots: RawNodeSlots<3> = Default::default();
if let Some(element) = ¤t_element {
if element.kind() == RawLanguageKind::L_PAREN_TOKEN {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == RawLanguageKind::LITERAL_EXPRESSION {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == RawLanguageKind::R_PAREN_TOKEN {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(kind.to_bogus(), children.into_iter().map(Some));
}
slots.into_node(kind, children)
}
_ => unreachable!("{:?} is not a node kind", kind),
}
}
}
#[doc(hidden)]
pub type RawSyntaxTreeBuilder<'a> = TreeBuilder<'a, RawLanguage, RawLanguageSyntaxFactory>;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/arc.rs | crates/rome_rowan/src/arc.rs | //! Vendored and stripped down version of triomphe
use std::{
alloc::{self, Layout},
cmp::Ordering,
hash::{Hash, Hasher},
marker::PhantomData,
mem::{self, ManuallyDrop},
ops::Deref,
ptr::{self, NonNull},
sync::atomic::{
self,
Ordering::{Acquire, Relaxed, Release},
},
};
use memoffset::offset_of;
/// A soft limit on the amount of references that may be made to an `Arc`.
///
/// Going above this limit will abort your program (although not
/// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references.
const MAX_REFCOUNT: usize = (isize::MAX) as usize;
/// The object allocated by an Arc<T>
#[repr(C)]
pub(crate) struct ArcInner<T: ?Sized> {
pub(crate) count: atomic::AtomicUsize,
pub(crate) data: T,
}
unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}
/// An atomically reference counted shared pointer
///
/// See the documentation for [`Arc`] in the standard library. Unlike the
/// standard library `Arc`, this `Arc` does not support weak reference counting.
///
/// [`Arc`]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html
#[repr(transparent)]
pub(crate) struct Arc<T: ?Sized> {
pub(crate) p: ptr::NonNull<ArcInner<T>>,
pub(crate) phantom: PhantomData<T>,
}
unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
impl<T> Arc<T> {
/// Reconstruct the Arc<T> from a raw pointer obtained from into_raw()
///
/// Note: This raw pointer will be offset in the allocation and must be preceded
/// by the atomic count.
///
/// It is recommended to use OffsetArc for this
#[inline]
pub(crate) unsafe fn from_raw(ptr: *const T) -> Self {
// To find the corresponding pointer to the `ArcInner` we need
// to subtract the offset of the `data` field from the pointer.
let ptr = (ptr as *const u8).sub(offset_of!(ArcInner<T>, data));
Arc {
p: ptr::NonNull::new_unchecked(ptr as *mut ArcInner<T>),
phantom: PhantomData,
}
}
}
impl<T: ?Sized> Arc<T> {
#[inline]
fn inner(&self) -> &ArcInner<T> {
// This unsafety is ok because while this arc is alive we're guaranteed
// that the inner pointer is valid. Furthermore, we know that the
// `ArcInner` structure itself is `Sync` because the inner data is
// `Sync` as well, so we're ok loaning out an immutable pointer to these
// contents.
unsafe { &*self.ptr() }
}
// Non-inlined part of `drop`. Just invokes the destructor.
#[inline(never)]
unsafe fn drop_slow(&mut self) {
let _ = Box::from_raw(self.ptr());
}
/// Test pointer equality between the two Arcs, i.e. they must be the _same_
/// allocation
#[inline]
pub(crate) fn ptr_eq(this: &Self, other: &Self) -> bool {
this.ptr() == other.ptr()
}
pub(crate) fn ptr(&self) -> *mut ArcInner<T> {
self.p.as_ptr()
}
#[inline]
pub(crate) fn into_raw(self) -> NonNull<T> {
let ptr = NonNull::from(&self.inner().data);
mem::forget(self);
ptr
}
}
impl<T: ?Sized> Clone for Arc<T> {
#[inline]
fn clone(&self) -> Self {
// Using a relaxed ordering is alright here, as knowledge of the
// original reference prevents other threads from erroneously deleting
// the object.
//
// As explained in the [Boost documentation][1], Increasing the
// reference counter can always be done with memory_order_relaxed: New
// references to an object can only be formed from an existing
// reference, and passing an existing reference from one thread to
// another must already provide any required synchronization.
//
// [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
let old_size = self.inner().count.fetch_add(1, Relaxed);
// However we need to guard against massive refcounts in case someone
// is `mem::forget`ing Arcs. If we don't do this the count can overflow
// and users will use-after free. We racily saturate to `isize::MAX` on
// the assumption that there aren't ~2 billion threads incrementing
// the reference count at once. This branch will never be taken in
// any realistic program.
//
// We abort because such a program is incredibly degenerate, and we
// don't care to support it.
if old_size > MAX_REFCOUNT {
std::process::abort();
}
unsafe {
Arc {
p: ptr::NonNull::new_unchecked(self.ptr()),
phantom: PhantomData,
}
}
}
}
impl<T: ?Sized> Deref for Arc<T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
&self.inner().data
}
}
impl<T: ?Sized> Arc<T> {
/// Provides mutable access to the contents _if_ the `Arc` is uniquely owned.
#[inline]
pub(crate) fn get_mut(this: &mut Self) -> Option<&mut T> {
if this.is_unique() {
unsafe {
// See make_mut() for documentation of the threadsafety here.
Some(&mut (*this.ptr()).data)
}
} else {
None
}
}
/// Whether or not the `Arc` is uniquely owned (is the refcount 1?).
pub(crate) fn is_unique(&self) -> bool {
// See the extensive discussion in [1] for why this needs to be Acquire.
//
// [1] https://github.com/servo/servo/issues/21186
self.inner().count.load(Acquire) == 1
}
}
impl<T: ?Sized> Drop for Arc<T> {
#[inline]
fn drop(&mut self) {
// Because `fetch_sub` is already atomic, we do not need to synchronize
// with other threads unless we are going to delete the object.
if self.inner().count.fetch_sub(1, Release) != 1 {
return;
}
// FIXME(bholley): Use the updated comment when [2] is merged.
//
// This load is needed to prevent reordering of use of the data and
// deletion of the data. Because it is marked `Release`, the decreasing
// of the reference count synchronizes with this `Acquire` load. This
// means that use of the data happens before decreasing the reference
// count, which happens before this load, which happens before the
// deletion of the data.
//
// As explained in the [Boost documentation][1],
//
// > It is important to enforce any possible access to the object in one
// > thread (through an existing reference) to *happen before* deleting
// > the object in a different thread. This is achieved by a "release"
// > operation after dropping a reference (any access to the object
// > through this reference must obviously happened before), and an
// > "acquire" operation before deleting the object.
//
// [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
// [2]: https://github.com/rust-lang/rust/pull/41714
self.inner().count.load(Acquire);
unsafe {
self.drop_slow();
}
}
}
impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
fn eq(&self, other: &Arc<T>) -> bool {
Self::ptr_eq(self, other) || *(*self) == *(*other)
}
}
impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
(**self).partial_cmp(&**other)
}
fn lt(&self, other: &Arc<T>) -> bool {
*(*self) < *(*other)
}
fn le(&self, other: &Arc<T>) -> bool {
*(*self) <= *(*other)
}
fn gt(&self, other: &Arc<T>) -> bool {
*(*self) > *(*other)
}
fn ge(&self, other: &Arc<T>) -> bool {
*(*self) >= *(*other)
}
}
impl<T: ?Sized + Ord> Ord for Arc<T> {
fn cmp(&self, other: &Arc<T>) -> Ordering {
(**self).cmp(&**other)
}
}
impl<T: ?Sized + Eq> Eq for Arc<T> {}
impl<T: ?Sized + Hash> Hash for Arc<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
(**self).hash(state)
}
}
#[derive(Debug, Eq, PartialEq, Hash, PartialOrd)]
#[repr(C)]
pub(crate) struct HeaderSlice<H, T: ?Sized> {
pub(crate) header: H,
length: usize,
slice: T,
}
impl<H, T> HeaderSlice<H, [T]> {
pub(crate) fn slice(&self) -> &[T] {
&self.slice
}
/// Returns the number of items
pub(crate) fn len(&self) -> usize {
self.length
}
}
impl<H, T> Deref for HeaderSlice<H, [T; 0]> {
type Target = HeaderSlice<H, [T]>;
fn deref(&self) -> &Self::Target {
unsafe {
let len = self.length;
let fake_slice: *const [T] =
ptr::slice_from_raw_parts(self as *const _ as *const T, len);
&*(fake_slice as *const HeaderSlice<H, [T]>)
}
}
}
/// A "thin" `Arc` containing dynamically sized data
///
/// This is functionally equivalent to `Arc<(H, [T])>`
///
/// When you create an `Arc` containing a dynamically sized type
/// like `HeaderSlice<H, [T]>`, the `Arc` is represented on the stack
/// as a "fat pointer", where the length of the slice is stored
/// alongside the `Arc`'s pointer. In some situations you may wish to
/// have a thin pointer instead, perhaps for FFI compatibility
/// or space efficiency.
///
/// Note that we use `[T; 0]` in order to have the right alignment for `T`.
///
/// `ThinArc` solves this by storing the length in the allocation itself,
/// via `HeaderSlice`.
#[repr(transparent)]
pub(crate) struct ThinArc<H, T> {
ptr: ptr::NonNull<ArcInner<HeaderSlice<H, [T; 0]>>>,
phantom: PhantomData<(H, T)>,
}
unsafe impl<H: Sync + Send, T: Sync + Send> Send for ThinArc<H, T> {}
unsafe impl<H: Sync + Send, T: Sync + Send> Sync for ThinArc<H, T> {}
// Synthesize a fat pointer from a thin pointer.
fn thin_to_thick<H, T>(
thin: *mut ArcInner<HeaderSlice<H, [T; 0]>>,
) -> *mut ArcInner<HeaderSlice<H, [T]>> {
let len = unsafe { (*thin).data.length };
let fake_slice: *mut [T] = ptr::slice_from_raw_parts_mut(thin as *mut T, len);
// Transplants metadata.
fake_slice as *mut ArcInner<HeaderSlice<H, [T]>>
}
impl<H, T> ThinArc<H, T> {
/// Temporarily converts |self| into a bonafide Arc and exposes it to the
/// provided callback. The refcount is not modified.
#[inline]
pub(crate) fn with_arc<F, U>(&self, f: F) -> U
where
F: FnOnce(&Arc<HeaderSlice<H, [T]>>) -> U,
{
// Synthesize transient Arc, which never touches the refcount of the ArcInner.
let transient = unsafe {
ManuallyDrop::new(Arc {
p: ptr::NonNull::new_unchecked(thin_to_thick(self.ptr.as_ptr())),
phantom: PhantomData,
})
};
// Expose the transient Arc to the callback, which may clone it if it wants.
// Forward the result.
f(&transient)
}
/// Creates a `ThinArc` for a HeaderSlice using the given header struct and
/// iterator to generate the slice.
pub(crate) fn from_header_and_iter<I>(header: H, mut items: I) -> Self
where
I: Iterator<Item = T> + ExactSizeIterator,
{
assert_ne!(mem::size_of::<T>(), 0, "Need to think about ZST");
let num_items = items.len();
// Offset of the start of the slice in the allocation.
let inner_to_data_offset = offset_of!(ArcInner<HeaderSlice<H, [T; 0]>>, data);
let data_to_slice_offset = offset_of!(HeaderSlice<H, [T; 0]>, slice);
let slice_offset = inner_to_data_offset + data_to_slice_offset;
// Compute the size of the real payload.
let slice_size = mem::size_of::<T>()
.checked_mul(num_items)
.expect("size overflows");
let usable_size = slice_offset
.checked_add(slice_size)
.expect("size overflows");
// Round up size to alignment.
let align = mem::align_of::<ArcInner<HeaderSlice<H, [T; 0]>>>();
let size = usable_size.wrapping_add(align - 1) & !(align - 1);
assert!(size >= usable_size, "size overflows");
let layout = Layout::from_size_align(size, align).expect("invalid layout");
let ptr: *mut ArcInner<HeaderSlice<H, [T; 0]>>;
unsafe {
let buffer = alloc::alloc(layout);
if buffer.is_null() {
alloc::handle_alloc_error(layout);
}
// // Synthesize the fat pointer. We do this by claiming we have a direct
// // pointer to a [T], and then changing the type of the borrow. The key
// // point here is that the length portion of the fat pointer applies
// // only to the number of elements in the dynamically-sized portion of
// // the type, so the value will be the same whether it points to a [T]
// // or something else with a [T] as its last member.
// let fake_slice: &mut [T] = slice::from_raw_parts_mut(buffer as *mut T, num_items);
// ptr = fake_slice as *mut [T] as *mut ArcInner<HeaderSlice<H, [T]>>;
ptr = buffer as *mut _;
let count = atomic::AtomicUsize::new(1);
// Write the data.
//
// Note that any panics here (i.e. from the iterator) are safe, since
// we'll just leak the uninitialized memory.
ptr::write(ptr::addr_of_mut!((*ptr).count), count);
ptr::write(ptr::addr_of_mut!((*ptr).data.header), header);
ptr::write(ptr::addr_of_mut!((*ptr).data.length), num_items);
if num_items != 0 {
let mut current = ptr::addr_of_mut!((*ptr).data.slice) as *mut T;
debug_assert_eq!(current as usize - buffer as usize, slice_offset);
for _ in 0..num_items {
ptr::write(
current,
items
.next()
.expect("ExactSizeIterator over-reported length"),
);
current = current.offset(1);
}
assert!(
items.next().is_none(),
"ExactSizeIterator under-reported length"
);
// We should have consumed the buffer exactly.
debug_assert_eq!(current as *mut u8, buffer.add(usable_size));
}
assert!(
items.next().is_none(),
"ExactSizeIterator under-reported length"
);
}
ThinArc {
ptr: unsafe { ptr::NonNull::new_unchecked(ptr) },
phantom: PhantomData,
}
}
}
impl<H, T> Deref for ThinArc<H, T> {
type Target = HeaderSlice<H, [T]>;
#[inline]
fn deref(&self) -> &Self::Target {
unsafe { &(*thin_to_thick(self.ptr.as_ptr())).data }
}
}
impl<H, T> Clone for ThinArc<H, T> {
#[inline]
fn clone(&self) -> Self {
ThinArc::with_arc(self, |a| Arc::into_thin(a.clone()))
}
}
impl<H, T> Drop for ThinArc<H, T> {
#[inline]
fn drop(&mut self) {
let _ = Arc::from_thin(ThinArc {
ptr: self.ptr,
phantom: PhantomData,
});
}
}
impl<H, T> Arc<HeaderSlice<H, [T]>> {
/// Converts an `Arc` into a `ThinArc`. This consumes the `Arc`, so the refcount
/// is not modified.
#[inline]
pub(crate) fn into_thin(a: Self) -> ThinArc<H, T> {
assert_eq!(
a.length,
a.slice.len(),
"Length needs to be correct for ThinArc to work"
);
let fat_ptr: *mut ArcInner<HeaderSlice<H, [T]>> = a.ptr();
mem::forget(a);
let thin_ptr = fat_ptr as *mut [usize] as *mut usize;
ThinArc {
ptr: unsafe {
ptr::NonNull::new_unchecked(thin_ptr as *mut ArcInner<HeaderSlice<H, [T; 0]>>)
},
phantom: PhantomData,
}
}
/// Converts a `ThinArc` into an `Arc`. This consumes the `ThinArc`, so the refcount
/// is not modified.
#[inline]
pub(crate) fn from_thin(a: ThinArc<H, T>) -> Self {
let ptr = thin_to_thick(a.ptr.as_ptr());
mem::forget(a);
unsafe {
Arc {
p: ptr::NonNull::new_unchecked(ptr),
phantom: PhantomData,
}
}
}
}
impl<H: PartialEq, T: PartialEq> PartialEq for ThinArc<H, T> {
#[inline]
fn eq(&self, other: &ThinArc<H, T>) -> bool {
**self == **other
}
}
impl<H: Eq, T: Eq> Eq for ThinArc<H, T> {}
impl<H: Hash, T: Hash> Hash for ThinArc<H, T> {
fn hash<HSR: Hasher>(&self, state: &mut HSR) {
(**self).hash(state)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/cursor/node.rs | crates/rome_rowan/src/cursor/node.rs | use crate::cursor::{NodeData, SyntaxElement, SyntaxToken, SyntaxTrivia};
use crate::green::{Child, Children, GreenElementRef, Slot};
use crate::{
Direction, GreenNode, GreenNodeData, NodeOrToken, RawSyntaxKind, SyntaxNodeText, TokenAtOffset,
WalkEvent,
};
use rome_text_size::{TextRange, TextSize};
use std::hash::{Hash, Hasher};
use std::iter::FusedIterator;
use std::ops;
use std::ptr::NonNull;
use std::rc::Rc;
use std::{fmt, iter};
use super::{GreenElement, NodeKind, WeakGreenElement};
#[derive(Clone)]
pub(crate) struct SyntaxNode {
pub(super) ptr: Rc<NodeData>,
}
impl SyntaxNode {
pub(crate) fn new_root(green: GreenNode) -> SyntaxNode {
SyntaxNode {
ptr: NodeData::new(
NodeKind::Root {
green: GreenElement::Node(green),
},
0,
0.into(),
),
}
}
pub(super) fn new_child(
green: &GreenNodeData,
parent: SyntaxNode,
slot: u32,
offset: TextSize,
) -> SyntaxNode {
SyntaxNode {
ptr: NodeData::new(
NodeKind::Child {
green: WeakGreenElement::new(GreenElementRef::Node(green)),
parent: parent.ptr,
},
slot,
offset,
),
}
}
pub fn clone_subtree(&self) -> SyntaxNode {
SyntaxNode::new_root(self.green().into())
}
#[inline]
pub(super) fn data(&self) -> &NodeData {
self.ptr.as_ref()
}
#[inline]
pub fn kind(&self) -> RawSyntaxKind {
self.data().kind()
}
#[inline]
pub(super) fn offset(&self) -> TextSize {
self.data().offset()
}
pub(crate) fn element_in_slot(&self, slot_index: u32) -> Option<SyntaxElement> {
let slot = self
.slots()
.nth(slot_index as usize)
.expect("Slot index out of bounds");
slot.map(|element| element)
}
#[inline]
pub(crate) fn slots(&self) -> SyntaxSlots {
SyntaxSlots::new(self.clone())
}
#[inline]
pub fn text_range(&self) -> TextRange {
self.data().text_range()
}
pub fn text_trimmed_range(&self) -> TextRange {
let range = self.text_range();
let mut start = range.start();
let mut end = range.end();
// Remove all trivia from the start of the node
let mut token = self.first_token();
while let Some(t) = token.take() {
let (leading_len, trailing_len, total_len) = t.green().leading_trailing_total_len();
let token_len: u32 = (total_len - leading_len - trailing_len).into();
if token_len == 0 {
start += total_len;
token = t.next_token();
} else {
start += leading_len;
}
}
// Remove all trivia from the end of the node
let mut token = self.last_token();
while let Some(t) = token.take() {
let (leading_len, trailing_len, total_len) = t.green().leading_trailing_total_len();
let token_len: u32 = (total_len - leading_len - trailing_len).into();
if token_len == 0 {
end -= total_len;
token = t.prev_token();
} else {
end -= trailing_len;
}
}
TextRange::new(start, end.max(start))
}
pub fn first_leading_trivia(&self) -> Option<SyntaxTrivia> {
self.first_token().map(|x| x.leading_trivia())
}
pub fn last_trailing_trivia(&self) -> Option<SyntaxTrivia> {
self.last_token().map(|x| x.trailing_trivia())
}
#[inline]
pub fn index(&self) -> usize {
self.data().slot() as usize
}
#[inline]
pub fn text(&self) -> SyntaxNodeText {
SyntaxNodeText::new(self.clone())
}
#[inline]
pub fn text_trimmed(&self) -> SyntaxNodeText {
SyntaxNodeText::with_range(self.clone(), self.text_trimmed_range())
}
#[inline]
pub(crate) fn key(&self) -> (NonNull<()>, TextSize) {
self.data().key()
}
#[inline]
pub(crate) fn green(&self) -> &GreenNodeData {
self.data().green().into_node().unwrap()
}
#[inline]
pub fn parent(&self) -> Option<SyntaxNode> {
self.data().parent_node()
}
#[inline]
pub fn ancestors(&self) -> impl Iterator<Item = SyntaxNode> {
iter::successors(Some(self.clone()), SyntaxNode::parent)
}
#[inline]
pub fn children(&self) -> SyntaxNodeChildren {
SyntaxNodeChildren::new(self.clone())
}
#[inline]
pub fn children_with_tokens(&self) -> SyntaxElementChildren {
SyntaxElementChildren::new(self.clone())
}
#[inline]
pub fn tokens(&self) -> impl Iterator<Item = SyntaxToken> + DoubleEndedIterator + '_ {
self.green().children().filter_map(|child| {
child.element().into_token().map(|token| {
SyntaxToken::new(
token,
self.clone(),
child.slot(),
self.offset() + child.rel_offset(),
)
})
})
}
pub fn first_child(&self) -> Option<SyntaxNode> {
self.green().children().find_map(|child| {
child.element().into_node().map(|green| {
SyntaxNode::new_child(
green,
self.clone(),
child.slot(),
self.offset() + child.rel_offset(),
)
})
})
}
pub fn last_child(&self) -> Option<SyntaxNode> {
self.green().children().rev().find_map(|child| {
child.element().into_node().map(|green| {
SyntaxNode::new_child(
green,
self.clone(),
child.slot(),
self.offset() + child.rel_offset(),
)
})
})
}
pub fn first_child_or_token(&self) -> Option<SyntaxElement> {
self.green().children().next().map(|child| {
SyntaxElement::new(
child.element(),
self.clone(),
child.slot(),
self.offset() + child.rel_offset(),
)
})
}
pub fn last_child_or_token(&self) -> Option<SyntaxElement> {
self.green().children().next_back().map(|child| {
SyntaxElement::new(
child.element(),
self.clone(),
child.slot(),
self.offset() + child.rel_offset(),
)
})
}
pub fn next_sibling(&self) -> Option<SyntaxNode> {
self.data().next_sibling()
}
pub fn prev_sibling(&self) -> Option<SyntaxNode> {
self.data().prev_sibling()
}
pub fn next_sibling_or_token(&self) -> Option<SyntaxElement> {
self.data().next_sibling_or_token()
}
pub fn prev_sibling_or_token(&self) -> Option<SyntaxElement> {
self.data().prev_sibling_or_token()
}
pub fn first_token(&self) -> Option<SyntaxToken> {
self.descendants_with_tokens(Direction::Next)
.find_map(|x| x.into_token())
}
pub fn last_token(&self) -> Option<SyntaxToken> {
PreorderWithTokens::new(self.clone(), Direction::Prev)
.filter_map(|event| match event {
WalkEvent::Enter(it) => Some(it),
WalkEvent::Leave(_) => None,
})
.find_map(|x| x.into_token())
}
#[inline]
pub fn siblings(&self, direction: Direction) -> impl Iterator<Item = SyntaxNode> {
iter::successors(Some(self.clone()), move |node| match direction {
Direction::Next => node.next_sibling(),
Direction::Prev => node.prev_sibling(),
})
}
#[inline]
pub fn siblings_with_tokens(
&self,
direction: Direction,
) -> impl Iterator<Item = SyntaxElement> {
let me: SyntaxElement = self.clone().into();
iter::successors(Some(me), move |el| match direction {
Direction::Next => el.next_sibling_or_token(),
Direction::Prev => el.prev_sibling_or_token(),
})
}
#[inline]
pub fn descendants(&self) -> impl Iterator<Item = SyntaxNode> {
self.preorder().filter_map(|event| match event {
WalkEvent::Enter(node) => Some(node),
WalkEvent::Leave(_) => None,
})
}
#[inline]
pub fn descendants_with_tokens(
&self,
direction: Direction,
) -> impl Iterator<Item = SyntaxElement> {
self.preorder_with_tokens(direction)
.filter_map(|event| match event {
WalkEvent::Enter(it) => Some(it),
WalkEvent::Leave(_) => None,
})
}
#[inline]
pub fn preorder(&self) -> Preorder {
Preorder::new(self.clone())
}
#[inline]
pub fn preorder_with_tokens(&self, direction: Direction) -> PreorderWithTokens {
PreorderWithTokens::new(self.clone(), direction)
}
pub(crate) fn preorder_slots(&self) -> SlotsPreorder {
SlotsPreorder::new(self.clone())
}
pub fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
// TODO: this could be faster if we first drill-down to node, and only
// then switch to token search. We should also replace explicit
// recursion with a loop.
let range = self.text_range();
assert!(
range.start() <= offset && offset <= range.end(),
"Bad offset: range {:?} offset {:?}",
range,
offset
);
if range.is_empty() {
return TokenAtOffset::None;
}
let mut children = self.children_with_tokens().filter(|child| {
let child_range = child.text_range();
!child_range.is_empty() && child_range.contains_inclusive(offset)
});
let left = children.next().unwrap();
let right = children.next();
assert!(children.next().is_none());
if let Some(right) = right {
match (left.token_at_offset(offset), right.token_at_offset(offset)) {
(TokenAtOffset::Single(left), TokenAtOffset::Single(right)) => {
TokenAtOffset::Between(left, right)
}
_ => unreachable!(),
}
} else {
left.token_at_offset(offset)
}
}
pub fn covering_element(&self, range: TextRange) -> SyntaxElement {
let mut res: SyntaxElement = self.clone().into();
loop {
assert!(
res.text_range().contains_range(range),
"Bad range: node range {:?}, range {:?}",
res.text_range(),
range,
);
res = match &res {
NodeOrToken::Token(_) => return res,
NodeOrToken::Node(node) => match node.child_or_token_at_range(range) {
Some(it) => it,
None => return res,
},
};
}
}
pub fn child_or_token_at_range(&self, range: TextRange) -> Option<SyntaxElement> {
let rel_range = range - self.offset();
self.green()
.slot_at_range(rel_range)
.and_then(|(index, rel_offset, slot)| {
slot.as_ref().map(|green| {
SyntaxElement::new(
green,
self.clone(),
index as u32,
self.offset() + rel_offset,
)
})
})
}
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn detach(self) -> Self {
Self {
ptr: self.ptr.detach(),
}
}
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn splice_slots<R, I>(self, range: R, replace_with: I) -> Self
where
R: ops::RangeBounds<usize>,
I: Iterator<Item = Option<SyntaxElement>>,
{
Self {
ptr: self.ptr.splice_slots(
range,
replace_with.into_iter().map(|element| {
element.map(|child| match child.detach() {
NodeOrToken::Node(it) => it.ptr.into_green(),
NodeOrToken::Token(it) => it.into_green(),
})
}),
),
}
}
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn replace_child(self, prev_elem: SyntaxElement, next_elem: SyntaxElement) -> Option<Self> {
Some(Self {
ptr: self.ptr.replace_child(prev_elem, next_elem)?,
})
}
}
// Identity semantics for hash & eq
impl PartialEq for SyntaxNode {
#[inline]
fn eq(&self, other: &SyntaxNode) -> bool {
self.data().key() == other.data().key()
}
}
impl Eq for SyntaxNode {}
impl Hash for SyntaxNode {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.data().key().hash(state);
}
}
impl fmt::Debug for SyntaxNode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SyntaxNode")
.field("kind", &self.kind())
.field("text_range", &self.text_range())
.finish()
}
}
impl fmt::Display for SyntaxNode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.preorder_with_tokens(Direction::Next)
.filter_map(|event| match event {
WalkEvent::Enter(NodeOrToken::Token(token)) => Some(token),
_ => None,
})
.try_for_each(|it| fmt::Display::fmt(&it, f))
}
}
// region: iterators
#[derive(Clone, Debug)]
pub(crate) struct SyntaxNodeChildren {
next: Option<SyntaxNode>,
}
impl SyntaxNodeChildren {
fn new(parent: SyntaxNode) -> SyntaxNodeChildren {
SyntaxNodeChildren {
next: parent.first_child(),
}
}
}
impl Iterator for SyntaxNodeChildren {
type Item = SyntaxNode;
fn next(&mut self) -> Option<SyntaxNode> {
self.next.take().map(|next| {
self.next = next.next_sibling();
next
})
}
}
impl FusedIterator for SyntaxNodeChildren {}
#[derive(Clone, Debug, Default)]
pub(crate) struct SyntaxElementChildren {
next: Option<SyntaxElement>,
}
impl SyntaxElementChildren {
fn new(parent: SyntaxNode) -> SyntaxElementChildren {
SyntaxElementChildren {
next: parent.first_child_or_token(),
}
}
}
impl Iterator for SyntaxElementChildren {
type Item = SyntaxElement;
fn next(&mut self) -> Option<SyntaxElement> {
self.next.take().map(|next| {
self.next = next.next_sibling_or_token();
next
})
}
}
impl FusedIterator for SyntaxElementChildren {}
pub(crate) struct Preorder {
start: SyntaxNode,
next: Option<WalkEvent<SyntaxNode>>,
skip_subtree: bool,
}
impl Preorder {
fn new(start: SyntaxNode) -> Preorder {
let next = Some(WalkEvent::Enter(start.clone()));
Preorder {
start,
next,
skip_subtree: false,
}
}
pub fn skip_subtree(&mut self) {
self.skip_subtree = true;
}
#[cold]
fn do_skip(&mut self) {
self.next = self.next.take().map(|next| match next {
WalkEvent::Enter(first_child) => WalkEvent::Leave(first_child.parent().unwrap()),
WalkEvent::Leave(parent) => WalkEvent::Leave(parent),
})
}
}
impl Iterator for Preorder {
type Item = WalkEvent<SyntaxNode>;
fn next(&mut self) -> Option<WalkEvent<SyntaxNode>> {
if self.skip_subtree {
self.do_skip();
self.skip_subtree = false;
}
let next = self.next.take();
self.next = next.as_ref().and_then(|next| {
Some(match next {
WalkEvent::Enter(node) => match node.first_child() {
Some(child) => WalkEvent::Enter(child),
None => WalkEvent::Leave(node.clone()),
},
WalkEvent::Leave(node) => {
if node == &self.start {
return None;
}
match node.next_sibling() {
Some(sibling) => WalkEvent::Enter(sibling),
None => WalkEvent::Leave(node.parent()?),
}
}
})
});
next
}
}
impl FusedIterator for Preorder {}
pub(crate) struct PreorderWithTokens {
start: SyntaxElement,
next: Option<WalkEvent<SyntaxElement>>,
skip_subtree: bool,
direction: Direction,
}
impl PreorderWithTokens {
fn new(start: SyntaxNode, direction: Direction) -> PreorderWithTokens {
let next = Some(WalkEvent::Enter(start.clone().into()));
PreorderWithTokens {
start: start.into(),
next,
direction,
skip_subtree: false,
}
}
pub fn skip_subtree(&mut self) {
self.skip_subtree = true;
}
#[cold]
fn do_skip(&mut self) {
self.next = self.next.take().map(|next| match next {
WalkEvent::Enter(first_child) => WalkEvent::Leave(first_child.parent().unwrap().into()),
WalkEvent::Leave(parent) => WalkEvent::Leave(parent),
})
}
}
impl Iterator for PreorderWithTokens {
type Item = WalkEvent<SyntaxElement>;
fn next(&mut self) -> Option<WalkEvent<SyntaxElement>> {
if self.skip_subtree {
self.do_skip();
self.skip_subtree = false;
}
let next = self.next.take();
self.next = next.as_ref().and_then(|next| {
Some(match next {
WalkEvent::Enter(el) => match el {
NodeOrToken::Node(node) => {
let next = match self.direction {
Direction::Next => node.first_child_or_token(),
Direction::Prev => node.last_child_or_token(),
};
match next {
Some(child) => WalkEvent::Enter(child),
None => WalkEvent::Leave(node.clone().into()),
}
}
NodeOrToken::Token(token) => WalkEvent::Leave(token.clone().into()),
},
WalkEvent::Leave(el) if el == &self.start => return None,
WalkEvent::Leave(el) => {
let next = match self.direction {
Direction::Next => el.next_sibling_or_token(),
Direction::Prev => el.prev_sibling_or_token(),
};
match next {
Some(sibling) => WalkEvent::Enter(sibling),
None => WalkEvent::Leave(el.parent()?.into()),
}
}
})
});
next
}
}
impl FusedIterator for PreorderWithTokens {}
/// Represents a cursor to a green node slot. A slot either contains an element or is empty
/// if the child isn't present in the source.
#[derive(Debug, Clone)]
pub(crate) enum SyntaxSlot {
Node(SyntaxNode),
Token(SyntaxToken),
Empty { parent: SyntaxNode, index: u32 },
}
impl From<SyntaxElement> for SyntaxSlot {
fn from(element: SyntaxElement) -> Self {
match element {
SyntaxElement::Node(node) => SyntaxSlot::Node(node),
SyntaxElement::Token(token) => SyntaxSlot::Token(token),
}
}
}
impl SyntaxSlot {
#[inline]
pub fn map<F, R>(self, mapper: F) -> Option<R>
where
F: FnOnce(SyntaxElement) -> R,
{
match self {
SyntaxSlot::Node(node) => Some(mapper(SyntaxElement::Node(node))),
SyntaxSlot::Token(token) => Some(mapper(SyntaxElement::Token(token))),
SyntaxSlot::Empty { .. } => None,
}
}
}
/// Iterator over a node's slots
#[derive(Debug, Clone)]
pub(crate) struct SyntaxSlots {
/// Position of the next element to return.
pos: u32,
/// Position of the last returned element from the back.
/// Initially points one element past the last slot.
///
/// [nth_back]: https://doc.rust-lang.org/std/iter/trait.DoubleEndedIterator.html#method.nth_back
back_pos: u32,
parent: SyntaxNode,
}
impl SyntaxSlots {
#[inline]
fn new(parent: SyntaxNode) -> Self {
Self {
pos: 0,
back_pos: parent.green().slice().len() as u32,
parent,
}
}
/// Returns a slice containing the remaining elements to iterate over
/// an empty slice if the iterator reached the end.
#[inline]
fn slice(&self) -> &[Slot] {
if self.pos < self.back_pos {
&self.parent.green().slice()[self.pos as usize..self.back_pos as usize]
} else {
&[]
}
}
fn map_slot(&self, slot: &Slot, slot_index: u32) -> SyntaxSlot {
match slot {
Slot::Empty { .. } => SyntaxSlot::Empty {
parent: self.parent.clone(),
index: slot_index,
},
Slot::Token { rel_offset, token } => SyntaxSlot::Token(SyntaxToken::new(
token,
self.parent.clone(),
slot_index,
self.parent.offset() + rel_offset,
)),
Slot::Node { rel_offset, node } => SyntaxSlot::Node(SyntaxNode::new_child(
node,
self.parent.clone(),
slot_index,
self.parent.offset() + rel_offset,
)),
}
}
}
impl Iterator for SyntaxSlots {
type Item = SyntaxSlot;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let slot = self.slice().first()?;
let mapped = self.map_slot(slot, self.pos);
self.pos += 1;
Some(mapped)
}
#[inline(always)]
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.slice().len();
(len, Some(len))
}
#[inline(always)]
fn count(self) -> usize
where
Self: Sized,
{
self.len()
}
#[inline]
fn last(mut self) -> Option<Self::Item>
where
Self: Sized,
{
self.next_back()
}
#[inline]
fn nth(&mut self, n: usize) -> Option<Self::Item> {
self.pos += n as u32;
self.next()
}
}
impl ExactSizeIterator for SyntaxSlots {
#[inline(always)]
fn len(&self) -> usize {
self.slice().len()
}
}
impl FusedIterator for SyntaxSlots {}
impl DoubleEndedIterator for SyntaxSlots {
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
let slot = self.slice().last()?;
let mapped = self.map_slot(slot, self.back_pos - 1);
self.back_pos -= 1;
Some(mapped)
}
#[inline]
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
self.back_pos -= n as u32;
self.next_back()
}
}
/// Iterator to visit a node's slots in pre-order.
pub(crate) struct SlotsPreorder {
start: SyntaxNode,
next: Option<WalkEvent<SyntaxSlot>>,
}
impl SlotsPreorder {
fn new(start: SyntaxNode) -> Self {
let next = Some(WalkEvent::Enter(SyntaxSlot::Node(start.clone())));
SlotsPreorder { start, next }
}
}
impl Iterator for SlotsPreorder {
type Item = WalkEvent<SyntaxSlot>;
fn next(&mut self) -> Option<WalkEvent<SyntaxSlot>> {
let next = self.next.take();
self.next = next.as_ref().and_then(|next| {
Some(match next {
WalkEvent::Enter(slot) => match slot {
SyntaxSlot::Empty { .. } | SyntaxSlot::Token(_) => {
WalkEvent::Leave(slot.clone())
}
SyntaxSlot::Node(node) => match node.slots().next() {
None => WalkEvent::Leave(SyntaxSlot::Node(node.clone())),
Some(first_slot) => WalkEvent::Enter(first_slot),
},
},
WalkEvent::Leave(slot) => {
let (parent, slot_index) = match slot {
SyntaxSlot::Empty { parent, index } => (parent.clone(), *index as usize),
SyntaxSlot::Token(token) => (token.parent()?, token.index()),
SyntaxSlot::Node(node) => {
if node == &self.start {
return None;
}
(node.parent()?, node.index())
}
};
let next_slot = parent.slots().nth(slot_index + 1);
match next_slot {
Some(slot) => WalkEvent::Enter(slot),
None => WalkEvent::Leave(SyntaxSlot::Node(parent)),
}
}
})
});
next
}
}
impl FusedIterator for SlotsPreorder {}
#[derive(Debug, Clone)]
pub(crate) struct Siblings<'a> {
parent: &'a GreenNodeData,
start_slot: u32,
}
impl<'a> Siblings<'a> {
pub fn new(parent: &'a GreenNodeData, start_slot: u32) -> Self {
assert!(
(start_slot as usize) < parent.slots().len(),
"Start slot {} out of bounds {}",
start_slot,
parent.slots().len()
);
Self { parent, start_slot }
}
/// Creates an iterator over the siblings following the start node.
/// For example, the following siblings of the if statement's condition are
/// * the consequence
/// * potentially the else clause
pub fn following(&self) -> Children<'a> {
let mut slots = self.parent.slots().enumerate();
// Navigate to the start slot so that calling `next` returns the first following sibling
slots.nth(self.start_slot as usize);
Children::new(slots)
}
/// Creates an iterator over the siblings preceding the start node in reverse order.
/// For example, the preceding siblings of the if statement's condition are:
/// * opening parentheses: (
/// * if keyword: if
pub fn previous(&self) -> impl Iterator<Item = Child<'a>> {
let mut slots = self.parent.slots().enumerate();
// Navigate to the start slot from the back so that calling `next_back` (or rev().next()) returns
// the first slot preceding the start node
slots.nth_back(slots.len() - 1 - self.start_slot as usize);
Children::new(slots).rev()
}
}
// endregion
#[cfg(test)]
mod tests {
use crate::raw_language::{RawLanguageKind, RawSyntaxTreeBuilder};
#[test]
fn slots_iter() {
let mut builder = RawSyntaxTreeBuilder::new();
builder.start_node(RawLanguageKind::EXPRESSION_LIST);
for number in [1, 2, 3, 4] {
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::NUMBER_TOKEN, &number.to_string());
builder.finish_node();
}
builder.finish_node();
let list = builder.finish();
let mut iter = list.slots();
assert_eq!(iter.size_hint(), (4, Some(4)));
assert_eq!(
iter.next()
.and_then(|slot| slot.into_node())
.map(|node| node.text().to_string())
.as_deref(),
Some("1")
);
assert_eq!(iter.size_hint(), (3, Some(3)));
assert_eq!(
iter.next_back()
.and_then(|slot| slot.into_node())
.map(|node| node.text().to_string())
.as_deref(),
Some("4")
);
assert_eq!(iter.size_hint(), (2, Some(2)));
assert_eq!(
iter.last()
.and_then(|slot| slot.into_node())
.map(|node| node.text().to_string())
.as_deref(),
Some("3")
);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/cursor/element.rs | crates/rome_rowan/src/cursor/element.rs | use crate::cursor::{SyntaxNode, SyntaxToken};
use crate::green::{GreenElement, GreenElementRef};
use crate::{NodeOrToken, RawSyntaxKind, TokenAtOffset};
use rome_text_size::{TextRange, TextSize};
use std::iter;
pub(crate) type SyntaxElement = NodeOrToken<SyntaxNode, SyntaxToken>;
impl SyntaxElement {
pub(super) fn new(
element: GreenElementRef<'_>,
parent: SyntaxNode,
slot: u32,
offset: TextSize,
) -> SyntaxElement {
match element {
NodeOrToken::Node(node) => SyntaxNode::new_child(node, parent, slot, offset).into(),
NodeOrToken::Token(token) => SyntaxToken::new(token, parent, slot, offset).into(),
}
}
#[inline]
pub fn text_range(&self) -> TextRange {
match self {
NodeOrToken::Node(it) => it.text_range(),
NodeOrToken::Token(it) => it.text_range(),
}
}
#[inline]
pub fn index(&self) -> usize {
match self {
NodeOrToken::Node(it) => it.index(),
NodeOrToken::Token(it) => it.index(),
}
}
#[inline]
pub fn kind(&self) -> RawSyntaxKind {
match self {
NodeOrToken::Node(it) => it.kind(),
NodeOrToken::Token(it) => it.kind(),
}
}
#[inline]
pub fn parent(&self) -> Option<SyntaxNode> {
match self {
NodeOrToken::Node(it) => it.parent(),
NodeOrToken::Token(it) => it.parent(),
}
}
#[inline]
pub fn ancestors(&self) -> impl Iterator<Item = SyntaxNode> {
let first = match self {
NodeOrToken::Node(it) => Some(it.clone()),
NodeOrToken::Token(it) => it.parent(),
};
iter::successors(first, SyntaxNode::parent)
}
pub fn first_token(&self) -> Option<SyntaxToken> {
match self {
NodeOrToken::Node(it) => it.first_token(),
NodeOrToken::Token(it) => Some(it.clone()),
}
}
pub fn last_token(&self) -> Option<SyntaxToken> {
match self {
NodeOrToken::Node(it) => it.last_token(),
NodeOrToken::Token(it) => Some(it.clone()),
}
}
pub fn next_sibling_or_token(&self) -> Option<SyntaxElement> {
match self {
NodeOrToken::Node(it) => it.next_sibling_or_token(),
NodeOrToken::Token(it) => it.next_sibling_or_token(),
}
}
pub fn prev_sibling_or_token(&self) -> Option<SyntaxElement> {
match self {
NodeOrToken::Node(it) => it.prev_sibling_or_token(),
NodeOrToken::Token(it) => it.prev_sibling_or_token(),
}
}
pub(super) fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken> {
assert!(self.text_range().start() <= offset && offset <= self.text_range().end());
match self {
NodeOrToken::Token(token) => TokenAtOffset::Single(token.clone()),
NodeOrToken::Node(node) => node.token_at_offset(offset),
}
}
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn detach(self) -> Self {
match self {
NodeOrToken::Node(it) => Self::Node(it.detach()),
NodeOrToken::Token(it) => Self::Token(it.detach()),
}
}
pub(crate) fn into_green(self) -> GreenElement {
match self {
NodeOrToken::Node(it) => it.ptr.into_green(),
NodeOrToken::Token(it) => it.into_green(),
}
}
}
// region: impls
impl From<SyntaxNode> for SyntaxElement {
#[inline]
fn from(node: SyntaxNode) -> SyntaxElement {
NodeOrToken::Node(node)
}
}
impl From<SyntaxToken> for SyntaxElement {
#[inline]
fn from(token: SyntaxToken) -> SyntaxElement {
NodeOrToken::Token(token)
}
}
// endregion
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/cursor/trivia.rs | crates/rome_rowan/src/cursor/trivia.rs | use crate::cursor::SyntaxToken;
use crate::green::GreenTrivia;
use crate::TriviaPiece;
use rome_text_size::{TextRange, TextSize};
use std::fmt;
use std::iter::FusedIterator;
#[derive(PartialEq, Eq, Clone, Hash)]
pub(crate) struct SyntaxTrivia {
token: SyntaxToken,
is_leading: bool,
}
impl SyntaxTrivia {
pub(super) fn leading(token: SyntaxToken) -> Self {
Self {
token,
is_leading: true,
}
}
pub(super) fn trailing(token: SyntaxToken) -> Self {
Self {
token,
is_leading: false,
}
}
pub(crate) fn text(&self) -> &str {
let trivia_range = self.text_range();
let relative_range = TextRange::at(
trivia_range.start() - self.token.data().offset,
trivia_range.len(),
);
&self.token.text()[relative_range]
}
pub(crate) fn token(&self) -> &SyntaxToken {
&self.token
}
pub(crate) fn text_range(&self) -> TextRange {
let length = self.green_trivia().text_len();
let token_range = self.token.text_range();
match self.is_leading {
true => TextRange::at(token_range.start(), length),
false => TextRange::at(token_range.end() - length, length),
}
}
/// Get the number of TriviaPiece inside this trivia
pub(crate) fn len(&self) -> usize {
self.green_trivia().len()
}
/// Gets index-th trivia piece when the token associated with this trivia was created.
/// See [SyntaxTriviaPiece].
pub(crate) fn get_piece(&self, index: usize) -> Option<&TriviaPiece> {
self.green_trivia().get_piece(index)
}
fn green_trivia(&self) -> &GreenTrivia {
match self.is_leading {
true => self.token.green().leading_trivia(),
false => self.token.green().trailing_trivia(),
}
}
/// Returns the last trivia piece element
pub(crate) fn last(&self) -> Option<&TriviaPiece> {
self.green_trivia().pieces().last()
}
/// Returns the first trivia piece element
pub(crate) fn first(&self) -> Option<&TriviaPiece> {
self.green_trivia().pieces().first()
}
/// Iterate over all pieces of the trivia. The iterator returns the offset
/// of the trivia as [TextSize] and its data as [Trivia], which contains its length.
/// See [SyntaxTriviaPiece].
pub(crate) fn pieces(&self) -> SyntaxTriviaPiecesIterator {
let range = self.text_range();
SyntaxTriviaPiecesIterator {
raw: self.clone(),
next_index: 0,
next_offset: range.start(),
end_index: self.len(),
end_offset: range.end(),
}
}
}
impl fmt::Debug for SyntaxTrivia {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut f = f.debug_struct("SyntaxTrivia");
f.field("text_range", &self.text_range());
f.finish()
}
}
impl fmt::Display for SyntaxTrivia {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self.text(), f)
}
}
#[derive(Clone)]
pub struct SyntaxTriviaPiecesIterator {
pub(crate) raw: SyntaxTrivia,
pub(crate) next_index: usize,
pub(crate) next_offset: TextSize,
pub(crate) end_index: usize,
pub(crate) end_offset: TextSize,
}
impl Iterator for SyntaxTriviaPiecesIterator {
type Item = (TextSize, TriviaPiece);
fn next(&mut self) -> Option<Self::Item> {
let trivia = self.raw.get_piece(self.next_index)?;
let piece = (self.next_offset, *trivia);
self.next_index += 1;
self.next_offset += trivia.text_len();
Some(piece)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.end_index.saturating_sub(self.next_index);
(len, Some(len))
}
}
impl FusedIterator for SyntaxTriviaPiecesIterator {}
impl DoubleEndedIterator for SyntaxTriviaPiecesIterator {
fn next_back(&mut self) -> Option<Self::Item> {
if self.end_index == self.next_index {
return None;
}
self.end_index -= 1;
let trivia = self.raw.get_piece(self.end_index)?;
self.end_offset -= trivia.text_len();
Some((self.end_offset, *trivia))
}
}
impl ExactSizeIterator for SyntaxTriviaPiecesIterator {}
#[cfg(test)]
mod tests {
use crate::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
use crate::{SyntaxNode, TriviaPiece, TriviaPieceKind};
#[test]
fn trivia_text() {
let mut builder = RawSyntaxTreeBuilder::new();
builder.start_node(RawLanguageKind::ROOT);
builder.token_with_trivia(
RawLanguageKind::WHITESPACE,
"\t let \t\t",
&[TriviaPiece::new(TriviaPieceKind::Whitespace, 2)],
&[TriviaPiece::new(TriviaPieceKind::Whitespace, 3)],
);
builder.finish_node();
let root = builder.finish_green();
let syntax: SyntaxNode<RawLanguage> = SyntaxNode::new_root(root);
let token = syntax.first_token().unwrap();
assert_eq!(token.leading_trivia().text(), "\t ");
assert_eq!(token.trailing_trivia().text(), " \t\t");
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/cursor/token.rs | crates/rome_rowan/src/cursor/token.rs | use crate::cursor::{NodeData, SyntaxElement, SyntaxNode, SyntaxTrivia};
use crate::green::GreenElementRef;
use crate::{green, Direction, GreenToken, GreenTokenData, RawSyntaxKind, TokenText, WalkEvent};
use rome_text_size::{TextRange, TextSize};
use std::hash::{Hash, Hasher};
use std::ptr::NonNull;
use std::rc::Rc;
use std::{fmt, iter};
use super::{GreenElement, NodeKind, WeakGreenElement};
#[derive(Clone, Debug)]
pub(crate) struct SyntaxToken {
ptr: Rc<NodeData>,
}
impl SyntaxToken {
pub(super) fn new(
green: &GreenTokenData,
parent: SyntaxNode,
index: u32,
offset: TextSize,
) -> SyntaxToken {
SyntaxToken {
ptr: NodeData::new(
NodeKind::Child {
green: WeakGreenElement::new(GreenElementRef::Token(green)),
parent: parent.ptr,
},
index,
offset,
),
}
}
pub(crate) fn new_detached(green: GreenToken) -> SyntaxToken {
SyntaxToken {
ptr: NodeData::new(
NodeKind::Root {
green: GreenElement::Token(green),
},
0,
TextSize::from(0),
),
}
}
#[inline]
pub(crate) fn green(&self) -> &GreenTokenData {
match self.data().green().as_token() {
Some(token) => token,
None => {
panic!(
"corrupted tree: a node thinks it is a token: {:?}",
self.data().green().as_node().unwrap().to_string()
);
}
}
}
pub(crate) fn key(&self) -> (NonNull<()>, TextSize) {
self.data().key()
}
#[inline]
pub(super) fn data(&self) -> &NodeData {
self.ptr.as_ref()
}
#[inline]
pub(super) fn into_green(self) -> green::GreenElement {
self.ptr.into_green()
}
#[inline]
pub fn kind(&self) -> RawSyntaxKind {
self.data().kind()
}
#[inline]
pub fn text_range(&self) -> TextRange {
self.data().text_range()
}
#[inline]
pub fn text_trimmed_range(&self) -> TextRange {
let green_token = self.green();
let leading_len = green_token.leading_trivia().text_len();
let trailing_len = green_token.trailing_trivia().text_len();
let range = self.text_range();
TextRange::new(range.start() + leading_len, range.end() - trailing_len)
}
#[inline]
pub fn index(&self) -> usize {
self.data().slot() as usize
}
#[inline]
pub fn text(&self) -> &str {
self.green().text()
}
#[inline]
pub fn token_text(&self) -> TokenText {
TokenText::new(self.green().to_owned())
}
#[inline]
pub fn token_text_trimmed(&self) -> TokenText {
let green = self.green().to_owned();
let mut range = self.text_trimmed_range();
range -= self.data().offset;
TokenText::with_range(green, range)
}
#[inline]
pub fn text_trimmed(&self) -> &str {
self.green().text_trimmed()
}
#[inline]
pub fn parent(&self) -> Option<SyntaxNode> {
self.data().parent_node()
}
#[inline]
pub fn ancestors(&self) -> impl Iterator<Item = SyntaxNode> {
std::iter::successors(self.parent(), SyntaxNode::parent)
}
pub fn next_sibling_or_token(&self) -> Option<SyntaxElement> {
self.data().next_sibling_or_token()
}
pub fn prev_sibling_or_token(&self) -> Option<SyntaxElement> {
self.data().prev_sibling_or_token()
}
#[inline]
pub fn siblings_with_tokens(
&self,
direction: Direction,
) -> impl Iterator<Item = SyntaxElement> {
let next = move |el: &SyntaxElement| match direction {
Direction::Next => el.next_sibling_or_token(),
Direction::Prev => el.prev_sibling_or_token(),
};
let me: SyntaxElement = self.clone().into();
iter::successors(next(&me), next)
}
pub fn next_token(&self) -> Option<SyntaxToken> {
self.next_token_impl(Direction::Next)
}
pub fn prev_token(&self) -> Option<SyntaxToken> {
self.next_token_impl(Direction::Prev)
}
/// Returns the token preceding or following this token depending on the passed `direction`.
fn next_token_impl(&self, direction: Direction) -> Option<SyntaxToken> {
let mut current: WalkEvent<SyntaxElement> =
WalkEvent::Leave(SyntaxElement::Token(self.clone()));
loop {
current = match current {
WalkEvent::Enter(element) => match element {
SyntaxElement::Token(token) => break Some(token),
SyntaxElement::Node(node) => {
let first_child = match direction {
Direction::Next => node.first_child_or_token(),
Direction::Prev => node.last_child_or_token(),
};
match first_child {
// If node is empty, leave parent
None => WalkEvent::Leave(SyntaxElement::Node(node)),
// Otherwise traverse full sub-tree
Some(child) => WalkEvent::Enter(child),
}
}
},
WalkEvent::Leave(element) => {
let mut current_element = element;
loop {
// Only traverse the left (pref) / right (next) siblings of the parent
// to avoid traversing into the same children again.
let sibling = match direction {
Direction::Next => current_element.next_sibling_or_token(),
Direction::Prev => current_element.prev_sibling_or_token(),
};
match sibling {
// Traverse all children of the sibling
Some(sibling) => break WalkEvent::Enter(sibling),
None => {
match current_element.parent() {
Some(node) => {
current_element = SyntaxElement::Node(node);
}
None => {
return None; // Reached root, no token found
}
}
}
}
}
}
}
}
}
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn detach(self) -> Self {
Self {
ptr: self.ptr.detach(),
}
}
#[inline]
pub fn leading_trivia(&self) -> SyntaxTrivia {
SyntaxTrivia::leading(self.clone())
}
#[inline]
pub fn trailing_trivia(&self) -> SyntaxTrivia {
SyntaxTrivia::trailing(self.clone())
}
}
// Identity semantics for hash & eq
impl PartialEq for SyntaxToken {
#[inline]
fn eq(&self, other: &SyntaxToken) -> bool {
self.data().key() == other.data().key()
}
}
impl Eq for SyntaxToken {}
impl Hash for SyntaxToken {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.data().key().hash(state);
}
}
impl fmt::Display for SyntaxToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self.text(), f)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/syntax_factory/raw_syntax.rs | crates/rome_rowan/src/syntax_factory/raw_syntax.rs | use crate::green::GreenElement;
use crate::{GreenNode, GreenToken, NodeOrToken, SyntaxKind};
use std::marker::PhantomData;
/// New-type wrapper around a `GreenNode`.
///
/// Allows third-party crates to access limited information about a `GreenNode` or construct
/// a `GreenNode` in a limited places.
#[derive(Debug)]
pub struct RawSyntaxNode<K: SyntaxKind> {
raw: GreenNode,
ph: PhantomData<K>,
}
impl<K: SyntaxKind> RawSyntaxNode<K> {
/// Creates a new node with the given `kind` and `slots`.
#[inline]
pub fn new<I>(kind: K, slots: I) -> Self
where
I: IntoIterator<Item = Option<RawSyntaxElement<K>>>,
I::IntoIter: ExactSizeIterator,
{
Self {
raw: GreenNode::new(
kind.to_raw(),
slots
.into_iter()
.map(|slot| slot.map(|element| element.into_green())),
),
ph: PhantomData,
}
}
#[inline]
pub fn kind(&self) -> K {
K::from_raw(self.raw.kind())
}
/// Unwraps this raw syntax into it's underlying green node.
#[inline]
pub(crate) fn into_green(self) -> GreenNode {
self.raw
}
}
impl<K: SyntaxKind> From<GreenNode> for RawSyntaxNode<K> {
#[inline]
fn from(node: GreenNode) -> Self {
Self {
raw: node,
ph: PhantomData,
}
}
}
/// New-type wrapper around a `GreenToken`. Allows third-party crates to access limited information
/// on not yet fully constructed nodes.
#[derive(Debug)]
pub struct RawSyntaxToken<K: SyntaxKind> {
raw: GreenToken,
ph: PhantomData<K>,
}
impl<K: SyntaxKind> RawSyntaxToken<K> {
#[inline]
pub fn kind(&self) -> K {
K::from_raw(self.raw.kind())
}
}
impl<K: SyntaxKind> From<GreenToken> for RawSyntaxToken<K> {
fn from(token: GreenToken) -> Self {
Self {
raw: token,
ph: PhantomData,
}
}
}
pub type RawSyntaxElement<K> = NodeOrToken<RawSyntaxNode<K>, RawSyntaxToken<K>>;
impl<K: SyntaxKind> RawSyntaxElement<K> {
#[inline]
pub fn kind(&self) -> K {
match self {
NodeOrToken::Node(node) => node.kind(),
NodeOrToken::Token(token) => token.kind(),
}
}
#[inline]
fn into_green(self) -> GreenElement {
match self {
NodeOrToken::Node(node) => NodeOrToken::Node(node.raw),
NodeOrToken::Token(token) => NodeOrToken::Token(token.raw),
}
}
}
impl<K: SyntaxKind> From<GreenElement> for RawSyntaxElement<K> {
#[inline]
fn from(element: GreenElement) -> Self {
match element {
NodeOrToken::Node(node) => NodeOrToken::Node(RawSyntaxNode::from(node)),
NodeOrToken::Token(token) => NodeOrToken::Token(RawSyntaxToken::from(token)),
}
}
}
/// New-type wrapper to a reference of a `GreenNode`.
#[derive(Debug)]
pub struct RawSyntaxNodeRef<'a, K: SyntaxKind> {
raw: &'a GreenNode,
ph: PhantomData<K>,
}
impl<'a, K: SyntaxKind> RawSyntaxNodeRef<'a, K> {
#[inline]
pub fn kind(&self) -> K {
K::from_raw(self.raw.kind())
}
}
impl<'a, K: SyntaxKind> From<&'a GreenNode> for RawSyntaxNodeRef<'a, K> {
#[inline]
fn from(node: &'a GreenNode) -> Self {
Self {
raw: node,
ph: PhantomData,
}
}
}
/// New-type wrapper to a reference of a `GreenToken`
#[derive(Debug)]
pub struct RawSyntaxTokenRef<'a, K: SyntaxKind> {
raw: &'a GreenToken,
ph: PhantomData<K>,
}
impl<'a, K: SyntaxKind> RawSyntaxTokenRef<'a, K> {
#[inline]
pub fn kind(&self) -> K {
K::from_raw(self.raw.kind())
}
}
impl<'a, K: SyntaxKind> From<&'a GreenToken> for RawSyntaxTokenRef<'a, K> {
#[inline]
fn from(token: &'a GreenToken) -> Self {
Self {
raw: token,
ph: PhantomData,
}
}
}
pub type RawSyntaxElementRef<'a, K> =
NodeOrToken<RawSyntaxNodeRef<'a, K>, RawSyntaxTokenRef<'a, K>>;
impl<'a, K: SyntaxKind> RawSyntaxElementRef<'a, K> {
#[inline]
pub fn kind(&self) -> K {
match self {
NodeOrToken::Node(node) => node.kind(),
NodeOrToken::Token(token) => token.kind(),
}
}
}
impl<'a, K: SyntaxKind> From<NodeOrToken<&'a GreenNode, &'a GreenToken>>
for RawSyntaxElementRef<'a, K>
{
#[inline]
fn from(element: NodeOrToken<&'a GreenNode, &'a GreenToken>) -> Self {
match element {
NodeOrToken::Node(node) => NodeOrToken::Node(RawSyntaxNodeRef::from(node)),
NodeOrToken::Token(token) => NodeOrToken::Token(RawSyntaxTokenRef::from(token)),
}
}
}
impl<'a, K: SyntaxKind> From<&'a GreenElement> for RawSyntaxElementRef<'a, K> {
#[inline]
fn from(element: &'a GreenElement) -> Self {
match element {
NodeOrToken::Node(node) => NodeOrToken::Node(RawSyntaxNodeRef::from(node)),
NodeOrToken::Token(token) => NodeOrToken::Token(RawSyntaxTokenRef::from(token)),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/syntax_factory/parsed_children.rs | crates/rome_rowan/src/syntax_factory/parsed_children.rs | use crate::green::GreenElement;
use crate::syntax_factory::raw_syntax::{RawSyntaxElement, RawSyntaxElementRef};
use crate::SyntaxKind;
use std::iter::FusedIterator;
use std::marker::PhantomData;
/// The parsed children of a node, not accounting for any missing children (required or optional)
#[derive(Debug)]
pub struct ParsedChildren<'a, K> {
/// Reference to an array containing all children of this node or any of its parents
all_children: &'a mut Vec<(u64, GreenElement)>,
/// The index of the first child of this node in the `all_children` array
first_child: usize,
ph: PhantomData<K>,
}
impl<'a, K: SyntaxKind> ParsedChildren<'a, K> {
pub(crate) fn new(all_children: &'a mut Vec<(u64, GreenElement)>, first_child: usize) -> Self {
Self {
all_children,
first_child,
ph: PhantomData,
}
}
pub fn len(&self) -> usize {
(self.first_child..self.all_children.len()).len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl<'a, K: SyntaxKind> IntoIterator for ParsedChildren<'a, K> {
type Item = RawSyntaxElement<K>;
type IntoIter = ParsedChildrenIntoIterator<'a, K>;
fn into_iter(self) -> Self::IntoIter {
ParsedChildrenIntoIterator {
inner: self.all_children.drain(self.first_child..),
ph: PhantomData,
}
}
}
#[derive(Debug)]
pub struct ParsedChildrenIntoIterator<'a, K> {
inner: std::vec::Drain<'a, (u64, GreenElement)>,
ph: PhantomData<K>,
}
impl<'a, K: SyntaxKind> Iterator for ParsedChildrenIntoIterator<'a, K> {
type Item = RawSyntaxElement<K>;
fn next(&mut self) -> Option<Self::Item> {
self.inner
.next()
.map(|(_, raw)| RawSyntaxElement::from(raw))
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
}
impl<'a, K: SyntaxKind> FusedIterator for ParsedChildrenIntoIterator<'a, K> {}
impl<'a, K: SyntaxKind> ExactSizeIterator for ParsedChildrenIntoIterator<'a, K> {
fn len(&self) -> usize {
self.inner.len()
}
}
impl<'a, K: SyntaxKind> DoubleEndedIterator for ParsedChildrenIntoIterator<'a, K> {
fn next_back(&mut self) -> Option<Self::Item> {
self.inner
.next_back()
.map(|(_, raw)| RawSyntaxElement::from(raw))
}
}
impl<'a, K: SyntaxKind> IntoIterator for &'a ParsedChildren<'a, K> {
type Item = RawSyntaxElementRef<'a, K>;
type IntoIter = ParsedChildrenIterator<'a, K>;
fn into_iter(self) -> Self::IntoIter {
ParsedChildrenIterator {
inner: self.all_children[self.first_child..].iter(),
ph: PhantomData,
}
}
}
#[derive(Debug)]
pub struct ParsedChildrenIterator<'a, K> {
inner: std::slice::Iter<'a, (u64, GreenElement)>,
ph: PhantomData<K>,
}
impl<'a, K: SyntaxKind> Iterator for ParsedChildrenIterator<'a, K> {
type Item = RawSyntaxElementRef<'a, K>;
fn next(&mut self) -> Option<Self::Item> {
self.inner
.next()
.map(|(_, raw)| RawSyntaxElementRef::from(raw))
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
}
impl<'a, K: SyntaxKind> FusedIterator for ParsedChildrenIterator<'a, K> {}
impl<'a, K: SyntaxKind> ExactSizeIterator for ParsedChildrenIterator<'a, K> {
fn len(&self) -> usize {
self.inner.len()
}
}
impl<'a, K: SyntaxKind> DoubleEndedIterator for ParsedChildrenIterator<'a, K> {
fn next_back(&mut self) -> Option<Self::Item> {
self.inner
.next_back()
.map(|(_, raw)| RawSyntaxElementRef::from(raw))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/syntax/node.rs | crates/rome_rowan/src/syntax/node.rs | use crate::green::GreenElement;
use crate::syntax::element::{SyntaxElement, SyntaxElementKey};
use crate::syntax::SyntaxTrivia;
use crate::{
cursor, Direction, GreenNode, Language, NodeOrToken, SyntaxKind, SyntaxList, SyntaxNodeText,
SyntaxToken, SyntaxTriviaPiece, TokenAtOffset, WalkEvent,
};
use rome_text_size::{TextRange, TextSize};
#[cfg(feature = "serde")]
use serde::Serialize;
use std::any::TypeId;
use std::fmt::{Debug, Formatter};
use std::iter::FusedIterator;
use std::marker::PhantomData;
use std::{fmt, ops};
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct SyntaxNode<L: Language> {
raw: cursor::SyntaxNode,
_p: PhantomData<L>,
}
impl<L: Language> SyntaxNode<L> {
pub(crate) fn new_root(green: GreenNode) -> SyntaxNode<L> {
SyntaxNode::from(cursor::SyntaxNode::new_root(green))
}
/// Create a new detached (root) node from a syntax kind and an iterator of slots
///
/// In general this function should not be used directly but through the
/// type-checked factory function / builders generated from the grammar of
/// the corresponding language (eg. `rome_js_factory::make`)
pub fn new_detached<I>(kind: L::Kind, slots: I) -> SyntaxNode<L>
where
I: IntoIterator<Item = Option<SyntaxElement<L>>>,
I::IntoIter: ExactSizeIterator,
{
SyntaxNode::from(cursor::SyntaxNode::new_root(GreenNode::new(
kind.to_raw(),
slots.into_iter().map(|slot| {
slot.map(|element| match element {
NodeOrToken::Node(node) => GreenElement::Node(node.green_node()),
NodeOrToken::Token(token) => GreenElement::Token(token.green_token()),
})
}),
)))
}
fn green_node(&self) -> GreenNode {
self.raw.green().to_owned()
}
pub fn key(&self) -> SyntaxElementKey {
let (node_data, offset) = self.raw.key();
SyntaxElementKey::new(node_data, offset)
}
/// Returns the element stored in the slot with the given index. Returns [None] if the slot is empty.
///
/// ## Panics
/// If the slot index is out of bounds
#[inline]
pub fn element_in_slot(&self, slot: u32) -> Option<SyntaxElement<L>> {
self.raw.element_in_slot(slot).map(SyntaxElement::from)
}
pub fn kind(&self) -> L::Kind {
L::Kind::from_raw(self.raw.kind())
}
/// Returns the text of all descendants tokens combined, including all trivia.
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t let \t\t",
/// &[TriviaPiece::whitespace(3)],
/// &[TriviaPiece::whitespace(3)],
/// );
/// builder.token(RawLanguageKind::STRING_TOKEN, "a");
/// builder.token_with_trivia(
/// RawLanguageKind::SEMICOLON_TOKEN,
/// "; \t\t",
/// &[TriviaPiece::whitespace(3)],
/// &[TriviaPiece::whitespace(3)],
/// );
/// });
/// assert_eq!("\n\t let \t\ta; \t\t", node.text());
/// ```
pub fn text(&self) -> SyntaxNodeText {
self.raw.text()
}
/// Returns the text of all descendants tokens combined,
/// excluding the first token leading trivia, and the last token trailing trivia.
/// All other trivia is included.
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t let \t\t",
/// &[TriviaPiece::whitespace(3)],
/// &[TriviaPiece::whitespace(3)],
/// );
/// builder.token(RawLanguageKind::STRING_TOKEN, "a");
/// builder.token_with_trivia(
/// RawLanguageKind::SEMICOLON_TOKEN,
/// "; \t\t",
/// &[],
/// &[TriviaPiece::whitespace(3)],
/// );
/// });
/// assert_eq!("let \t\ta;", node.text_trimmed());
/// ```
pub fn text_trimmed(&self) -> SyntaxNodeText {
self.raw.text_trimmed()
}
/// Returns the range corresponding for the text of all descendants tokens combined, including all trivia.
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t let \t\t",
/// &[TriviaPiece::whitespace(3)],
/// &[TriviaPiece::whitespace(3)],
/// );
/// builder.token(RawLanguageKind::STRING_TOKEN, "a");
/// builder.token_with_trivia(
/// RawLanguageKind::SEMICOLON_TOKEN,
/// "; \t\t",
/// &[],
/// &[TriviaPiece::whitespace(3)],
/// );
/// });
/// let range = node.text_range();
/// assert_eq!(0u32, u32::from(range.start()));
/// assert_eq!(14u32, u32::from(range.end()));
/// ```
pub fn text_range(&self) -> TextRange {
self.raw.text_range()
}
/// Returns the range corresponding for the text of all descendants tokens combined,
/// excluding the first token leading trivia, and the last token trailing trivia.
/// All other trivia is included.
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t let \t\t",
/// &[TriviaPiece::whitespace(3)],
/// &[TriviaPiece::whitespace(3)],
/// );
/// builder.token(RawLanguageKind::STRING_TOKEN, "a");
/// builder.token_with_trivia(
/// RawLanguageKind::SEMICOLON_TOKEN,
/// "; \t\t",
/// &[],
/// &[TriviaPiece::whitespace(3)],
/// );
/// });
/// let range = node.text_trimmed_range();
/// assert_eq!(3u32, u32::from(range.start()));
/// assert_eq!(11u32, u32::from(range.end()));
/// ```
pub fn text_trimmed_range(&self) -> TextRange {
self.raw.text_trimmed_range()
}
/// Returns the leading trivia of the [first_token](SyntaxNode::first_token), or [None] if the node does not have any descendant tokens.
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t let \t\t",
/// &[TriviaPiece::whitespace(3)],
/// &[TriviaPiece::whitespace(3)],
/// );
/// builder.token(RawLanguageKind::STRING_TOKEN, "a");
/// builder.token_with_trivia(
/// RawLanguageKind::SEMICOLON_TOKEN,
/// "; \t\t",
/// &[],
/// &[TriviaPiece::whitespace(3)],
/// );
/// });
/// let trivia = node.first_leading_trivia();
/// assert!(trivia.is_some());
/// assert_eq!("\n\t ", trivia.unwrap().text());
///
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {});
/// let trivia = node.first_leading_trivia();
/// assert!(trivia.is_none());
/// ```
pub fn first_leading_trivia(&self) -> Option<SyntaxTrivia<L>> {
self.raw.first_leading_trivia().map(SyntaxTrivia::new)
}
/// Returns the trailing trivia of the [last_token](SyntaxNode::last_token), or [None] if the node does not have any descendant tokens.
///
/// ## Examples
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t let \t\t",
/// &[TriviaPiece::whitespace(3)],
/// &[TriviaPiece::whitespace(3)],
/// );
/// builder.token(RawLanguageKind::STRING_TOKEN, "a");
/// builder.token_with_trivia(
/// RawLanguageKind::SEMICOLON_TOKEN,
/// "; \t\t",
/// &[],
/// &[TriviaPiece::whitespace(3)],
/// );
/// });
/// let trivia = node.last_trailing_trivia();
/// assert!(trivia.is_some());
/// assert_eq!(" \t\t", trivia.unwrap().text());
///
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {});
/// let trivia = node.last_trailing_trivia();
/// assert!(trivia.is_none());
/// ```
pub fn last_trailing_trivia(&self) -> Option<SyntaxTrivia<L>> {
self.raw.last_trailing_trivia().map(SyntaxTrivia::new)
}
pub fn parent(&self) -> Option<SyntaxNode<L>> {
self.raw.parent().map(Self::from)
}
/// Returns the grand parent.
pub fn grand_parent(&self) -> Option<SyntaxNode<L>> {
self.parent().and_then(|parent| parent.parent())
}
/// Returns the index of this node inside of its parent
#[inline]
pub fn index(&self) -> usize {
self.raw.index()
}
pub fn ancestors(&self) -> impl Iterator<Item = SyntaxNode<L>> {
self.raw.ancestors().map(SyntaxNode::from)
}
pub fn children(&self) -> SyntaxNodeChildren<L> {
SyntaxNodeChildren {
raw: self.raw.children(),
_p: PhantomData,
}
}
/// Returns an iterator over all the slots of this syntax node.
pub fn slots(&self) -> SyntaxSlots<L> {
SyntaxSlots {
raw: self.raw.slots(),
_p: PhantomData,
}
}
pub fn children_with_tokens(&self) -> SyntaxElementChildren<L> {
SyntaxElementChildren {
raw: self.raw.children_with_tokens(),
_p: PhantomData,
}
}
pub fn tokens(&self) -> impl Iterator<Item = SyntaxToken<L>> + DoubleEndedIterator + '_ {
self.raw.tokens().map(SyntaxToken::from)
}
pub fn first_child(&self) -> Option<SyntaxNode<L>> {
self.raw.first_child().map(Self::from)
}
pub fn last_child(&self) -> Option<SyntaxNode<L>> {
self.raw.last_child().map(Self::from)
}
pub fn first_child_or_token(&self) -> Option<SyntaxElement<L>> {
self.raw.first_child_or_token().map(NodeOrToken::from)
}
pub fn last_child_or_token(&self) -> Option<SyntaxElement<L>> {
self.raw.last_child_or_token().map(NodeOrToken::from)
}
pub fn next_sibling(&self) -> Option<SyntaxNode<L>> {
self.raw.next_sibling().map(Self::from)
}
pub fn prev_sibling(&self) -> Option<SyntaxNode<L>> {
self.raw.prev_sibling().map(Self::from)
}
pub fn next_sibling_or_token(&self) -> Option<SyntaxElement<L>> {
self.raw.next_sibling_or_token().map(NodeOrToken::from)
}
pub fn prev_sibling_or_token(&self) -> Option<SyntaxElement<L>> {
self.raw.prev_sibling_or_token().map(NodeOrToken::from)
}
/// Return the leftmost token in the subtree of this node.
pub fn first_token(&self) -> Option<SyntaxToken<L>> {
self.raw.first_token().map(SyntaxToken::from)
}
/// Return the rightmost token in the subtree of this node.
pub fn last_token(&self) -> Option<SyntaxToken<L>> {
self.raw.last_token().map(SyntaxToken::from)
}
pub fn siblings(&self, direction: Direction) -> impl Iterator<Item = SyntaxNode<L>> {
self.raw.siblings(direction).map(SyntaxNode::from)
}
pub fn siblings_with_tokens(
&self,
direction: Direction,
) -> impl Iterator<Item = SyntaxElement<L>> {
self.raw
.siblings_with_tokens(direction)
.map(SyntaxElement::from)
}
pub fn descendants(&self) -> impl Iterator<Item = SyntaxNode<L>> {
self.raw.descendants().map(SyntaxNode::from)
}
pub fn descendants_tokens(&self, direction: Direction) -> impl Iterator<Item = SyntaxToken<L>> {
self.descendants_with_tokens(direction)
.filter_map(|x| x.as_token().cloned())
}
pub fn descendants_with_tokens(
&self,
direction: Direction,
) -> impl Iterator<Item = SyntaxElement<L>> {
self.raw
.descendants_with_tokens(direction)
.map(NodeOrToken::from)
}
/// Traverse the subtree rooted at the current node (including the current
/// node) in preorder, excluding tokens.
pub fn preorder(&self) -> Preorder<L> {
Preorder {
raw: self.raw.preorder(),
_p: PhantomData,
}
}
/// Traverse the subtree rooted at the current node (including the current
/// node) in preorder, including tokens.
pub fn preorder_with_tokens(&self, direction: Direction) -> PreorderWithTokens<L> {
PreorderWithTokens {
raw: self.raw.preorder_with_tokens(direction),
_p: PhantomData,
}
}
/// Find a token in the subtree corresponding to this node, which covers the offset.
/// Precondition: offset must be withing node's range.
pub fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken<L>> {
self.raw.token_at_offset(offset).map(SyntaxToken::from)
}
/// Return the deepest node or token in the current subtree that fully
/// contains the range. If the range is empty and is contained in two leaf
/// nodes, either one can be returned. Precondition: range must be contained
/// withing the current node
pub fn covering_element(&self, range: TextRange) -> SyntaxElement<L> {
NodeOrToken::from(self.raw.covering_element(range))
}
/// Finds a [`SyntaxElement`] which intersects with a given `range`. If
/// there are several intersecting elements, any one can be returned.
///
/// The method uses binary search internally, so it's complexity is
/// `O(log(N))` where `N = self.children_with_tokens().count()`.
pub fn child_or_token_at_range(&self, range: TextRange) -> Option<SyntaxElement<L>> {
self.raw
.child_or_token_at_range(range)
.map(SyntaxElement::from)
}
/// Returns an independent copy of the subtree rooted at this node.
///
/// The parent of the returned node will be `None`, the start offset will be
/// zero, but, otherwise, it'll be equivalent to the source node.
pub fn clone_subtree(&self) -> SyntaxNode<L> {
SyntaxNode::from(self.raw.clone_subtree())
}
/// Return a new version of this node detached from its parent node
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn detach(self) -> Self {
Self {
raw: self.raw.detach(),
_p: PhantomData,
}
}
/// Return a clone of this node with the specified range of slots replaced
/// with the elements of the provided iterator
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn splice_slots<R, I>(self, range: R, replace_with: I) -> Self
where
R: ops::RangeBounds<usize>,
I: IntoIterator<Item = Option<SyntaxElement<L>>>,
{
Self {
raw: self.raw.splice_slots(
range,
replace_with
.into_iter()
.map(|element| element.map(cursor::SyntaxElement::from)),
),
_p: PhantomData,
}
}
/// Return a new version of this node with the element `prev_elem` replaced with `next_elem`
///
/// `prev_elem` can be a direct child of this node, or an indirect child through any descendant node
///
/// Returns `None` if `prev_elem` is not a descendant of this node
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn replace_child(
self,
prev_elem: SyntaxElement<L>,
next_elem: SyntaxElement<L>,
) -> Option<Self> {
Some(Self {
raw: self.raw.replace_child(prev_elem.into(), next_elem.into())?,
_p: PhantomData,
})
}
/// Return a new version of this node with the leading trivia of its first token replaced with `trivia`.
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn with_leading_trivia_pieces<I>(self, trivia: I) -> Option<Self>
where
I: IntoIterator<Item = SyntaxTriviaPiece<L>>,
I::IntoIter: ExactSizeIterator,
{
let first_token = self.first_token()?;
let new_first_token = first_token.with_leading_trivia_pieces(trivia);
self.replace_child(first_token.into(), new_first_token.into())
}
/// Return a new version of this node with the trailing trivia of its last token replaced with `trivia`.
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn with_trailing_trivia_pieces<I>(self, trivia: I) -> Option<Self>
where
I: IntoIterator<Item = SyntaxTriviaPiece<L>>,
I::IntoIter: ExactSizeIterator,
{
let last_token = self.last_token()?;
let new_last_token = last_token.with_trailing_trivia_pieces(trivia);
self.replace_child(last_token.into(), new_last_token.into())
}
// Return a new version of this node with `trivia` prepended to the leading trivia of the first token.
///
/// ## Examples
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
///
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\t let ",
/// &[TriviaPiece::whitespace(2)],
/// &[TriviaPiece::whitespace(1)],
/// );
/// builder.token(RawLanguageKind::STRING_TOKEN, "a");
/// builder.token_with_trivia(
/// RawLanguageKind::SEMICOLON_TOKEN,
/// "; ",
/// &[],
/// &[TriviaPiece::whitespace(1)],
/// );
/// });
///
/// let new_node = node.clone().prepend_trivia_pieces(node.last_trailing_trivia().unwrap().pieces()).unwrap();
/// let leading_trivia = new_node.first_leading_trivia().unwrap();
/// let trailing_trivia = new_node.last_trailing_trivia().unwrap();
///
/// assert_eq!(" \t ", leading_trivia.text());
/// assert_eq!(" ", trailing_trivia.text());
/// ```
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn prepend_trivia_pieces<I>(self, trivia: I) -> Option<Self>
where
I: IntoIterator<Item = SyntaxTriviaPiece<L>>,
I::IntoIter: ExactSizeIterator,
{
let first_token = self.first_token()?;
let new_first_token = first_token.prepend_trivia_pieces(trivia);
self.replace_child(first_token.into(), new_first_token.into())
}
// Return a new version of this node with `trivia` appended to the trailing trivia of the last token.
///
/// ## Examples
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
///
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\t let ",
/// &[TriviaPiece::whitespace(2)],
/// &[TriviaPiece::whitespace(1)],
/// );
/// builder.token(RawLanguageKind::STRING_TOKEN, "a");
/// builder.token_with_trivia(
/// RawLanguageKind::SEMICOLON_TOKEN,
/// "; ",
/// &[],
/// &[TriviaPiece::whitespace(1)],
/// );
/// });
///
/// let new_node = node.clone().append_trivia_pieces(node.first_leading_trivia().unwrap().pieces()).unwrap();
/// let leading_trivia = new_node.first_leading_trivia().unwrap();
/// let trailing_trivia = new_node.last_trailing_trivia().unwrap();
///
/// assert_eq!("\t ", leading_trivia.text());
/// assert_eq!(" \t ", trailing_trivia.text());
/// ```
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn append_trivia_pieces<I>(self, trivia: I) -> Option<Self>
where
I: IntoIterator<Item = SyntaxTriviaPiece<L>>,
I::IntoIter: ExactSizeIterator,
{
let last_token = self.last_token()?;
let new_last_token = last_token.append_trivia_pieces(trivia);
self.replace_child(last_token.into(), new_last_token.into())
}
/// Return a new version of this node without leading and trailing newlines and whitespaces.
///
/// ## Examples
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
///
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n let ",
/// &[TriviaPiece::newline(1), TriviaPiece::whitespace(1)],
/// &[TriviaPiece::whitespace(1)],
/// );
/// builder.token(RawLanguageKind::STRING_TOKEN, "a");
/// builder.token_with_trivia(
/// RawLanguageKind::SEMICOLON_TOKEN,
/// "; ",
/// &[],
/// &[TriviaPiece::whitespace(1)],
/// );
/// });
///
/// let new_node = node.trim_trivia().unwrap();
/// let leading_trivia = new_node.first_leading_trivia().unwrap();
/// let trailing_trivia = new_node.last_trailing_trivia().unwrap();
///
/// assert_eq!("", leading_trivia.text());
/// assert_eq!("", trailing_trivia.text());
/// ```
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn trim_trivia(self) -> Option<Self> {
self.trim_leading_trivia()?.trim_trailing_trivia()
}
/// Return a new version of this node without leading newlines and whitespaces.
///
/// ## Examples
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
///
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n let ",
/// &[TriviaPiece::newline(1), TriviaPiece::whitespace(1)],
/// &[TriviaPiece::whitespace(1)],
/// );
/// builder.token(RawLanguageKind::STRING_TOKEN, "a");
/// builder.token_with_trivia(
/// RawLanguageKind::SEMICOLON_TOKEN,
/// "; ",
/// &[],
/// &[TriviaPiece::whitespace(1)],
/// );
/// });
///
/// let new_node = node.trim_leading_trivia().unwrap();
/// let leading_trivia = new_node.first_leading_trivia().unwrap();
/// let trailing_trivia = new_node.last_trailing_trivia().unwrap();
///
/// assert_eq!("", leading_trivia.text());
/// assert_eq!(" ", trailing_trivia.text());
/// ```
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn trim_leading_trivia(self) -> Option<Self> {
let first_token = self.first_token()?;
let new_first_token = first_token.trim_leading_trivia();
self.replace_child(first_token.into(), new_first_token.into())
}
/// Return a new version of this token without trailing whitespaces.
///
/// ## Examples
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
///
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n let ",
/// &[TriviaPiece::newline(1), TriviaPiece::whitespace(1)],
/// &[TriviaPiece::whitespace(1)],
/// );
/// builder.token(RawLanguageKind::STRING_TOKEN, "a");
/// builder.token_with_trivia(
/// RawLanguageKind::SEMICOLON_TOKEN,
/// "; ",
/// &[],
/// &[TriviaPiece::whitespace(1)],
/// );
/// });
///
/// let new_node = node.trim_trailing_trivia().unwrap();
/// let leading_trivia = new_node.first_leading_trivia().unwrap();
/// let trailing_trivia = new_node.last_trailing_trivia().unwrap();
///
/// assert_eq!("\n ", leading_trivia.text());
/// assert_eq!("", trailing_trivia.text());
/// ```
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn trim_trailing_trivia(self) -> Option<Self> {
let last_token = self.last_token()?;
let new_last_token = last_token.trim_trailing_trivia();
self.replace_child(last_token.into(), new_last_token.into())
}
pub fn into_list(self) -> SyntaxList<L> {
SyntaxList::new(self)
}
/// Whether the node contains any comments. This function checks
/// **all the descendants** of the current node.
pub fn has_comments_descendants(&self) -> bool {
self.descendants_tokens(Direction::Next)
.any(|tok| tok.has_trailing_comments() || tok.has_leading_comments())
}
/// It checks if the current node has trailing or leading trivia
pub fn has_comments_direct(&self) -> bool {
self.has_trailing_comments() || self.has_leading_comments()
}
/// It checks if the current node has comments at the edges:
/// if first or last tokens contain comments (leading or trailing)
pub fn first_or_last_token_have_comments(&self) -> bool {
self.first_token_has_comments() || self.last_token_has_comments()
}
/// Whether the node contains trailing comments.
pub fn has_trailing_comments(&self) -> bool {
self.last_token()
.map_or(false, |tok| tok.has_trailing_comments())
}
/// Whether the last token of a node has comments (leading or trailing)
pub fn last_token_has_comments(&self) -> bool {
self.last_token().map_or(false, |tok| {
tok.has_trailing_comments() || tok.has_leading_comments()
})
}
/// Whether the first token of a node has comments (leading or trailing)
pub fn first_token_has_comments(&self) -> bool {
self.first_token().map_or(false, |tok| {
tok.has_trailing_comments() || tok.has_leading_comments()
})
}
/// Whether the node contains leading comments.
pub fn has_leading_comments(&self) -> bool {
self.first_token()
.map_or(false, |tok| tok.has_leading_comments())
}
/// Whether the node contains leading newlines.
pub fn has_leading_newline(&self) -> bool {
self.first_token()
.map_or(false, |tok| tok.has_leading_newline())
}
}
impl<L> SyntaxNode<L>
where
L: Language + 'static,
{
/// Create a [Send] + [Sync] handle to this node
///
/// Returns `None` if self is not a root node
pub fn as_send(&self) -> Option<SendNode> {
if self.parent().is_none() {
Some(SendNode {
language: TypeId::of::<L>(),
green: self.green_node(),
})
} else {
None
}
}
}
impl<L: Language> fmt::Debug for SyntaxNode<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
let mut level = 0;
for event in self.raw.preorder_slots() {
match event {
WalkEvent::Enter(element) => {
for _ in 0..level {
write!(f, " ")?;
}
match element {
cursor::SyntaxSlot::Node(node) => {
writeln!(f, "{}: {:?}", node.index(), SyntaxNode::<L>::from(node))?
}
cursor::SyntaxSlot::Token(token) => writeln!(
f,
"{}: {:?}",
token.index(),
SyntaxToken::<L>::from(token)
)?,
cursor::SyntaxSlot::Empty { index, .. } => {
writeln!(f, "{}: (empty)", index)?
}
}
level += 1;
}
WalkEvent::Leave(_) => level -= 1,
}
}
assert_eq!(level, 0);
Ok(())
} else {
write!(f, "{:?}@{:?}", self.kind(), self.text_range())
}
}
}
impl<L: Language> fmt::Display for SyntaxNode<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.raw, f)
}
}
impl<L: Language> From<SyntaxNode<L>> for cursor::SyntaxNode {
fn from(node: SyntaxNode<L>) -> cursor::SyntaxNode {
node.raw
}
}
impl<L: Language> From<cursor::SyntaxNode> for SyntaxNode<L> {
fn from(raw: cursor::SyntaxNode) -> SyntaxNode<L> {
SyntaxNode {
raw,
_p: PhantomData,
}
}
}
/// Language-agnostic representation of the root node of a syntax tree, can be
/// sent or shared between threads
#[derive(Clone)]
pub struct SendNode {
language: TypeId,
green: GreenNode,
}
impl SendNode {
/// Downcast this handle back into a [SyntaxNode]
///
/// Returns `None` if the specified language `L` is not the one this node
/// was created with
pub fn into_node<L>(self) -> Option<SyntaxNode<L>>
where
L: Language + 'static,
{
if TypeId::of::<L>() == self.language {
Some(SyntaxNode::new_root(self.green))
} else {
None
}
}
}
#[derive(Debug, Clone)]
pub struct SyntaxNodeChildren<L: Language> {
raw: cursor::SyntaxNodeChildren,
_p: PhantomData<L>,
}
impl<L: Language> Iterator for SyntaxNodeChildren<L> {
type Item = SyntaxNode<L>;
fn next(&mut self) -> Option<Self::Item> {
self.raw.next().map(SyntaxNode::from)
}
}
#[derive(Clone)]
pub struct SyntaxElementChildren<L: Language> {
raw: cursor::SyntaxElementChildren,
_p: PhantomData<L>,
}
impl<L: Language> Debug for SyntaxElementChildren<L> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
impl<L: Language> Default for SyntaxElementChildren<L> {
fn default() -> Self {
SyntaxElementChildren {
raw: cursor::SyntaxElementChildren::default(),
_p: PhantomData,
}
}
}
impl<L: Language> Iterator for SyntaxElementChildren<L> {
type Item = SyntaxElement<L>;
fn next(&mut self) -> Option<Self::Item> {
self.raw.next().map(NodeOrToken::from)
}
}
pub struct Preorder<L: Language> {
raw: cursor::Preorder,
_p: PhantomData<L>,
}
impl<L: Language> Preorder<L> {
pub fn skip_subtree(&mut self) {
self.raw.skip_subtree()
}
}
impl<L: Language> Iterator for Preorder<L> {
type Item = WalkEvent<SyntaxNode<L>>;
fn next(&mut self) -> Option<Self::Item> {
self.raw.next().map(|it| it.map(SyntaxNode::from))
}
}
pub struct PreorderWithTokens<L: Language> {
raw: cursor::PreorderWithTokens,
_p: PhantomData<L>,
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/syntax/element.rs | crates/rome_rowan/src/syntax/element.rs | use crate::syntax::SyntaxTrivia;
use crate::{cursor, Language, NodeOrToken, SyntaxNode, SyntaxToken};
use rome_text_size::{TextRange, TextSize};
use std::iter;
use std::ptr::NonNull;
pub type SyntaxElement<L> = NodeOrToken<SyntaxNode<L>, SyntaxToken<L>>;
impl<L: Language> SyntaxElement<L> {
pub fn key(&self) -> SyntaxElementKey {
match self {
NodeOrToken::Node(it) => it.key(),
NodeOrToken::Token(it) => it.key(),
}
}
pub fn text_range(&self) -> TextRange {
match self {
NodeOrToken::Node(it) => it.text_range(),
NodeOrToken::Token(it) => it.text_range(),
}
}
pub fn text_trimmed_range(&self) -> TextRange {
match self {
NodeOrToken::Node(it) => it.text_trimmed_range(),
NodeOrToken::Token(it) => it.text_trimmed_range(),
}
}
pub fn leading_trivia(&self) -> Option<SyntaxTrivia<L>> {
match self {
NodeOrToken::Node(it) => it.first_leading_trivia(),
NodeOrToken::Token(it) => Some(it.leading_trivia()),
}
}
pub fn trailing_trivia(&self) -> Option<SyntaxTrivia<L>> {
match self {
NodeOrToken::Node(it) => it.last_trailing_trivia(),
NodeOrToken::Token(it) => Some(it.trailing_trivia()),
}
}
pub fn kind(&self) -> L::Kind {
match self {
NodeOrToken::Node(it) => it.kind(),
NodeOrToken::Token(it) => it.kind(),
}
}
pub fn parent(&self) -> Option<SyntaxNode<L>> {
match self {
NodeOrToken::Node(it) => it.parent(),
NodeOrToken::Token(it) => it.parent(),
}
}
pub(crate) fn index(&self) -> usize {
match self {
NodeOrToken::Node(it) => it.index(),
NodeOrToken::Token(it) => it.index(),
}
}
pub fn ancestors(&self) -> impl Iterator<Item = SyntaxNode<L>> {
let first = match self {
NodeOrToken::Node(it) => Some(it.clone()),
NodeOrToken::Token(it) => it.parent(),
};
iter::successors(first, SyntaxNode::parent)
}
pub fn next_sibling_or_token(&self) -> Option<SyntaxElement<L>> {
match self {
NodeOrToken::Node(it) => it.next_sibling_or_token(),
NodeOrToken::Token(it) => it.next_sibling_or_token(),
}
}
pub fn prev_sibling_or_token(&self) -> Option<SyntaxElement<L>> {
match self {
NodeOrToken::Node(it) => it.prev_sibling_or_token(),
NodeOrToken::Token(it) => it.prev_sibling_or_token(),
}
}
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn detach(self) -> Self {
match self {
NodeOrToken::Node(it) => Self::Node(it.detach()),
NodeOrToken::Token(it) => Self::Token(it.detach()),
}
}
}
impl<L: Language> From<cursor::SyntaxElement> for SyntaxElement<L> {
fn from(raw: cursor::SyntaxElement) -> SyntaxElement<L> {
match raw {
NodeOrToken::Node(it) => NodeOrToken::Node(it.into()),
NodeOrToken::Token(it) => NodeOrToken::Token(it.into()),
}
}
}
impl<L: Language> From<SyntaxElement<L>> for cursor::SyntaxElement {
fn from(element: SyntaxElement<L>) -> cursor::SyntaxElement {
match element {
NodeOrToken::Node(it) => NodeOrToken::Node(it.into()),
NodeOrToken::Token(it) => NodeOrToken::Token(it.into()),
}
}
}
impl<L: Language> From<SyntaxToken<L>> for SyntaxElement<L> {
fn from(token: SyntaxToken<L>) -> SyntaxElement<L> {
NodeOrToken::Token(token)
}
}
impl<L: Language> From<SyntaxNode<L>> for SyntaxElement<L> {
fn from(node: SyntaxNode<L>) -> SyntaxElement<L> {
NodeOrToken::Node(node)
}
}
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct SyntaxElementKey {
node_data: NonNull<()>,
offset: TextSize,
}
impl SyntaxElementKey {
pub(crate) fn new(node_data: NonNull<()>, offset: TextSize) -> Self {
Self { node_data, offset }
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/syntax/trivia.rs | crates/rome_rowan/src/syntax/trivia.rs | use crate::{cursor, Language, SyntaxToken};
use rome_text_size::{TextRange, TextSize};
use std::fmt;
use std::fmt::Formatter;
use std::iter::FusedIterator;
use std::marker::PhantomData;
#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
pub enum TriviaPieceKind {
/// A line break (`\n`, `\r`, `\r\n`, ...)
Newline,
/// Any whitespace character
Whitespace,
/// Comment that does not contain any line breaks
SingleLineComment,
/// Comment that contains at least one line break
MultiLineComment,
/// Token that the parser skipped for some reason.
Skipped,
}
impl TriviaPieceKind {
pub const fn is_newline(&self) -> bool {
matches!(self, TriviaPieceKind::Newline)
}
pub const fn is_whitespace(&self) -> bool {
matches!(self, TriviaPieceKind::Whitespace)
}
pub const fn is_comment(&self) -> bool {
self.is_single_line_comment() || self.is_multiline_comment()
}
pub const fn is_single_line_comment(&self) -> bool {
matches!(self, TriviaPieceKind::SingleLineComment)
}
pub const fn is_multiline_comment(&self) -> bool {
matches!(self, TriviaPieceKind::MultiLineComment)
}
pub const fn is_skipped(&self) -> bool {
matches!(self, TriviaPieceKind::Skipped)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct TriviaPiece {
pub(crate) kind: TriviaPieceKind,
pub(crate) length: TextSize,
}
impl TriviaPiece {
/// Creates a new whitespace trivia piece with the given length
pub fn whitespace<L: Into<TextSize>>(len: L) -> Self {
Self::new(TriviaPieceKind::Whitespace, len)
}
/// Creates a new newline trivia piece with the given text length
pub fn newline<L: Into<TextSize>>(len: L) -> Self {
Self::new(TriviaPieceKind::Newline, len)
}
/// Creates a new comment trivia piece that does not contain any line breaks.
/// For example, JavaScript's `//` comments are guaranteed to not spawn multiple lines. However,
/// this can also be a `/* ... */` comment if it doesn't contain any line break characters.
pub fn single_line_comment<L: Into<TextSize>>(len: L) -> Self {
Self::new(TriviaPieceKind::SingleLineComment, len)
}
/// Creates a new comment trivia piece that contains at least one line breaks.
/// For example, a JavaScript `/* ... */` comment that spawns at least two lines (contains at least one line break character).
pub fn multi_line_comment<L: Into<TextSize>>(len: L) -> Self {
Self::new(TriviaPieceKind::MultiLineComment, len)
}
pub fn new<L: Into<TextSize>>(kind: TriviaPieceKind, length: L) -> Self {
Self {
kind,
length: length.into(),
}
}
/// Returns the trivia's length
pub fn text_len(&self) -> TextSize {
self.length
}
/// Returns the trivia's kind
pub fn kind(&self) -> TriviaPieceKind {
self.kind
}
}
#[derive(Debug, Clone)]
pub struct SyntaxTriviaPieceNewline<L: Language>(SyntaxTriviaPiece<L>);
#[derive(Debug, Clone)]
pub struct SyntaxTriviaPieceWhitespace<L: Language>(SyntaxTriviaPiece<L>);
#[derive(Debug, Clone)]
pub struct SyntaxTriviaPieceComments<L: Language>(SyntaxTriviaPiece<L>);
#[derive(Debug, Clone)]
pub struct SyntaxTriviaPieceSkipped<L: Language>(SyntaxTriviaPiece<L>);
impl<L: Language> SyntaxTriviaPieceNewline<L> {
pub fn text(&self) -> &str {
self.0.text()
}
pub fn text_len(&self) -> TextSize {
self.0.text_len()
}
pub fn text_range(&self) -> TextRange {
self.0.text_range()
}
/// Returns a reference to its [SyntaxTriviaPiece]
pub fn as_piece(&self) -> &SyntaxTriviaPiece<L> {
&self.0
}
/// Returns its [SyntaxTriviaPiece]
pub fn into_piece(self) -> SyntaxTriviaPiece<L> {
self.0
}
}
impl<L: Language> SyntaxTriviaPieceWhitespace<L> {
pub fn text(&self) -> &str {
self.0.text()
}
pub fn text_len(&self) -> TextSize {
self.0.text_len()
}
pub fn text_range(&self) -> TextRange {
self.0.text_range()
}
/// Returns a reference to its [SyntaxTriviaPiece]
pub fn as_piece(&self) -> &SyntaxTriviaPiece<L> {
&self.0
}
/// Returns its [SyntaxTriviaPiece]
pub fn into_piece(self) -> SyntaxTriviaPiece<L> {
self.0
}
}
impl<L: Language> SyntaxTriviaPieceComments<L> {
pub fn text(&self) -> &str {
self.0.text()
}
pub fn text_len(&self) -> TextSize {
self.0.text_len()
}
pub fn text_range(&self) -> TextRange {
self.0.text_range()
}
pub fn has_newline(&self) -> bool {
self.0.trivia.kind.is_multiline_comment()
}
/// Returns a reference to its [SyntaxTriviaPiece]
pub fn as_piece(&self) -> &SyntaxTriviaPiece<L> {
&self.0
}
/// Returns its [SyntaxTriviaPiece]
pub fn into_piece(self) -> SyntaxTriviaPiece<L> {
self.0
}
}
impl<L: Language> SyntaxTriviaPieceSkipped<L> {
pub fn text(&self) -> &str {
self.0.text()
}
pub fn text_len(&self) -> TextSize {
self.0.text_len()
}
pub fn text_range(&self) -> TextRange {
self.0.text_range()
}
/// Returns a reference to its [SyntaxTriviaPiece]
pub fn as_piece(&self) -> &SyntaxTriviaPiece<L> {
&self.0
}
/// Returns its [SyntaxTriviaPiece]
pub fn into_piece(self) -> SyntaxTriviaPiece<L> {
self.0
}
}
/// [SyntaxTriviaPiece] gives access to the most granular information about the trivia
/// that was specified by the lexer at the token creation time.
///
/// For example:
///
/// ```no_test
/// builder.token_with_trivia(
/// RawSyntaxKind(1),
/// "\n\t /**/let \t\t",
/// &[TriviaPiece::whitespace(3), TriviaPiece::single_line_comment(4)],
/// &[TriviaPiece::whitespace(3)],
/// );
/// });
/// ```
/// This token has two pieces in the leading trivia, and one piece at the trailing trivia. Each
/// piece is defined by the [TriviaPiece]; its content is irrelevant.
///
#[derive(Clone)]
pub struct SyntaxTriviaPiece<L: Language> {
raw: cursor::SyntaxTrivia,
/// Absolute offset from the beginning of the file
offset: TextSize,
trivia: TriviaPiece,
_p: PhantomData<L>,
}
impl<L: Language> SyntaxTriviaPiece<L> {
pub(crate) fn into_raw_piece(self) -> TriviaPiece {
self.trivia
}
/// Returns the internal kind of this trivia piece
pub fn kind(&self) -> TriviaPieceKind {
self.trivia.kind()
}
/// Returns the associated text just for this trivia piece. This is different from [SyntaxTrivia::text()],
/// which returns the text of the whole trivia.
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// use std::iter::Iterator;
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t /**/let \t\t",
/// &[
/// TriviaPiece::whitespace(3),
/// TriviaPiece::single_line_comment(4),
/// ],
/// &[TriviaPiece::whitespace(3)],
/// );
/// });
/// let leading: Vec<_> = node.first_leading_trivia().unwrap().pieces().collect();
/// assert_eq!("\n\t ", leading[0].text());
/// assert_eq!("/**/", leading[1].text());
///
/// let trailing: Vec<_> = node.last_trailing_trivia().unwrap().pieces().collect();
/// assert_eq!(" \t\t", trailing[0].text());
/// ```
pub fn text(&self) -> &str {
let token = self.raw.token();
let txt = token.text();
// Compute the offset relative to the token
let start = self.offset - token.text_range().start();
let end = start + self.text_len();
// Don't use self.raw.text(). It iterates over all pieces
&txt[start.into()..end.into()]
}
/// Returns the associated text length just for this trivia piece. This is different from `SyntaxTrivia::len()`,
/// which returns the text length of the whole trivia.
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// use std::iter::Iterator;
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t /**/let \t\t",
/// &[
/// TriviaPiece::whitespace(3),
/// TriviaPiece::single_line_comment(4),
/// ],
/// &[TriviaPiece::whitespace(3)],
/// );
/// });
/// let pieces: Vec<_> = node.first_leading_trivia().unwrap().pieces().collect();
/// assert_eq!(TextSize::from(3), pieces[0].text_len());
/// ```
pub fn text_len(&self) -> TextSize {
self.trivia.text_len()
}
/// Returns the associated text range just for this trivia piece. This is different from [SyntaxTrivia::text_range()],
/// which returns the text range of the whole trivia.
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// use std::iter::Iterator;
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t /**/let \t\t",
/// &[
/// TriviaPiece::whitespace(3),
/// TriviaPiece::single_line_comment(4),
/// ],
/// &[TriviaPiece::whitespace(3)],
/// );
/// });
/// let pieces: Vec<_> = node.first_leading_trivia().unwrap().pieces().collect();
/// assert_eq!(TextRange::new(0.into(), 3.into()), pieces[0].text_range());
/// ```
pub fn text_range(&self) -> TextRange {
TextRange::at(self.offset, self.text_len())
}
/// Returns true if this trivia piece is a [SyntaxTriviaPieceNewline].
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// use std::iter::Iterator;
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t/**/let",
/// &[
/// TriviaPiece::newline(1),
/// TriviaPiece::whitespace(1),
/// TriviaPiece::single_line_comment(4),
/// ],
/// &[],
/// );
/// });
/// let pieces: Vec<_> = node.first_leading_trivia().unwrap().pieces().collect();
/// assert!(pieces[0].is_newline())
/// ```
pub fn is_newline(&self) -> bool {
self.trivia.kind.is_newline()
}
/// Returns true if this trivia piece is a [SyntaxTriviaPieceWhitespace].
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// use std::iter::Iterator;
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t/**/let",
/// &[
/// TriviaPiece::newline(1),
/// TriviaPiece::whitespace(1),
/// TriviaPiece::single_line_comment(4),
/// ],
/// &[],
/// );
/// });
/// let pieces: Vec<_> = node.first_leading_trivia().unwrap().pieces().collect();
/// assert!(pieces[1].is_whitespace())
/// ```
pub fn is_whitespace(&self) -> bool {
self.trivia.kind.is_whitespace()
}
/// Returns true if this trivia piece is a [SyntaxTriviaPieceComments].
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// use std::iter::Iterator;
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t/**/let",
/// &[
/// TriviaPiece::newline(1),
/// TriviaPiece::whitespace(1),
/// TriviaPiece::single_line_comment(4),
/// ],
/// &[],
/// );
/// });
/// let pieces: Vec<_> = node.first_leading_trivia().unwrap().pieces().collect();
/// assert!(pieces[2].is_comments())
/// ```
pub const fn is_comments(&self) -> bool {
matches!(
self.trivia.kind,
TriviaPieceKind::SingleLineComment | TriviaPieceKind::MultiLineComment
)
}
/// Returns true if this trivia piece is a [SyntaxTriviaPieceSkipped].
pub fn is_skipped(&self) -> bool {
self.trivia.kind.is_skipped()
}
/// Cast this trivia piece to [SyntaxTriviaPieceNewline].
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// use std::iter::Iterator;
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n/**/let \t\t",
/// &[TriviaPiece::newline(1), TriviaPiece::single_line_comment(4)],
/// &[TriviaPiece::newline(3)],
/// );
/// });
/// let pieces: Vec<_> = node.first_leading_trivia().unwrap().pieces().collect();
/// let w = pieces[0].as_newline();
/// assert!(w.is_some());
/// let w = pieces[1].as_newline();
/// assert!(w.is_none());
/// ```
pub fn as_newline(&self) -> Option<SyntaxTriviaPieceNewline<L>> {
match &self.trivia.kind {
TriviaPieceKind::Newline => Some(SyntaxTriviaPieceNewline(self.clone())),
_ => None,
}
}
/// Cast this trivia piece to [SyntaxTriviaPieceWhitespace].
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// use std::iter::Iterator;
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\t /**/let \t\t",
/// &[
/// TriviaPiece::whitespace(2),
/// TriviaPiece::single_line_comment(4),
/// ],
/// &[TriviaPiece::whitespace(3)],
/// );
/// });
/// let pieces: Vec<_> = node.first_leading_trivia().unwrap().pieces().collect();
/// let w = pieces[0].as_whitespace();
/// assert!(w.is_some());
/// let w = pieces[1].as_whitespace();
/// assert!(w.is_none());
/// ```
pub fn as_whitespace(&self) -> Option<SyntaxTriviaPieceWhitespace<L>> {
match &self.trivia.kind {
TriviaPieceKind::Whitespace => Some(SyntaxTriviaPieceWhitespace(self.clone())),
_ => None,
}
}
/// Cast this trivia piece to [SyntaxTriviaPieceComments].
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// use std::iter::Iterator;
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t /**/let \t\t",
/// &[
/// TriviaPiece::whitespace(3),
/// TriviaPiece::single_line_comment(4),
/// ],
/// &[TriviaPiece::whitespace(3)],
/// );
/// });
/// let pieces: Vec<_> = node.first_leading_trivia().unwrap().pieces().collect();
/// let w = pieces[0].as_comments();
/// assert!(w.is_none());
/// let w = pieces[1].as_comments();
/// assert!(w.is_some());
/// ```
pub fn as_comments(&self) -> Option<SyntaxTriviaPieceComments<L>> {
match &self.trivia.kind {
TriviaPieceKind::SingleLineComment | TriviaPieceKind::MultiLineComment => {
Some(SyntaxTriviaPieceComments(self.clone()))
}
_ => None,
}
}
/// Casts this piece to a skipped trivia piece.
pub fn as_skipped(&self) -> Option<SyntaxTriviaPieceSkipped<L>> {
match &self.trivia.kind {
TriviaPieceKind::Skipped => Some(SyntaxTriviaPieceSkipped(self.clone())),
_ => None,
}
}
pub fn token(&self) -> SyntaxToken<L> {
SyntaxToken::from(self.raw.token().clone())
}
}
impl<L: Language> fmt::Debug for SyntaxTriviaPiece<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.trivia.kind {
TriviaPieceKind::Newline => write!(f, "Newline(")?,
TriviaPieceKind::Whitespace => write!(f, "Whitespace(")?,
TriviaPieceKind::SingleLineComment | TriviaPieceKind::MultiLineComment => {
write!(f, "Comments(")?
}
TriviaPieceKind::Skipped => write!(f, "Skipped(")?,
}
print_debug_str(self.text(), f)?;
write!(f, ")")
}
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct SyntaxTrivia<L: Language> {
raw: cursor::SyntaxTrivia,
_p: PhantomData<L>,
}
#[derive(Clone)]
pub struct SyntaxTriviaPiecesIterator<L: Language> {
iter: cursor::SyntaxTriviaPiecesIterator,
_p: PhantomData<L>,
}
impl<L: Language> Iterator for SyntaxTriviaPiecesIterator<L> {
type Item = SyntaxTriviaPiece<L>;
fn next(&mut self) -> Option<Self::Item> {
let (offset, trivia) = self.iter.next()?;
Some(SyntaxTriviaPiece {
raw: self.iter.raw.clone(),
offset,
trivia,
_p: PhantomData,
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<L: Language> DoubleEndedIterator for SyntaxTriviaPiecesIterator<L> {
fn next_back(&mut self) -> Option<Self::Item> {
let (offset, trivia) = self.iter.next_back()?;
Some(SyntaxTriviaPiece {
raw: self.iter.raw.clone(),
offset,
trivia,
_p: PhantomData,
})
}
}
impl<L: Language> ExactSizeIterator for SyntaxTriviaPiecesIterator<L> {}
impl<L: Language> SyntaxTrivia<L> {
pub(super) fn new(raw: cursor::SyntaxTrivia) -> Self {
Self {
raw,
_p: PhantomData,
}
}
/// Returns all [SyntaxTriviaPiece] of this trivia.
///
/// ```
/// use crate::*;
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// use std::iter::Iterator;
/// let mut node = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t /**/let \t\t",
/// &[
/// TriviaPiece::whitespace(3),
/// TriviaPiece::single_line_comment(4),
/// ],
/// &[TriviaPiece::whitespace(3)],
/// );
/// });
/// let pieces: Vec<_> = node.first_leading_trivia().unwrap().pieces().collect();
/// assert_eq!(2, pieces.len());
/// let pieces: Vec<_> = node.last_trailing_trivia().unwrap().pieces().collect();
/// assert_eq!(1, pieces.len());
/// ```
pub fn pieces(&self) -> SyntaxTriviaPiecesIterator<L> {
SyntaxTriviaPiecesIterator {
iter: self.raw.pieces(),
_p: PhantomData,
}
}
pub fn last(&self) -> Option<SyntaxTriviaPiece<L>> {
let piece = self.raw.last()?;
Some(SyntaxTriviaPiece {
raw: self.raw.clone(),
offset: self.raw.text_range().end() - piece.length,
trivia: *piece,
_p: Default::default(),
})
}
pub fn first(&self) -> Option<SyntaxTriviaPiece<L>> {
let piece = self.raw.first()?;
Some(SyntaxTriviaPiece {
raw: self.raw.clone(),
offset: self.raw.text_range().start(),
trivia: *piece,
_p: Default::default(),
})
}
pub fn text(&self) -> &str {
self.raw.text()
}
pub fn text_range(&self) -> TextRange {
self.raw.text_range()
}
pub fn is_empty(&self) -> bool {
self.raw.len() == 0
}
pub fn has_skipped(&self) -> bool {
self.pieces().any(|piece| piece.is_skipped())
}
}
fn print_debug_str<S: AsRef<str>>(text: S, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let text = text.as_ref();
if text.len() < 25 {
write!(f, "{:?}", text)
} else {
for idx in 21..25 {
if text.is_char_boundary(idx) {
let text = format!("{} ...", &text[..idx]);
return write!(f, "{:?}", text);
}
}
write!(f, "")
}
}
impl<L: Language> std::fmt::Debug for SyntaxTrivia<L> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "[")?;
let mut first_piece = true;
for piece in self.pieces() {
if !first_piece {
write!(f, ", ")?;
}
first_piece = false;
write!(f, "{:?}", piece)?;
}
write!(f, "]")
}
}
/// Remove leading newlines and whitespaces from `trivia`.
///
/// ## Examples
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind};
/// use rome_rowan::{trim_leading_trivia_pieces, RawSyntaxToken, SyntaxToken, TriviaPiece};
///
/// let token = SyntaxToken::<RawLanguage>::new_detached(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t /*c*/ let \t",
/// [TriviaPiece::newline(1), TriviaPiece::whitespace(2), TriviaPiece::multi_line_comment(5), TriviaPiece::whitespace(1)],
/// [TriviaPiece::whitespace(2)]
/// );
/// let new_token = token.with_leading_trivia_pieces(
/// trim_leading_trivia_pieces(token.leading_trivia().pieces())
/// );
///
/// assert_eq!(
/// format!("{:?}", new_token),
/// "LET_TOKEN@0..11 \"let\" [Comments(\"/*c*/\"), Whitespace(\" \")] [Whitespace(\" \\t\")]"
/// );
/// ```
pub fn trim_leading_trivia_pieces<L: Language>(
trivia: impl ExactSizeIterator<Item = SyntaxTriviaPiece<L>>,
) -> impl ExactSizeIterator<Item = SyntaxTriviaPiece<L>> {
let mut trivia = trivia.peekable();
// We cannot use `skip_while` because `SkipWhile` doesn't implement `ExactSizeIterator`.
// Eager version of `skip_while` which eagerly consume trivia.
while trivia
.next_if(|x| x.is_whitespace() || x.is_newline())
.is_some()
{}
trivia
}
/// Remove trailing newlines and whitespaces from `trivia`.
///
/// ## Examples
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind};
/// use rome_rowan::{trim_trailing_trivia_pieces, RawSyntaxToken, SyntaxToken, TriviaPiece};
///
/// let token = SyntaxToken::<RawLanguage>::new_detached(
/// RawLanguageKind::LET_TOKEN,
/// "\t/*c*/\n\t let ",
/// [TriviaPiece::whitespace(1), TriviaPiece::multi_line_comment(5), TriviaPiece::newline(1), TriviaPiece::whitespace(2)],
/// [TriviaPiece::whitespace(1)],
/// );
/// let new_token = token.with_leading_trivia_pieces(
/// trim_trailing_trivia_pieces(token.leading_trivia().pieces())
/// );
///
/// assert_eq!(
/// format!("{:?}", new_token),
/// "LET_TOKEN@0..10 \"let\" [Whitespace(\"\\t\"), Comments(\"/*c*/\")] [Whitespace(\" \")]"
/// );
/// ```
pub fn trim_trailing_trivia_pieces<L: Language>(
trivia: impl ExactSizeIterator<Item = SyntaxTriviaPiece<L>> + DoubleEndedIterator,
) -> impl ExactSizeIterator<Item = SyntaxTriviaPiece<L>> {
let mut trivia = trivia.rev().peekable();
let mut take_count = trivia.len();
// We cannot use `take_while` because `TakeWhile` doesn't implement `ExactSizeIterator`.
while trivia
.next_if(|x| x.is_whitespace() || x.is_newline())
.is_some()
{
take_count -= 1;
}
// We have to use `take` to avoid panicking on `ExactSizeIterator under-reported length`.
trivia.rev().take(take_count)
}
/// It creates an iterator by chaining two trivia pieces. This iterator
/// of trivia can be attached to a token using `*_pieces` APIs.
///
/// ## Examples
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::{chain_trivia_pieces, RawSyntaxToken, SyntaxToken, TriviaPiece, TriviaPieceKind};
///
/// let first_token = SyntaxToken::<RawLanguage>::new_detached(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t let \t\t",
/// [TriviaPiece::whitespace(3)],
/// [TriviaPiece::whitespace(3)]
/// );
/// let second_token = SyntaxToken::<RawLanguage>::new_detached(
/// RawLanguageKind::SEMICOLON_TOKEN,
/// "; \t\t",
/// [TriviaPiece::whitespace(1)],
/// [TriviaPiece::whitespace(1)],
/// );
///
/// let leading_trivia = chain_trivia_pieces(
/// first_token.leading_trivia().pieces(),
/// second_token.leading_trivia().pieces()
/// );
///
/// let new_first_token = first_token.with_leading_trivia_pieces(leading_trivia);
///
/// let new_token = format!("{:?}", new_first_token);
/// assert_eq!(new_token, "LET_TOKEN@0..10 \"let\" [Whitespace(\"\\n\\t \"), Whitespace(\";\")] [Whitespace(\" \\t\\t\")]");
///
/// ```
///
pub fn chain_trivia_pieces<L, F, S>(first: F, second: S) -> ChainTriviaPiecesIterator<F, S>
where
L: Language,
F: Iterator<Item = SyntaxTriviaPiece<L>>,
S: Iterator<Item = SyntaxTriviaPiece<L>>,
{
ChainTriviaPiecesIterator::new(first, second)
}
/// Chain iterator that chains two iterators over syntax trivia together.
///
/// This is the same as Rust's [std::iter::Chain] iterator but implements [ExactSizeIterator].
/// Rust doesn't implement [ExactSizeIterator] because adding the sizes of both pieces may overflow.
///
/// Implementing [ExactSizeIterator] in our case is safe because this may only overflow if
/// a source document has more than 2^32 trivia which isn't possible because our source documents are limited to 2^32
/// length.
pub struct ChainTriviaPiecesIterator<F, S> {
first: Option<F>,
second: S,
}
impl<F, S> ChainTriviaPiecesIterator<F, S> {
fn new(first: F, second: S) -> Self {
Self {
first: Some(first),
second,
}
}
}
impl<L, F, S> Iterator for ChainTriviaPiecesIterator<F, S>
where
L: Language,
F: Iterator<Item = SyntaxTriviaPiece<L>>,
S: Iterator<Item = SyntaxTriviaPiece<L>>,
{
type Item = SyntaxTriviaPiece<L>;
fn next(&mut self) -> Option<Self::Item> {
match &mut self.first {
Some(first) => match first.next() {
Some(next) => Some(next),
None => {
self.first.take();
self.second.next()
}
},
None => self.second.next(),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match &self.first {
Some(first) => {
let (first_lower, first_upper) = first.size_hint();
let (second_lower, second_upper) = self.second.size_hint();
let lower = first_lower.saturating_add(second_lower);
let upper = match (first_upper, second_upper) {
(Some(first), Some(second)) => first.checked_add(second),
_ => None,
};
(lower, upper)
}
None => self.second.size_hint(),
}
}
}
impl<L, F, S> FusedIterator for ChainTriviaPiecesIterator<F, S>
where
L: Language,
F: Iterator<Item = SyntaxTriviaPiece<L>>,
S: Iterator<Item = SyntaxTriviaPiece<L>>,
{
}
impl<L, F, S> ExactSizeIterator for ChainTriviaPiecesIterator<F, S>
where
L: Language,
F: ExactSizeIterator<Item = SyntaxTriviaPiece<L>>,
S: ExactSizeIterator<Item = SyntaxTriviaPiece<L>>,
{
fn len(&self) -> usize {
match &self.first {
Some(first) => {
let first_len = first.len();
let second_len = self.second.len();
// SAFETY: Should be safe because a program can never contain more than u32 pieces
// because the text ranges are represented as u32 (and each piece must at least contain a single character).
first_len + second_len
}
None => self.second.len(),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/syntax/rewriter.rs | crates/rome_rowan/src/syntax/rewriter.rs | //! A module that exports utilities to rewrite a syntax trees
use crate::{Language, SyntaxNode, SyntaxSlot, SyntaxToken};
/// A visitor that re-writes a syntax tree while visiting the nodes.
///
/// The rewriter visits the nodes in pre-order from top-down.
/// Meaning, it first visits the `root`, and then visits the children of the root from left to right,
/// recursively traversing into child nodes and calling [`visit_node`](SyntaxRewriter) for every node.
///
/// Inspired by Roslyn's [`CSharpSyntaxRewriter`](https://docs.microsoft.com/en-us/dotnet/api/microsoft.codeanalysis.csharp.csharpsyntaxrewriter?view=roslyn-dotnet-4.2.0)
///
/// # Unsupported
///
/// The current implementation does not yet support node removal.
///
/// # Examples
///
/// Implementation of a rewritten that replaces all literal expression nodes that contain a number token
/// with a bogus node.
///
/// ```
/// # use std::iter;
/// # use rome_rowan::{AstNode, SyntaxNode, SyntaxRewriter, VisitNodeSignal};
/// # use rome_rowan::raw_language::{LiteralExpression, RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
///
/// struct ReplaceNumberLiteralRewriter;
///
/// impl SyntaxRewriter for ReplaceNumberLiteralRewriter {
/// type Language = RawLanguage;
///
/// fn visit_node(
/// &mut self,
/// node: SyntaxNode<Self::Language>,
/// ) -> VisitNodeSignal<Self::Language> {
/// match node.kind() {
/// RawLanguageKind::LITERAL_EXPRESSION => {
/// let expression = LiteralExpression::unwrap_cast(node);
///
/// let mut token = expression
/// .syntax()
/// .slots()
/// .nth(0)
/// .unwrap()
/// .into_token()
/// .unwrap();
///
/// match token.kind() {
/// RawLanguageKind::NUMBER_TOKEN => {
/// // Use your language's syntax factory instead
/// let bogus_node = SyntaxNode::new_detached(
/// RawLanguageKind::BOGUS,
/// iter::once(Some(token.into())),
/// );
///
/// VisitNodeSignal::Replace(bogus_node)
/// }
/// // Not interested in string literal expressions, continue traversal
/// _ => VisitNodeSignal::Traverse(expression.into_syntax()),
/// }
/// }
/// _ => {
/// // Traverse into the childrens of node
/// VisitNodeSignal::Traverse(node)
/// }
/// }
/// }
/// }
///
/// let mut builder = RawSyntaxTreeBuilder::new();
///
/// builder.start_node(RawLanguageKind::ROOT);
/// builder.start_node(RawLanguageKind::SEPARATED_EXPRESSION_LIST);
///
/// builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
/// builder.token(RawLanguageKind::NUMBER_TOKEN, "5");
/// builder.finish_node();
///
/// builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
/// builder.token(RawLanguageKind::STRING_TOKEN, "'abcd'");
/// builder.finish_node();
///
/// builder.finish_node();
/// builder.finish_node();
///
/// let root = builder.finish();
///
/// let transformed = ReplaceNumberLiteralRewriter.transform(root.clone());
///
/// let original_literal_expressions: Vec<_> = root
/// .descendants()
/// .filter(|p| p.kind() == RawLanguageKind::LITERAL_EXPRESSION)
/// .collect();
///
/// assert_ne!(
/// &root, &transformed,
/// "It returns a new root with the updated children"
/// );
///
/// let literal_expressions: Vec<_> = transformed
/// .descendants()
/// .filter(|p| p.kind() == RawLanguageKind::LITERAL_EXPRESSION)
/// .collect();
///
/// // The literal expression containing a string token should be unchanged
/// assert_eq!(&literal_expressions, &original_literal_expressions[1..]);
///
/// let mut bogus: Vec<_> = transformed
/// .descendants()
/// .filter(|p| p.kind() == RawLanguageKind::BOGUS)
/// .collect();
///
/// // It replaced the number literal expression with a bogus node.
/// assert_eq!(bogus.len(), 1);
/// assert_eq!(bogus.pop().unwrap().text(), "5");
/// ```
pub trait SyntaxRewriter {
type Language: Language;
/// Recursively transforms the subtree of `node` by calling [`visit_node`](SyntaxRewriter::visit_node)
/// for every token and [`visit_token`](SyntaxRewriter::visit_token) for every token in the subtree.
///
/// Returns a new syntax tree reflecting the changes by the rewriter if it replaced any node and
/// returns `node` if no changes were made.
fn transform(&mut self, node: SyntaxNode<Self::Language>) -> SyntaxNode<Self::Language>
where
Self: Sized,
{
match self.visit_node(node) {
VisitNodeSignal::Replace(updated) => updated,
VisitNodeSignal::Traverse(node) => traverse(node, self),
}
}
/// Called for every node in the tree. The method should return a signal specifying what should be done with the node
///
/// * [VisitNodeSignal::Traverse]: Recourse into `node` so that [`visit_node`](SyntaxRewriter::visit_node)
/// gets called for all children of `node`. The `node` will only be replaced if any node in its subtree changes.
/// * [VisitNodeSignal::Replace]: Replaces `node` with the node specified in the [`Replace`](VisitNodeSignal::Replace) variant.
/// It's your responsibility to call [`traverse`](SyntaxRewriter::transform) for any child of `node` for which you want the rewritter
/// to recurse into its content.
fn visit_node(&mut self, node: SyntaxNode<Self::Language>) -> VisitNodeSignal<Self::Language> {
VisitNodeSignal::Traverse(node)
}
/// Called for every token in the tree. Returning a new token changes the token in the parent node.
fn visit_token(&mut self, token: SyntaxToken<Self::Language>) -> SyntaxToken<Self::Language> {
token
}
}
#[derive(Debug, Clone)]
pub enum VisitNodeSignal<L: Language> {
/// Signals the [SyntaxRewriter] to replace the current node with the specified node.
Replace(SyntaxNode<L>),
/// Signals the [SyntaxRewriter] to traverse into the children of the specified node.
Traverse(SyntaxNode<L>),
}
fn traverse<R>(mut parent: SyntaxNode<R::Language>, rewriter: &mut R) -> SyntaxNode<R::Language>
where
R: SyntaxRewriter,
{
for slot in parent.slots() {
match slot {
SyntaxSlot::Node(node) => {
let original_key = node.key();
let index = node.index();
let updated = rewriter.transform(node);
if updated.key() != original_key {
parent = parent.splice_slots(index..=index, [Some(updated.into())]);
}
}
SyntaxSlot::Token(token) => {
let original_key = token.key();
let index = token.index();
let updated = rewriter.visit_token(token);
if updated.key() != original_key {
parent = parent.splice_slots(index..=index, [Some(updated.into())]);
}
}
SyntaxSlot::Empty => {
// Nothing to visit
}
}
}
parent
}
#[cfg(test)]
mod tests {
use crate::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
use crate::{SyntaxNode, SyntaxRewriter, SyntaxToken, VisitNodeSignal};
#[test]
pub fn test_visits_each_node() {
let mut builder = RawSyntaxTreeBuilder::new();
builder.start_node(RawLanguageKind::ROOT);
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::NUMBER_TOKEN, "5");
builder.finish_node();
builder.finish_node();
let root = builder.finish();
let mut recorder = RecordRewritter::default();
let transformed = recorder.transform(root.clone());
assert_eq!(
&root, &transformed,
"It should return the same node if the rewritter doesn't replace a node."
);
let literal_expression = root
.descendants()
.find(|node| node.kind() == RawLanguageKind::LITERAL_EXPRESSION)
.unwrap();
assert_eq!(&recorder.nodes, &[root.clone(), literal_expression]);
let number_literal = root.first_token().unwrap();
assert_eq!(&recorder.tokens, &[number_literal]);
}
/// Visitor that records every `visit_node` and `visit_token` call.
#[derive(Default)]
struct RecordRewritter {
nodes: Vec<SyntaxNode<RawLanguage>>,
tokens: Vec<SyntaxToken<RawLanguage>>,
}
impl SyntaxRewriter for RecordRewritter {
type Language = RawLanguage;
fn visit_node(
&mut self,
node: SyntaxNode<Self::Language>,
) -> VisitNodeSignal<Self::Language> {
self.nodes.push(node.clone());
VisitNodeSignal::Traverse(node)
}
fn visit_token(
&mut self,
token: SyntaxToken<Self::Language>,
) -> SyntaxToken<Self::Language> {
self.tokens.push(token.clone());
token
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/syntax/token.rs | crates/rome_rowan/src/syntax/token.rs | use crate::green::{GreenToken, GreenTrivia};
use crate::syntax::element::SyntaxElementKey;
use crate::syntax::SyntaxTrivia;
use crate::token_text::TokenText;
use crate::{
chain_trivia_pieces, cursor, Direction, Language, NodeOrToken, SyntaxElement, SyntaxKind,
SyntaxNode, SyntaxTriviaPiece, TriviaPiece, TriviaPieceKind,
};
use rome_text_size::{TextLen, TextRange, TextSize};
use std::fmt;
use std::marker::PhantomData;
use super::trivia::{trim_leading_trivia_pieces, trim_trailing_trivia_pieces};
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct SyntaxToken<L: Language> {
raw: cursor::SyntaxToken,
_p: PhantomData<L>,
}
impl<L: Language> SyntaxToken<L> {
/// Create a new token detached from any tree
///
/// This is mainly useful for creating a small number of individual tokens
/// when mutating an existing tree, the bulk of the tokens in a given file
/// should be created through the [crate::TreeBuilder] abstraction instead
/// as it will efficiently cache and reuse the created tokens
pub fn new_detached<Leading, Trailing>(
kind: L::Kind,
text: &str,
leading: Leading,
trailing: Trailing,
) -> Self
where
Leading: IntoIterator<Item = TriviaPiece>,
Leading::IntoIter: ExactSizeIterator,
Trailing: IntoIterator<Item = TriviaPiece>,
Trailing::IntoIter: ExactSizeIterator,
{
Self {
raw: cursor::SyntaxToken::new_detached(GreenToken::with_trivia(
kind.to_raw(),
text,
GreenTrivia::new(leading),
GreenTrivia::new(trailing),
)),
_p: PhantomData,
}
}
pub(super) fn green_token(&self) -> GreenToken {
self.raw.green().to_owned()
}
pub fn key(&self) -> SyntaxElementKey {
let (node_data, offset) = self.raw.key();
SyntaxElementKey::new(node_data, offset)
}
pub fn kind(&self) -> L::Kind {
L::Kind::from_raw(self.raw.kind())
}
pub fn text_range(&self) -> TextRange {
self.raw.text_range()
}
pub fn text_trimmed_range(&self) -> TextRange {
self.raw.text_trimmed_range()
}
pub(crate) fn index(&self) -> usize {
self.raw.index()
}
/// Returns the text of the token, including all trivia.
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// let mut token = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t let \t\t",
/// &[TriviaPiece::whitespace(3)],
/// &[TriviaPiece::whitespace(3)],
/// );
/// })
/// .first_token()
/// .unwrap();
/// assert_eq!("\n\t let \t\t", token.text());
/// ```
pub fn text(&self) -> &str {
self.raw.text()
}
/// Returns the text of a token, including all trivia as an owned value.
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// let mut token = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t let \t\t",
/// &[TriviaPiece::whitespace(3)],
/// &[TriviaPiece::whitespace(3)],
/// );
/// })
/// .first_token()
/// .unwrap();
/// assert_eq!("\n\t let \t\t", token.token_text());
/// assert_eq!(
/// format!("{}", "\n\t let \t\t"),
/// format!("{}", token.token_text())
/// );
/// assert_eq!(
/// format!("{:?}", "\n\t let \t\t"),
/// format!("{:?}", token.token_text())
/// );
/// ```
pub fn token_text(&self) -> TokenText {
self.raw.token_text()
}
pub fn token_text_trimmed(&self) -> TokenText {
self.raw.token_text_trimmed()
}
/// Returns the text of the token, excluding all trivia.
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// let mut token = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t let \t\t",
/// &[TriviaPiece::whitespace(3)],
/// &[TriviaPiece::whitespace(3)],
/// );
/// })
/// .first_token()
/// .unwrap();
/// assert_eq!("let", token.text_trimmed());
/// ```
pub fn text_trimmed(&self) -> &str {
self.raw.text_trimmed()
}
pub fn parent(&self) -> Option<SyntaxNode<L>> {
self.raw.parent().map(SyntaxNode::from)
}
pub fn ancestors(&self) -> impl Iterator<Item = SyntaxNode<L>> {
self.raw.ancestors().map(SyntaxNode::from)
}
pub fn next_sibling_or_token(&self) -> Option<SyntaxElement<L>> {
self.raw.next_sibling_or_token().map(NodeOrToken::from)
}
pub fn prev_sibling_or_token(&self) -> Option<SyntaxElement<L>> {
self.raw.prev_sibling_or_token().map(NodeOrToken::from)
}
pub fn siblings_with_tokens(
&self,
direction: Direction,
) -> impl Iterator<Item = SyntaxElement<L>> {
self.raw
.siblings_with_tokens(direction)
.map(SyntaxElement::from)
}
/// Next token in the tree (i.e, not necessary a sibling).
pub fn next_token(&self) -> Option<SyntaxToken<L>> {
self.raw.next_token().map(SyntaxToken::from)
}
/// Previous token in the tree (i.e, not necessary a sibling).
pub fn prev_token(&self) -> Option<SyntaxToken<L>> {
self.raw.prev_token().map(SyntaxToken::from)
}
/// Return a new version of this token detached from its parent node
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn detach(self) -> Self {
Self {
raw: self.raw.detach(),
_p: PhantomData,
}
}
/// Return a new version of this token with its leading trivia replaced with `trivia`
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn with_leading_trivia<'a, I>(&self, trivia: I) -> Self
where
I: IntoIterator<Item = (TriviaPieceKind, &'a str)>,
I::IntoIter: ExactSizeIterator,
{
let mut token_text = String::new();
let trivia = trivia.into_iter().map(|(kind, text)| {
token_text.push_str(text);
TriviaPiece::new(kind, TextSize::of(text))
});
let leading = GreenTrivia::new(trivia);
// Copy over token text and trailing trivia
let leading_len = self.raw.green().leading_trivia().text_len();
token_text.push_str(&self.text()[usize::from(leading_len)..]);
Self {
raw: cursor::SyntaxToken::new_detached(GreenToken::with_trivia(
self.kind().to_raw(),
&token_text,
leading,
self.green_token().trailing_trivia().clone(),
)),
_p: PhantomData,
}
}
/// Return a new version of this token with its leading trivia replaced with `trivia`
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn with_leading_trivia_pieces<I>(&self, trivia: I) -> Self
where
I: IntoIterator<Item = SyntaxTriviaPiece<L>>,
I::IntoIter: ExactSizeIterator,
{
let mut token_text = String::new();
let trivia = trivia.into_iter().map(|piece| {
token_text.push_str(piece.text());
piece.into_raw_piece()
});
let leading = GreenTrivia::new(trivia);
// Copy over token text and trailing trivia
let leading_len = self.raw.green().leading_trivia().text_len();
token_text.push_str(&self.text()[usize::from(leading_len)..]);
Self {
raw: cursor::SyntaxToken::new_detached(GreenToken::with_trivia(
self.kind().to_raw(),
&token_text,
leading,
self.green_token().trailing_trivia().clone(),
)),
_p: PhantomData,
}
}
/// Return a new version of this token with its trailing trivia replaced with `trivia`
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn with_trailing_trivia<'a, I>(&self, trivia: I) -> Self
where
I: IntoIterator<Item = (TriviaPieceKind, &'a str)>,
I::IntoIter: ExactSizeIterator,
{
let mut token_text = String::new();
// copy over leading trivia and token text
let trailing_len = self.green_token().trailing_trivia().text_len();
token_text.push_str(&self.text()[..usize::from(self.text().text_len() - trailing_len)]);
let trivia = trivia.into_iter().map(|(kind, text)| {
token_text.push_str(text);
TriviaPiece::new(kind, TextSize::of(text))
});
let trailing = GreenTrivia::new(trivia);
Self {
raw: cursor::SyntaxToken::new_detached(GreenToken::with_trivia(
self.kind().to_raw(),
&token_text,
self.green_token().leading_trivia().clone(),
trailing,
)),
_p: PhantomData,
}
}
/// Return a new version of this token with its trailing trivia replaced with `trivia`
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn with_trailing_trivia_pieces<I>(&self, trivia: I) -> Self
where
I: IntoIterator<Item = SyntaxTriviaPiece<L>>,
I::IntoIter: ExactSizeIterator,
{
let mut token_text = String::new();
// copy over leading trivia and token text
let trailing_len = self.green_token().trailing_trivia().text_len();
token_text.push_str(&self.text()[..usize::from(self.text().text_len() - trailing_len)]);
let trivia = trivia.into_iter().map(|piece| {
token_text.push_str(piece.text());
piece.into_raw_piece()
});
let trailing = GreenTrivia::new(trivia);
Self {
raw: cursor::SyntaxToken::new_detached(GreenToken::with_trivia(
self.kind().to_raw(),
&token_text,
self.green_token().leading_trivia().clone(),
trailing,
)),
_p: PhantomData,
}
}
// Return a new version of this token with `trivia` prepended to its leading trivia.
///
/// # Examples
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind};
/// use rome_rowan::{RawSyntaxToken, SyntaxToken, TriviaPiece};
///
/// let token = SyntaxToken::<RawLanguage>::new_detached(
/// RawLanguageKind::LET_TOKEN,
/// "/*c*/ let \t",
/// [TriviaPiece::multi_line_comment(5), TriviaPiece::whitespace(1)],
/// [TriviaPiece::whitespace(2)]
/// );
/// let new_token = token.prepend_trivia_pieces(token.trailing_trivia().pieces());
///
/// assert_eq!(
/// format!("{:?}", new_token),
/// "LET_TOKEN@0..13 \"let\" [Whitespace(\" \\t\"), Comments(\"/*c*/\"), Whitespace(\" \")] [Whitespace(\" \\t\")]"
/// );
/// ```
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn prepend_trivia_pieces<I>(&self, trivia: I) -> Self
where
I: IntoIterator<Item = SyntaxTriviaPiece<L>>,
I::IntoIter: ExactSizeIterator,
{
self.with_leading_trivia_pieces(chain_trivia_pieces(
trivia.into_iter(),
self.leading_trivia().pieces(),
))
}
// Return a new version of this token with `trivia` appended to its trailing trivia.
///
/// # Examples
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind};
/// use rome_rowan::{RawSyntaxToken, SyntaxToken, TriviaPiece};
///
/// let token = SyntaxToken::<RawLanguage>::new_detached(
/// RawLanguageKind::LET_TOKEN,
/// "\t let /*c*/",
/// [TriviaPiece::whitespace(2)],
/// [TriviaPiece::whitespace(1), TriviaPiece::multi_line_comment(5)],
/// );
/// let new_token = token.append_trivia_pieces(token.leading_trivia().pieces());
///
/// assert_eq!(
/// format!("{:?}", new_token),
/// "LET_TOKEN@0..13 \"let\" [Whitespace(\"\\t \")] [Whitespace(\" \"), Comments(\"/*c*/\"), Whitespace(\"\\t \")]"
/// );
/// ```
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn append_trivia_pieces<I>(&self, trivia: I) -> Self
where
I: IntoIterator<Item = SyntaxTriviaPiece<L>>,
I::IntoIter: ExactSizeIterator,
{
self.with_trailing_trivia_pieces(chain_trivia_pieces(
self.trailing_trivia().pieces(),
trivia.into_iter(),
))
}
/// Return a new version of this token without leading newlines and whitespaces.
///
/// # Examples
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind};
/// use rome_rowan::{RawSyntaxToken, SyntaxToken, TriviaPiece};
///
/// let token = SyntaxToken::<RawLanguage>::new_detached(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t /*c*/ let \t",
/// [TriviaPiece::newline(1), TriviaPiece::whitespace(2), TriviaPiece::multi_line_comment(5), TriviaPiece::whitespace(1)],
/// [TriviaPiece::whitespace(2)]
/// );
/// let new_token = token.trim_leading_trivia();
///
/// assert_eq!(
/// format!("{:?}", new_token),
/// "LET_TOKEN@0..11 \"let\" [Comments(\"/*c*/\"), Whitespace(\" \")] [Whitespace(\" \\t\")]"
/// );
/// ```
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn trim_leading_trivia(&self) -> Self {
self.with_leading_trivia_pieces(trim_leading_trivia_pieces(self.leading_trivia().pieces()))
}
/// Return a new version of this token without trailing whitespaces.
///
/// # Examples
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind};
/// use rome_rowan::{RawSyntaxToken, SyntaxToken, TriviaPiece};
///
/// let token = SyntaxToken::<RawLanguage>::new_detached(
/// RawLanguageKind::LET_TOKEN,
/// "\n let /*c*/\t ",
/// [TriviaPiece::newline(1), TriviaPiece::whitespace(1)],
/// [TriviaPiece::whitespace(1), TriviaPiece::multi_line_comment(5), TriviaPiece::whitespace(2)]
/// );
/// let new_token = token.trim_trailing_trivia();
///
/// assert_eq!(
/// format!("{:?}", new_token),
/// "LET_TOKEN@0..11 \"let\" [Newline(\"\\n\"), Whitespace(\" \")] [Whitespace(\" \"), Comments(\"/*c*/\")]"
/// );
/// ```
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub fn trim_trailing_trivia(&self) -> Self {
self.with_trailing_trivia_pieces(trim_trailing_trivia_pieces(
self.trailing_trivia().pieces(),
))
}
/// Return whitespace that juxtapose the token until the first non-whitespace item.
pub fn indentation_trivia_pieces(&self) -> impl ExactSizeIterator<Item = SyntaxTriviaPiece<L>> {
let leading_trivia = self.leading_trivia().pieces();
let skip_count = leading_trivia.len()
- leading_trivia
.rev()
.position(|x| !x.is_whitespace())
.map(|pos| pos + 1)
.unwrap_or(0);
self.leading_trivia().pieces().skip(skip_count)
}
/// Returns the token's leading trivia.
///
/// Looking backward in the text, a token owns all of its preceding trivia up to and including the first newline character.
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// let mut token = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t let \t\t",
/// &[TriviaPiece::whitespace(3)],
/// &[TriviaPiece::whitespace(3)],
/// );
/// })
/// .first_token()
/// .unwrap();
/// assert_eq!("\n\t ", token.leading_trivia().text());
/// ```
#[inline]
pub fn leading_trivia(&self) -> SyntaxTrivia<L> {
SyntaxTrivia::new(self.raw.leading_trivia())
}
/// Returns the token's trailing trivia.
///
/// A token owns all of its following trivia up to, but not including, the next newline character.
///
/// ```
/// use rome_rowan::raw_language::{RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder};
/// use rome_rowan::*;
/// let mut token = RawSyntaxTreeBuilder::wrap_with_node(RawLanguageKind::ROOT, |builder| {
/// builder.token_with_trivia(
/// RawLanguageKind::LET_TOKEN,
/// "\n\t let \t\t",
/// &[TriviaPiece::whitespace(3)],
/// &[TriviaPiece::whitespace(3)],
/// );
/// })
/// .first_token()
/// .unwrap();
/// assert_eq!(" \t\t", token.trailing_trivia().text());
/// ```
#[inline]
pub fn trailing_trivia(&self) -> SyntaxTrivia<L> {
SyntaxTrivia::new(self.raw.trailing_trivia())
}
/// Checks if the current token has trailing comments
pub fn has_trailing_comments(&self) -> bool {
self.trailing_trivia()
.pieces()
.any(|piece| piece.is_comments())
}
/// Checks if the current token has leading comments
pub fn has_leading_comments(&self) -> bool {
self.leading_trivia()
.pieces()
.any(|piece| piece.is_comments())
}
/// Checks if the token has any leading trivia that isn't a whitespace nor a line break
pub fn has_leading_non_whitespace_trivia(&self) -> bool {
self.leading_trivia()
.pieces()
.any(|piece| piece.is_whitespace() || piece.is_newline())
}
/// Checks if the current token has leading newline
pub fn has_leading_newline(&self) -> bool {
self.leading_trivia()
.pieces()
.any(|piece| piece.is_newline())
}
}
impl<L: Language> fmt::Debug for SyntaxToken<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{:?}@{:?} {:?} ",
self.kind(),
self.text_range(),
self.text_trimmed()
)?;
self.leading_trivia().fmt(f)?;
write!(f, " ")?;
self.trailing_trivia().fmt(f)
}
}
impl<L: Language> fmt::Display for SyntaxToken<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.raw, f)
}
}
impl<L: Language> From<SyntaxToken<L>> for cursor::SyntaxToken {
fn from(token: SyntaxToken<L>) -> cursor::SyntaxToken {
token.raw
}
}
impl<L: Language> From<cursor::SyntaxToken> for SyntaxToken<L> {
fn from(raw: cursor::SyntaxToken) -> SyntaxToken<L> {
SyntaxToken {
raw,
_p: PhantomData,
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/ast/batch.rs | crates/rome_rowan/src/ast/batch.rs | use crate::{
chain_trivia_pieces, AstNode, Language, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxSlot,
SyntaxToken,
};
use rome_text_edit::TextEdit;
use rome_text_size::TextRange;
use std::{
cmp,
collections::BinaryHeap,
iter::{empty, once},
};
pub trait BatchMutationExt<L>: AstNode<Language = L>
where
L: Language,
{
/// It starts a [BatchMutation]
#[must_use = "This method consumes the node and return the BatchMutation api that returns the new SynytaxNode on commit"]
fn begin(self) -> BatchMutation<L>;
}
impl<L, T> BatchMutationExt<L> for T
where
L: Language,
T: AstNode<Language = L>,
{
#[must_use = "This method consumes the node and return the BatchMutation api that returns the new SynytaxNode on commit"]
fn begin(self) -> BatchMutation<L> {
BatchMutation::new(self.into_syntax())
}
}
/// Stores the changes internally used by the [BatchMutation::commit] algorithm.
/// It needs to be sorted by depth in decreasing order, then by range start and
/// by slot in increasing order.
///
/// This is necesasry so we can aggregate all changes to the same node using "peek".
#[derive(Debug, Clone)]
struct CommitChange<L: Language> {
parent_depth: usize,
parent: Option<SyntaxNode<L>>,
parent_range: Option<(u32, u32)>,
new_node_slot: usize,
new_node: Option<SyntaxElement<L>>,
}
impl<L: Language> CommitChange<L> {
/// Returns the "ordering key" for a change, controlling in what order this
/// change will be applied relatively to other changes. The key consists of
/// a tuple of numeric values representing the depth, parent start and slot
/// of the corresponding change
fn key(&self) -> (usize, cmp::Reverse<u32>, cmp::Reverse<usize>) {
(
self.parent_depth,
cmp::Reverse(self.parent_range.map(|(start, _)| start).unwrap_or(0)),
cmp::Reverse(self.new_node_slot),
)
}
}
impl<L: Language> PartialEq for CommitChange<L> {
fn eq(&self, other: &Self) -> bool {
self.key() == other.key()
}
}
impl<L: Language> Eq for CommitChange<L> {}
/// We order first by depth. Then by the range of the node.
///
/// The first is important to guarantee that all nodes that will be changed
/// in the future are still valid with using SyntaxNode that we have.
///
/// The second is important to guarante that the ".peek()" we do below is sufficient
/// to see the same node in case of two or more nodes having the same depth.
impl<L: Language> PartialOrd for CommitChange<L> {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
impl<L: Language> Ord for CommitChange<L> {
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.key().cmp(&other.key())
}
}
#[derive(Debug, Clone)]
pub struct BatchMutation<L>
where
L: Language,
{
root: SyntaxNode<L>,
changes: BinaryHeap<CommitChange<L>>,
}
impl<L> BatchMutation<L>
where
L: Language,
{
pub fn new(root: SyntaxNode<L>) -> Self {
Self {
root,
changes: BinaryHeap::new(),
}
}
/// Push a change to replace the "prev_node" with "next_node".
/// Trivia from "prev_node" is automatically copied to "next_node".
///
/// Changes to take effect must be commited.
pub fn replace_node<T>(&mut self, prev_node: T, next_node: T)
where
T: AstNode<Language = L>,
{
self.replace_element(
prev_node.into_syntax().into(),
next_node.into_syntax().into(),
)
}
/// Push a change to replace the "prev_token" with "next_token".
/// Trivia from "prev_token" is automatically copied to "next_token".
///
/// Changes to take effect must be commited.
pub fn replace_token(&mut self, prev_token: SyntaxToken<L>, next_token: SyntaxToken<L>) {
self.replace_element(prev_token.into(), next_token.into())
}
/// Push a change to replace the "prev_element" with "next_element".
/// Trivia from "prev_element" is automatically copied to "next_element".
///
/// Changes to take effect must be commited.
pub fn replace_element(
&mut self,
prev_element: SyntaxElement<L>,
next_element: SyntaxElement<L>,
) {
let (prev_leading_trivia, prev_trailing_trivia) = match &prev_element {
SyntaxElement::Node(node) => (
node.first_token().map(|token| token.leading_trivia()),
node.last_token().map(|token| token.trailing_trivia()),
),
SyntaxElement::Token(token) => {
(Some(token.leading_trivia()), Some(token.trailing_trivia()))
}
};
let next_element = match next_element {
SyntaxElement::Node(mut node) => {
if let Some(token) = node.first_token() {
let new_token = match prev_leading_trivia {
Some(prev_leading_trivia) => {
token.with_leading_trivia_pieces(prev_leading_trivia.pieces())
}
None => token.with_leading_trivia_pieces(empty()),
};
node = node.replace_child(token.into(), new_token.into()).unwrap();
}
if let Some(token) = node.last_token() {
let new_token = match prev_trailing_trivia {
Some(prev_trailing_trivia) => {
token.with_trailing_trivia_pieces(prev_trailing_trivia.pieces())
}
None => token.with_trailing_trivia_pieces([]),
};
node = node.replace_child(token.into(), new_token.into()).unwrap();
}
SyntaxElement::Node(node)
}
SyntaxElement::Token(token) => {
let new_token = match prev_leading_trivia {
Some(prev_leading_trivia) => {
token.with_leading_trivia_pieces(prev_leading_trivia.pieces())
}
None => token.with_leading_trivia_pieces([]),
};
let new_token = match prev_trailing_trivia {
Some(prev_trailing_trivia) => {
new_token.with_trailing_trivia_pieces(prev_trailing_trivia.pieces())
}
None => new_token.with_trailing_trivia_pieces([]),
};
SyntaxElement::Token(new_token)
}
};
self.push_change(prev_element, Some(next_element))
}
/// Push a change to replace the "prev_node" with "next_node".
///
/// Changes to take effect must be committed.
pub fn replace_node_discard_trivia<T>(&mut self, prev_node: T, next_node: T)
where
T: AstNode<Language = L>,
{
self.replace_element_discard_trivia(
prev_node.into_syntax().into(),
next_node.into_syntax().into(),
)
}
/// Push a change to replace the "prev_token" with "next_token".
///
/// Changes to take effect must be committed.
pub fn replace_token_discard_trivia(
&mut self,
prev_token: SyntaxToken<L>,
next_token: SyntaxToken<L>,
) {
self.replace_element_discard_trivia(prev_token.into(), next_token.into())
}
/// Push a change to replace the "prev_token" with "next_token".
///
/// - leading trivia of `prev_token`
/// - leading trivia of `next_token`
/// - trailing trivia of `prev_token`
/// - trailing trivia of `next_token`
pub fn replace_token_transfer_trivia(
&mut self,
prev_token: SyntaxToken<L>,
next_token: SyntaxToken<L>,
) {
let leading_trivia = chain_trivia_pieces(
prev_token.leading_trivia().pieces(),
next_token.leading_trivia().pieces(),
);
let trailing_trivia = chain_trivia_pieces(
prev_token.trailing_trivia().pieces(),
next_token.trailing_trivia().pieces(),
);
let new_token = next_token
.with_leading_trivia_pieces(leading_trivia)
.with_trailing_trivia_pieces(trailing_trivia);
self.replace_token_discard_trivia(prev_token, new_token)
}
/// Push a change to replace the "prev_element" with "next_element".
///
/// Changes to take effect must be committed.
pub fn replace_element_discard_trivia(
&mut self,
prev_element: SyntaxElement<L>,
next_element: SyntaxElement<L>,
) {
self.push_change(prev_element, Some(next_element))
}
/// Push a change to remove the specified token.
///
/// Changes to take effect must be committed.
pub fn remove_token(&mut self, prev_token: SyntaxToken<L>) {
self.remove_element(prev_token.into())
}
/// Push a change to remove the specified node.
///
/// Changes to take effect must be committed.
pub fn remove_node<T>(&mut self, prev_node: T)
where
T: AstNode<Language = L>,
{
self.remove_element(prev_node.into_syntax().into())
}
/// Push a change to remove the specified element.
///
/// Changes to take effect must be committed.
pub fn remove_element(&mut self, prev_element: SyntaxElement<L>) {
self.push_change(prev_element, None)
}
fn push_change(
&mut self,
prev_element: SyntaxElement<L>,
next_element: Option<SyntaxElement<L>>,
) {
let new_node_slot = prev_element.index();
let parent = prev_element.parent();
let parent_range: Option<(u32, u32)> = parent.as_ref().map(|p| {
let range = p.text_range();
(range.start().into(), range.end().into())
});
let parent_depth = parent.as_ref().map(|p| p.ancestors().count()).unwrap_or(0);
tracing::debug!("pushing change...");
self.changes.push(CommitChange {
parent_depth,
parent,
parent_range,
new_node_slot,
new_node: next_element,
});
}
/// Returns the range of the document modified by this mutation along with
/// a list of individual text edits to be performed on the source code, or
/// [None] if the mutation is empty
pub fn as_text_edits(&self) -> Option<(TextRange, TextEdit)> {
let mut range = None;
tracing::debug!(" changes {:?}", &self.changes);
for change in &self.changes {
let parent = change.parent.as_ref().unwrap_or(&self.root);
let delete = match parent.slots().nth(change.new_node_slot) {
Some(SyntaxSlot::Node(node)) => node.text_range(),
Some(SyntaxSlot::Token(token)) => token.text_range(),
_ => continue,
};
range = match range {
None => Some(delete),
Some(range) => Some(range.cover(delete)),
};
}
let text_range = range?;
let old = self.root.to_string();
let new = self.clone().commit().to_string();
let text_edit = TextEdit::from_unicode_words(&old, &new);
Some((text_range, text_edit))
}
/// The core of the batch mutation algorithm can be summarized as:
/// 1 - Iterate all requested changes;
/// 2 - Insert them into a heap (priority queue) by depth. Deeper changes are done first;
/// 3 - Loop popping requested changes from the heap, taking the deepest change we have for the moment;
/// 4 - Each requested change has a "parent", an "index" and the "new node" (or None);
/// 5 - Clone the current parent's "parent", the "grandparent";
/// 6 - Detach the current "parent" from the tree;
/// 7 - Replace the old node at "index" at the current "parent" with the current "new node";
/// 8 - Insert into the heap the grandparent as the parent and the current "parent" as the "new node";
///
/// This is the simple case. The algorithm also has a more complex case when to changes have a common ancestor,
/// which can actually be one of the changed nodes.
///
/// To address this case at step 3, when we pop a new change to apply it, we actually aggregate all changes to the current
/// parent together. This is done by the heap because we also sort by node and it's range.
///
pub fn commit(self) -> SyntaxNode<L> {
let BatchMutation { root, mut changes } = self;
// Fill the heap with the requested changes
while let Some(item) = changes.pop() {
// If parent is None, we reached the root
if let Some(current_parent) = item.parent {
// This must be done before the detachment below
// because we need nodes that are still valid in the old tree
let grandparent = current_parent.parent();
let grandparent_range = grandparent.as_ref().map(|g| {
let range = g.text_range();
(range.start().into(), range.end().into())
});
let current_parent_slot = current_parent.index();
// Aggregate all modifications to the current parent
// This works because of the Ord we defined in the [CommitChange] struct
let mut modifications = vec![(item.new_node_slot, item.new_node)];
loop {
if let Some(next_change_parent) = changes.peek().and_then(|i| i.parent.as_ref())
{
if *next_change_parent == current_parent {
// SAFETY: We can .pop().unwrap() because we .peek() above
let next_change = changes.pop().expect("changes.pop");
// If we have two modification to the same slot,
// last write wins
if let Some(last) = modifications.last() {
if last.0 == next_change.new_node_slot {
modifications.pop();
}
}
modifications.push((next_change.new_node_slot, next_change.new_node));
continue;
}
}
break;
}
// Now we detach the current parent, make all the modifications
// and push a pending change to its parent.
let mut current_parent = current_parent.detach();
let is_list = current_parent.kind().is_list();
let mut removed_slots = 0;
for (index, replace_with) in modifications {
debug_assert!(index >= removed_slots);
let index = index.checked_sub(removed_slots)
.unwrap_or_else(|| panic!("cannot replace element in slot {index} with {removed_slots} removed slots"));
current_parent = if is_list && replace_with.is_none() {
removed_slots += 1;
current_parent.clone().splice_slots(index..=index, empty())
} else {
current_parent
.clone()
.splice_slots(index..=index, once(replace_with))
};
}
changes.push(CommitChange {
parent_depth: item.parent_depth - 1,
parent: grandparent,
parent_range: grandparent_range,
new_node_slot: current_parent_slot,
new_node: Some(SyntaxElement::Node(current_parent)),
});
} else {
let root = item
.new_node
.expect("new_node")
.into_node()
.expect("expected root to be a node and not a token");
return root;
}
}
root
}
pub fn root(&self) -> &SyntaxNode<L> {
&self.root
}
}
#[cfg(test)]
pub mod tests {
use crate::{
raw_language::{LiteralExpression, RawLanguageKind, RawLanguageRoot, RawSyntaxTreeBuilder},
AstNode, BatchMutationExt, SyntaxNodeCast,
};
/// ```
/// 0: ROOT@0..1
/// 0: LITERAL_EXPRESSION@0..1
/// 0: STRING_TOKEN@0..1 "a" [] []
/// ```
fn tree_one(a: &str) -> (RawLanguageRoot, String) {
let mut builder = RawSyntaxTreeBuilder::new();
builder
.start_node(RawLanguageKind::ROOT)
.start_node(RawLanguageKind::LITERAL_EXPRESSION)
.token(RawLanguageKind::STRING_TOKEN, a)
.finish_node()
.finish_node();
let root = builder.finish().cast::<RawLanguageRoot>().unwrap();
let s = format!("{:#?}", root.syntax());
(root, s)
}
/// ```
/// 0: ROOT@0..1
/// 0: LITERAL_EXPRESSION@0..1
/// 0: STRING_TOKEN@0..1 "a" [] []
/// 1: LITERAL_EXPRESSION@0..1
/// 0: STRING_TOKEN@0..1 "b" [] []
/// ```
fn tree_two(a: &str, b: &str) -> (RawLanguageRoot, String) {
let mut builder = RawSyntaxTreeBuilder::new();
builder
.start_node(RawLanguageKind::ROOT)
.start_node(RawLanguageKind::LITERAL_EXPRESSION)
.token(RawLanguageKind::STRING_TOKEN, a)
.finish_node()
.start_node(RawLanguageKind::LITERAL_EXPRESSION)
.token(RawLanguageKind::STRING_TOKEN, b)
.finish_node()
.finish_node();
let root = builder.finish().cast::<RawLanguageRoot>().unwrap();
let s = format!("{:#?}", root.syntax());
(root, s)
}
fn find(root: &RawLanguageRoot, name: &str) -> LiteralExpression {
root.syntax()
.descendants()
.find(|x| x.kind() == RawLanguageKind::LITERAL_EXPRESSION && x.text_trimmed() == name)
.unwrap()
.cast::<LiteralExpression>()
.unwrap()
}
fn clone_detach(root: &RawLanguageRoot, name: &str) -> LiteralExpression {
root.syntax()
.descendants()
.find(|x| x.kind() == RawLanguageKind::LITERAL_EXPRESSION && x.text_trimmed() == name)
.unwrap()
.detach()
.cast::<LiteralExpression>()
.unwrap()
}
#[test]
pub fn ok_batch_mutation_no_changes() {
let (before, before_debug) = tree_one("a");
let batch = before.begin();
let after = batch.commit();
assert_eq!(before_debug, format!("{:#?}", after));
}
#[test]
pub fn ok_batch_mutation_one_change() {
let (before, _) = tree_one("a");
let (expected, expected_debug) = tree_one("b");
let a = find(&before, "a");
let b = clone_detach(&expected, "b");
let mut batch = before.begin();
batch.replace_node(a, b);
let root = batch.commit();
assert_eq!(expected_debug, format!("{:#?}", root));
}
#[test]
pub fn ok_batch_mutation_multiple_changes_different_branches() {
let (before, _) = tree_two("a", "b");
let (expected, expected_debug) = tree_two("c", "d");
let a = find(&before, "a");
let b = find(&before, "b");
let c = clone_detach(&expected, "c");
let d = clone_detach(&expected, "d");
let mut batch = before.begin();
batch.replace_node(a, c);
batch.replace_node(b, d);
let after = batch.commit();
assert_eq!(expected_debug, format!("{:#?}", after));
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/ast/mutation.rs | crates/rome_rowan/src/ast/mutation.rs | use std::ops;
use crate::{AstNode, AstNodeList, AstSeparatedList, SyntaxToken};
pub trait AstNodeExt: AstNode {
/// Return a new version of this node with the node `prev_node` replaced with `next_node`
///
/// `prev_node` can be a direct child of this node, or an indirect child through any descendant node
///
/// Returns `None` if `prev_node` is not a descendant of this node
fn replace_node_discard_trivia<N>(self, prev_node: N, next_node: N) -> Option<Self>
where
N: AstNode<Language = Self::Language>,
Self: Sized;
/// Return a new version of this node with the node `prev_node` replaced with `next_node`,
/// transfering the leading and trailing trivia of `prev_node` to `next_node`
///
/// `prev_node` can be a direct child of this node, or an indirect child through any descendant node
///
/// Returns `None` if `prev_node` is not a descendant of this node
fn replace_node<N>(self, prev_node: N, next_node: N) -> Option<Self>
where
N: AstNode<Language = Self::Language>,
Self: Sized;
/// Return a new version of this node with the token `prev_token` replaced with `next_token`
///
/// `prev_token` can be a direct child of this node, or an indirect child through any descendant node
///
/// Returns `None` if `prev_token` is not a descendant of this node
fn replace_token_discard_trivia(
self,
prev_token: SyntaxToken<Self::Language>,
next_token: SyntaxToken<Self::Language>,
) -> Option<Self>
where
Self: Sized;
/// Return a new version of this node with the token `prev_token` replaced with `next_token`,
/// transfering the leading and trailing trivia of `prev_token` to `next_token`
///
/// `prev_token` can be a direct child of this node, or an indirect child through any descendant node
///
/// Returns `None` if `prev_token` is not a descendant of this node
fn replace_token(
self,
prev_token: SyntaxToken<Self::Language>,
next_token: SyntaxToken<Self::Language>,
) -> Option<Self>
where
Self: Sized;
fn detach(self) -> Self;
}
impl<T> AstNodeExt for T
where
T: AstNode,
{
fn replace_node_discard_trivia<N>(self, prev_node: N, next_node: N) -> Option<Self>
where
N: AstNode<Language = Self::Language>,
Self: Sized,
{
Some(Self::unwrap_cast(self.into_syntax().replace_child(
prev_node.into_syntax().into(),
next_node.into_syntax().into(),
)?))
}
fn replace_node<N>(self, prev_node: N, mut next_node: N) -> Option<Self>
where
N: AstNode<Language = Self::Language>,
Self: Sized,
{
// Lookup the first token of `prev_node` and `next_node`, and transfer the leading
// trivia of the former to the later
let prev_first = prev_node.syntax().first_token();
let next_first = next_node.syntax().first_token();
if let (Some(prev_first), Some(next_first)) = (prev_first, next_first) {
let pieces: Vec<_> = prev_first.leading_trivia().pieces().collect();
next_node = next_node.replace_token_discard_trivia(
next_first.clone(),
next_first
.with_leading_trivia(pieces.iter().map(|piece| (piece.kind(), piece.text()))),
)?;
}
// Lookup the last token of `prev_node` and `next_node`, and transfer the trailing
// trivia of the former to the later
let prev_last = prev_node.syntax().last_token();
let next_last = next_node.syntax().last_token();
if let (Some(prev_last), Some(next_last)) = (prev_last, next_last) {
next_node = next_node.replace_token_discard_trivia(
next_last.clone(),
next_last.with_trailing_trivia_pieces(prev_last.trailing_trivia().pieces()),
)?;
}
// Call replace node with the modified `next_node`
self.replace_node_discard_trivia(prev_node, next_node)
}
fn replace_token_discard_trivia(
self,
prev_token: SyntaxToken<Self::Language>,
next_token: SyntaxToken<Self::Language>,
) -> Option<Self>
where
Self: Sized,
{
Some(Self::unwrap_cast(
self.into_syntax()
.replace_child(prev_token.into(), next_token.into())?,
))
}
fn replace_token(
self,
prev_token: SyntaxToken<Self::Language>,
next_token: SyntaxToken<Self::Language>,
) -> Option<Self>
where
Self: Sized,
{
let leading_trivia = prev_token.leading_trivia().pieces();
let trailing_trivia = prev_token.trailing_trivia().pieces();
self.replace_token_discard_trivia(
prev_token,
next_token
.with_leading_trivia_pieces(leading_trivia)
.with_trailing_trivia_pieces(trailing_trivia),
)
}
fn detach(self) -> Self {
Self::unwrap_cast(self.into_syntax().detach())
}
}
pub trait AstNodeListExt: AstNodeList {
/// Replace a range of the children of this list with the content of an iterator
fn splice<R, I>(self, range: R, replace_with: I) -> Self
where
Self: AstNode<Language = <Self as AstNodeList>::Language> + Sized,
R: ops::RangeBounds<usize>,
I: IntoIterator<Item = Self::Node>;
}
impl<T> AstNodeListExt for T
where
T: AstNodeList,
{
fn splice<R, I>(self, range: R, replace_with: I) -> Self
where
Self: AstNode<Language = <Self as AstNodeList>::Language> + Sized,
R: ops::RangeBounds<usize>,
I: IntoIterator<Item = Self::Node>,
{
Self::unwrap_cast(
self.into_syntax_list().into_node().splice_slots(
range,
replace_with
.into_iter()
.map(|node| Some(node.into_syntax().into())),
),
)
}
}
pub trait AstSeparatedListExt: AstSeparatedList {
/// Replace a range of the children of this list with the content of an iterator
///
/// Both the range and iterator work on pairs of node and separator token
fn splice<R, I>(self, range: R, replace_with: I) -> Self
where
Self: AstNode<Language = <Self as AstSeparatedList>::Language> + Sized,
R: ops::RangeBounds<usize>,
I: IntoIterator<
Item = (
Self::Node,
Option<SyntaxToken<<Self as AstSeparatedList>::Language>>,
),
>;
}
impl<T> AstSeparatedListExt for T
where
T: AstSeparatedList,
{
fn splice<R, I>(self, range: R, replace_with: I) -> Self
where
Self: AstNode<Language = <Self as AstSeparatedList>::Language> + Sized,
R: ops::RangeBounds<usize>,
I: IntoIterator<
Item = (
Self::Node,
Option<SyntaxToken<<Self as AstSeparatedList>::Language>>,
),
>,
{
let start_bound = match range.start_bound() {
ops::Bound::Included(index) => ops::Bound::Included(*index * 2),
ops::Bound::Excluded(index) => ops::Bound::Excluded(*index * 2),
ops::Bound::Unbounded => ops::Bound::Unbounded,
};
let end_bound = match range.end_bound() {
ops::Bound::Included(index) => ops::Bound::Included(*index * 2),
ops::Bound::Excluded(index) => ops::Bound::Excluded(*index * 2),
ops::Bound::Unbounded => ops::Bound::Unbounded,
};
Self::unwrap_cast(self.into_syntax_list().into_node().splice_slots(
(start_bound, end_bound),
replace_with.into_iter().flat_map(|(node, separator)| {
[
Some(node.into_syntax().into()),
separator.map(|token| token.into()),
]
}),
))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/ast/mod.rs | crates/rome_rowan/src/ast/mod.rs | //! AST definitions for converting untyped syntax nodes into typed AST nodes.
//!
//! Every field of every AST node is optional, this is to allow the parser to recover
//! from any error and produce an ast from any source code. If you don't want to account for
//! optionals for everything, you can use ...
use rome_text_size::TextRange;
#[cfg(feature = "serde")]
use serde::Serialize;
use std::error::Error;
use std::fmt::{self, Debug, Display, Formatter};
use std::iter::FusedIterator;
use std::marker::PhantomData;
mod batch;
mod mutation;
use crate::syntax::{SyntaxSlot, SyntaxSlots};
use crate::{
Language, RawSyntaxKind, SyntaxKind, SyntaxList, SyntaxNode, SyntaxToken, SyntaxTriviaPiece,
};
pub use batch::*;
pub use mutation::{AstNodeExt, AstNodeListExt, AstSeparatedListExt};
/// Represents a set of [SyntaxKind] as a bitfield, with each bit representing
/// whether the corresponding [RawSyntaxKind] value is contained in the set
///
/// This is similar to the `TokenSet` struct in `rome_js_parser`, with the
/// bitfield here being twice as large as it needs to cover all nodes as well
/// as all token kinds
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SyntaxKindSet<L: ?Sized + Language>([u128; 4], PhantomData<L>);
impl<L> SyntaxKindSet<L>
where
L: Language,
{
/// Create a new [SyntaxKindSet] containing only the provided [SyntaxKind]
pub fn of(kind: L::Kind) -> Self {
Self::from_raw(kind.to_raw())
}
/// Create a new [SyntaxKindSet] containing only the provided [RawSyntaxKind]
///
/// Unlike `SyntaxKindSet::of` this function can be evaluated in constants,
/// and will result in a compile-time error if the value overflows:
///
/// ```compile_fail
/// # use rome_rowan::{SyntaxKindSet, RawSyntaxKind, raw_language::RawLanguage};
/// const EXAMPLE: SyntaxKindSet<RawLanguage> =
/// SyntaxKindSet::<RawLanguage>::from_raw(RawSyntaxKind(512));
/// # println!("{EXAMPLE:?}"); // The constant must be used to be evaluated
/// ```
pub const fn from_raw(kind: RawSyntaxKind) -> Self {
let RawSyntaxKind(kind) = kind;
let index = kind as usize / u128::BITS as usize;
let shift = kind % u128::BITS as u16;
let mask = 1 << shift;
let mut bits = [0; 4];
bits[index] = mask;
Self(bits, PhantomData)
}
/// Returns the union of the two sets `self` and `other`
pub const fn union(self, other: Self) -> Self {
Self(
[
self.0[0] | other.0[0],
self.0[1] | other.0[1],
self.0[2] | other.0[2],
self.0[3] | other.0[3],
],
PhantomData,
)
}
/// Returns true if `kind` is contained in this set
pub fn matches(self, kind: L::Kind) -> bool {
let RawSyntaxKind(kind) = kind.to_raw();
let index = kind as usize / u128::BITS as usize;
let shift = kind % u128::BITS as u16;
let mask = 1 << shift;
self.0[index] & mask != 0
}
/// Returns an iterator over all the [SyntaxKind] contained in this set
pub fn iter(self) -> impl Iterator<Item = L::Kind> {
self.0.into_iter().enumerate().flat_map(|(index, item)| {
let index = index as u16 * u128::BITS as u16;
(0..u128::BITS).filter_map(move |bit| {
if (item & (1 << bit)) != 0 {
let raw = index + bit as u16;
let raw = RawSyntaxKind(raw);
Some(<L::Kind as SyntaxKind>::from_raw(raw))
} else {
None
}
})
})
}
}
/// The main trait to go from untyped `SyntaxNode` to a typed ast. The
/// conversion itself has zero runtime cost: ast and syntax nodes have exactly
/// the same representation: a pointer to the tree root and a pointer to the
/// node itself.
pub trait AstNode: Clone {
type Language: Language;
const KIND_SET: SyntaxKindSet<Self::Language>;
/// Returns `true` if a node with the given kind can be cased to this AST node.
fn can_cast(kind: <Self::Language as Language>::Kind) -> bool;
/// Tries to cast the passed syntax node to this AST node.
///
/// # Returns
///
/// [None] if the passed node is of a different kind. [Some] otherwise.
fn cast(syntax: SyntaxNode<Self::Language>) -> Option<Self>
where
Self: Sized;
/// Takes a reference of a syntax node and tries to cast it to this AST node.
///
/// Only creates a clone of the syntax node if casting the node is possible.
fn cast_ref(syntax: &SyntaxNode<Self::Language>) -> Option<Self>
where
Self: Sized,
{
if Self::can_cast(syntax.kind()) {
Self::cast(syntax.clone())
} else {
None
}
}
/// Tries to cast the passed syntax node to this AST node.
///
/// # Returns
/// * [Ok] if the passed node can be cast into this [AstNode]
/// * [Err(syntax)](Err) If the node is of another kind.
///
/// # Examples
///
/// ```
/// # use rome_rowan::AstNode;
/// # use rome_rowan::raw_language::{LiteralExpression, RawLanguageKind, RawLanguageRoot, RawSyntaxTreeBuilder};
///
/// let mut builder = RawSyntaxTreeBuilder::new();
///
/// builder.start_node(RawLanguageKind::ROOT);
/// builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
/// builder.token(RawLanguageKind::STRING_TOKEN, "'abcd'");
/// builder.finish_node();
/// builder.finish_node();
///
/// let root_syntax = builder.finish();
/// let root = RawLanguageRoot::cast(root_syntax.clone()).expect("Root to be a raw language root");
///
/// // Returns `OK` because syntax is a `RawLanguageRoot`
/// assert_eq!(RawLanguageRoot::try_cast(root.syntax().clone()), Ok(root.clone()));
/// // Returns `Err` with the syntax node passed to `try_cast` because `root` isn't a `LiteralExpression`
/// assert_eq!(LiteralExpression::try_cast(root.syntax().clone()), Err(root_syntax));
/// ```
fn try_cast(syntax: SyntaxNode<Self::Language>) -> Result<Self, SyntaxNode<Self::Language>> {
if Self::can_cast(syntax.kind()) {
Ok(Self::cast(syntax).expect("Expected casted node because 'can_cast' returned true."))
} else {
Err(syntax)
}
}
/// Tries to cast the AST `node` into this node.
///
/// # Returns
/// * [Ok] if the passed node can be cast into this [AstNode]
/// * [Err] if the node is of another kind
/// ```
/// # use rome_rowan::AstNode;
/// # use rome_rowan::raw_language::{LiteralExpression, RawLanguageKind, RawLanguageRoot, RawSyntaxTreeBuilder};
///
/// let mut builder = RawSyntaxTreeBuilder::new();
///
/// builder.start_node(RawLanguageKind::ROOT);
/// builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
/// builder.token(RawLanguageKind::STRING_TOKEN, "'abcd'");
/// builder.finish_node();
/// builder.finish_node();
///
/// let root_syntax = builder.finish();
/// let root = RawLanguageRoot::cast(root_syntax.clone()).expect("Root to be a raw language root");
///
/// // Returns `OK` because syntax is a `RawLanguageRoot`
/// assert_eq!(RawLanguageRoot::try_cast_node(root.clone()), Ok(root.clone()));
///
/// // Returns `Err` with the node passed to `try_cast_node` because `root` isn't a `LiteralExpression`
/// assert_eq!(LiteralExpression::try_cast_node(root.clone()), Err(root.clone()));
/// ```
fn try_cast_node<T: AstNode<Language = Self::Language>>(node: T) -> Result<Self, T> {
if Self::can_cast(node.syntax().kind()) {
Ok(Self::cast(node.into_syntax())
.expect("Expected casted node because 'can_cast' returned true."))
} else {
Err(node)
}
}
/// Returns the underlying syntax node.
fn syntax(&self) -> &SyntaxNode<Self::Language>;
/// Returns the underlying syntax node.
fn into_syntax(self) -> SyntaxNode<Self::Language>;
/// Cast this node to this AST node
///
/// # Panics
/// Panics if the underlying node cannot be cast to this AST node
fn unwrap_cast(syntax: SyntaxNode<Self::Language>) -> Self
where
Self: Sized,
{
let kind = syntax.kind();
Self::cast(syntax).unwrap_or_else(|| {
panic!(
"Tried to cast node with kind {:?} as `{:?}` but was unable to cast",
kind,
std::any::type_name::<Self>()
)
})
}
/// Returns the string representation of this node without the leading and trailing trivia
fn text(&self) -> std::string::String {
self.syntax().text_trimmed().to_string()
}
fn range(&self) -> TextRange {
self.syntax().text_trimmed_range()
}
fn clone_subtree(&self) -> Self
where
Self: Sized,
{
Self::cast(self.syntax().clone_subtree()).unwrap()
}
fn parent<T: AstNode<Language = Self::Language>>(&self) -> Option<T> {
self.syntax().parent().and_then(T::cast)
}
/// Return a new version of this node with the leading trivia of its first token replaced with `trivia`.
fn with_leading_trivia_pieces<I>(self, trivia: I) -> Option<Self>
where
I: IntoIterator<Item = SyntaxTriviaPiece<Self::Language>>,
I::IntoIter: ExactSizeIterator,
{
Self::cast(self.into_syntax().with_leading_trivia_pieces(trivia)?)
}
/// Return a new version of this node with the trailing trivia of its last token replaced with `trivia`.
fn with_trailing_trivia_pieces<I>(self, trivia: I) -> Option<Self>
where
I: IntoIterator<Item = SyntaxTriviaPiece<Self::Language>>,
I::IntoIter: ExactSizeIterator,
{
Self::cast(self.into_syntax().with_trailing_trivia_pieces(trivia)?)
}
// Return a new version of this node with `trivia` prepended to the leading trivia of the first token.
fn prepend_trivia_pieces<I>(self, trivia: I) -> Option<Self>
where
I: IntoIterator<Item = SyntaxTriviaPiece<Self::Language>>,
I::IntoIter: ExactSizeIterator,
{
Self::cast(self.into_syntax().prepend_trivia_pieces(trivia)?)
}
// Return a new version of this node with `trivia` appended to the trailing trivia of the last token.
fn append_trivia_pieces<I>(self, trivia: I) -> Option<Self>
where
I: IntoIterator<Item = SyntaxTriviaPiece<Self::Language>>,
I::IntoIter: ExactSizeIterator,
{
Self::cast(self.into_syntax().append_trivia_pieces(trivia)?)
}
/// Return a new version of this node without leading and trailing newlines and whitespaces.
fn trim(self) -> Option<Self> {
Self::cast(
self.into_syntax()
.trim_leading_trivia()?
.trim_trailing_trivia()?,
)
}
/// Return a new version of this node without leading newlines and whitespaces.
fn trim_start(self) -> Option<Self> {
Self::cast(self.into_syntax().trim_leading_trivia()?)
}
/// Return a new version of this node without trailing newlines and whitespaces.
fn trim_end(self) -> Option<Self> {
Self::cast(self.into_syntax().trim_trailing_trivia()?)
}
}
pub trait SyntaxNodeCast<L: Language> {
/// Tries to cast the current syntax node to specified AST node.
///
/// # Returns
///
/// [None] if the current node is of a different kind. [Some] otherwise.
fn cast<T: AstNode<Language = L>>(self) -> Option<T>;
}
impl<L: Language> SyntaxNodeCast<L> for SyntaxNode<L> {
fn cast<T: AstNode<Language = L>>(self) -> Option<T> {
T::cast(self)
}
}
/// List of homogenous nodes
pub trait AstNodeList {
type Language: Language;
type Node: AstNode<Language = Self::Language>;
/// Returns the underlying syntax list
fn syntax_list(&self) -> &SyntaxList<Self::Language>;
/// Returns the underlying syntax list
fn into_syntax_list(self) -> SyntaxList<Self::Language>;
fn iter(&self) -> AstNodeListIterator<Self::Language, Self::Node> {
AstNodeListIterator {
inner: self.syntax_list().iter(),
ph: PhantomData,
}
}
#[inline]
fn len(&self) -> usize {
self.syntax_list().len()
}
/// Returns the first node from this list or None
#[inline]
fn first(&self) -> Option<Self::Node> {
self.iter().next()
}
/// Returns the last node from this list or None
fn last(&self) -> Option<Self::Node> {
self.iter().last()
}
#[inline]
fn is_empty(&self) -> bool {
self.syntax_list().is_empty()
}
}
#[derive(Debug, Clone)]
pub struct AstNodeListIterator<L, N>
where
L: Language,
{
inner: SyntaxSlots<L>,
ph: PhantomData<N>,
}
impl<L: Language, N: AstNode<Language = L>> AstNodeListIterator<L, N> {
fn slot_to_node(slot: &SyntaxSlot<L>) -> N {
match slot {
SyntaxSlot::Empty => panic!("Node isn't permitted to contain empty slots"),
SyntaxSlot::Node(node) => N::unwrap_cast(node.to_owned()),
SyntaxSlot::Token(token) => panic!(
"Expected node of type `{:?}` but found token `{:?}` instead.",
std::any::type_name::<N>(),
token
),
}
}
}
impl<L: Language, N: AstNode<Language = L>> Iterator for AstNodeListIterator<L, N> {
type Item = N;
fn next(&mut self) -> Option<Self::Item> {
Some(Self::slot_to_node(&self.inner.next()?))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
fn last(self) -> Option<Self::Item>
where
Self: Sized,
{
Some(Self::slot_to_node(&self.inner.last()?))
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
Some(Self::slot_to_node(&self.inner.nth(n)?))
}
}
impl<L: Language, N: AstNode<Language = L>> ExactSizeIterator for AstNodeListIterator<L, N> {}
impl<L: Language, N: AstNode<Language = L>> FusedIterator for AstNodeListIterator<L, N> {}
impl<L: Language, N: AstNode<Language = L>> DoubleEndedIterator for AstNodeListIterator<L, N> {
fn next_back(&mut self) -> Option<Self::Item> {
Some(Self::slot_to_node(&self.inner.next_back()?))
}
}
#[derive(Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct AstSeparatedElement<L: Language, N> {
pub node: SyntaxResult<N>,
pub trailing_separator: SyntaxResult<Option<SyntaxToken<L>>>,
}
impl<L: Language, N: AstNode<Language = L>> AstSeparatedElement<L, N> {
pub fn node(&self) -> SyntaxResult<&N> {
match &self.node {
Ok(node) => Ok(node),
Err(err) => Err(*err),
}
}
pub fn into_node(self) -> SyntaxResult<N> {
self.node
}
pub fn trailing_separator(&self) -> SyntaxResult<Option<&SyntaxToken<L>>> {
match &self.trailing_separator {
Ok(Some(sep)) => Ok(Some(sep)),
Ok(_) => Ok(None),
Err(err) => Err(*err),
}
}
pub fn into_trailing_separator(self) -> SyntaxResult<Option<SyntaxToken<L>>> {
self.trailing_separator
}
}
impl<L: Language, N: Debug> Debug for AstSeparatedElement<L, N> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match &self.node {
Ok(node) => N::fmt(node, f)?,
Err(_) => f.write_str("missing element")?,
};
match &self.trailing_separator {
Ok(Some(separator)) => {
f.write_str(",\n")?;
Debug::fmt(&separator, f)
}
Err(_) => f.write_str(",\nmissing separator"),
Ok(None) => Ok(()),
}
}
}
/// List of nodes where every two nodes are separated by a token.
/// For example, the elements of an array where every two elements are separated by a comma token.
/// The list expects that the underlying syntax node has a slot for every node and separator
/// even if they are missing from the source code. For example, a list for `a b` where the `,` separator
/// is missing contains the slots `Node(a), Empty, Node(b)`. This also applies for missing nodes:
/// the list for `, b,` must have the slots `Empty, Token(,), Node(b), Token(,)`.
pub trait AstSeparatedList {
type Language: Language;
type Node: AstNode<Language = Self::Language>;
/// Returns the underlying syntax list
fn syntax_list(&self) -> &SyntaxList<Self::Language>;
/// Returns the underlying syntax list
fn into_syntax_list(self) -> SyntaxList<Self::Language>;
/// Returns an iterator over all nodes with their trailing separator
fn elements(&self) -> AstSeparatedListElementsIterator<Self::Language, Self::Node> {
AstSeparatedListElementsIterator::new(self.syntax_list())
}
/// Returns an iterator over all separator tokens
fn separators(&self) -> AstSeparatorIterator<Self::Language, Self::Node> {
AstSeparatorIterator {
inner: self.elements(),
}
}
/// Returns an iterator over all nodes
fn iter(&self) -> AstSeparatedListNodesIterator<Self::Language, Self::Node> {
AstSeparatedListNodesIterator {
inner: self.elements(),
}
}
/// Returns the first node
fn first(&self) -> Option<SyntaxResult<Self::Node>> {
self.iter().next()
}
/// Returns the last node
fn last(&self) -> Option<SyntaxResult<Self::Node>> {
self.iter().next_back()
}
#[inline]
fn is_empty(&self) -> bool {
self.len() == 0
}
fn len(&self) -> usize {
(self.syntax_list().len() + 1) / 2
}
fn trailing_separator(&self) -> Option<SyntaxToken<Self::Language>> {
match self.syntax_list().last()? {
SyntaxSlot::Token(token) => Some(token),
_ => None,
}
}
}
pub struct AstSeparatorIterator<L: Language, N> {
inner: AstSeparatedListElementsIterator<L, N>,
}
impl<L, N> Iterator for AstSeparatorIterator<L, N>
where
L: Language,
N: AstNode<Language = L>,
{
type Item = SyntaxResult<SyntaxToken<L>>;
fn next(&mut self) -> Option<Self::Item> {
loop {
let element = self.inner.next()?;
match element.trailing_separator {
Ok(Some(separator)) => return Some(Ok(separator)),
Err(missing) => return Some(Err(missing)),
_ => {}
}
}
}
}
impl<L, N> DoubleEndedIterator for AstSeparatorIterator<L, N>
where
L: Language,
N: AstNode<Language = L>,
{
fn next_back(&mut self) -> Option<Self::Item> {
loop {
let element = self.inner.next_back()?;
match element.trailing_separator {
Ok(Some(separator)) => return Some(Ok(separator)),
Err(missing) => return Some(Err(missing)),
_ => {}
}
}
}
}
#[derive(Debug, Clone)]
pub struct AstSeparatedListElementsIterator<L: Language, N> {
slots: SyntaxSlots<L>,
ph: PhantomData<N>,
}
impl<L: Language, N: AstNode<Language = L>> AstSeparatedListElementsIterator<L, N> {
fn new(list: &SyntaxList<L>) -> Self {
Self {
slots: list.iter(),
ph: PhantomData,
}
}
}
impl<L: Language, N: AstNode<Language = L>> Iterator for AstSeparatedListElementsIterator<L, N> {
type Item = AstSeparatedElement<L, N>;
fn next(&mut self) -> Option<Self::Item> {
let slot = self.slots.next()?;
let node = match slot {
// The node for this element is missing if the next child is a token instead of a node.
SyntaxSlot::Token(token) => panic!("Malformed list, node expected but found token {:?} instead. You must add missing markers for missing elements.", token),
// Missing element
SyntaxSlot::Empty => Err(SyntaxError::MissingRequiredChild),
SyntaxSlot::Node(node) => Ok(N::unwrap_cast(node))
};
let separator = match self.slots.next() {
Some(SyntaxSlot::Empty) => Err(
SyntaxError::MissingRequiredChild,
),
Some(SyntaxSlot::Token(token)) => Ok(Some(token)),
// End of list, no trailing separator
None => Ok(None),
Some(SyntaxSlot::Node(node)) => panic!("Malformed separated list, separator expected but found node {:?} instead. You must add missing markers for missing separators.", node),
};
Some(AstSeparatedElement {
node,
trailing_separator: separator,
})
}
}
impl<L: Language, N: AstNode<Language = L>> FusedIterator
for AstSeparatedListElementsIterator<L, N>
{
}
impl<L: Language, N: AstNode<Language = L>> DoubleEndedIterator
for AstSeparatedListElementsIterator<L, N>
{
fn next_back(&mut self) -> Option<Self::Item> {
let first_slot = self.slots.next_back()?;
let separator = match first_slot {
SyntaxSlot::Node(node) => {
// if we fallback here, it means that we are at the end of the iterator
// which means that we don't have the optional separator and
// we have only a node, we bail early.
return Some(AstSeparatedElement {
node: Ok(N::unwrap_cast(node)),
trailing_separator: Ok(None),
});
}
SyntaxSlot::Token(token) => Ok(Some(token)),
SyntaxSlot::Empty => Ok(None),
};
let node = match self.slots.next_back() {
None => panic!("Malformed separated list, expected a node but found none"),
Some(SyntaxSlot::Empty) => Err(SyntaxError::MissingRequiredChild),
Some(SyntaxSlot::Token(token)) => panic!("Malformed list, node expected but found token {:?} instead. You must add missing markers for missing elements.", token),
Some(SyntaxSlot::Node(node)) => {
Ok(N::unwrap_cast(node))
}
};
Some(AstSeparatedElement {
node,
trailing_separator: separator,
})
}
}
#[derive(Debug, Clone)]
pub struct AstSeparatedListNodesIterator<L: Language, N> {
inner: AstSeparatedListElementsIterator<L, N>,
}
impl<L: Language, N: AstNode<Language = L>> Iterator for AstSeparatedListNodesIterator<L, N> {
type Item = SyntaxResult<N>;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|element| element.node)
}
}
impl<L: Language, N: AstNode<Language = L>> FusedIterator for AstSeparatedListNodesIterator<L, N> {}
impl<L: Language, N: AstNode<Language = L>> DoubleEndedIterator
for AstSeparatedListNodesIterator<L, N>
{
fn next_back(&mut self) -> Option<Self::Item> {
self.inner.next_back().map(|element| element.node)
}
}
/// Specific result used when navigating nodes using AST APIs
pub type SyntaxResult<ResultType> = Result<ResultType, SyntaxError>;
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub enum SyntaxError {
/// Error thrown when a mandatory node is not found
MissingRequiredChild,
}
impl Display for SyntaxError {
fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
match self {
SyntaxError::MissingRequiredChild => fmt.write_str("missing required child"),
}
}
}
impl Error for SyntaxError {}
pub mod support {
use super::{AstNode, SyntaxNode, SyntaxToken};
use super::{Language, SyntaxError, SyntaxResult};
use crate::syntax::SyntaxSlot;
use crate::SyntaxElementChildren;
use std::fmt::{Debug, Formatter};
pub fn node<L: Language, N: AstNode<Language = L>>(
parent: &SyntaxNode<L>,
slot_index: usize,
) -> Option<N> {
match parent.slots().nth(slot_index)? {
SyntaxSlot::Empty => None,
SyntaxSlot::Node(node) => Some(N::unwrap_cast(node)),
SyntaxSlot::Token(token) => panic!(
"expected a node in the slot {} but found token {:?}",
slot_index, token
),
}
}
pub fn required_node<L: Language, N: AstNode<Language = L>>(
parent: &SyntaxNode<L>,
slot_index: usize,
) -> SyntaxResult<N> {
self::node(parent, slot_index).ok_or(SyntaxError::MissingRequiredChild)
}
pub fn elements<L: Language>(parent: &SyntaxNode<L>) -> SyntaxElementChildren<L> {
parent.children_with_tokens()
}
pub fn list<L: Language, N: AstNode<Language = L>>(
parent: &SyntaxNode<L>,
slot_index: usize,
) -> N {
required_node(parent, slot_index)
.unwrap_or_else(|_| panic!("expected a list in slot {}", slot_index))
}
pub fn token<L: Language>(parent: &SyntaxNode<L>, slot_index: usize) -> Option<SyntaxToken<L>> {
match parent.slots().nth(slot_index)? {
SyntaxSlot::Empty => None,
SyntaxSlot::Token(token) => Some(token),
SyntaxSlot::Node(node) => panic!(
"expected a token in the slot {} but found node {:?}",
slot_index, node
),
}
}
pub fn required_token<L: Language>(
parent: &SyntaxNode<L>,
slot_index: usize,
) -> SyntaxResult<SyntaxToken<L>> {
token(parent, slot_index).ok_or(SyntaxError::MissingRequiredChild)
}
/// New-type wrapper to flatten the debug output of syntax result fields when printing [AstNode]s.
/// Omits the [Ok] if the node is present and prints `missing (required)` if the child is missing
pub struct DebugSyntaxResult<N>(pub SyntaxResult<N>);
impl<N: Debug> Debug for DebugSyntaxResult<N> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match &self.0 {
Ok(node) => std::fmt::Debug::fmt(node, f),
Err(SyntaxError::MissingRequiredChild) => f.write_str("missing (required)"),
}
}
}
/// New-type wrapper to flatten the debug output of optional children when printing [AstNode]s.
/// Omits the [Some] if the node is present and prints `missing (optional)` if the child is missing
pub struct DebugOptionalElement<N>(pub Option<N>);
impl<N: Debug> Debug for DebugOptionalElement<N> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match &self.0 {
Some(node) => std::fmt::Debug::fmt(node, f),
None => f.write_str("missing (optional)"),
}
}
}
}
#[cfg(test)]
mod tests {
use crate::raw_language::{
LiteralExpression, RawLanguage, RawLanguageKind, RawSyntaxTreeBuilder,
SeparatedExpressionList,
};
use crate::{AstNode, AstSeparatedElement, AstSeparatedList, SyntaxResult};
/// Creates a ast separated list over a sequence of numbers separated by ",".
/// The elements are pairs of: (value, separator).
fn build_list<'a>(
elements: impl IntoIterator<Item = (Option<i32>, Option<&'a str>)>,
) -> SeparatedExpressionList {
let mut builder = RawSyntaxTreeBuilder::new();
builder.start_node(RawLanguageKind::SEPARATED_EXPRESSION_LIST);
for (node, separator) in elements.into_iter() {
if let Some(node) = node {
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::NUMBER_TOKEN, node.to_string().as_str());
builder.finish_node();
}
if let Some(separator) = separator {
builder.token(RawLanguageKind::COMMA_TOKEN, separator);
}
}
builder.finish_node();
let node = builder.finish();
SeparatedExpressionList::new(node.into_list())
}
type MappedElement = Vec<(Option<f64>, Option<String>)>;
fn map_elements<'a>(
actual: impl Iterator<Item = AstSeparatedElement<RawLanguage, LiteralExpression>>
+ DoubleEndedIterator,
expected: impl IntoIterator<Item = (Option<f64>, Option<&'a str>)>,
revert: bool,
) -> (MappedElement, MappedElement) {
let actual: Vec<_> = if revert {
actual.rev().collect()
} else {
actual.collect()
};
let actual = actual
.into_iter()
.map(|element| {
(
element.node.ok().map(|n| n.text().parse::<f64>().unwrap()),
element
.trailing_separator
.ok()
.flatten()
.map(|separator| separator.text().to_string()),
)
})
.collect::<Vec<_>>();
let expected = expected
.into_iter()
.map(|(value, separator)| (value, separator.map(|sep| sep.to_string())))
.collect::<Vec<_>>();
(actual, expected)
}
fn assert_elements<'a>(
actual: impl Iterator<Item = AstSeparatedElement<RawLanguage, LiteralExpression>>
+ DoubleEndedIterator,
expected: impl IntoIterator<Item = (Option<f64>, Option<&'a str>)>,
) {
let (actual, expected) = map_elements(actual, expected, false);
assert_eq!(actual, expected);
}
fn assert_rev_elements<'a>(
actual: impl Iterator<Item = AstSeparatedElement<RawLanguage, LiteralExpression>>
+ DoubleEndedIterator,
expected: impl IntoIterator<Item = (Option<f64>, Option<&'a str>)>,
) {
let (actual, expected) = map_elements(actual, expected, true);
assert_eq!(actual, expected);
}
fn assert_nodes(
actual: impl Iterator<Item = SyntaxResult<LiteralExpression>>,
expected: impl IntoIterator<Item = f64>,
) {
assert_eq!(
actual
.map(|literal| literal.unwrap().text().parse::<f64>().unwrap())
.collect::<Vec<_>>(),
expected.into_iter().collect::<Vec<_>>()
);
}
#[test]
fn empty() {
let list = build_list(vec![]);
assert_eq!(list.len(), 0);
assert!(list.is_empty());
assert_eq!(list.separators().count(), 0);
assert_nodes(list.iter(), vec![]);
assert_elements(list.elements(), vec![]);
assert_rev_elements(list.elements(), vec![]);
assert_eq!(list.trailing_separator(), None);
}
#[test]
fn separated_list() {
let list = build_list(vec![
(Some(1), Some(",")),
(Some(2), Some(",")),
(Some(3), Some(",")),
(Some(4), None),
]);
assert_eq!(list.len(), 4);
assert!(!list.is_empty());
assert_eq!(list.separators().count(), 3);
assert_nodes(list.iter(), vec![1., 2., 3., 4.]);
assert_elements(
list.elements(),
vec![
(Some(1.), Some(",")),
(Some(2.), Some(",")),
(Some(3.), Some(",")),
(Some(4.), None),
],
);
assert_rev_elements(
list.elements(),
vec![
(Some(4.), None),
(Some(3.), Some(",")),
(Some(2.), Some(",")),
(Some(1.), Some(",")),
],
);
assert_eq!(list.trailing_separator(), None);
}
#[test]
fn double_iterator_meet_at_middle() {
let list = build_list(vec![
(Some(1), Some(",")),
(Some(2), Some(",")),
(Some(3), Some(",")),
(Some(4), None),
]);
let mut iter = list.elements();
let element = iter.next().unwrap();
assert_eq!(element.node().unwrap().text(), "1");
let element = iter.next_back().unwrap();
assert_eq!(element.node().unwrap().text(), "4");
let element = iter.next().unwrap();
assert_eq!(element.node().unwrap().text(), "2");
let element = iter.next_back().unwrap();
assert_eq!(element.node().unwrap().text(), "3");
assert!(iter.next().is_none());
assert!(iter.next_back().is_none());
}
#[test]
fn separated_with_trailing() {
// list(1, 2, 3, 4,)
let list = build_list(vec![
(Some(1), Some(",")),
(Some(2), Some(",")),
(Some(3), Some(",")),
(Some(4), Some(",")),
]);
assert_eq!(list.len(), 4);
assert!(!list.is_empty());
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/green/node_cache.rs | crates/rome_rowan/src/green/node_cache.rs | use hashbrown::hash_map::{RawEntryMut, RawOccupiedEntryMut, RawVacantEntryMut};
use rome_text_size::TextSize;
use rustc_hash::FxHasher;
use std::fmt::{self, Debug, Formatter};
use std::hash::{BuildHasherDefault, Hash, Hasher};
use std::marker::PhantomData;
use std::ops::Not;
use std::ptr::NonNull;
use crate::green::Slot;
use crate::syntax::{TriviaPiece, TriviaPieceKind};
use crate::{
green::GreenElementRef, GreenNode, GreenNodeData, GreenToken, GreenTokenData, NodeOrToken,
RawSyntaxKind,
};
use super::element::GreenElement;
use super::trivia::{GreenTrivia, GreenTriviaData};
type HashMap<K, V> = hashbrown::HashMap<K, V, BuildHasherDefault<FxHasher>>;
/// Internal representation for a green pointer and a generation index in the
/// cache, packed into a single `usize`. This relies on the fact that "green
/// elements" (tokens, nodes and trivia) have memory alignment constraints that
/// exceed a single byte (and thus the lower bits of the pointer will always be
/// zero), while the generation index only needs a single bit of storage.
struct GenerationalPointer<T: IntoRawPointer> {
data: usize,
_ty: PhantomData<T>,
}
impl<T: IntoRawPointer> GenerationalPointer<T> {
fn new(value: T, generation: Generation) -> Self {
let ptr = value.into_raw();
let mut data = ptr as usize;
debug_assert!(data & 1 == 0);
data |= generation as usize;
Self {
data,
_ty: PhantomData,
}
}
fn value(&self) -> &T::Pointee {
// SAFETY: This clears the least significant bit from `data`. This bit
// should have been set to zero in the original pointer due to the
// alignment requirements of the underlying data (this is checked by an
// assertion on debug builds), so this essentially extracts the pointer
// value from the bit field. Said point is safe to dereference at this
// point since we're holding a valid reference to `self` which
// guarantees `Drop` has not been called and the memory associated with
// the pointer has not been released yet.
let data = self.data & !1;
let ptr = data as *const T::Pointee;
unsafe { &*ptr }
}
fn generation(&self) -> Generation {
match self.data & 1 {
0 => Generation::A,
1 => Generation::B,
// SAFETY: The `& 1` operation above ensures only the least
// significant bit can be set
_ => unreachable!(),
}
}
fn set_generation(&mut self, generation: Generation) {
let data = self.data & !1;
self.data = data | generation as usize;
}
}
impl<T: IntoRawPointer> Debug for GenerationalPointer<T>
where
T::Pointee: Debug,
{
fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
fmt.debug_struct("GenerationalPointer")
.field("value", self.value())
.field("generation", &self.generation())
.finish()
}
}
impl<T: IntoRawPointer> Drop for GenerationalPointer<T> {
fn drop(&mut self) {
let ptr = self.value() as *const _ as *mut _;
let value = unsafe { T::from_raw(ptr) };
drop(value);
}
}
/// Trait implemented for types that can be turned into a raw pointer, and
/// reconstructed back from it. Used by [GenerationalPointer] internally.
trait IntoRawPointer {
type Pointee;
fn into_raw(self) -> *mut Self::Pointee;
unsafe fn from_raw(ptr: *mut Self::Pointee) -> Self;
}
/// A token stored in the `NodeCache`.
/// Does intentionally not implement `Hash` to have compile-time guarantees that the `NodeCache`
/// uses the correct hash.
#[derive(Debug)]
struct CachedToken(GenerationalPointer<GreenToken>);
impl IntoRawPointer for GreenToken {
type Pointee = GreenTokenData;
fn into_raw(self) -> *mut Self::Pointee {
GreenToken::into_raw(self).as_ptr()
}
unsafe fn from_raw(ptr: *mut Self::Pointee) -> Self {
GreenToken::from_raw(NonNull::new(ptr).unwrap())
}
}
/// A node stored in the `NodeCache`. It stores a pre-computed hash
/// because re-computing the hash requires traversing the whole sub-tree.
/// The hash also differs from the `GreenNode` hash implementation as it
/// only hashes occupied slots and excludes empty slots.
///
/// Does intentionally not implement `Hash` to have compile-time guarantees that the `NodeCache`
/// uses the correct hash.
#[derive(Debug)]
struct CachedNode {
node: GenerationalPointer<GreenNode>,
// Store the hash as it's expensive to re-compute
// involves re-computing the hash of the whole sub-tree
hash: u64,
}
impl IntoRawPointer for GreenNode {
type Pointee = GreenNodeData;
fn into_raw(self) -> *mut Self::Pointee {
GreenNode::into_raw(self).as_ptr()
}
unsafe fn from_raw(ptr: *mut Self::Pointee) -> Self {
GreenNode::from_raw(NonNull::new(ptr).unwrap())
}
}
/// Interner for GreenTokens and GreenNodes
// XXX: the impl is a bit tricky. As usual when writing interners, we want to
// store all values in one HashSet.
//
// However, hashing trees is fun: hash of the tree is recursively defined. We
// maintain an invariant -- if the tree is interned, then all of its children
// are interned as well.
//
// That means that computing the hash naively is wasteful -- we just *know*
// hashes of children, and we can re-use those.
//
// So here we use *raw* API of hashbrown and provide the hashes manually,
// instead of going via a `Hash` impl. Our manual `Hash` and the
// `#[derive(Hash)]` are actually different! At some point we had a fun bug,
// where we accidentally mixed the two hashes, which made the cache much less
// efficient.
//
// To fix that, we additionally wrap the data in `Cached*` wrappers, to make sure
// we don't accidentally use the wrong hash!
#[derive(Default, Debug)]
pub struct NodeCache {
nodes: HashMap<CachedNode, ()>,
tokens: HashMap<CachedToken, ()>,
trivia: TriviaCache,
generation: Generation,
}
/// Represents a "generation" in the garbage collection scheme of the node
/// cache. For our purpose we only need to track two generations at most (the
/// previous and next generation) so this is represented as an enum with two
/// variants.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
enum Generation {
#[default]
A = 0,
B = 1,
}
impl Not for Generation {
type Output = Self;
fn not(self) -> Self::Output {
match self {
Generation::A => Generation::B,
Generation::B => Generation::A,
}
}
}
fn token_hash_of(kind: RawSyntaxKind, text: &str) -> u64 {
let mut h = FxHasher::default();
kind.hash(&mut h);
text.hash(&mut h);
h.finish()
}
fn token_hash(token: &GreenTokenData) -> u64 {
token_hash_of(token.kind(), token.text())
}
fn element_id(elem: GreenElementRef<'_>) -> *const () {
match elem {
NodeOrToken::Node(it) => it as *const GreenNodeData as *const (),
NodeOrToken::Token(it) => it as *const GreenTokenData as *const (),
}
}
impl NodeCache {
/// Hash used for nodes that haven't been cached because it has too many slots or
/// one of its children wasn't cached.
const UNCACHED_NODE_HASH: u64 = 0;
/// Tries to retrieve a node with the given `kind` and `children` from the cache.
///
/// Returns an entry that allows the caller to:
/// * Retrieve the cached node if it is present in the cache
/// * Insert a node if it isn't present in the cache
pub(crate) fn node<'a>(
&'a mut self,
kind: RawSyntaxKind,
children: &[(u64, GreenElement)],
) -> NodeCacheNodeEntryMut<'a> {
if children.len() > 3 {
return NodeCacheNodeEntryMut::NoCache(Self::UNCACHED_NODE_HASH);
}
let hash = {
let mut h = FxHasher::default();
kind.hash(&mut h);
for &(hash, _) in children {
if hash == Self::UNCACHED_NODE_HASH {
return NodeCacheNodeEntryMut::NoCache(Self::UNCACHED_NODE_HASH);
}
hash.hash(&mut h);
}
h.finish()
};
// Green nodes are fully immutable, so it's ok to deduplicate them.
// This is the same optimization that Roslyn does
// https://github.com/KirillOsenkov/Bliki/wiki/Roslyn-Immutable-Trees
//
// For example, all `#[inline]` in this file share the same green node!
// For `libsyntax/parse/parser.rs`, measurements show that deduping saves
// 17% of the memory for green nodes!
let entry = self.nodes.raw_entry_mut().from_hash(hash, |no_hash| {
no_hash.node.value().kind() == kind && {
let lhs = no_hash.node.value().slots().filter_map(|slot| match slot {
// Ignore empty slots. The queried node only has the present children
Slot::Empty { .. } => None,
Slot::Node { node, .. } => Some(element_id(NodeOrToken::Node(node))),
Slot::Token { token, .. } => Some(element_id(NodeOrToken::Token(token))),
});
let rhs = children
.iter()
.map(|(_, element)| element_id(element.as_deref()));
lhs.eq(rhs)
}
});
match entry {
RawEntryMut::Occupied(mut entry) => {
entry.key_mut().node.set_generation(self.generation);
NodeCacheNodeEntryMut::Cached(CachedNodeEntry {
hash,
raw_entry: entry,
})
}
RawEntryMut::Vacant(entry) => NodeCacheNodeEntryMut::Vacant(VacantNodeEntry {
raw_entry: entry,
original_kind: kind,
hash,
generation: self.generation,
}),
}
}
pub(crate) fn token(&mut self, kind: RawSyntaxKind, text: &str) -> (u64, GreenToken) {
self.token_with_trivia(kind, text, &[], &[])
}
pub(crate) fn token_with_trivia(
&mut self,
kind: RawSyntaxKind,
text: &str,
leading: &[TriviaPiece],
trailing: &[TriviaPiece],
) -> (u64, GreenToken) {
let hash = token_hash_of(kind, text);
let entry = self.tokens.raw_entry_mut().from_hash(hash, |token| {
token.0.value().kind() == kind && token.0.value().text() == text
});
let token = match entry {
RawEntryMut::Occupied(mut entry) => {
entry.key_mut().0.set_generation(self.generation);
entry.key().0.value().to_owned()
}
RawEntryMut::Vacant(entry) => {
let leading = self.trivia.get(self.generation, leading);
let trailing = self.trivia.get(self.generation, trailing);
let token = GreenToken::with_trivia(kind, text, leading, trailing);
let key = CachedToken(GenerationalPointer::new(token.clone(), self.generation));
entry.insert_with_hasher(hash, key, (), |t| token_hash(t.0.value()));
token
}
};
(hash, token)
}
/// Increment the generation counter of the cache, all cache access from
/// this point onward will update the generation of the corresponding entry
/// to this new value
pub(crate) fn increment_generation(&mut self) {
debug_assert!(
self.nodes
.keys()
.all(|entry| entry.node.generation() == self.generation)
&& self
.tokens
.keys()
.all(|token| token.0.generation() == self.generation)
&& self
.trivia
.cache
.keys()
.all(|trivia| trivia.0.generation() == self.generation)
);
self.generation = !self.generation;
}
/// Removes nodes, tokens and trivia entries from the cache when their
/// generation doesn't match the current generation of the whole cache
pub(crate) fn sweep_cache(&mut self) {
self.nodes
.drain_filter(|node, _| node.node.generation() != self.generation);
self.tokens
.drain_filter(|token, _| token.0.generation() != self.generation);
self.trivia
.cache
.drain_filter(|trivia, _| trivia.0.generation() != self.generation);
}
}
pub(crate) enum NodeCacheNodeEntryMut<'a> {
Cached(CachedNodeEntry<'a>),
/// A node that should not be cached
NoCache(u64),
Vacant(VacantNodeEntry<'a>),
}
/// Represents a vacant entry, a node that hasn't been cached yet.
/// The `insert` method allows to place a node inside of the vacant entry. The inserted node
/// may have a different representation (kind or children) than the originally queried node.
/// For example, a node may change its kind to bogus or add empty slots. The only importance is
/// that these changes apply for all nodes that have the same shape as the originally queried node.
pub(crate) struct VacantNodeEntry<'a> {
hash: u64,
original_kind: RawSyntaxKind,
raw_entry: RawVacantEntryMut<'a, CachedNode, (), BuildHasherDefault<FxHasher>>,
generation: Generation,
}
/// Represents an entry of a cached node.
pub(crate) struct CachedNodeEntry<'a> {
hash: u64,
raw_entry: RawOccupiedEntryMut<'a, CachedNode, (), BuildHasherDefault<FxHasher>>,
}
impl<'a> CachedNodeEntry<'a> {
pub fn node(&self) -> &GreenNodeData {
self.raw_entry.key().node.value()
}
pub fn hash(&self) -> u64 {
self.hash
}
}
impl<'a> VacantNodeEntry<'a> {
/// Inserts the `node` into the cache so that future queries for the same kind and children resolve to the passed `node`.
///
/// Returns the hash of the node.
///
/// The cache does not cache the `node` if the kind doesn't match the `kind` of the queried node because
/// cache lookups wouldn't be successful because the hash collision prevention check compares the kinds of the
/// cached and queried node.
pub fn cache(self, node: GreenNode) -> u64 {
if self.original_kind != node.kind() {
// The kind has changed since it has been queried. For example, the node has been converted to an
// unknown node. Never cache these nodes because cache lookups will never match.
NodeCache::UNCACHED_NODE_HASH
} else {
self.raw_entry.insert_with_hasher(
self.hash,
CachedNode {
node: GenerationalPointer::new(node, self.generation),
hash: self.hash,
},
(),
|n| n.hash,
);
self.hash
}
}
}
/// A cached [GreenTrivia].
/// Deliberately doesn't implement `Hash` to make sure all
/// usages go through the custom `FxHasher`.
#[derive(Debug)]
struct CachedTrivia(GenerationalPointer<GreenTrivia>);
impl IntoRawPointer for GreenTrivia {
type Pointee = GreenTriviaData;
fn into_raw(self) -> *mut Self::Pointee {
GreenTrivia::into_raw(self)
}
unsafe fn from_raw(ptr: *mut Self::Pointee) -> Self {
GreenTrivia::from_raw(ptr)
}
}
#[derive(Debug)]
struct TriviaCache {
/// Generic cache for trivia
cache: HashMap<CachedTrivia, ()>,
/// Cached single whitespace trivia.
whitespace: GreenTrivia,
}
impl Default for TriviaCache {
fn default() -> Self {
Self {
cache: Default::default(),
whitespace: GreenTrivia::new([TriviaPiece::whitespace(1)]),
}
}
}
impl TriviaCache {
/// Tries to retrieve a [GreenTrivia] with the given pieces from the cache or creates a new one and caches
/// it for further calls.
fn get(&mut self, generation: Generation, pieces: &[TriviaPiece]) -> GreenTrivia {
match pieces {
[] => GreenTrivia::empty(),
[TriviaPiece {
kind: TriviaPieceKind::Whitespace,
length,
}] if *length == TextSize::from(1) => self.whitespace.clone(),
_ => {
let hash = Self::trivia_hash_of(pieces);
let entry = self
.cache
.raw_entry_mut()
.from_hash(hash, |trivia| trivia.0.value().pieces() == pieces);
match entry {
RawEntryMut::Occupied(mut entry) => {
entry.key_mut().0.set_generation(generation);
entry.key().0.value().to_owned()
}
RawEntryMut::Vacant(entry) => {
let trivia = GreenTrivia::new(pieces.iter().copied());
entry.insert_with_hasher(
hash,
CachedTrivia(GenerationalPointer::new(trivia.clone(), generation)),
(),
|cached| Self::trivia_hash_of(cached.0.value().pieces()),
);
trivia
}
}
}
}
}
fn trivia_hash_of(pieces: &[TriviaPiece]) -> u64 {
let mut h = FxHasher::default();
pieces.len().hash(&mut h);
for piece in pieces {
piece.hash(&mut h);
}
h.finish()
}
}
#[cfg(test)]
mod tests {
use std::mem::size_of;
use crate::green::node_cache::{token_hash, CachedNode, CachedToken, CachedTrivia};
use crate::green::trivia::GreenTrivia;
use crate::{GreenToken, RawSyntaxKind};
use rome_text_size::TextSize;
#[test]
fn green_token_hash() {
let kind = RawSyntaxKind(0);
let text = " let ";
let t1 = GreenToken::with_trivia(
kind,
text,
GreenTrivia::whitespace(TextSize::from(1)),
GreenTrivia::whitespace(TextSize::from(1)),
);
let t2 = GreenToken::with_trivia(
kind,
text,
GreenTrivia::whitespace(1),
GreenTrivia::whitespace(1),
);
assert_eq!(token_hash(&t1), token_hash(&t2));
let t3 = GreenToken::new(kind, "let");
assert_ne!(token_hash(&t1), token_hash(&t3));
let t4 = GreenToken::with_trivia(
kind,
"\tlet ",
GreenTrivia::whitespace(1),
GreenTrivia::whitespace(1),
);
assert_ne!(token_hash(&t1), token_hash(&t4));
}
#[test]
fn cache_entry_size() {
assert_eq!(size_of::<CachedNode>(), 16);
assert_eq!(size_of::<CachedToken>(), 8);
assert_eq!(size_of::<CachedTrivia>(), 8);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/green/node.rs | crates/rome_rowan/src/green/node.rs | use std::convert::TryFrom;
use std::fmt::Formatter;
use std::iter::Enumerate;
use std::{
borrow::{Borrow, Cow},
fmt,
iter::FusedIterator,
mem::{self, ManuallyDrop},
ops, ptr, slice,
};
#[cfg(target_pointer_width = "64")]
use crate::utility_types::static_assert;
use countme::Count;
use crate::{
arc::{Arc, HeaderSlice, ThinArc},
green::{GreenElement, GreenElementRef, RawSyntaxKind},
GreenToken, NodeOrToken, TextRange, TextSize,
};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(super) struct GreenNodeHead {
kind: RawSyntaxKind,
text_len: TextSize,
_c: Count<GreenNode>,
}
pub(crate) fn has_live() -> bool {
countme::get::<GreenNode>().live > 0
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum Slot {
Node {
rel_offset: TextSize,
node: GreenNode,
},
Token {
rel_offset: TextSize,
token: GreenToken,
},
/// An empty slot for a child that was missing in the source because:
/// * it's an optional child which is missing for this node
/// * it's a mandatory child but it's missing because of a syntax error
Empty { rel_offset: TextSize },
}
impl std::fmt::Display for Slot {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Slot::Empty { .. } => write!(f, "∅"),
Slot::Node { node, .. } => std::fmt::Display::fmt(node, f),
Slot::Token { token, .. } => std::fmt::Display::fmt(token, f),
}
}
}
#[cfg(target_pointer_width = "64")]
static_assert!(mem::size_of::<Slot>() == mem::size_of::<usize>() * 2);
type Repr = HeaderSlice<GreenNodeHead, [Slot]>;
type ReprThin = HeaderSlice<GreenNodeHead, [Slot; 0]>;
#[repr(transparent)]
pub(crate) struct GreenNodeData {
data: ReprThin,
}
impl PartialEq for GreenNodeData {
fn eq(&self, other: &Self) -> bool {
self.header() == other.header() && self.slice() == other.slice()
}
}
/// Internal node in the immutable tree.
/// It has other nodes and tokens as children.
#[derive(Clone, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub(crate) struct GreenNode {
ptr: ThinArc<GreenNodeHead, Slot>,
}
impl ToOwned for GreenNodeData {
type Owned = GreenNode;
#[inline]
fn to_owned(&self) -> GreenNode {
unsafe {
let green = GreenNode::from_raw(ptr::NonNull::from(self));
let green = ManuallyDrop::new(green);
GreenNode::clone(&green)
}
}
}
impl Borrow<GreenNodeData> for GreenNode {
#[inline]
fn borrow(&self) -> &GreenNodeData {
self
}
}
impl From<Cow<'_, GreenNodeData>> for GreenNode {
#[inline]
fn from(cow: Cow<'_, GreenNodeData>) -> Self {
cow.into_owned()
}
}
impl From<&'_ GreenNodeData> for GreenNode {
#[inline]
fn from(borrow: &'_ GreenNodeData) -> Self {
borrow.to_owned()
}
}
impl fmt::Debug for GreenNodeData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GreenNode")
.field("kind", &self.kind())
.field("text_len", &self.text_len())
.field("n_slots", &self.slots().len())
.finish()
}
}
impl fmt::Debug for GreenNode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let data: &GreenNodeData = self;
fmt::Debug::fmt(data, f)
}
}
impl fmt::Display for GreenNode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let data: &GreenNodeData = self;
fmt::Display::fmt(data, f)
}
}
impl fmt::Display for GreenNodeData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for child in self.slots() {
write!(f, "{}", child)?;
}
Ok(())
}
}
impl GreenNodeData {
#[inline]
fn header(&self) -> &GreenNodeHead {
&self.data.header
}
#[inline]
pub(crate) fn slice(&self) -> &[Slot] {
self.data.slice()
}
/// Kind of this node.
#[inline]
pub fn kind(&self) -> RawSyntaxKind {
self.header().kind
}
/// Returns the length of the text covered by this node.
#[inline]
pub fn text_len(&self) -> TextSize {
self.header().text_len
}
/// Children of this node.
#[inline]
pub fn children(&self) -> Children<'_> {
Children::new(self.slots().enumerate())
}
/// Returns the slots of this node. Every node of a specific kind has the same number of slots
/// to allow using fixed offsets to retrieve a specific child even if some other child is missing.
#[inline]
pub fn slots(&self) -> Slots<'_> {
Slots {
raw: self.slice().iter(),
}
}
pub(crate) fn slot_at_range(
&self,
rel_range: TextRange,
) -> Option<(usize, TextSize, &'_ Slot)> {
let idx = self
.slice()
.binary_search_by(|it| {
let child_range = it.rel_range();
TextRange::ordering(child_range, rel_range)
})
// XXX: this handles empty ranges
.unwrap_or_else(|it| it.saturating_sub(1));
let slot = &self
.slice()
.get(idx)
.filter(|it| it.rel_range().contains_range(rel_range))?;
Some((idx, slot.rel_offset(), slot))
}
#[must_use = "syntax elements are immutable, the result of update methods must be propagated to have any effect"]
pub(crate) fn splice_slots<R, I>(&self, range: R, replace_with: I) -> GreenNode
where
R: ops::RangeBounds<usize>,
I: Iterator<Item = Option<GreenElement>>,
{
let mut slots: Vec<_> = self
.slots()
.map(|slot| match slot {
Slot::Empty { .. } => None,
Slot::Node { node, .. } => Some(NodeOrToken::Node(node.to_owned())),
Slot::Token { token, .. } => Some(NodeOrToken::Token(token.to_owned())),
})
.collect();
slots.splice(range, replace_with);
GreenNode::new(self.kind(), slots)
}
}
impl ops::Deref for GreenNode {
type Target = GreenNodeData;
#[inline]
fn deref(&self) -> &GreenNodeData {
unsafe {
let repr: &Repr = &self.ptr;
let repr: &ReprThin = &*(repr as *const Repr as *const ReprThin);
mem::transmute::<&ReprThin, &GreenNodeData>(repr)
}
}
}
impl GreenNode {
/// Creates new Node.
#[inline]
pub fn new<I>(kind: RawSyntaxKind, slots: I) -> GreenNode
where
I: IntoIterator<Item = Option<GreenElement>>,
I::IntoIter: ExactSizeIterator,
{
let mut text_len: TextSize = 0.into();
let slots = slots.into_iter().map(|el| {
let rel_offset = text_len;
match el {
Some(el) => {
text_len += el.text_len();
match el {
NodeOrToken::Node(node) => Slot::Node { rel_offset, node },
NodeOrToken::Token(token) => Slot::Token { rel_offset, token },
}
}
None => Slot::Empty { rel_offset },
}
});
let data = ThinArc::from_header_and_iter(
GreenNodeHead {
kind,
text_len: 0.into(),
_c: Count::new(),
},
slots,
);
// XXX: fixup `text_len` after construction, because we can't iterate
// `slots` twice.
let data = {
let mut data = Arc::from_thin(data);
Arc::get_mut(&mut data).unwrap().header.text_len = text_len;
Arc::into_thin(data)
};
GreenNode { ptr: data }
}
#[inline]
pub(crate) fn into_raw(self) -> ptr::NonNull<GreenNodeData> {
// SAFETY: casting from `HeaderSlice<GreenNodeHead, [green::node::Slot]>` to `GreenNodeData`
// if safe since `GreenNodeData` is marked as `repr(transparent)`
Arc::from_thin(self.ptr).into_raw().cast()
}
#[inline]
pub(crate) unsafe fn from_raw(ptr: ptr::NonNull<GreenNodeData>) -> GreenNode {
let arc = Arc::from_raw(&ptr.as_ref().data as *const ReprThin);
let arc = mem::transmute::<Arc<ReprThin>, ThinArc<GreenNodeHead, Slot>>(arc);
GreenNode { ptr: arc }
}
}
impl Slot {
#[inline]
pub(crate) fn as_ref(&self) -> Option<GreenElementRef> {
match self {
Slot::Node { node, .. } => Some(NodeOrToken::Node(node)),
Slot::Token { token, .. } => Some(NodeOrToken::Token(token)),
Slot::Empty { .. } => None,
}
}
#[inline]
pub(crate) fn rel_offset(&self) -> TextSize {
match self {
Slot::Node { rel_offset, .. }
| Slot::Token { rel_offset, .. }
| Slot::Empty { rel_offset } => *rel_offset,
}
}
#[inline]
fn rel_range(&self) -> TextRange {
let text_len = match self.as_ref() {
None => TextSize::from(0),
Some(element) => element.text_len(),
};
TextRange::at(self.rel_offset(), text_len)
}
}
#[derive(Debug, Clone)]
pub(crate) struct Slots<'a> {
pub(crate) raw: slice::Iter<'a, Slot>,
}
// NB: forward everything stable that iter::Slice specializes as of Rust 1.39.0
impl ExactSizeIterator for Slots<'_> {
#[inline(always)]
fn len(&self) -> usize {
self.raw.len()
}
}
impl<'a> Iterator for Slots<'a> {
type Item = &'a Slot;
#[inline]
fn next(&mut self) -> Option<&'a Slot> {
self.raw.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.raw.size_hint()
}
#[inline]
fn count(self) -> usize
where
Self: Sized,
{
self.raw.count()
}
#[inline]
fn last(mut self) -> Option<Self::Item>
where
Self: Sized,
{
self.next_back()
}
#[inline]
fn nth(&mut self, n: usize) -> Option<Self::Item> {
self.raw.nth(n)
}
#[inline]
fn fold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
let mut accum = init;
for x in self {
accum = f(accum, x);
}
accum
}
}
impl<'a> DoubleEndedIterator for Slots<'a> {
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
self.raw.next_back()
}
#[inline]
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
self.raw.nth_back(n)
}
#[inline]
fn rfold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
let mut accum = init;
while let Some(x) = self.next_back() {
accum = f(accum, x);
}
accum
}
}
impl FusedIterator for Slots<'_> {}
#[derive(Debug, Clone)]
pub(crate) struct Child<'a> {
slot: u32,
rel_offset: TextSize,
element: GreenElementRef<'a>,
}
impl<'a> Child<'a> {
pub fn slot(&self) -> u32 {
self.slot
}
pub fn rel_offset(&self) -> TextSize {
self.rel_offset
}
pub fn element(&self) -> GreenElementRef<'a> {
self.element
}
}
impl<'a> TryFrom<(usize, &'a Slot)> for Child<'a> {
type Error = ();
fn try_from((index, slot): (usize, &'a Slot)) -> Result<Self, Self::Error> {
match slot {
Slot::Empty { .. } => Err(()),
Slot::Node { node, rel_offset } => Ok(Child {
element: NodeOrToken::Node(node),
slot: index as u32,
rel_offset: *rel_offset,
}),
Slot::Token { token, rel_offset } => Ok(Child {
element: NodeOrToken::Token(token),
slot: index as u32,
rel_offset: *rel_offset,
}),
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct Children<'a> {
slots: Enumerate<Slots<'a>>,
}
impl<'a> Children<'a> {
pub fn new(slots: Enumerate<Slots<'a>>) -> Self {
Self { slots }
}
}
impl<'a> Iterator for Children<'a> {
type Item = Child<'a>;
fn next(&mut self) -> Option<Self::Item> {
self.slots.find_map(|it| Child::try_from(it).ok())
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.slots.size_hint()
}
}
impl<'a> DoubleEndedIterator for Children<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
loop {
let next = self.slots.next_back()?;
if let Ok(child) = Child::try_from(next) {
return Some(child);
}
}
}
}
impl FusedIterator for Children<'_> {}
#[cfg(test)]
mod tests {
use crate::raw_language::{RawLanguageKind, RawSyntaxTreeBuilder};
use crate::GreenNode;
fn build_test_list() -> GreenNode {
let mut builder: RawSyntaxTreeBuilder = RawSyntaxTreeBuilder::new();
// list
builder.start_node(RawLanguageKind::SEPARATED_EXPRESSION_LIST);
// element 1
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::STRING_TOKEN, "a");
builder.finish_node();
// Missing ,
// element 2
builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
builder.token(RawLanguageKind::STRING_TOKEN, "b");
builder.finish_node();
builder.finish_node();
builder.finish_green()
}
#[test]
fn children() {
let root = build_test_list();
// Test that children skips missing
assert_eq!(root.children().count(), 2);
assert_eq!(
root.children()
.map(|child| child.element.to_string())
.collect::<Vec<_>>(),
vec!["a", "b"]
);
// Slot 2 (index 1) is empty
assert_eq!(
root.children().map(|child| child.slot).collect::<Vec<_>>(),
vec![0, 2]
);
// Same when reverse
assert_eq!(
root.children()
.rev()
.map(|child| child.slot)
.collect::<Vec<_>>(),
vec![2, 0]
);
}
#[test]
fn slots() {
let root = build_test_list();
// Has 3 slots, one is missing
assert_eq!(root.slots().len(), 3);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/green/element.rs | crates/rome_rowan/src/green/element.rs | use crate::{
green::{GreenNode, GreenToken, RawSyntaxKind},
GreenNodeData, NodeOrToken, TextSize,
};
use std::borrow::Cow;
use super::GreenTokenData;
pub(crate) type GreenElement = NodeOrToken<GreenNode, GreenToken>;
pub(crate) type GreenElementRef<'a> = NodeOrToken<&'a GreenNodeData, &'a GreenTokenData>;
impl From<GreenNode> for GreenElement {
#[inline]
fn from(node: GreenNode) -> GreenElement {
NodeOrToken::Node(node)
}
}
impl<'a> From<&'a GreenNode> for GreenElementRef<'a> {
#[inline]
fn from(node: &'a GreenNode) -> GreenElementRef<'a> {
NodeOrToken::Node(node)
}
}
impl From<GreenToken> for GreenElement {
#[inline]
fn from(token: GreenToken) -> GreenElement {
NodeOrToken::Token(token)
}
}
impl From<Cow<'_, GreenNodeData>> for GreenElement {
#[inline]
fn from(cow: Cow<'_, GreenNodeData>) -> Self {
NodeOrToken::Node(cow.into_owned())
}
}
impl<'a> From<&'a GreenToken> for GreenElementRef<'a> {
#[inline]
fn from(token: &'a GreenToken) -> GreenElementRef<'a> {
NodeOrToken::Token(token)
}
}
impl GreenElementRef<'_> {
pub fn to_owned(self) -> GreenElement {
match self {
NodeOrToken::Node(it) => NodeOrToken::Node(it.to_owned()),
NodeOrToken::Token(it) => NodeOrToken::Token(it.to_owned()),
}
}
}
impl GreenElement {
/// Returns kind of this element.
#[inline]
pub fn kind(&self) -> RawSyntaxKind {
match self {
NodeOrToken::Node(node) => node.kind(),
NodeOrToken::Token(token) => token.kind(),
}
}
/// Returns the length of the text covered by this element.
#[inline]
pub fn text_len(&self) -> TextSize {
match self {
NodeOrToken::Token(token) => token.text_len(),
NodeOrToken::Node(node) => node.text_len(),
}
}
}
impl GreenElementRef<'_> {
/// Returns kind of this element.
#[inline]
pub fn kind(&self) -> RawSyntaxKind {
match self {
NodeOrToken::Node(it) => it.kind(),
NodeOrToken::Token(it) => it.kind(),
}
}
/// Returns the length of the text covered by this element.
#[inline]
pub fn text_len(self) -> TextSize {
match self {
NodeOrToken::Node(it) => it.text_len(),
NodeOrToken::Token(it) => it.text_len(),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/green/trivia.rs | crates/rome_rowan/src/green/trivia.rs | use crate::arc::{Arc, HeaderSlice, ThinArc};
use crate::TriviaPiece;
use countme::Count;
use rome_text_size::TextSize;
use std::fmt::Formatter;
use std::mem::ManuallyDrop;
use std::{fmt, mem, ptr};
#[derive(PartialEq, Eq, Hash)]
pub(crate) struct GreenTriviaHead {
_c: Count<GreenTrivia>,
}
pub(crate) fn has_live() -> bool {
countme::get::<GreenTrivia>().live > 0
}
type ReprThin = HeaderSlice<GreenTriviaHead, [TriviaPiece; 0]>;
#[repr(transparent)]
pub(crate) struct GreenTriviaData {
data: ReprThin,
}
impl GreenTriviaData {
#[allow(unused)]
#[inline]
pub fn header(&self) -> &GreenTriviaHead {
&self.data.header
}
#[inline]
pub fn pieces(&self) -> &[TriviaPiece] {
self.data.slice()
}
#[inline]
pub(crate) fn to_owned(&self) -> GreenTrivia {
unsafe {
let green = GreenTrivia::from_raw(self as *const _ as *mut _);
let green = ManuallyDrop::new(green);
GreenTrivia::clone(&green)
}
}
}
impl PartialEq for GreenTriviaData {
fn eq(&self, other: &Self) -> bool {
self.pieces() == other.pieces()
}
}
impl fmt::Debug for GreenTriviaData {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.pieces().iter()).finish()
}
}
/// List of trivia. Used to store either the leading or trailing trivia of a token.
/// The identity of a trivia is defined by the kinds and lengths of its items but not by
/// the texts of an individual piece. That means, that `\r` and `\n` can both be represented
/// by the same trivia, a trivia with a single `LINEBREAK` piece with the length 1.
/// This is safe because the text is stored on the token to which the trivia belongs and
/// `a\n` and `a\r` never resolve to the same tokens. Thus, they only share the trivia but are
/// otherwise two different tokens.
#[derive(Eq, PartialEq, Hash, Clone)]
#[repr(transparent)]
pub(crate) struct GreenTrivia {
ptr: Option<ThinArc<GreenTriviaHead, TriviaPiece>>,
}
impl fmt::Debug for GreenTrivia {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.pieces(), f)
}
}
impl GreenTrivia {
/// Creates a new trivia containing the passed in pieces
pub fn new<I>(pieces: I) -> Self
where
I: IntoIterator<Item = TriviaPiece>,
I::IntoIter: ExactSizeIterator,
{
let data =
ThinArc::from_header_and_iter(GreenTriviaHead { _c: Count::new() }, pieces.into_iter());
GreenTrivia { ptr: Some(data) }
}
/// Creates an empty trivia
pub fn empty() -> Self {
GreenTrivia { ptr: None }
}
/// Returns the total length of all pieces
pub fn text_len(&self) -> TextSize {
let mut len = TextSize::default();
for piece in self.pieces() {
len += piece.length
}
len
}
/// Returns the pieces count
pub fn len(&self) -> usize {
match &self.ptr {
None => 0,
Some(ptr) => ptr.len(),
}
}
/// Returns the pieces of the trivia
pub fn pieces(&self) -> &[TriviaPiece] {
match &self.ptr {
None => &[],
Some(ptr) => ptr.slice(),
}
}
/// Returns the piece at the given index.
pub fn get_piece(&self, index: usize) -> Option<&TriviaPiece> {
self.pieces().get(index)
}
pub(crate) fn into_raw(self) -> *mut GreenTriviaData {
self.ptr.map_or_else(ptr::null_mut, |ptr| {
Arc::from_thin(ptr).into_raw().cast().as_ptr()
})
}
pub(crate) unsafe fn from_raw(ptr: *mut GreenTriviaData) -> Self {
if let Some(ptr) = ptr.as_ref() {
let arc = Arc::from_raw(&ptr.data as *const ReprThin);
let arc = mem::transmute::<Arc<ReprThin>, ThinArc<GreenTriviaHead, TriviaPiece>>(arc);
Self { ptr: Some(arc) }
} else {
Self { ptr: None }
}
}
}
#[cfg(test)]
mod tests {
use crate::green::trivia::{GreenTrivia, GreenTriviaHead};
use crate::syntax::TriviaPieceKind;
use crate::TriviaPiece;
use rome_text_size::TextSize;
impl GreenTrivia {
/// Creates a trivia with a single whitespace piece
pub fn whitespace<L: Into<TextSize>>(len: L) -> Self {
Self::single(TriviaPieceKind::Whitespace, len.into())
}
/// Creates a trivia with one single line comment piece
pub fn single_line_comment<L: Into<TextSize>>(len: L) -> Self {
Self::single(TriviaPieceKind::SingleLineComment, len.into())
}
/// Creates a trivia containing a single piece
pub fn single<L: Into<TextSize>>(kind: TriviaPieceKind, len: L) -> Self {
Self::new([TriviaPiece::new(kind, len)])
}
}
#[test]
fn sizes() {
assert_eq!(0, std::mem::size_of::<GreenTriviaHead>());
assert_eq!(8, std::mem::size_of::<GreenTrivia>());
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/src/green/token.rs | crates/rome_rowan/src/green/token.rs | use std::{
borrow::Borrow,
fmt,
mem::{self, ManuallyDrop},
ops, ptr,
};
use countme::Count;
use crate::green::trivia::GreenTrivia;
use crate::{
arc::{Arc, HeaderSlice, ThinArc},
green::RawSyntaxKind,
TextSize,
};
#[derive(PartialEq, Eq, Hash)]
struct GreenTokenHead {
kind: RawSyntaxKind,
leading: GreenTrivia,
trailing: GreenTrivia,
_c: Count<GreenToken>,
}
pub(crate) fn has_live() -> bool {
countme::get::<GreenToken>().live > 0
}
type Repr = HeaderSlice<GreenTokenHead, [u8]>;
type ReprThin = HeaderSlice<GreenTokenHead, [u8; 0]>;
#[repr(transparent)]
pub(crate) struct GreenTokenData {
data: ReprThin,
}
impl PartialEq for GreenTokenData {
fn eq(&self, other: &Self) -> bool {
self.kind() == other.kind() && self.text() == other.text()
}
}
/// Leaf node in the immutable tree.
#[derive(PartialEq, Eq, Hash, Clone)]
#[repr(transparent)]
pub(crate) struct GreenToken {
ptr: ThinArc<GreenTokenHead, u8>,
}
impl ToOwned for GreenTokenData {
type Owned = GreenToken;
#[inline]
fn to_owned(&self) -> GreenToken {
unsafe {
let green = GreenToken::from_raw(ptr::NonNull::from(self));
let green = ManuallyDrop::new(green);
GreenToken::clone(&green)
}
}
}
impl Borrow<GreenTokenData> for GreenToken {
#[inline]
fn borrow(&self) -> &GreenTokenData {
self
}
}
impl fmt::Debug for GreenTokenData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GreenToken")
.field("kind", &self.kind())
.field("text", &self.text())
.field("leading", &self.leading_trivia())
.field("trailing", &self.trailing_trivia())
.finish()
}
}
impl fmt::Debug for GreenToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let data: &GreenTokenData = self;
fmt::Debug::fmt(data, f)
}
}
impl fmt::Display for GreenToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let data: &GreenTokenData = self;
fmt::Display::fmt(data, f)
}
}
impl fmt::Display for GreenTokenData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.text())
}
}
impl GreenTokenData {
/// Kind of this Token.
#[inline]
pub fn kind(&self) -> RawSyntaxKind {
self.data.header.kind
}
/// Whole text of this Token, including all trivia.
#[inline]
pub fn text(&self) -> &str {
unsafe { std::str::from_utf8_unchecked(self.data.slice()) }
}
pub(crate) fn leading_trailing_total_len(&self) -> (TextSize, TextSize, TextSize) {
let leading_len = self.data.header.leading.text_len();
let trailing_len = self.data.header.trailing.text_len();
let total_len = self.data.slice().len() as u32;
(leading_len, trailing_len, total_len.into())
}
/// Text of this Token, excluding all trivia.
#[inline]
pub fn text_trimmed(&self) -> &str {
let (leading_len, trailing_len, total_len) = self.leading_trailing_total_len();
let start: usize = leading_len.into();
let end: usize = (total_len - trailing_len).into();
let text = unsafe { std::str::from_utf8_unchecked(self.data.slice()) };
&text[start..end]
}
/// Returns the length of the text covered by this token.
#[inline]
pub fn text_len(&self) -> TextSize {
TextSize::of(self.text())
}
#[inline]
pub fn leading_trivia(&self) -> &GreenTrivia {
&self.data.header.leading
}
#[inline]
pub fn trailing_trivia(&self) -> &GreenTrivia {
&self.data.header.trailing
}
}
impl GreenToken {
#[inline]
#[cfg(test)]
pub fn new(kind: RawSyntaxKind, text: &str) -> GreenToken {
let leading = GreenTrivia::empty();
let trailing = leading.clone();
Self::with_trivia(kind, text, leading, trailing)
}
#[inline]
pub fn with_trivia(
kind: RawSyntaxKind,
text: &str,
leading: GreenTrivia,
trailing: GreenTrivia,
) -> GreenToken {
let head = GreenTokenHead {
kind,
leading,
trailing,
_c: Count::new(),
};
let ptr = ThinArc::from_header_and_iter(head, text.bytes());
GreenToken { ptr }
}
#[inline]
pub(crate) fn into_raw(self) -> ptr::NonNull<GreenTokenData> {
Arc::from_thin(self.ptr).into_raw().cast()
}
#[inline]
pub(crate) unsafe fn from_raw(ptr: ptr::NonNull<GreenTokenData>) -> GreenToken {
let arc = Arc::from_raw(&ptr.as_ref().data as *const ReprThin);
let arc = mem::transmute::<Arc<ReprThin>, ThinArc<GreenTokenHead, u8>>(arc);
GreenToken { ptr: arc }
}
}
impl ops::Deref for GreenToken {
type Target = GreenTokenData;
#[inline]
fn deref(&self) -> &GreenTokenData {
unsafe {
let repr: &Repr = &self.ptr;
let repr: &ReprThin = &*(repr as *const Repr as *const ReprThin);
mem::transmute::<&ReprThin, &GreenTokenData>(repr)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck_macros::*;
#[test]
fn green_token_text_and_len() {
let t = GreenToken::with_trivia(
RawSyntaxKind(0),
"\n\t let \t\t",
GreenTrivia::whitespace(3),
GreenTrivia::whitespace(3),
);
assert_eq!("\n\t let \t\t", t.text());
assert_eq!(TextSize::from(9), t.text_len());
assert_eq!("let", t.text_trimmed());
assert_eq!("\n\t let \t\t", format!("{}", t));
}
#[test]
fn empty_text_len() {
assert_eq!(TextSize::from(0), GreenTrivia::empty().text_len());
}
#[quickcheck]
fn whitespace_and_comments_text_len(len: u32) {
let len = TextSize::from(len);
assert_eq!(len, GreenTrivia::whitespace(len).text_len());
assert_eq!(len, GreenTrivia::single_line_comment(len).text_len());
}
#[test]
fn sizes() {
assert_eq!(24, std::mem::size_of::<GreenTokenHead>());
assert_eq!(8, std::mem::size_of::<GreenToken>());
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_rowan/benches/mutation.rs | crates/rome_rowan/benches/mutation.rs | use rome_rowan::{
raw_language::{LiteralExpression, RawLanguageKind, RawLanguageRoot, RawSyntaxTreeBuilder},
AstNode, AstNodeExt, BatchMutationExt, SyntaxNodeCast,
};
/// ```
/// 0: ROOT@0..1
/// 0: LITERAL_EXPRESSION@0..1
/// 0: STRING_TOKEN@0..1 "a" [] []
/// ```
fn tree_one(a: &str) -> (RawLanguageRoot, String) {
let mut builder = RawSyntaxTreeBuilder::new();
builder
.start_node(RawLanguageKind::ROOT)
.start_node(RawLanguageKind::LITERAL_EXPRESSION)
.token(RawLanguageKind::STRING_TOKEN, a)
.finish_node()
.finish_node();
let root = builder.finish().cast::<RawLanguageRoot>().unwrap();
let s = format!("{:#?}", root.syntax());
(root, s)
}
fn find(root: &RawLanguageRoot, name: &str) -> LiteralExpression {
root.syntax()
.descendants()
.find(|x| x.kind() == RawLanguageKind::LITERAL_EXPRESSION && x.text_trimmed() == name)
.unwrap()
.cast::<LiteralExpression>()
.unwrap()
}
fn clone_detach(root: &RawLanguageRoot, name: &str) -> LiteralExpression {
root.syntax()
.descendants()
.find(|x| x.kind() == RawLanguageKind::LITERAL_EXPRESSION && x.text_trimmed() == name)
.unwrap()
.detach()
.cast::<LiteralExpression>()
.unwrap()
}
fn mutation_replace_node() -> usize {
let (before, _) = tree_one("a");
let (expected, _) = tree_one("b");
let a = find(&before, "a");
let b = clone_detach(&expected, "b");
let root = before.replace_node(a, b).unwrap();
root.syntax().descendants().count()
}
fn mutation_batch() -> usize {
let (before, _) = tree_one("a");
let (expected, _) = tree_one("b");
let a = find(&before, "a");
let b = clone_detach(&expected, "b");
let mut batch = before.begin();
batch.replace_node(a, b);
let root = batch.commit();
root.descendants().count()
}
iai::main!(mutation_replace_node, mutation_batch);
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_migrate/src/lib.rs | crates/rome_migrate/src/lib.rs | mod analyzers;
mod macros;
mod registry;
use crate::registry::visit_migration_registry;
pub use rome_analyze::ControlFlow;
use rome_analyze::{
AnalysisFilter, Analyzer, AnalyzerContext, AnalyzerOptions, AnalyzerSignal, InspectMatcher,
LanguageRoot, MatchQueryParams, MetadataRegistry, RuleRegistry,
};
use rome_diagnostics::Error;
use rome_json_syntax::JsonLanguage;
use std::convert::Infallible;
use std::path::{Path, PathBuf};
/// Return the static [MetadataRegistry] for the JS analyzer rules
pub fn metadata() -> &'static MetadataRegistry {
lazy_static::lazy_static! {
static ref METADATA: MetadataRegistry = {
let mut metadata = MetadataRegistry::default();
visit_migration_registry(&mut metadata);
metadata
};
}
&METADATA
}
/// Run the analyzer on the provided `root`: this process will use the given `filter`
/// to selectively restrict analysis to specific rules / a specific source range,
/// then call `emit_signal` when an analysis rule emits a diagnostic or action.
/// Additionally, this function takes a `inspect_matcher` function that can be
/// used to inspect the "query matches" emitted by the analyzer before they are
/// processed by the lint rules registry
pub fn analyze_with_inspect_matcher<'a, V, F, B>(
root: &LanguageRoot<JsonLanguage>,
configuration_file_path: &'a Path,
inspect_matcher: V,
mut emit_signal: F,
) -> (Option<B>, Vec<Error>)
where
V: FnMut(&MatchQueryParams<JsonLanguage>) + 'a,
F: FnMut(&dyn AnalyzerSignal<JsonLanguage>) -> ControlFlow<B> + 'a,
B: 'a,
{
let filter = AnalysisFilter::default();
let options = AnalyzerOptions {
file_path: PathBuf::from(configuration_file_path),
..AnalyzerOptions::default()
};
let mut registry = RuleRegistry::builder(&filter, root);
visit_migration_registry(&mut registry);
let (migration_registry, services, diagnostics, visitors) = registry.build();
// Bail if we can't parse a rule option
if !diagnostics.is_empty() {
return (None, diagnostics);
}
let mut analyzer = Analyzer::new(
metadata(),
InspectMatcher::new(migration_registry, inspect_matcher),
|_| -> Vec<Result<_, Infallible>> { unreachable!() },
|_| {},
&mut emit_signal,
);
for ((phase, _), visitor) in visitors {
analyzer.add_visitor(phase, visitor);
}
(
analyzer.run(AnalyzerContext {
root: root.clone(),
range: filter.range,
services,
options: &options,
}),
diagnostics,
)
}
pub fn migrate_configuration<'a, F, B>(
root: &LanguageRoot<JsonLanguage>,
configuration_file_path: &'a Path,
emit_signal: F,
) -> (Option<B>, Vec<Error>)
where
F: FnMut(&dyn AnalyzerSignal<JsonLanguage>) -> ControlFlow<B> + 'a,
B: 'a,
{
analyze_with_inspect_matcher(root, configuration_file_path, |_| {}, emit_signal)
}
#[cfg(test)]
mod test {
use crate::migrate_configuration;
use rome_analyze::{ControlFlow, Never};
use rome_json_parser::{parse_json, JsonParserOptions};
use std::path::Path;
#[test]
#[ignore]
fn smoke() {
let source = r#"{ "something": "else" }"#;
let parsed = parse_json(source, JsonParserOptions::default());
migrate_configuration(&parsed.tree().value().unwrap(), Path::new(""), |signal| {
for action in signal.actions() {
let new_code = action.mutation.commit();
eprintln!("{new_code}");
}
ControlFlow::<Never>::Continue(())
});
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_migrate/src/macros.rs | crates/rome_migrate/src/macros.rs | #[macro_export]
macro_rules! declare_migration {
( $vis:vis $id:ident {
version: $version:literal,
name: $name:tt,
$( $key:ident: $value:expr, )*
} ) => {
$vis enum $id {}
impl rome_analyze::RuleMeta for $id {
type Group = $crate::analyzers::MigrationGroup;
const METADATA: rome_analyze::RuleMetadata =
rome_analyze::RuleMetadata::new($version, $name, "") $( .$key($value) )*;
}
// Declare a new `rule_category!` macro in the module context that
// expands to the category of this rule
// This is implemented by calling the `group_category!` macro from the
// parent module (that should be declared by a call to `declare_group!`)
// and providing it with the name of this rule as a string literal token
#[allow(unused_macros)]
macro_rules! rule_category {
() => { super::group_category!( $name ) };
}
};
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_migrate/src/registry.rs | crates/rome_migrate/src/registry.rs | use crate::analyzers::MigrationCategory;
use rome_analyze::RegistryVisitor;
use rome_json_syntax::JsonLanguage;
pub fn visit_migration_registry<V: RegistryVisitor<JsonLanguage>>(registry: &mut V) {
registry.record_category::<MigrationCategory>();
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_migrate/src/analyzers.rs | crates/rome_migrate/src/analyzers.rs | use crate::analyzers::rule_set::RuleSet;
use rome_analyze::{GroupCategory, RegistryVisitor, RuleCategory, RuleGroup};
use rome_json_syntax::JsonLanguage;
mod rule_set;
pub(crate) struct MigrationGroup;
pub(crate) struct MigrationCategory;
impl RuleGroup for MigrationGroup {
type Language = JsonLanguage;
type Category = MigrationCategory;
const NAME: &'static str = "migrations";
fn record_rules<V: RegistryVisitor<Self::Language> + ?Sized>(registry: &mut V) {
// Order here is important, rules should be added from the most old, to the most recent
// v13.0.0
registry.record_rule::<RuleSet>();
}
}
impl GroupCategory for MigrationCategory {
type Language = JsonLanguage;
const CATEGORY: RuleCategory = RuleCategory::Action;
fn record_groups<V: RegistryVisitor<Self::Language> + ?Sized>(registry: &mut V) {
registry.record_group::<MigrationGroup>();
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_migrate/src/analyzers/rule_set.rs | crates/rome_migrate/src/analyzers/rule_set.rs | use crate::declare_migration;
use rome_analyze::context::RuleContext;
use rome_analyze::{Ast, Rule};
use rome_json_syntax::JsonObjectValue;
declare_migration! {
pub(crate) RuleSet {
version: "11.0.0",
name: "ruleSet",
}
}
impl Rule for RuleSet {
type Query = Ast<JsonObjectValue>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(_: &RuleContext<Self>) -> Self::Signals {
// TODO: write rule to create a "ruleSet" config
// ruleSet -> "recommended", "all", "none" as a starter
// It should merge "recommended" and "all"
None
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/diagnostics.rs | crates/rome_cli/src/diagnostics.rs | use rome_console::fmt::Formatter;
use rome_console::markup;
use rome_diagnostics::adapters::{BpafError, IoError};
use rome_diagnostics::{
Advices, Category, Diagnostic, DiagnosticTags, Error, Location, LogCategory,
MessageAndDescription, Severity, Visit,
};
use rome_service::WorkspaceError;
use std::process::{ExitCode, Termination};
use std::{env::current_exe, fmt::Debug};
fn command_name() -> String {
current_exe()
.ok()
.and_then(|path| Some(path.file_name()?.to_str()?.to_string()))
.unwrap_or_else(|| String::from("rome"))
}
/// A diagnostic that is emitted when running rome via CLI.
///
/// When displaying the diagnostic,
#[derive(Debug)]
pub enum CliDiagnostic {
/// Returned when it is called with a subcommand it doesn't know
UnknownCommand(UnknownCommand),
/// Return by the help command when it is called with a subcommand it doesn't know
UnknownCommandHelp(UnknownCommandHelp),
/// Returned when the value of a command line argument could not be parsed
ParseError(ParseDiagnostic),
/// Returned when the CLI doesn't recognize a command line argument
UnexpectedArgument(UnexpectedArgument),
/// Returned when a required argument is not present in the command line
MissingArgument(MissingArgument),
/// Returned when a subcommand is called without any arguments
EmptyArguments(EmptyArguments),
/// Returned when a subcommand is called with an unsupported combination of arguments
IncompatibleArguments(IncompatibleArguments),
/// Returned by a traversal command when error diagnostics were emitted
CheckError(CheckError),
/// Emitted when a file is fixed, but it still contains diagnostics.
///
/// This happens when these diagnostics come from rules that don't have a code action.
FileCheckApply(FileCheckApply),
/// When an argument is higher than the expected maximum
OverflowNumberArgument(OverflowNumberArgument),
/// Wrapper for an underlying `rome_service` error
WorkspaceError(WorkspaceError),
/// Wrapper for an underlying `std::io` error
IoError(IoDiagnostic),
/// The daemon is not running
ServerNotRunning(ServerNotRunning),
/// The end configuration (`rome.json` + other options) is incompatible with the command
IncompatibleEndConfiguration(IncompatibleEndConfiguration),
/// No files processed during the file system traversal
NoFilesWereProcessed(NoFilesWereProcessed),
/// Errors thrown when running the `rome migrate` command
MigrateError(MigrationDiagnostic),
/// When the VCS folder couldn't be found
NoVcsFolderFound(NoVcsFolderFound),
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "flags/invalid",
severity = Error,
message(
description = "Unknown command {command_name}",
message("Unknown command "<Emphasis>{self.command_name}</Emphasis>)
),
)]
pub struct UnknownCommand {
command_name: String,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "flags/invalid",
severity = Error,
message(
description = "Cannot print help for unknown command {command_name}",
message("Cannot print help for unknown command "<Emphasis>{self.command_name}</Emphasis>)
),
)]
pub struct UnknownCommandHelp {
command_name: String,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "flags/invalid",
severity = Error,
)]
pub struct ParseDiagnostic {
#[message]
#[description]
message: MessageAndDescription,
#[source]
source: Option<Error>,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "flags/invalid",
severity = Error,
message(
description = "Unrecognized option {argument}",
message("Unrecognized option "<Emphasis>{self.argument}</Emphasis>".")
),
)]
pub struct UnexpectedArgument {
argument: String,
#[advice]
help: CliAdvice,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "flags/invalid",
severity = Error,
message(
description = "Unrecognized option {argument}",
message("Missing argument "<Emphasis>{self.argument}</Emphasis>)
),
)]
pub struct MissingArgument {
argument: String,
#[advice]
advice: CliAdvice,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "flags/invalid",
severity = Error,
message = "Empty arguments"
)]
pub struct EmptyArguments;
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "flags/invalid",
severity = Error,
message(
description = "Incompatible arguments {first_argument} and {second_argument}",
message("Incompatible arguments "<Emphasis>{self.first_argument}</Emphasis>" and "<Emphasis>{self.second_argument}</Emphasis>)
)
)]
pub struct IncompatibleArguments {
first_argument: String,
second_argument: String,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
severity = Error,
)]
pub struct CheckError {
#[category]
category: &'static Category,
#[message]
message: MessageAndDescription,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
severity = Error,
message = "Fixes applied to the file, but there are still diagnostics to address."
)]
pub struct FileCheckApply {
#[location(resource)]
pub file_path: String,
#[category]
pub category: &'static Category,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "flags/invalid",
severity = Error,
message(
description = "The value of the argument {argument} is too high, maximum accepted {maximum}",
message("The value of the argument "<Emphasis>{self.argument}</Emphasis>" is too high, maximum accepted "{{self.maximum}})
)
)]
pub struct OverflowNumberArgument {
argument: String,
maximum: u16,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "internalError/io",
severity = Error,
message = "Errors occurred while executing I/O operations."
)]
pub struct IoDiagnostic {
#[source]
source: Option<Error>,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "internalError/io",
severity = Error,
message = "No running instance of the Rome daemon server was found."
)]
// TODO: add advice
pub struct ServerNotRunning;
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "internalError/io",
severity = Error,
message(
description = "The combination of configuration and arguments is invalid: \n{reason}",
message("The combination of configuration and arguments is invalid: \n"{{&self.reason}})
)
)]
pub struct IncompatibleEndConfiguration {
reason: String,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "internalError/io",
severity = Error,
message = "No files were processed in the specified paths."
)]
pub struct NoFilesWereProcessed;
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "migrate",
severity = Error,
message(
message("Migration has encountered an error: "{{&self.reason}}),
description = "Migration has encountered an error: {reason}"
)
)]
pub struct MigrationDiagnostic {
pub reason: String,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "internalError/fs",
severity = Error,
message(
description = "Rome couldn't find the VCS folder at the following path: {path}",
message("Rome couldn't find the VCS folder at the following path: "<Emphasis>{self.path}</Emphasis>),
)
)]
pub struct NoVcsFolderFound {
#[location(resource)]
pub path: String,
#[source]
pub source: Option<Error>,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "internalError/fs",
severity = Warning,
message = "Rome couldn't determine a directory for the VCS integration. VCS integration will be disabled."
)]
pub struct DisabledVcs {}
/// Advices for the [CliDiagnostic]
#[derive(Debug, Default)]
struct CliAdvice {
/// Used to print the help command
sub_command: String,
}
impl CliAdvice {
fn new_with_help(sub_command: impl Into<String>) -> Self {
Self {
sub_command: sub_command.into(),
}
}
}
impl Advices for CliAdvice {
fn record(&self, visitor: &mut dyn Visit) -> std::io::Result<()> {
let command_name = command_name();
let help_sub_command = format!("{} {} --help", command_name, &self.sub_command);
visitor.record_log(
LogCategory::Info,
&markup! { "Type the following command for more information" },
)?;
visitor.record_command(&help_sub_command)?;
Ok(())
}
}
impl CliDiagnostic {
/// Returned when a subcommand is called with an unsupported combination of arguments
pub fn incompatible_arguments(
first_argument: impl Into<String>,
second_argument: impl Into<String>,
) -> Self {
Self::IncompatibleArguments(IncompatibleArguments {
first_argument: first_argument.into(),
second_argument: second_argument.into(),
})
}
/// To throw when there's been an error while parsing an argument
pub fn parse_error_bpaf(source: bpaf::ParseFailure) -> Self {
Self::ParseError(ParseDiagnostic {
source: Some(Error::from(BpafError::from(source))),
message: MessageAndDescription::from("Failed to parse CLI arguments.".to_string()),
})
}
/// Returned when it is called with a subcommand it doesn't know
pub fn unknown_command(command: impl Into<String>) -> Self {
Self::UnknownCommand(UnknownCommand {
command_name: command.into(),
})
}
/// Returned when a subcommand is called without any arguments
pub fn empty_arguments() -> Self {
Self::EmptyArguments(EmptyArguments)
}
/// Returned when a required argument is not present in the command line
pub fn missing_argument(argument: impl Into<String>, subcommand: impl Into<String>) -> Self {
Self::MissingArgument(MissingArgument {
argument: argument.into(),
advice: CliAdvice::new_with_help(subcommand),
})
}
/// When no files were processed while traversing the file system
pub fn no_files_processed() -> Self {
Self::NoFilesWereProcessed(NoFilesWereProcessed)
}
/// Returned when the CLI doesn't recognize a command line argument
pub fn unexpected_argument(argument: impl Into<String>, subcommand: impl Into<String>) -> Self {
Self::UnexpectedArgument(UnexpectedArgument {
argument: argument.into(),
help: CliAdvice::new_with_help(subcommand),
})
}
/// When there's been error inside the workspace
pub fn workspace_error(error: WorkspaceError) -> Self {
Self::WorkspaceError(error)
}
/// An I/O error
pub fn io_error(error: std::io::Error) -> Self {
Self::IoError(IoDiagnostic {
source: Some(Error::from(IoError::from(error))),
})
}
/// Emitted when errors were emitted while running `check` command
pub fn check_error(category: &'static Category) -> Self {
Self::CheckError(CheckError {
category,
message: MessageAndDescription::from(
markup! {
"Some "<Emphasis>"errors"</Emphasis>" were emitted while "<Emphasis>"running checks"</Emphasis>"."
}
.to_owned(),
),
})
}
/// Emitted when warnings were emitted while running `check` command
pub fn check_warnings(category: &'static Category) -> Self {
Self::CheckError(CheckError {
category,
message: MessageAndDescription::from(
markup! {
"Some "<Emphasis>"warnings"</Emphasis>" were emitted while "<Emphasis>"running checks"</Emphasis>"."
}
.to_owned(),
),
})
}
/// Emitted when errors were emitted while apply code fixes
pub fn apply_error(category: &'static Category) -> Self {
Self::CheckError(CheckError {
category,
message: MessageAndDescription::from(
markup! {
"Some "<Emphasis>"errors"</Emphasis>" were emitted while "<Emphasis>"applying fixes"</Emphasis>"."
}
.to_owned(),
),
})
}
/// Emitted when warnings were emitted while apply code fixes
pub fn apply_warnings(category: &'static Category) -> Self {
Self::CheckError(CheckError {
category,
message: MessageAndDescription::from(
markup! {
"Some "<Emphasis>"warnings"</Emphasis>" were emitted while "<Emphasis>"running checks"</Emphasis>"."
}
.to_owned(),
),
})
}
/// Emitted for a file that has code fixes, but still has diagnostics to address
pub fn file_apply_error(file_path: impl Into<String>, category: &'static Category) -> Self {
Self::FileCheckApply(FileCheckApply {
file_path: file_path.into(),
category,
})
}
/// Emitted when the server is not running
pub fn server_not_running() -> Self {
Self::ServerNotRunning(ServerNotRunning)
}
/// Emitted when the end configuration (`rome.json` file + CLI arguments + LSP configuration)
/// results in a combination of options that doesn't allow to run the command correctly.
///
/// A reason needs to be provided
pub fn incompatible_end_configuration(reason: impl Into<String>) -> Self {
Self::IncompatibleEndConfiguration(IncompatibleEndConfiguration {
reason: reason.into(),
})
}
/// Emitted when an argument value is greater than the allowed value
pub fn overflown_argument(argument: impl Into<String>, maximum: u16) -> Self {
Self::OverflowNumberArgument(OverflowNumberArgument {
argument: argument.into(),
maximum,
})
}
/// Return by the help command when it is called with a subcommand it doesn't know
pub fn new_unknown_help(command: impl Into<String>) -> Self {
Self::UnknownCommandHelp(UnknownCommandHelp {
command_name: command.into(),
})
}
}
impl Diagnostic for CliDiagnostic {
fn category(&self) -> Option<&'static Category> {
match self {
CliDiagnostic::UnknownCommand(diagnostic) => diagnostic.category(),
CliDiagnostic::UnknownCommandHelp(diagnostic) => diagnostic.category(),
CliDiagnostic::ParseError(diagnostic) => diagnostic.category(),
CliDiagnostic::UnexpectedArgument(diagnostic) => diagnostic.category(),
CliDiagnostic::MissingArgument(diagnostic) => diagnostic.category(),
CliDiagnostic::EmptyArguments(diagnostic) => diagnostic.category(),
CliDiagnostic::IncompatibleArguments(diagnostic) => diagnostic.category(),
CliDiagnostic::CheckError(diagnostic) => diagnostic.category(),
CliDiagnostic::OverflowNumberArgument(diagnostic) => diagnostic.category(),
CliDiagnostic::WorkspaceError(diagnostic) => diagnostic.category(),
CliDiagnostic::IoError(diagnostic) => diagnostic.category(),
CliDiagnostic::ServerNotRunning(diagnostic) => diagnostic.category(),
CliDiagnostic::IncompatibleEndConfiguration(diagnostic) => diagnostic.category(),
CliDiagnostic::NoFilesWereProcessed(diagnostic) => diagnostic.category(),
CliDiagnostic::FileCheckApply(diagnostic) => diagnostic.category(),
CliDiagnostic::MigrateError(diagnostic) => diagnostic.category(),
CliDiagnostic::NoVcsFolderFound(diagnostic) => diagnostic.category(),
}
}
fn tags(&self) -> DiagnosticTags {
match self {
CliDiagnostic::UnknownCommand(diagnostic) => diagnostic.tags(),
CliDiagnostic::UnknownCommandHelp(diagnostic) => diagnostic.tags(),
CliDiagnostic::ParseError(diagnostic) => diagnostic.tags(),
CliDiagnostic::UnexpectedArgument(diagnostic) => diagnostic.tags(),
CliDiagnostic::MissingArgument(diagnostic) => diagnostic.tags(),
CliDiagnostic::EmptyArguments(diagnostic) => diagnostic.tags(),
CliDiagnostic::IncompatibleArguments(diagnostic) => diagnostic.tags(),
CliDiagnostic::CheckError(diagnostic) => diagnostic.tags(),
CliDiagnostic::OverflowNumberArgument(diagnostic) => diagnostic.tags(),
CliDiagnostic::WorkspaceError(diagnostic) => diagnostic.tags(),
CliDiagnostic::IoError(diagnostic) => diagnostic.tags(),
CliDiagnostic::ServerNotRunning(diagnostic) => diagnostic.tags(),
CliDiagnostic::IncompatibleEndConfiguration(diagnostic) => diagnostic.tags(),
CliDiagnostic::NoFilesWereProcessed(diagnostic) => diagnostic.tags(),
CliDiagnostic::FileCheckApply(diagnostic) => diagnostic.tags(),
CliDiagnostic::MigrateError(diagnostic) => diagnostic.tags(),
CliDiagnostic::NoVcsFolderFound(diagnostic) => diagnostic.tags(),
}
}
fn severity(&self) -> Severity {
match self {
CliDiagnostic::UnknownCommand(diagnostic) => diagnostic.severity(),
CliDiagnostic::UnknownCommandHelp(diagnostic) => diagnostic.severity(),
CliDiagnostic::ParseError(diagnostic) => diagnostic.severity(),
CliDiagnostic::UnexpectedArgument(diagnostic) => diagnostic.severity(),
CliDiagnostic::MissingArgument(diagnostic) => diagnostic.severity(),
CliDiagnostic::EmptyArguments(diagnostic) => diagnostic.severity(),
CliDiagnostic::IncompatibleArguments(diagnostic) => diagnostic.severity(),
CliDiagnostic::CheckError(diagnostic) => diagnostic.severity(),
CliDiagnostic::OverflowNumberArgument(diagnostic) => diagnostic.severity(),
CliDiagnostic::WorkspaceError(diagnostic) => diagnostic.severity(),
CliDiagnostic::IoError(diagnostic) => diagnostic.severity(),
CliDiagnostic::ServerNotRunning(diagnostic) => diagnostic.severity(),
CliDiagnostic::IncompatibleEndConfiguration(diagnostic) => diagnostic.severity(),
CliDiagnostic::NoFilesWereProcessed(diagnostic) => diagnostic.severity(),
CliDiagnostic::FileCheckApply(diagnostic) => diagnostic.severity(),
CliDiagnostic::MigrateError(diagnostic) => diagnostic.severity(),
CliDiagnostic::NoVcsFolderFound(diagnostic) => diagnostic.severity(),
}
}
fn location(&self) -> Location<'_> {
match self {
CliDiagnostic::UnknownCommand(diagnostic) => diagnostic.location(),
CliDiagnostic::UnknownCommandHelp(diagnostic) => diagnostic.location(),
CliDiagnostic::ParseError(diagnostic) => diagnostic.location(),
CliDiagnostic::UnexpectedArgument(diagnostic) => diagnostic.location(),
CliDiagnostic::MissingArgument(diagnostic) => diagnostic.location(),
CliDiagnostic::EmptyArguments(diagnostic) => diagnostic.location(),
CliDiagnostic::IncompatibleArguments(diagnostic) => diagnostic.location(),
CliDiagnostic::CheckError(diagnostic) => diagnostic.location(),
CliDiagnostic::OverflowNumberArgument(diagnostic) => diagnostic.location(),
CliDiagnostic::WorkspaceError(diagnostic) => diagnostic.location(),
CliDiagnostic::IoError(diagnostic) => diagnostic.location(),
CliDiagnostic::ServerNotRunning(diagnostic) => diagnostic.location(),
CliDiagnostic::IncompatibleEndConfiguration(diagnostic) => diagnostic.location(),
CliDiagnostic::NoFilesWereProcessed(diagnostic) => diagnostic.location(),
CliDiagnostic::FileCheckApply(diagnostic) => diagnostic.location(),
CliDiagnostic::MigrateError(diagnostic) => diagnostic.location(),
CliDiagnostic::NoVcsFolderFound(diagnostic) => diagnostic.location(),
}
}
fn message(&self, fmt: &mut Formatter<'_>) -> std::io::Result<()> {
match self {
CliDiagnostic::UnknownCommand(diagnostic) => diagnostic.message(fmt),
CliDiagnostic::UnknownCommandHelp(diagnostic) => diagnostic.message(fmt),
CliDiagnostic::ParseError(diagnostic) => diagnostic.message(fmt),
CliDiagnostic::UnexpectedArgument(diagnostic) => diagnostic.message(fmt),
CliDiagnostic::MissingArgument(diagnostic) => diagnostic.message(fmt),
CliDiagnostic::EmptyArguments(diagnostic) => diagnostic.message(fmt),
CliDiagnostic::IncompatibleArguments(diagnostic) => diagnostic.message(fmt),
CliDiagnostic::CheckError(diagnostic) => diagnostic.message(fmt),
CliDiagnostic::OverflowNumberArgument(diagnostic) => diagnostic.message(fmt),
CliDiagnostic::WorkspaceError(diagnostic) => diagnostic.message(fmt),
CliDiagnostic::IoError(diagnostic) => diagnostic.message(fmt),
CliDiagnostic::ServerNotRunning(diagnostic) => diagnostic.message(fmt),
CliDiagnostic::IncompatibleEndConfiguration(diagnostic) => diagnostic.message(fmt),
CliDiagnostic::NoFilesWereProcessed(diagnostic) => diagnostic.message(fmt),
CliDiagnostic::FileCheckApply(diagnostic) => diagnostic.message(fmt),
CliDiagnostic::MigrateError(diagnostic) => diagnostic.message(fmt),
CliDiagnostic::NoVcsFolderFound(diagnostic) => diagnostic.message(fmt),
}
}
fn description(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CliDiagnostic::UnknownCommand(diagnostic) => diagnostic.description(fmt),
CliDiagnostic::UnknownCommandHelp(diagnostic) => diagnostic.description(fmt),
CliDiagnostic::ParseError(diagnostic) => diagnostic.description(fmt),
CliDiagnostic::UnexpectedArgument(diagnostic) => diagnostic.description(fmt),
CliDiagnostic::MissingArgument(diagnostic) => diagnostic.description(fmt),
CliDiagnostic::EmptyArguments(diagnostic) => diagnostic.description(fmt),
CliDiagnostic::IncompatibleArguments(diagnostic) => diagnostic.description(fmt),
CliDiagnostic::CheckError(diagnostic) => diagnostic.description(fmt),
CliDiagnostic::OverflowNumberArgument(diagnostic) => diagnostic.description(fmt),
CliDiagnostic::WorkspaceError(diagnostic) => diagnostic.description(fmt),
CliDiagnostic::IoError(diagnostic) => diagnostic.description(fmt),
CliDiagnostic::ServerNotRunning(diagnostic) => diagnostic.description(fmt),
CliDiagnostic::IncompatibleEndConfiguration(diagnostic) => diagnostic.description(fmt),
CliDiagnostic::NoFilesWereProcessed(diagnostic) => diagnostic.description(fmt),
CliDiagnostic::FileCheckApply(diagnostic) => diagnostic.description(fmt),
CliDiagnostic::MigrateError(diagnostic) => diagnostic.description(fmt),
CliDiagnostic::NoVcsFolderFound(diagnostic) => diagnostic.description(fmt),
}
}
fn advices(&self, visitor: &mut dyn Visit) -> std::io::Result<()> {
match self {
CliDiagnostic::UnknownCommand(diagnostic) => diagnostic.advices(visitor),
CliDiagnostic::UnknownCommandHelp(diagnostic) => diagnostic.advices(visitor),
CliDiagnostic::ParseError(diagnostic) => diagnostic.advices(visitor),
CliDiagnostic::UnexpectedArgument(diagnostic) => diagnostic.advices(visitor),
CliDiagnostic::MissingArgument(diagnostic) => diagnostic.advices(visitor),
CliDiagnostic::EmptyArguments(diagnostic) => diagnostic.advices(visitor),
CliDiagnostic::IncompatibleArguments(diagnostic) => diagnostic.advices(visitor),
CliDiagnostic::CheckError(diagnostic) => diagnostic.advices(visitor),
CliDiagnostic::OverflowNumberArgument(diagnostic) => diagnostic.advices(visitor),
CliDiagnostic::WorkspaceError(diagnostic) => diagnostic.advices(visitor),
CliDiagnostic::IoError(diagnostic) => diagnostic.advices(visitor),
CliDiagnostic::ServerNotRunning(diagnostic) => diagnostic.advices(visitor),
CliDiagnostic::IncompatibleEndConfiguration(diagnostic) => diagnostic.advices(visitor),
CliDiagnostic::NoFilesWereProcessed(diagnostic) => diagnostic.advices(visitor),
CliDiagnostic::FileCheckApply(diagnostic) => diagnostic.advices(visitor),
CliDiagnostic::MigrateError(diagnostic) => diagnostic.advices(visitor),
CliDiagnostic::NoVcsFolderFound(diagnostic) => diagnostic.advices(visitor),
}
}
fn verbose_advices(&self, visitor: &mut dyn Visit) -> std::io::Result<()> {
match self {
CliDiagnostic::UnknownCommand(diagnostic) => diagnostic.verbose_advices(visitor),
CliDiagnostic::UnknownCommandHelp(diagnostic) => diagnostic.verbose_advices(visitor),
CliDiagnostic::ParseError(diagnostic) => diagnostic.verbose_advices(visitor),
CliDiagnostic::UnexpectedArgument(diagnostic) => diagnostic.verbose_advices(visitor),
CliDiagnostic::MissingArgument(diagnostic) => diagnostic.verbose_advices(visitor),
CliDiagnostic::EmptyArguments(diagnostic) => diagnostic.verbose_advices(visitor),
CliDiagnostic::IncompatibleArguments(diagnostic) => diagnostic.verbose_advices(visitor),
CliDiagnostic::CheckError(diagnostic) => diagnostic.verbose_advices(visitor),
CliDiagnostic::OverflowNumberArgument(diagnostic) => {
diagnostic.verbose_advices(visitor)
}
CliDiagnostic::WorkspaceError(diagnostic) => diagnostic.verbose_advices(visitor),
CliDiagnostic::IoError(diagnostic) => diagnostic.verbose_advices(visitor),
CliDiagnostic::ServerNotRunning(diagnostic) => diagnostic.verbose_advices(visitor),
CliDiagnostic::IncompatibleEndConfiguration(diagnostic) => {
diagnostic.verbose_advices(visitor)
}
CliDiagnostic::NoFilesWereProcessed(diagnostic) => diagnostic.verbose_advices(visitor),
CliDiagnostic::FileCheckApply(diagnostic) => diagnostic.verbose_advices(visitor),
CliDiagnostic::MigrateError(diagnostic) => diagnostic.verbose_advices(visitor),
CliDiagnostic::NoVcsFolderFound(diagnostic) => diagnostic.verbose_advices(visitor),
}
}
fn source(&self) -> Option<&dyn Diagnostic> {
match self {
CliDiagnostic::UnknownCommand(diagnostic) => diagnostic.source(),
CliDiagnostic::UnknownCommandHelp(diagnostic) => diagnostic.source(),
CliDiagnostic::ParseError(diagnostic) => diagnostic.source(),
CliDiagnostic::UnexpectedArgument(diagnostic) => diagnostic.source(),
CliDiagnostic::MissingArgument(diagnostic) => diagnostic.source(),
CliDiagnostic::EmptyArguments(diagnostic) => diagnostic.source(),
CliDiagnostic::IncompatibleArguments(diagnostic) => diagnostic.source(),
CliDiagnostic::CheckError(diagnostic) => diagnostic.source(),
CliDiagnostic::OverflowNumberArgument(diagnostic) => diagnostic.source(),
CliDiagnostic::WorkspaceError(diagnostic) => diagnostic.source(),
CliDiagnostic::IoError(diagnostic) => diagnostic.source(),
CliDiagnostic::ServerNotRunning(diagnostic) => diagnostic.source(),
CliDiagnostic::IncompatibleEndConfiguration(diagnostic) => diagnostic.source(),
CliDiagnostic::NoFilesWereProcessed(diagnostic) => diagnostic.source(),
CliDiagnostic::FileCheckApply(diagnostic) => diagnostic.source(),
CliDiagnostic::MigrateError(diagnostic) => diagnostic.source(),
CliDiagnostic::NoVcsFolderFound(diagnostic) => diagnostic.source(),
}
}
}
impl From<WorkspaceError> for CliDiagnostic {
fn from(error: WorkspaceError) -> Self {
CliDiagnostic::workspace_error(error)
}
}
impl From<std::io::Error> for CliDiagnostic {
fn from(error: std::io::Error) -> Self {
CliDiagnostic::io_error(error)
}
}
impl Termination for CliDiagnostic {
fn report(self) -> ExitCode {
let severity = self.severity();
if severity >= Severity::Error {
ExitCode::FAILURE
} else {
ExitCode::SUCCESS
}
}
}
#[cfg(test)]
mod test {
use crate::CliDiagnostic;
#[test]
fn termination_diagnostic_size() {
assert_eq!(
std::mem::size_of::<CliDiagnostic>(),
104,
"you successfully decreased the size of the diagnostic!"
)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/lib.rs | crates/rome_cli/src/lib.rs | #![doc = include_str!("../README.md")]
//!
//! # Module
//!
//! This is where the main CLI session starts. The module is responsible
//! to parse commands and arguments, redirect the execution of the commands and
//! execute the traversal of directory and files, based on the command that were passed.
use rome_console::{ColorMode, Console};
use rome_fs::OsFileSystem;
use rome_service::{App, DynRef, Workspace, WorkspaceRef};
use std::env;
mod cli_options;
mod commands;
mod configuration;
mod diagnostics;
mod execute;
mod metrics;
mod panic;
mod reports;
mod service;
mod vcs;
use crate::cli_options::ColorsArg;
use crate::commands::check::CheckCommandPayload;
use crate::commands::ci::CiCommandPayload;
use crate::commands::format::FormatCommandPayload;
use crate::commands::lint::LintCommandPayload;
pub use crate::commands::{rome_command, RomeCommand};
pub use diagnostics::CliDiagnostic;
pub(crate) use execute::{execute_mode, Execution, TraversalMode};
pub use panic::setup_panic_handler;
pub use reports::{
formatter::{FormatterReport, FormatterReportFileDetail, FormatterReportSummary},
Report, ReportDiagnostic, ReportDiff, ReportErrorKind, ReportKind,
};
pub use service::{open_transport, SocketTransport};
pub(crate) const VERSION: &str = match option_env!("ROME_VERSION") {
Some(version) => version,
None => env!("CARGO_PKG_VERSION"),
};
/// Global context for an execution of the CLI
pub struct CliSession<'app> {
/// Instance of [App] used by this run of the CLI
pub app: App<'app>,
}
impl<'app> CliSession<'app> {
pub fn new(
workspace: &'app dyn Workspace,
console: &'app mut dyn Console,
) -> Result<Self, CliDiagnostic> {
Ok(Self {
app: App::new(
DynRef::Owned(Box::new(OsFileSystem)),
console,
WorkspaceRef::Borrowed(workspace),
),
})
}
/// Main function to run Rome CLI
pub fn run(self, command: RomeCommand) -> Result<(), CliDiagnostic> {
let has_metrics = command.has_metrics();
if has_metrics {
crate::metrics::init_metrics();
}
let result = match command {
RomeCommand::Version(_) => commands::version::full_version(self),
RomeCommand::Rage(_) => commands::rage::rage(self),
RomeCommand::Start => commands::daemon::start(self),
RomeCommand::Stop => commands::daemon::stop(self),
RomeCommand::Check {
apply,
apply_unsafe,
cli_options,
configuration: rome_configuration,
paths,
stdin_file_path,
linter_enabled,
organize_imports_enabled,
formatter_enabled,
} => commands::check::check(
self,
CheckCommandPayload {
apply_unsafe,
apply,
cli_options,
configuration: rome_configuration,
paths,
stdin_file_path,
linter_enabled,
organize_imports_enabled,
formatter_enabled,
},
),
RomeCommand::Lint {
apply,
apply_unsafe,
cli_options,
configuration: rome_configuration,
paths,
stdin_file_path,
} => commands::lint::lint(
self,
LintCommandPayload {
apply_unsafe,
apply,
cli_options,
configuration: rome_configuration,
paths,
stdin_file_path,
},
),
RomeCommand::Ci {
linter_enabled,
formatter_enabled,
organize_imports_enabled,
configuration: rome_configuration,
paths,
cli_options,
} => commands::ci::ci(
self,
CiCommandPayload {
linter_enabled,
formatter_enabled,
organize_imports_enabled,
rome_configuration,
paths,
cli_options,
},
),
RomeCommand::Format {
javascript_formatter,
formatter_configuration,
stdin_file_path,
write,
cli_options,
paths,
vcs_configuration,
files_configuration,
} => commands::format::format(
self,
FormatCommandPayload {
javascript_formatter,
formatter_configuration,
stdin_file_path,
write,
cli_options,
paths,
vcs_configuration,
files_configuration,
},
),
RomeCommand::Init => commands::init::init(self),
RomeCommand::LspProxy(_) => commands::daemon::lsp_proxy(),
RomeCommand::Migrate(cli_options, write) => {
commands::migrate::migrate(self, cli_options, write)
}
RomeCommand::RunServer { stop_on_disconnect } => {
commands::daemon::run_server(stop_on_disconnect)
}
RomeCommand::PrintSocket => commands::daemon::print_socket(),
};
if has_metrics {
metrics::print_metrics();
}
result
}
}
pub fn to_color_mode(color: Option<&ColorsArg>) -> ColorMode {
match color {
Some(ColorsArg::Off) => ColorMode::Disabled,
Some(ColorsArg::Force) => ColorMode::Enabled,
None => ColorMode::Auto,
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/configuration.rs | crates/rome_cli/src/configuration.rs | use crate::cli_options::CliOptions;
use crate::{CliDiagnostic, CliSession};
use rome_console::{markup, Console, ConsoleExt};
use rome_deserialize::json::deserialize_from_json_str;
use rome_deserialize::Deserialized;
use rome_diagnostics::{DiagnosticExt, Error, PrintDiagnostic};
use rome_fs::{FileSystem, OpenOptions};
use rome_json_parser::JsonParserOptions;
use rome_service::configuration::diagnostics::CantLoadExtendFile;
use rome_service::configuration::ConfigurationPayload;
use rome_service::{
load_config, Configuration, ConfigurationBasePath, ConfigurationDiagnostic, DynRef, MergeWith,
WorkspaceError,
};
use std::path::PathBuf;
#[derive(Default)]
pub struct LoadedConfiguration {
pub(crate) directory_path: Option<PathBuf>,
pub(crate) file_path: Option<PathBuf>,
pub(crate) configuration: Configuration,
pub(crate) diagnostics: Vec<Error>,
}
impl LoadedConfiguration {
/// It updates the loaded configuration by resolving the `extends` field.
///
/// If a configuration can't be resolved from the file system, the operation will fail.
pub fn apply_extends(&mut self, fs: &DynRef<dyn FileSystem>) -> Result<(), WorkspaceError> {
let deserialized = self.deserialize_extends(fs)?;
let (configurations, errors): (Vec<_>, Vec<_>) =
deserialized.into_iter().map(|d| d.consume()).unzip();
for c in configurations {
self.configuration.merge_with(c);
}
self.diagnostics
.extend(errors.into_iter().flatten().collect::<Vec<_>>());
Ok(())
}
fn deserialize_extends(
&mut self,
fs: &DynRef<dyn FileSystem>,
) -> Result<Vec<Deserialized<Configuration>>, WorkspaceError> {
let Some(extends) = &self.configuration.extends else {
return Ok(vec![]);
};
let directory_path = self
.directory_path
.as_ref()
.cloned()
.unwrap_or(fs.working_directory().unwrap_or(PathBuf::from("./")));
let mut deserialized_configurations = vec![];
for path in extends.index_set() {
let config_path = directory_path.join(path);
let mut file = fs
.open_with_options(config_path.as_path(), OpenOptions::default().read(true))
.map_err(|err| {
CantLoadExtendFile::new(config_path.display().to_string(), err.to_string()).with_verbose_advice(
markup!{
"Rome tried to load the configuration file "<Emphasis>{directory_path.display().to_string()}</Emphasis>" using "<Emphasis>{config_path.display().to_string()}</Emphasis>" as base path."
}
)
})?;
let mut content = String::new();
file.read_to_string(&mut content).map_err(|err| {
CantLoadExtendFile::new(config_path.display().to_string(), err.to_string()).with_verbose_advice(
markup!{
"It's possible that the file was created with a different user/group. Make sure you have the rights to read the file."
}
)
})?;
let deserialized = deserialize_from_json_str::<Configuration>(
content.as_str(),
JsonParserOptions::default(),
);
deserialized_configurations.push(deserialized)
}
Ok(deserialized_configurations)
}
pub fn or_diagnostic(
self,
console: &mut dyn Console,
verbose: bool,
) -> Result<Self, CliDiagnostic> {
if !self.diagnostics.is_empty() {
for diagnostic in self.diagnostics {
let diagnostic = if let Some(file_path) = &self.file_path {
diagnostic.with_file_path(file_path.display().to_string())
} else {
diagnostic
};
console.error(markup! {
{if verbose { PrintDiagnostic::verbose(&diagnostic) } else { PrintDiagnostic::simple(&diagnostic) }}
})
}
return Err(CliDiagnostic::workspace_error(
WorkspaceError::Configuration(ConfigurationDiagnostic::invalid_configuration(
"Rome exited because the configuration resulted in errors. Please fix them.",
)),
));
}
Ok(self)
}
}
impl From<Option<ConfigurationPayload>> for LoadedConfiguration {
fn from(value: Option<ConfigurationPayload>) -> Self {
if let Some(value) = value {
let ConfigurationPayload {
configuration_directory_path,
configuration_file_path,
deserialized,
} = value;
let (configuration, diagnostics) = deserialized.consume();
LoadedConfiguration {
configuration,
diagnostics,
directory_path: Some(configuration_directory_path),
file_path: Some(configuration_file_path),
}
} else {
LoadedConfiguration::default()
}
}
}
/// Load the configuration for this session of the CLI, merging the content of
/// the `rome.json` file if it exists on disk with common command line options
pub(crate) fn load_configuration(
session: &mut CliSession,
cli_options: &CliOptions,
) -> Result<LoadedConfiguration, CliDiagnostic> {
let base_path = match &cli_options.config_path {
None => ConfigurationBasePath::default(),
Some(path) => ConfigurationBasePath::FromUser(PathBuf::from(path)),
};
let fs = &session.app.fs;
let config = load_config(fs, base_path)?;
let mut loaded_configuration = LoadedConfiguration::from(config);
loaded_configuration.apply_extends(fs)?;
Ok(loaded_configuration)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/panic.rs | crates/rome_cli/src/panic.rs | use std::{
fmt::Write,
panic::{set_hook, PanicInfo},
thread,
};
/// Installs a global panic handler to show a user-friendly error message
/// in case the CLI panics
pub fn setup_panic_handler() {
set_hook(Box::new(panic_handler))
}
fn panic_handler(info: &PanicInfo) {
// Buffer the error message to a string before printing it at once
// to prevent it from getting mixed with other errors if multiple threads
// panic at the same time
let mut error = String::new();
writeln!(error, "Rome encountered an unexpected error").unwrap();
writeln!(error).unwrap();
writeln!(error, "This is a bug in Rome, not an error in your code, and we would appreciate it if you could report it to https://github.com/rome/tools/issues/ along with the following information to help us fixing the issue:").unwrap();
writeln!(error).unwrap();
if let Some(location) = info.location() {
writeln!(error, "Source Location: {location}").unwrap();
}
if let Some(thread) = thread::current().name() {
writeln!(error, "Thread Name: {thread}").unwrap();
}
let payload = info.payload();
if let Some(msg) = payload.downcast_ref::<&'static str>() {
writeln!(error, "Message: {msg}").unwrap();
} else if let Some(msg) = payload.downcast_ref::<String>() {
writeln!(error, "Message: {msg}").unwrap();
}
// Write the panic to stderr
eprintln!("{error}");
// Write the panic to the log file, this is done last since the `tracing`
// infrastructure could panic a second time and abort the process, so we
// want to ensure the error has at least been logged to stderr beforehand
tracing::error!("{error}");
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/vcs.rs | crates/rome_cli/src/vcs.rs | use crate::cli_options::CliOptions;
use crate::diagnostics::{DisabledVcs, NoVcsFolderFound};
use crate::{CliDiagnostic, CliSession};
use rome_console::{markup, ConsoleExt};
use rome_deserialize::StringSet;
use rome_diagnostics::PrintDiagnostic;
use rome_service::configuration::vcs::{VcsClientKind, VcsConfiguration};
use rome_service::configuration::FilesConfiguration;
use rome_service::{Configuration, WorkspaceError};
use std::path::PathBuf;
/// This function will check if the configuration is set to use the VCS integration and try to
/// read the ignored files.
pub(crate) fn store_path_to_ignore_from_vcs(
session: &mut CliSession,
configuration: &mut Configuration,
vcs_base_path: Option<PathBuf>,
cli_options: &CliOptions,
) -> Result<(), CliDiagnostic> {
let Some(vcs) = &configuration.vcs else {
return Ok(())
};
if vcs.is_enabled() {
let vcs_base_path = match (vcs_base_path, &vcs.root) {
(Some(vcs_base_path), Some(root)) => vcs_base_path.join(root),
(None, Some(root)) => PathBuf::from(root),
(Some(vcs_base_path), None) => vcs_base_path,
(None, None) => {
let console = &mut session.app.console;
let diagnostic = DisabledVcs {};
console.error(markup! {
{if cli_options.verbose { PrintDiagnostic::verbose(&diagnostic) } else { PrintDiagnostic::simple(&diagnostic) }}
});
return Ok(());
}
};
let files_to_ignore = read_vcs_ignore_file(session, vcs_base_path, vcs)?;
if !files_to_ignore.is_empty() {
let files = configuration
.files
.get_or_insert_with(FilesConfiguration::default);
let ignored_files = files.ignore.get_or_insert_with(StringSet::default);
ignored_files.extend(files_to_ignore.into_iter());
}
}
Ok(())
}
pub(crate) fn read_vcs_ignore_file(
session: &mut CliSession,
current_directory: PathBuf,
configuration: &VcsConfiguration,
) -> Result<Vec<String>, CliDiagnostic> {
if !configuration.is_enabled() {
return Ok(vec![]);
}
let file_system = &session.app.fs;
if let Some(client_kind) = &configuration.client_kind {
match client_kind {
VcsClientKind::Git => {
let git_folder = current_directory.join(".git");
if !file_system.path_exists(git_folder.as_path()) {
return Err(CliDiagnostic::NoVcsFolderFound(NoVcsFolderFound {
path: git_folder.display().to_string(),
source: None,
}));
}
}
}
if !configuration.ignore_file_disabled() {
let result = file_system
.auto_search(current_directory, client_kind.ignore_file(), false)
.map_err(WorkspaceError::from)?;
if let Some(result) = result {
return Ok(result
.content
.lines()
// remove empty lines
.filter(|line| !line.is_empty())
.filter_map(|item| {
let line = item.to_string();
// remove comments
if !line.starts_with('#') {
Some(line)
} else {
None
}
})
.collect::<Vec<String>>());
}
}
}
Ok(vec![])
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/main.rs | crates/rome_cli/src/main.rs | //! This is the main binary of Rome.
//!
//! If you're curious about how to use it, check Rome's [website]
//!
//! [website]: https://rome.tools
use bpaf::{Args, ParseFailure};
use rome_cli::{
open_transport, rome_command, setup_panic_handler, to_color_mode, CliDiagnostic, CliSession,
RomeCommand,
};
use rome_console::{markup, ConsoleExt, EnvConsole};
use rome_diagnostics::{set_bottom_frame, PrintDiagnostic};
use rome_service::workspace;
use std::process::{ExitCode, Termination};
use tokio::runtime::Runtime;
#[cfg(target_os = "windows")]
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
#[cfg(not(target_os = "windows"))]
#[global_allocator]
static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
fn main() -> ExitCode {
setup_panic_handler();
set_bottom_frame(main as usize);
let mut console = EnvConsole::default();
let command = rome_command().run_inner(Args::current_args());
match command {
Ok(command) => {
let color_mode = to_color_mode(command.get_color());
console.set_color(color_mode);
let is_verbose = command.is_verbose();
let result = run_workspace(&mut console, command);
match result {
Err(termination) => {
console.error(markup! {
{if is_verbose { PrintDiagnostic::verbose(&termination) } else { PrintDiagnostic::simple(&termination) }}
});
termination.report()
}
Ok(_) => ExitCode::SUCCESS,
}
}
Err(failure) => {
return if let ParseFailure::Stdout(help, _) = &failure {
console.log(markup! {{help.to_string()}});
ExitCode::FAILURE
} else {
let diagnostic = CliDiagnostic::parse_error_bpaf(failure);
console.error(markup! { {PrintDiagnostic::simple(&diagnostic)}});
ExitCode::FAILURE
}
}
}
}
fn run_workspace(console: &mut EnvConsole, command: RomeCommand) -> Result<(), CliDiagnostic> {
// If the `--use-server` CLI flag is set, try to open a connection to an
// existing Rome server socket
let workspace = if command.should_use_server() {
let runtime = Runtime::new()?;
match open_transport(runtime)? {
Some(transport) => workspace::client(transport)?,
None => return Err(CliDiagnostic::server_not_running()),
}
} else {
workspace::server()
};
let session = CliSession::new(&*workspace, console)?;
session.run(command)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/metrics.rs | crates/rome_cli/src/metrics.rs | use std::{
borrow::Cow,
collections::HashMap,
hash::Hash,
ops::Sub,
ptr,
time::{Duration, Instant},
};
use hdrhistogram::Histogram;
use std::sync::{Mutex, RwLock};
use tracing::{span, subscriber::Interest, Level, Metadata, Subscriber};
use tracing_subscriber::{
layer::Context,
prelude::*,
registry::{LookupSpan, SpanRef},
Layer,
};
/// Implementation of a tracing [Layer] that collects timing information for spans into [Histogram]s
struct MetricsLayer;
lazy_static::lazy_static! {
/// Global storage for metrics data
static ref METRICS: RwLock<HashMap<CallsiteKey, Mutex<CallsiteEntry>>> = RwLock::default();
}
/// Static pointer to the metadata of a callsite, used as a unique identifier
/// for collecting spans created from there in the global metrics map
struct CallsiteKey(&'static Metadata<'static>);
impl PartialEq for CallsiteKey {
fn eq(&self, other: &Self) -> bool {
ptr::eq(self.0, other.0)
}
}
impl Eq for CallsiteKey {}
impl Hash for CallsiteKey {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
ptr::hash(self.0, state);
}
}
/// Single entry in the global callsite storage, containing handles to the
/// histograms associated with this callsite
enum CallsiteEntry {
/// Spans with the debug level only count their total duration
Debug { total: Histogram<u64> },
/// Spans with the trace level count their total duration as well as
/// individual busy and idle times
Trace {
total: Histogram<u64>,
busy: Histogram<u64>,
idle: Histogram<u64>,
},
}
impl CallsiteEntry {
fn from_level(level: &Level) -> Self {
/// Number of significant figures retained by the histogram
const SIGNIFICANT_FIGURES: u8 = 3;
match level {
&Level::TRACE => Self::Trace {
// SAFETY: Histogram::new only returns an error if the value of
// SIGNIFICANT_FIGURES is invalid, 3 is statically known to work
total: Histogram::new(SIGNIFICANT_FIGURES).unwrap(),
busy: Histogram::new(SIGNIFICANT_FIGURES).unwrap(),
idle: Histogram::new(SIGNIFICANT_FIGURES).unwrap(),
},
_ => Self::Debug {
total: Histogram::new(SIGNIFICANT_FIGURES).unwrap(),
},
}
}
fn into_histograms(self, name: &str) -> Vec<(Cow<str>, Histogram<u64>)> {
match self {
CallsiteEntry::Debug { total } => vec![(Cow::Borrowed(name), total)],
CallsiteEntry::Trace { total, busy, idle } => vec![
(Cow::Borrowed(name), total),
(Cow::Owned(format!("{name}.busy")), busy),
(Cow::Owned(format!("{name}.idle")), idle),
],
}
}
}
/// Extension data attached to tracing spans to keep track of their idle and busy time
///
/// Most of the associated code is based on the similar logic found in `tracing-subscriber`
/// for printing span timings to the console:
/// https://github.com/tokio-rs/tracing/blob/6f23c128fced6409008838a3223d76d7332d79e9/tracing-subscriber/src/fmt/fmt_subscriber.rs#L973
struct Timings<I = Instant> {
idle: u64,
busy: u64,
last: I,
}
trait Timepoint: Sub<Self, Output = Duration> + Copy + Sized {
fn now() -> Self;
}
impl Timepoint for Instant {
fn now() -> Self {
Instant::now()
}
}
impl<I: Timepoint> Timings<I> {
fn new() -> Self {
Self {
idle: 0,
busy: 0,
last: I::now(),
}
}
/// Count the time between the last update and now as idle
fn enter(&mut self, now: I) {
self.idle += (now - self.last).as_nanos() as u64;
self.last = now;
}
/// Count the time between the last update and now as busy
fn exit(&mut self, now: I) {
self.busy += (now - self.last).as_nanos() as u64;
self.last = now;
}
/// Exit the timing for this span, and record it into a callsite entry
fn record(mut self, now: I, entry: &mut CallsiteEntry) {
self.exit(now);
match entry {
CallsiteEntry::Debug { total } => {
total.record(self.busy + self.idle).unwrap();
}
CallsiteEntry::Trace { total, busy, idle } => {
busy.record(self.busy).unwrap();
idle.record(self.idle).unwrap();
total.record(self.busy + self.idle).unwrap();
}
}
}
}
fn read_span<'ctx, S>(ctx: &'ctx Context<'_, S>, id: &span::Id) -> SpanRef<'ctx, S>
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
ctx.span(id)
.expect("Span not found, it should have been stored in the registry")
}
impl<S> Layer<S> for MetricsLayer
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
/// Only express interest in span callsites, disabling collection of events,
/// and create new histogram for the spans created by this callsite
fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
if !metadata.is_span() {
return Interest::never();
}
let entry = CallsiteEntry::from_level(metadata.level());
METRICS
.write()
.unwrap()
.insert(CallsiteKey(metadata), Mutex::new(entry));
Interest::always()
}
/// When a new span is created, attach the timing data extension to it
fn on_new_span(&self, _attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
let span = read_span(&ctx, id);
let mut extensions = span.extensions_mut();
if extensions.get_mut::<Timings>().is_none() {
extensions.insert(Timings::<Instant>::new());
}
}
/// When a span is entered, start counting idle time for the parent span if
/// it exists and busy time for the entered span itself
fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
let span = read_span(&ctx, id);
let now = Instant::now();
if let Some(parent) = span.parent() {
let mut extensions = parent.extensions_mut();
if let Some(timings) = extensions.get_mut::<Timings>() {
// The parent span was busy until now
timings.exit(now);
}
}
let mut extensions = span.extensions_mut();
if let Some(timings) = extensions.get_mut::<Timings>() {
// The child span was idle until now
timings.enter(now);
}
}
/// When a span is exited, stop it from counting busy time and start
/// counting the parent as busy instead
fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
let span = read_span(&ctx, id);
let now = Instant::now();
let mut extensions = span.extensions_mut();
if let Some(timings) = extensions.get_mut::<Timings>() {
// Child span was busy until now
timings.exit(now);
}
// Re-enter parent
if let Some(parent) = span.parent() {
let mut extensions = parent.extensions_mut();
if let Some(timings) = extensions.get_mut::<Timings>() {
// Parent span was idle until now
timings.enter(now);
}
}
}
/// When a span is closed, extract its timing information and write it to
/// the associated histograms
fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
let span = read_span(&ctx, &id);
let mut extensions = span.extensions_mut();
if let Some(timing) = extensions.remove::<Timings>() {
let now = Instant::now();
// Acquire a read lock on the metrics storage, access the metrics entry
// associated with this call site and acquire a write lock on it
let metrics = METRICS.read().unwrap();
let entry = metrics
.get(&CallsiteKey(span.metadata()))
.expect("callsite not found, it should have been registered in register_callsite");
let mut entry = entry.lock().unwrap();
timing.record(now, &mut entry);
}
}
}
/// Initializes metrics recording
pub fn init_metrics() {
// Create and injects the metrics recording layer with the tracing library
tracing_subscriber::registry().with(MetricsLayer).init();
}
/// Flush and print the recorded metrics to the console
pub fn print_metrics() {
let mut write_guard = METRICS.write().unwrap();
let mut histograms: Vec<_> = write_guard
.drain()
.flat_map(|(key, entry)| entry.into_inner().unwrap().into_histograms(key.0.name()))
.collect();
histograms.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
for (key, histogram) in histograms {
// Print the header line for the histogram with its name, mean sample
// duration and standard deviation
println!(
"{}: mean = {:.1?}, stdev = {:.1?}",
key,
Duration::from_nanos(histogram.mean().round() as u64),
Duration::from_nanos(histogram.stdev().round() as u64),
);
// For each quantile bucket in the histogram print out the associated
// duration, a bar corresponding to the percentage of the total number
// of samples falling within this bucket and the percentile
// corresponding to this bucket
let total = histogram.len() as f64;
for v in histogram.iter_quantiles(1) {
let duration = Duration::from_nanos(v.value_iterated_to());
let count = v.count_since_last_iteration() as f64;
let bar_length = (count * 40.0 / total).ceil() as usize;
println!(
"{: >7.1?} | {:40} | {:5.1}%",
duration,
"*".repeat(bar_length),
v.quantile_iterated_to() * 100.0,
);
}
// Print an empty line after each histogram
println!();
}
}
#[cfg(test)]
mod tests {
use std::{ops::Sub, thread, time::Duration};
use tracing::Level;
use tracing_subscriber::prelude::*;
use super::{CallsiteEntry, CallsiteKey, MetricsLayer, Timepoint, Timings, METRICS};
#[derive(Clone, Copy)]
struct TestTime(u64);
impl Sub for TestTime {
type Output = Duration;
fn sub(self, rhs: Self) -> Self::Output {
Duration::from_nanos(self.0 - rhs.0)
}
}
impl Timepoint for TestTime {
fn now() -> Self {
Self(0)
}
}
#[test]
fn test_timing() {
let mut entry = CallsiteEntry::from_level(&Level::TRACE);
for i in 1..=5 {
let mut timing = Timings::<TestTime>::new();
timing.enter(TestTime(i));
timing.record(TestTime(i * 2), &mut entry);
}
let histograms = entry.into_histograms("test");
for (name, histogram) in histograms {
let scale = match name.as_ref() {
"test" => 2.0,
"test.idle" | "test.busy" => 1.0,
_ => unreachable!(),
};
let sample_count = 5;
assert_eq!(histogram.len(), sample_count);
let mean = 3.0 * scale;
assert_eq!(histogram.mean(), mean);
let sum = (1..=5).fold(0.0, |sum, i| {
let sample = i as f64 * scale;
sum + (sample - mean).powi(2)
});
let stddev = (sum / sample_count as f64).sqrt();
assert_eq!(histogram.stdev(), stddev);
let s = scale as u64 - 1;
let expected_buckets = [
(0, s, 0.0),
(1, 2 * s + 1, 0.2),
(1, 3 * s + 2, 0.4),
(1, 4 * s + 3, 0.6),
(1, 5 * s + 4, 0.8),
(1, 6 * s + 5, 1.0),
];
for (bucket, expected) in histogram.iter_linear(scale as u64).zip(&expected_buckets) {
let (count, value, quantile) = *expected;
assert_eq!(bucket.count_since_last_iteration(), count);
assert_eq!(bucket.value_iterated_to(), value);
assert_eq!(bucket.quantile_iterated_to(), quantile);
}
}
}
#[test]
fn test_layer() {
let _guard = tracing_subscriber::registry()
.with(MetricsLayer)
.set_default();
let key = {
let span = tracing::trace_span!("test_layer");
span.in_scope(|| {
thread::sleep(Duration::from_millis(1));
});
span.metadata().expect("span is disabled")
};
let entry = {
let mut metrics = METRICS.write().unwrap();
metrics.remove(&CallsiteKey(key))
};
let entry = entry.expect("callsite does not exist in metrics storage");
let entry = entry.into_inner().unwrap();
let histograms = entry.into_histograms(key.name());
for (_, histogram) in histograms {
assert_eq!(histogram.len(), 1);
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/cli_options.rs | crates/rome_cli/src/cli_options.rs | use bpaf::Bpaf;
use std::str::FromStr;
/// Global options applied to all commands
#[derive(Debug, Clone, Bpaf)]
pub struct CliOptions {
/// Set the formatting mode for markup: "off" prints everything as plain text, "force" forces the formatting of markup using ANSI even if the console output is determined to be incompatible
#[bpaf(long("colors"), argument("off|force"))]
pub colors: Option<ColorsArg>,
/// Connect to a running instance of the Rome daemon server.
#[bpaf(long("use-server"), switch, fallback(false))]
pub use_server: bool,
/// Print additional verbose advices on diagnostics
#[bpaf(long("verbose"), switch, fallback(false))]
pub verbose: bool,
/// Set the filesystem path to the directory of the rome.json configuration file
#[bpaf(long("config-path"), argument("PATH"), optional)]
pub config_path: Option<String>,
/// Cap the amount of diagnostics displayed.
#[bpaf(
long("max-diagnostics"),
argument("NUMBER"),
fallback(20),
display_fallback
)]
pub max_diagnostics: u16,
/// Skip over files containing syntax errors instead of emitting an error diagnostic.
#[bpaf(long("skip-errors"), switch)]
pub skip_errors: bool,
/// Silence errors that would be emitted in case no files were processed during the execution of the command.
#[bpaf(long("no-errors-on-unmatched"), switch)]
pub no_errors_on_unmatched: bool,
/// Tell Rome to exit with an error code if some diagnostics emit warnings.
#[bpaf(long("error-on-warnings"), switch)]
pub error_on_warnings: bool,
/// Reports information using the JSON format
#[bpaf(long("json"), switch, hide_usage)]
pub json: bool,
}
#[derive(Debug, Clone)]
pub enum ColorsArg {
Off,
Force,
}
impl FromStr for ColorsArg {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"off" => Ok(Self::Off),
"force" => Ok(Self::Force),
_ => Err(format!(
"value {s:?} is not valid for the --colors argument"
)),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/service/unix.rs | crates/rome_cli/src/service/unix.rs | use std::{
convert::Infallible,
env, fs,
io::{self, ErrorKind},
path::PathBuf,
time::Duration,
};
use rome_lsp::{ServerConnection, ServerFactory};
use tokio::{
io::Interest,
net::{
unix::{OwnedReadHalf, OwnedWriteHalf},
UnixListener, UnixStream,
},
process::{Child, Command},
time,
};
use tracing::{debug, info, Instrument};
/// Returns the filesystem path of the global socket used to communicate with
/// the server daemon
fn get_socket_name() -> PathBuf {
env::temp_dir().join(format!("rome-socket-{}", rome_service::VERSION))
}
pub(crate) fn enumerate_pipes() -> io::Result<impl Iterator<Item = String>> {
fs::read_dir(env::temp_dir()).map(|iter| {
iter.filter_map(|entry| {
let entry = entry.ok()?.path();
let file_name = entry.file_name()?;
let file_name = file_name.to_str()?;
let rome_version = file_name.strip_prefix("rome-socket")?;
if rome_version.is_empty() {
Some(String::new())
} else {
Some(rome_version.strip_prefix('-')?.to_string())
}
})
})
}
/// Try to connect to the global socket and wait for the connection to become ready
async fn try_connect() -> io::Result<UnixStream> {
let socket_name = get_socket_name();
info!("Trying to connect to socket {}", socket_name.display());
let stream = UnixStream::connect(socket_name).await?;
stream
.ready(Interest::READABLE | Interest::WRITABLE)
.await?;
Ok(stream)
}
/// Spawn the daemon server process in the background
fn spawn_daemon(stop_on_disconnect: bool) -> io::Result<Child> {
let binary = env::current_exe()?;
let mut cmd = Command::new(binary);
debug!("command {:?}", &cmd);
cmd.arg("__run_server");
if stop_on_disconnect {
cmd.arg("--stop-on-disconnect");
}
// Create a new session for the process and make it the leader, this will
// ensures that the child process is fully detached from its parent and will
// continue running in the background even after the parent process exits
//
// SAFETY: This closure runs in the forked child process before it starts
// executing, this is a highly unsafe environment because the process isn't
// running yet so seemingly innocuous operation like allocating memory may
// hang indefinitely.
// The only thing we do here is issuing a syscall, which is safe to do in
// this state but still "unsafe" in Rust semantics because it's technically
// mutating the shared global state of the process
unsafe {
cmd.pre_exec(|| {
libc::setsid();
Ok(())
});
}
let child = cmd.spawn()?;
Ok(child)
}
/// Open a connection to the daemon server process, returning [None] if the
/// server is not running
pub(crate) async fn open_socket() -> io::Result<Option<(OwnedReadHalf, OwnedWriteHalf)>> {
match try_connect().await {
Ok(socket) => Ok(Some(socket.into_split())),
Err(err)
// The OS will return `ConnectionRefused` if the socket file exists
// but no server process is listening on it
if matches!(
err.kind(),
ErrorKind::NotFound | ErrorKind::ConnectionRefused
) =>
{
Ok(None)
}
Err(err) => Err(err),
}
}
/// Ensure the server daemon is running and ready to receive connections
///
/// Returns false if the daemon process was already running or true if it had
/// to be started
pub(crate) async fn ensure_daemon(stop_on_disconnect: bool) -> io::Result<bool> {
let mut current_child: Option<Child> = None;
let mut last_error = None;
// Try to initialize the connection a few times
for _ in 0..10 {
// Try to open a connection on the global socket
match try_connect().await {
// The connection is open and ready
Ok(_) => {
return Ok(current_child.is_some());
}
// There's no process listening on the global socket
Err(err)
if matches!(
err.kind(),
ErrorKind::NotFound | ErrorKind::ConnectionRefused
) =>
{
last_error = Some(err);
if let Some(current_child) = &mut current_child {
// If we have a handle to the daemon process, wait for a few
// milliseconds for it to exit, or retry the connection
tokio::select! {
result = current_child.wait() => {
let _status = result?;
return Err(io::Error::new(
io::ErrorKind::ConnectionReset,
"the server process exited before the connection could be established",
));
}
_ = time::sleep(Duration::from_millis(50)) => {}
}
} else {
// Spawn the daemon process and wait a few milliseconds for
// it to become ready then retry the connection
current_child = Some(spawn_daemon(stop_on_disconnect)?);
time::sleep(Duration::from_millis(50)).await;
}
}
Err(err) => return Err(err),
}
}
// If the connection couldn't be opened after 10 tries fail with the last
// error message from the OS, or a generic error message otherwise
Err(last_error.unwrap_or_else(|| {
io::Error::new(
io::ErrorKind::Other,
"could not connect to the daemon socket",
)
}))
}
/// Ensure the server daemon is running and ready to receive connections and
/// print the global socket name in the standard output
pub(crate) async fn print_socket() -> io::Result<()> {
ensure_daemon(true).await?;
println!("{}", get_socket_name().display());
Ok(())
}
/// Start listening on the global socket and accepting connections with the
/// provided [ServerFactory]
pub(crate) async fn run_daemon(factory: ServerFactory) -> io::Result<Infallible> {
let path = get_socket_name();
info!("Trying to connect to socket {}", path.display());
// Try to remove the socket file if it already exists
if path.exists() {
info!("Remove socket folder {}", path.display());
fs::remove_file(&path)?;
}
let listener = UnixListener::bind(path)?;
loop {
let (stream, _) = listener.accept().await?;
let connection = factory.create();
let span = tracing::trace_span!("run_server");
tokio::spawn(run_server(connection, stream).instrument(span.or_current()));
}
}
/// Async task driving a single client connection
async fn run_server(connection: ServerConnection, stream: UnixStream) {
let (read, write) = stream.into_split();
connection.accept(read, write).await;
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/service/windows.rs | crates/rome_cli/src/service/windows.rs | use std::{
convert::Infallible,
env,
fs::read_dir,
io::{self, ErrorKind},
mem::swap,
os::windows::process::CommandExt,
pin::Pin,
process::Command,
sync::Arc,
task::{Context, Poll},
time::Duration,
};
use rome_lsp::{ServerConnection, ServerFactory};
use tokio::{
io::{AsyncRead, AsyncWrite, ReadBuf},
net::windows::named_pipe::{ClientOptions, NamedPipeClient, NamedPipeServer, ServerOptions},
time,
};
use tracing::Instrument;
/// Returns the name of the global named pipe used to communicate with the
/// server daemon
fn get_pipe_name() -> String {
format!(r"\\.\pipe\rome-service-{}", rome_service::VERSION)
}
pub(crate) fn enumerate_pipes() -> io::Result<impl Iterator<Item = String>> {
read_dir(r"\\.\pipe").map(|iter| {
iter.filter_map(|entry| {
let entry = entry.ok()?.path();
let file_name = entry.file_name()?;
let file_name = file_name.to_str()?;
let rome_version = file_name.strip_prefix("rome-service")?;
if rome_version.is_empty() {
Some(String::new())
} else {
Some(rome_version.strip_prefix('-')?.to_string())
}
})
})
}
/// Error code from the Win32 API
const ERROR_PIPE_BUSY: i32 = 231;
/// Try to connect to the global pipe and wait for the connection to become ready
async fn try_connect() -> io::Result<NamedPipeClient> {
loop {
match ClientOptions::new().open(get_pipe_name()) {
Ok(client) => return Ok(client),
// If the connection failed with ERROR_PIPE_BUSY, wait a few
// milliseconds then retry the connection (we should be using
// WaitNamedPipe here but that's not exposed by tokio / mio)
Err(e) if e.raw_os_error() == Some(ERROR_PIPE_BUSY) => {}
Err(e) => return Err(e),
}
time::sleep(Duration::from_millis(50)).await;
}
}
/// Process creationg flag from the Win32 API, ensures the process is created
/// in its own group and will not be killed when the parent process exits
const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
/// Spawn the daemon server process in the background
fn spawn_daemon(stop_on_disconnect: bool) -> io::Result<()> {
let binary = env::current_exe()?;
let mut cmd = Command::new(binary);
cmd.arg("__run_server");
if stop_on_disconnect {
cmd.arg("--stop-on-disconnect");
}
cmd.creation_flags(CREATE_NEW_PROCESS_GROUP);
cmd.spawn()?;
Ok(())
}
/// Open a connection to the daemon server process, returning [None] if the
/// server is not running
pub(crate) async fn open_socket() -> io::Result<Option<(ClientReadHalf, ClientWriteHalf)>> {
match try_connect().await {
Ok(socket) => {
let inner = Arc::new(socket);
Ok(Some((
ClientReadHalf {
inner: inner.clone(),
},
ClientWriteHalf { inner },
)))
}
Err(err) if err.kind() == ErrorKind::NotFound => Ok(None),
Err(err) => Err(err),
}
}
pub(crate) struct ClientReadHalf {
inner: Arc<NamedPipeClient>,
}
impl AsyncRead for ClientReadHalf {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
loop {
match self.inner.poll_read_ready(cx) {
Poll::Ready(Ok(())) => match self.inner.try_read(buf.initialize_unfilled()) {
Ok(count) => {
buf.advance(count);
return Poll::Ready(Ok(()));
}
Err(err) if err.kind() == io::ErrorKind::WouldBlock => continue,
Err(err) => return Poll::Ready(Err(err)),
},
Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
Poll::Pending => return Poll::Pending,
};
}
}
}
pub(crate) struct ClientWriteHalf {
inner: Arc<NamedPipeClient>,
}
impl AsyncWrite for ClientWriteHalf {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, io::Error>> {
loop {
match self.inner.poll_write_ready(cx) {
Poll::Ready(Ok(())) => match self.inner.try_write(buf) {
Ok(count) => return Poll::Ready(Ok(count)),
Err(err) if err.kind() == io::ErrorKind::WouldBlock => continue,
Err(err) => return Poll::Ready(Err(err)),
},
Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
Poll::Pending => return Poll::Pending,
}
}
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
Poll::Ready(Ok(()))
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
self.poll_flush(cx)
}
}
/// Ensure the server daemon is running and ready to receive connections
///
/// Returns false if the daemon process was already running or true if it had
/// to be started
pub(crate) async fn ensure_daemon(stop_on_disconnect: bool) -> io::Result<bool> {
let mut did_spawn = false;
loop {
match open_socket().await {
Ok(Some(_)) => break,
Ok(None) => {
spawn_daemon(stop_on_disconnect)?;
did_spawn = true;
time::sleep(Duration::from_millis(50)).await;
}
Err(err) => return Err(err),
}
}
Ok(did_spawn)
}
/// Ensure the server daemon is running and ready to receive connections and
/// print the global pipe name in the standard output
pub(crate) async fn print_socket() -> io::Result<()> {
ensure_daemon(true).await?;
println!("{}", get_pipe_name());
Ok(())
}
/// Start listening on the global pipe and accepting connections with the
/// provided [ServerFactory]
pub(crate) async fn run_daemon(factory: ServerFactory) -> io::Result<Infallible> {
let mut prev_server = ServerOptions::new()
.first_pipe_instance(true)
.create(get_pipe_name())?;
loop {
prev_server.connect().await?;
let mut next_server = ServerOptions::new().create(get_pipe_name())?;
swap(&mut prev_server, &mut next_server);
let connection = factory.create();
let span = tracing::trace_span!("run_server");
tokio::spawn(run_server(connection, next_server).instrument(span.or_current()));
}
}
/// Async task driving a single client connection
async fn run_server(connection: ServerConnection, stream: NamedPipeServer) {
let inner = Arc::new(stream);
let read = ServerReadHalf {
inner: inner.clone(),
};
let write = ServerWriteHalf { inner };
connection.accept(read, write).await;
}
struct ServerReadHalf {
inner: Arc<NamedPipeServer>,
}
impl AsyncRead for ServerReadHalf {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
loop {
match self.inner.poll_read_ready(cx) {
Poll::Ready(Ok(())) => match self.inner.try_read(buf.initialize_unfilled()) {
Ok(count) => {
buf.advance(count);
return Poll::Ready(Ok(()));
}
Err(err) if err.kind() == io::ErrorKind::WouldBlock => continue,
Err(err) => return Poll::Ready(Err(err)),
},
Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
Poll::Pending => return Poll::Pending,
};
}
}
}
struct ServerWriteHalf {
inner: Arc<NamedPipeServer>,
}
impl AsyncWrite for ServerWriteHalf {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, io::Error>> {
loop {
match self.inner.poll_write_ready(cx) {
Poll::Ready(Ok(())) => match self.inner.try_write(buf) {
Ok(count) => return Poll::Ready(Ok(count)),
Err(err) if err.kind() == io::ErrorKind::WouldBlock => continue,
Err(err) => return Poll::Ready(Err(err)),
},
Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
Poll::Pending => return Poll::Pending,
}
}
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
Poll::Ready(Ok(()))
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
self.poll_flush(cx)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/service/mod.rs | crates/rome_cli/src/service/mod.rs | //! Implements the OS dependent transport layer for the server protocol. This
//! uses a domain socket created in the global temporary directory on Unix
//! systems, and a named pipe on Windows. The protocol used for message frames
//! is based on the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#baseProtocol),
//! a simplified derivative of the HTTP protocol
use std::{
any::type_name,
borrow::Cow,
io,
ops::Deref,
panic::RefUnwindSafe,
str::{from_utf8, FromStr},
sync::Arc,
time::Duration,
};
use anyhow::{bail, ensure, Context, Error};
use dashmap::DashMap;
use rome_service::{
workspace::{TransportRequest, WorkspaceTransport},
TransportError,
};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::{
from_slice, from_str, to_vec,
value::{to_raw_value, RawValue},
Value,
};
use tokio::{
io::{
AsyncBufRead, AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt,
BufReader, BufWriter,
},
runtime::Runtime,
sync::{
mpsc::{channel, Receiver, Sender},
oneshot, Notify,
},
time::sleep,
};
#[cfg(windows)]
mod windows;
#[cfg(windows)]
pub(crate) use self::windows::{
ensure_daemon, enumerate_pipes, open_socket, print_socket, run_daemon,
};
#[cfg(unix)]
mod unix;
#[cfg(unix)]
pub(crate) use self::unix::{
ensure_daemon, enumerate_pipes, open_socket, print_socket, run_daemon,
};
/// Tries to open a connection to a running daemon instance, returning a
/// [WorkspaceTransport] instance if the socket is currently active
pub fn open_transport(runtime: Runtime) -> io::Result<Option<impl WorkspaceTransport>> {
match runtime.block_on(open_socket()) {
Ok(Some((read, write))) => Ok(Some(SocketTransport::open(runtime, read, write))),
Ok(None) => Ok(None),
Err(err) => Err(err),
}
}
type JsonRpcResult = Result<Box<RawValue>, TransportError>;
/// Implementation of [WorkspaceTransport] for types implementing [AsyncRead]
/// and [AsyncWrite]
///
/// This structs holds an instance of the `tokio` runtime, as well as the
/// following fields:
/// - `write_send` is a sender handle to the "write channel", an MPSC channel
/// that's used to queue up requests to be sent to the server (for simplicity
/// the requests are pushed to the channel as serialized byte buffers)
/// - `pending_requests` is handle to a shared hashmap where the keys are `u64`
/// corresponding to request IDs, and the values are sender handles to oneshot
/// channel instances that can be consumed to fullfill the associated request
///
/// Creating a new `SocketTransport` instance requires providing a `tokio`
/// runtime instance as well as the "read half" and "write half" of the socket
/// object to be used by this transport instance. These two objects implement
/// [AsyncRead] and [AsyncWrite] respectively, and should generally map to the
/// same underlying I/O object but are represented as separate so they can be
/// used concurrently
///
/// This concurrent handling of I/O is implemented useing two "background tasks":
/// - the `write_task` pulls outgoing messages from the "write channel" and
/// writes them to the "write half" of the socket
/// - the `read_task` reads incoming messages from the "read half" of the
/// - the `read_task` reads incoming messages from the "read half" of the
/// socket, then looks up a request with an ID corresponding to the received
/// message in the "pending requests" map. If a pending request is found, it's
/// fulfilled with the content of the message that was just received
///
/// In addition to these, a new "foreground task" is created for each request.
/// Each foreground task creates a oneshot channel and stores it in the pending
/// requests map using the request ID as a key, then serialize the content of
/// the request and send it over the write channel. Finally, the task blocks
/// the current thread until a response is received over the oneshot channel
/// from the read task, or the request times out
pub struct SocketTransport {
runtime: Runtime,
write_send: Sender<(Vec<u8>, bool)>,
pending_requests: PendingRequests,
}
/// Stores a handle to the map of pending requests, and clears the map
/// automatically when the handle is dropped
#[derive(Clone, Default)]
struct PendingRequests {
inner: Arc<DashMap<u64, oneshot::Sender<JsonRpcResult>>>,
}
impl Deref for PendingRequests {
type Target = DashMap<u64, oneshot::Sender<JsonRpcResult>>;
fn deref(&self) -> &Self::Target {
self.inner.as_ref()
}
}
/// There are two live handles to the pending requests map: one is in the
/// `SocketTransport` and the other in the `read_task`. The `SocketTransport`
/// instance can only be dropped if it's empty (since the `request` method
/// blocks until the request is resolved, `&self` will always outlive any
/// pending request), but the `read_task` may abort if it encounters an error
/// or receives a shutdown broadcast while there are still pending requests. In
/// this case the `Drop` implementation will ensure that all pending requests
/// are cancelled immediately instead of timing out.
impl Drop for PendingRequests {
fn drop(&mut self) {
self.inner.clear();
}
}
impl SocketTransport {
pub fn open<R, W>(runtime: Runtime, socket_read: R, socket_write: W) -> Self
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
/// Capacity of the "write channel", once this many requests have been
/// queued up, calls to `write_send.send` will block the sending task
/// until enough capacity is available again
///
/// Note that this does not limit how many requests can be in flight at
/// a given time, it only serves as a loose rate-limit on how many new
/// requests can be sent to the server within a given time frame
const WRITE_CHANNEL_CAPACITY: usize = 16;
let (write_send, write_recv) = channel(WRITE_CHANNEL_CAPACITY);
let pending_requests = PendingRequests::default();
let pending_requests_2 = pending_requests.clone();
let socket_read = BufReader::new(socket_read);
let socket_write = BufWriter::new(socket_write);
let broadcast_shutdown = Arc::new(Notify::new());
runtime.spawn(write_task(
broadcast_shutdown.clone(),
write_recv,
socket_write,
));
runtime.spawn(async move {
tokio::select! {
_ = read_task(socket_read, &pending_requests) => {}
_ = broadcast_shutdown.notified() => {}
}
});
Self {
runtime,
write_send,
pending_requests: pending_requests_2,
}
}
}
// Allow the socket to be recovered across panic boundaries
impl RefUnwindSafe for SocketTransport {}
impl WorkspaceTransport for SocketTransport {
fn request<P, R>(&self, request: TransportRequest<P>) -> Result<R, TransportError>
where
P: Serialize,
R: DeserializeOwned,
{
let (send, recv) = oneshot::channel();
self.pending_requests.insert(request.id, send);
let is_shutdown = request.method == "rome/shutdown";
let request = JsonRpcRequest {
jsonrpc: Cow::Borrowed("2.0"),
id: request.id,
method: Cow::Borrowed(request.method),
params: request.params,
};
let request = to_vec(&request).map_err(|err| {
TransportError::SerdeError(format!(
"failed to serialize {} into byte buffer: {err}",
type_name::<P>()
))
})?;
let response = self.runtime.block_on(async move {
self.write_send
.send((request, is_shutdown))
.await
.map_err(|_| TransportError::ChannelClosed)?;
tokio::select! {
result = recv => {
match result {
Ok(Ok(response)) => Ok(response),
Ok(Err(error)) => Err(error),
Err(_) => Err(TransportError::ChannelClosed),
}
}
_ = sleep(Duration::from_secs(15)) => {
Err(TransportError::Timeout)
}
}
})?;
let response = response.get();
let result = from_str(response).map_err(|err| {
TransportError::SerdeError(format!(
"failed to deserialize {} from {response:?}: {err}",
type_name::<R>()
))
})?;
Ok(result)
}
}
async fn read_task<R>(mut socket_read: BufReader<R>, pending_requests: &PendingRequests)
where
R: AsyncRead + Unpin,
{
loop {
let message = read_message(&mut socket_read).await;
let message = match message {
Ok(message) => {
let response = from_slice(&message).with_context(|| {
if let Ok(message) = from_utf8(&message) {
format!("failed to deserialize JSON-RPC response from {message:?}")
} else {
format!("failed to deserialize JSON-RPC response from {message:?}")
}
});
response.map(|response| (message, response))
}
Err(err) => Err(err),
};
let (message, response): (_, JsonRpcResponse) = match message {
Ok(message) => message,
Err(err) => {
eprintln!(
"{:?}",
err.context("remote connection read task exited with an error")
);
break;
}
};
if let Some((_, channel)) = pending_requests.remove(&response.id) {
let response = match (response.result, response.error) {
(Some(result), None) => Ok(result),
(None, Some(err)) => Err(TransportError::RPCError(err.message)),
// Both result and error will be None if the request
// returns a null-ish result, in this case create a
// "null" RawValue as the result
//
// SAFETY: Calling `to_raw_value` with a static "null"
// JSON Value will always succeed
(None, None) => Ok(to_raw_value(&Value::Null).unwrap()),
_ => {
let message = if let Ok(message) = from_utf8(&message) {
format!("invalid response {message:?}")
} else {
format!("invalid response {message:?}")
};
Err(TransportError::SerdeError(message))
}
};
channel.send(response).ok();
}
}
}
async fn read_message<R>(mut socket_read: R) -> Result<Vec<u8>, Error>
where
R: AsyncBufRead + Unpin,
{
let mut length = None;
let mut line = String::new();
loop {
match socket_read
.read_line(&mut line)
.await
.context("failed to read header line from the socket")?
{
// A read of 0 bytes means the connection was closed
0 => {
bail!("the connection to the remote workspace was unexpectedly closed");
}
// A read of two bytes corresponds to the "\r\n" sequence
// that indicates the end of the header section
2 => {
if line != "\r\n" {
bail!("unexpected byte sequence received from the remote workspace, got {line:?} expected \"\\r\\n\"");
}
break;
}
_ => {
let header: TransportHeader = line
.parse()
.context("failed to parse header from the remote workspace")?;
match header {
TransportHeader::ContentLength(value) => {
length = Some(value);
}
TransportHeader::ContentType => {}
TransportHeader::Unknown(name) => {
eprintln!("ignoring unknown header {name:?}");
}
}
line.clear();
}
}
}
let length = length.context(
"incoming response from the remote workspace is missing the Content-Length header",
)?;
let mut result = vec![0u8; length];
socket_read
.read_exact(&mut result)
.await
.with_context(|| format!("failed to read message of {length} bytes from the socket"))?;
Ok(result)
}
async fn write_task<W>(
broadcast_shutdown: Arc<Notify>,
mut write_recv: Receiver<(Vec<u8>, bool)>,
mut socket_write: BufWriter<W>,
) where
W: AsyncWrite + Unpin,
{
while let Some((message, is_shutdown)) = write_recv.recv().await {
if is_shutdown {
broadcast_shutdown.notify_waiters();
}
if let Err(err) = write_message(&mut socket_write, message).await {
eprintln!(
"{:?}",
err.context("remote connection write task exited with an error")
);
break;
}
if is_shutdown {
break;
}
}
}
async fn write_message<W>(mut socket_write: W, message: Vec<u8>) -> Result<(), Error>
where
W: AsyncWrite + Unpin,
{
socket_write.write_all(b"Content-Length: ").await?;
let length = message.len().to_string();
socket_write.write_all(length.as_bytes()).await?;
socket_write.write_all(b"\r\n").await?;
socket_write
.write_all(b"Content-Type: application/vscode-jsonrpc; charset=utf-8\r\n")
.await?;
socket_write.write_all(b"\r\n").await?;
socket_write.write_all(&message).await?;
socket_write.flush().await?;
Ok(())
}
#[derive(Debug, Serialize)]
struct JsonRpcRequest<P> {
jsonrpc: Cow<'static, str>,
id: u64,
method: Cow<'static, str>,
params: P,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct JsonRpcResponse {
#[allow(dead_code)]
jsonrpc: Cow<'static, str>,
id: u64,
result: Option<Box<RawValue>>,
error: Option<JsonRpcError>,
}
#[derive(Debug, Deserialize)]
struct JsonRpcError {
#[allow(dead_code)]
code: i64,
message: String,
#[allow(dead_code)]
data: Option<Box<RawValue>>,
}
enum TransportHeader {
ContentLength(usize),
ContentType,
Unknown(String),
}
impl FromStr for TransportHeader {
type Err = Error;
fn from_str(line: &str) -> Result<Self, Self::Err> {
let colon = line
.find(':')
.with_context(|| format!("could not find colon token in {line:?}"))?;
let (name, value) = line.split_at(colon);
let value = value[1..].trim();
match name {
"Content-Length" => {
let value = value.parse().with_context(|| {
format!("could not parse Content-Length header value {value:?}")
})?;
Ok(TransportHeader::ContentLength(value))
}
"Content-Type" => {
ensure!(
value.starts_with( "application/vscode-jsonrpc"),
"invalid value for Content-Type expected \"application/vscode-jsonrpc\", got {value:?}"
);
Ok(TransportHeader::ContentType)
}
_ => Ok(TransportHeader::Unknown(name.into())),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/commands/ci.rs | crates/rome_cli/src/commands/ci.rs | use crate::cli_options::CliOptions;
use crate::configuration::LoadedConfiguration;
use crate::vcs::store_path_to_ignore_from_vcs;
use crate::{
configuration::load_configuration, execute_mode, CliDiagnostic, CliSession, Execution,
TraversalMode,
};
use rome_service::configuration::organize_imports::OrganizeImports;
use rome_service::configuration::{FormatterConfiguration, LinterConfiguration};
use rome_service::workspace::UpdateSettingsParams;
use rome_service::{Configuration, MergeWith};
use std::ffi::OsString;
pub(crate) struct CiCommandPayload {
pub(crate) formatter_enabled: Option<bool>,
pub(crate) linter_enabled: Option<bool>,
pub(crate) organize_imports_enabled: Option<bool>,
pub(crate) paths: Vec<OsString>,
pub(crate) rome_configuration: Configuration,
pub(crate) cli_options: CliOptions,
}
/// Handler for the "ci" command of the Rome CLI
pub(crate) fn ci(mut session: CliSession, payload: CiCommandPayload) -> Result<(), CliDiagnostic> {
let LoadedConfiguration {
mut configuration,
directory_path: configuration_path,
..
} = load_configuration(&mut session, &payload.cli_options)?
.or_diagnostic(session.app.console, payload.cli_options.verbose)?;
let formatter = configuration
.formatter
.get_or_insert_with(FormatterConfiguration::default);
if !matches!(payload.formatter_enabled, None) {
formatter.enabled = payload.formatter_enabled;
}
let linter = configuration
.linter
.get_or_insert_with(LinterConfiguration::default);
if !matches!(payload.linter_enabled, None) {
linter.enabled = payload.linter_enabled;
}
let organize_imports = configuration
.organize_imports
.get_or_insert_with(OrganizeImports::default);
if !matches!(payload.organize_imports_enabled, None) {
organize_imports.enabled = payload.organize_imports_enabled;
}
// no point in doing the traversal if all the checks have been disabled
if configuration.is_formatter_disabled()
&& configuration.is_linter_disabled()
&& configuration.is_organize_imports_disabled()
{
return Err(CliDiagnostic::incompatible_end_configuration("Formatter, linter and organize imports are disabled, can't perform the command. This is probably and error."));
}
configuration.merge_with(payload.rome_configuration.files);
configuration.merge_with(payload.rome_configuration.vcs);
configuration.merge_with_if(
payload.rome_configuration.formatter,
!configuration.is_formatter_disabled(),
);
configuration.merge_with_if(
payload.rome_configuration.organize_imports,
!configuration.is_organize_imports_disabled(),
);
// check if support of git ignore files is enabled
let vcs_base_path = configuration_path.or(session.app.fs.working_directory());
store_path_to_ignore_from_vcs(
&mut session,
&mut configuration,
vcs_base_path,
&payload.cli_options,
)?;
session
.app
.workspace
.update_settings(UpdateSettingsParams { configuration })?;
execute_mode(
Execution::new(TraversalMode::CI),
session,
&payload.cli_options,
payload.paths,
)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/commands/version.rs | crates/rome_cli/src/commands/version.rs | use rome_console::fmt::Formatter;
use rome_console::{fmt, markup, ConsoleExt};
use rome_service::workspace::ServerInfo;
use crate::{CliDiagnostic, CliSession, VERSION};
/// Handle of the `version` command. Prints a more in detail version of rome.
pub(crate) fn full_version(session: CliSession) -> Result<(), CliDiagnostic> {
session.app.console.log(markup! {
"CLI: "{VERSION}
});
match session.app.workspace.server_info() {
None => {
session.app.console.log(markup! {
"Server: "<Dim>"not connected"</Dim>
});
}
Some(info) => {
session.app.console.log(markup! {
"Server:
Name: "{info.name}"
Version: "{DisplayServerVersion(info)}
});
}
};
Ok(())
}
pub(super) struct DisplayServerVersion<'a>(pub &'a ServerInfo);
impl fmt::Display for DisplayServerVersion<'_> {
fn fmt(&self, fmt: &mut Formatter) -> std::io::Result<()> {
match &self.0.version {
None => markup!(<Dim>"-"</Dim>).fmt(fmt),
Some(version) => {
write!(fmt, "{version}")
}
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/commands/rage.rs | crates/rome_cli/src/commands/rage.rs | use rome_console::fmt::{Display, Formatter};
use rome_console::{fmt, markup, ConsoleExt, HorizontalLine, Markup};
use rome_diagnostics::termcolor::{ColorChoice, WriteColor};
use rome_diagnostics::{termcolor, PrintDescription};
use rome_fs::FileSystem;
use rome_service::workspace::{client, RageEntry, RageParams};
use rome_service::{load_config, ConfigurationBasePath, DynRef, Workspace};
use std::{env, io, ops::Deref};
use tokio::runtime::Runtime;
use crate::commands::daemon::read_most_recent_log_file;
use crate::service::enumerate_pipes;
use crate::{service, CliDiagnostic, CliSession, VERSION};
/// Handler for the `rage` command
pub(crate) fn rage(session: CliSession) -> Result<(), CliDiagnostic> {
let terminal_supports_colors = termcolor::BufferWriter::stdout(ColorChoice::Auto)
.buffer()
.supports_color();
session.app.console.log(markup!("CLI:\n"
{KeyValuePair("Version", markup!({VERSION}))}
{KeyValuePair("Color support", markup!({DebugDisplay(terminal_supports_colors)}))}
{Section("Platform")}
{KeyValuePair("CPU Architecture", markup!({std::env::consts::ARCH}))}
{KeyValuePair("OS", markup!({std::env::consts::OS}))}
{Section("Environment")}
{EnvVarOs("ROME_LOG_DIR")}
{EnvVarOs("NO_COLOR")}
{EnvVarOs("TERM")}
{EnvVarOs("JS_RUNTIME_VERSION")}
{EnvVarOs("JS_RUNTIME_NAME")}
{EnvVarOs("NODE_PACKAGE_MANAGER")}
{RageConfiguration(&session.app.fs)}
{WorkspaceRage(session.app.workspace.deref())}
{ConnectedClientServerLog(session.app.workspace.deref())}
));
if session.app.workspace.server_info().is_none() {
session
.app
.console
.log(markup!("Discovering running Rome servers..."));
session.app.console.log(markup!({ RunningRomeServer }));
}
Ok(())
}
struct WorkspaceRage<'a>(&'a dyn Workspace);
impl Display for WorkspaceRage<'_> {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
let workspace = self.0;
let rage_result = workspace.rage(RageParams {});
match rage_result {
Ok(result) => {
for entry in result.entries {
match entry {
RageEntry::Section(title) => {
Section(&title).fmt(fmt)?;
}
RageEntry::Pair { name, value } => {
KeyValuePair(&name, markup!({ value })).fmt(fmt)?;
}
RageEntry::Markup(markup) => markup.fmt(fmt)?,
}
}
Ok(())
}
Err(err) => {
writeln!(fmt)?;
(markup! {<Error>"\u{2716} Workspace rage failed:"</Error>}).fmt(fmt)?;
writeln!(fmt, " {err}")
}
}
}
}
/// Prints information about other running rome server instances.
struct RunningRomeServer;
impl Display for RunningRomeServer {
fn fmt(&self, f: &mut Formatter) -> io::Result<()> {
let versions = match enumerate_pipes() {
Ok(iter) => iter,
Err(err) => {
(markup! {<Error>"\u{2716} Enumerating Rome instances failed:"</Error>}).fmt(f)?;
return writeln!(f, " {err}");
}
};
for version in versions {
if version == rome_service::VERSION {
let runtime = Runtime::new()?;
match service::open_transport(runtime) {
Ok(None) => {
markup!(
{Section("Server")}
{KeyValuePair("Status", markup!(<Dim>"stopped"</Dim>))}
)
.fmt(f)?;
continue;
}
Ok(Some(transport)) => {
markup!("\n"<Emphasis>"Running Rome Server:"</Emphasis>" "{HorizontalLine::new(78)}"
"<Info>"\u{2139} The client isn't connected to any server but rage discovered this running Rome server."</Info>"
")
.fmt(f)?;
match client(transport) {
Ok(client) => WorkspaceRage(client.deref()).fmt(f)?,
Err(err) => {
markup!(<Error>"\u{2716} Failed to connect: "</Error>).fmt(f)?;
writeln!(f, "{err}")?;
}
}
}
Err(err) => {
markup!("\n"<Error>"\u{2716} Failed to connect: "</Error>).fmt(f)?;
writeln!(f, "{err}")?;
}
}
RomeServerLog.fmt(f)?;
} else {
markup!("\n"<Emphasis>"Incompatible Rome Server:"</Emphasis>" "{HorizontalLine::new(78)}"
"<Info>"\u{2139} Rage discovered this running server using an incompatible version of Rome."</Info>"
")
.fmt(f)?;
// Version 10.0.0 and below did not include a service version in the pipe name
let version = if version.is_empty() {
"<=10.0.0"
} else {
version.as_str()
};
markup!(
{Section("Server")}
{KeyValuePair("Version", markup!({version}))}
)
.fmt(f)?;
}
}
Ok(())
}
}
struct RageConfiguration<'a, 'app>(&'a DynRef<'app, dyn FileSystem>);
impl Display for RageConfiguration<'_, '_> {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
Section("Rome Configuration").fmt(fmt)?;
match load_config(self.0, ConfigurationBasePath::default()) {
Ok(None) => KeyValuePair("Status", markup!(<Dim>"unset"</Dim>)).fmt(fmt)?,
Ok(Some(result)) => {
let (configuration, diagnostics) = result.deserialized.consume();
let status = if !diagnostics.is_empty() {
for diagnostic in diagnostics {
(markup! {
{KeyValuePair("Error", markup!{
{format!{"{}", PrintDescription(&diagnostic)}}
})}
})
.fmt(fmt)?;
}
markup!(<Dim>"Loaded with errors"</Dim>)
} else {
markup!(<Dim>"Loaded successfully"</Dim>)
};
markup! (
{KeyValuePair("Status", status)}
{KeyValuePair("Formatter disabled", markup!({DebugDisplay(configuration.is_formatter_disabled())}))}
{KeyValuePair("Linter disabled", markup!({DebugDisplay(configuration.is_linter_disabled())}))}
{KeyValuePair("Organize imports disabled", markup!({DebugDisplay(configuration.is_organize_imports_disabled())}))}
{KeyValuePair("VCS disabled", markup!({DebugDisplay(configuration.is_vcs_disabled())}))}
).fmt(fmt)?
}
Err(err) => markup! (
{KeyValuePair("Status", markup!(<Error>"Failed to load"</Error>))}
{KeyValuePair("Error", markup!({format!("{err}")}))}
)
.fmt(fmt)?,
}
Ok(())
}
}
struct DebugDisplay<T>(T);
impl<T> Display for DebugDisplay<T>
where
T: std::fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> io::Result<()> {
write!(f, "{:?}", self.0)
}
}
struct EnvVarOs(&'static str);
impl fmt::Display for EnvVarOs {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
let name = self.0;
match env::var_os(name) {
None => KeyValuePair(name, markup! { <Dim>"unset"</Dim> }).fmt(fmt),
Some(value) => KeyValuePair(name, markup! {{DebugDisplay(value)}}).fmt(fmt),
}
}
}
struct Section<'a>(&'a str);
impl Display for Section<'_> {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
writeln!(fmt, "\n{}:", self.0)
}
}
struct KeyValuePair<'a>(&'a str, Markup<'a>);
impl Display for KeyValuePair<'_> {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
let KeyValuePair(key, value) = self;
write!(fmt, " {key}:")?;
let padding_width = 30usize.saturating_sub(key.len() + 1);
for _ in 0..padding_width {
fmt.write_str(" ")?;
}
value.fmt(fmt)?;
fmt.write_str("\n")
}
}
struct RomeServerLog;
impl Display for RomeServerLog {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
if let Ok(Some(log)) = read_most_recent_log_file() {
markup!("\n"<Emphasis><Underline>"Rome Server Log:"</Underline></Emphasis>"
"<Warn>"\u{26a0} Please review the content of the log file before sharing it publicly as it may contain sensitive information:
* Path names that may reveal your name, a project name, or the name of your employer.
* Source code
"</Warn>)
.fmt(fmt)?;
write!(fmt, "\n{log}")?;
}
Ok(())
}
}
/// Prints the server logs but only if the client is connected to a rome server.
struct ConnectedClientServerLog<'a>(&'a dyn Workspace);
impl Display for ConnectedClientServerLog<'_> {
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
if self.0.server_info().is_some() {
RomeServerLog.fmt(fmt)
} else {
Ok(())
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/commands/migrate.rs | crates/rome_cli/src/commands/migrate.rs | use crate::cli_options::CliOptions;
use crate::configuration::{load_configuration, LoadedConfiguration};
use crate::diagnostics::MigrationDiagnostic;
use crate::execute::{execute_mode, Execution, TraversalMode};
use crate::{CliDiagnostic, CliSession};
/// Handler for the "check" command of the Rome CLI
pub(crate) fn migrate(
mut session: CliSession,
cli_options: CliOptions,
write: bool,
) -> Result<(), CliDiagnostic> {
let LoadedConfiguration {
configuration: _,
diagnostics: _,
directory_path: path,
..
} = load_configuration(&mut session, &cli_options)?;
let config_name = session.app.fs.config_name();
if let Some(path) = path {
execute_mode(
Execution::new(TraversalMode::Migrate {
write,
configuration_path: path.join(config_name),
}),
session,
&cli_options,
vec![],
)
} else {
Err(CliDiagnostic::MigrateError(MigrationDiagnostic {
reason: "Rome couldn't find the configuration file".to_string(),
}))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/commands/check.rs | crates/rome_cli/src/commands/check.rs | use crate::cli_options::CliOptions;
use crate::configuration::{load_configuration, LoadedConfiguration};
use crate::vcs::store_path_to_ignore_from_vcs;
use crate::{execute_mode, CliDiagnostic, CliSession, Execution, TraversalMode};
use rome_service::configuration::organize_imports::OrganizeImports;
use rome_service::configuration::{FormatterConfiguration, LinterConfiguration};
use rome_service::workspace::{FixFileMode, UpdateSettingsParams};
use rome_service::{Configuration, MergeWith};
use std::ffi::OsString;
use std::path::PathBuf;
pub(crate) struct CheckCommandPayload {
pub(crate) apply: bool,
pub(crate) apply_unsafe: bool,
pub(crate) cli_options: CliOptions,
pub(crate) configuration: Option<Configuration>,
pub(crate) paths: Vec<OsString>,
pub(crate) stdin_file_path: Option<String>,
pub(crate) formatter_enabled: Option<bool>,
pub(crate) linter_enabled: Option<bool>,
pub(crate) organize_imports_enabled: Option<bool>,
}
/// Handler for the "check" command of the Rome CLI
pub(crate) fn check(
mut session: CliSession,
payload: CheckCommandPayload,
) -> Result<(), CliDiagnostic> {
let CheckCommandPayload {
apply,
apply_unsafe,
cli_options,
configuration,
paths,
stdin_file_path,
linter_enabled,
organize_imports_enabled,
formatter_enabled,
} = payload;
let fix_file_mode = if apply && apply_unsafe {
return Err(CliDiagnostic::incompatible_arguments(
"--apply",
"--apply-unsafe",
));
} else if !apply && !apply_unsafe {
None
} else if apply && !apply_unsafe {
Some(FixFileMode::SafeFixes)
} else {
Some(FixFileMode::SafeAndUnsafeFixes)
};
let LoadedConfiguration {
configuration: mut fs_configuration,
directory_path: configuration_path,
..
} = load_configuration(&mut session, &cli_options)?
.or_diagnostic(session.app.console, cli_options.verbose)?;
let formatter = fs_configuration
.formatter
.get_or_insert_with(FormatterConfiguration::default);
if !matches!(formatter_enabled, None) {
formatter.enabled = formatter_enabled;
}
let linter = fs_configuration
.linter
.get_or_insert_with(LinterConfiguration::default);
if !matches!(linter_enabled, None) {
linter.enabled = linter_enabled;
}
let organize_imports = fs_configuration
.organize_imports
.get_or_insert_with(OrganizeImports::default);
if !matches!(organize_imports_enabled, None) {
organize_imports.enabled = organize_imports_enabled;
}
fs_configuration.merge_with(configuration);
// check if support of git ignore files is enabled
let vcs_base_path = configuration_path.or(session.app.fs.working_directory());
store_path_to_ignore_from_vcs(
&mut session,
&mut fs_configuration,
vcs_base_path,
&cli_options,
)?;
let stdin = if let Some(stdin_file_path) = stdin_file_path {
let console = &mut session.app.console;
let input_code = console.read();
if let Some(input_code) = input_code {
let path = PathBuf::from(stdin_file_path);
Some((path, input_code))
} else {
// we provided the argument without a piped stdin, we bail
return Err(CliDiagnostic::missing_argument("stdin", "check"));
}
} else {
None
};
session
.app
.workspace
.update_settings(UpdateSettingsParams {
configuration: fs_configuration,
})?;
execute_mode(
Execution::new(TraversalMode::Check {
fix_file_mode,
stdin,
}),
session,
&cli_options,
paths,
)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/commands/lint.rs | crates/rome_cli/src/commands/lint.rs | use crate::cli_options::CliOptions;
use crate::configuration::{load_configuration, LoadedConfiguration};
use crate::vcs::store_path_to_ignore_from_vcs;
use crate::{execute_mode, CliDiagnostic, CliSession, Execution, TraversalMode};
use rome_service::workspace::{FixFileMode, UpdateSettingsParams};
use rome_service::{Configuration, MergeWith};
use std::ffi::OsString;
use std::path::PathBuf;
pub(crate) struct LintCommandPayload {
pub(crate) apply: bool,
pub(crate) apply_unsafe: bool,
pub(crate) cli_options: CliOptions,
pub(crate) configuration: Option<Configuration>,
pub(crate) paths: Vec<OsString>,
pub(crate) stdin_file_path: Option<String>,
}
/// Handler for the "lint" command of the Rome CLI
pub(crate) fn lint(
mut session: CliSession,
payload: LintCommandPayload,
) -> Result<(), CliDiagnostic> {
let LintCommandPayload {
apply,
apply_unsafe,
cli_options,
configuration,
paths,
stdin_file_path,
} = payload;
let fix_file_mode = if apply && apply_unsafe {
return Err(CliDiagnostic::incompatible_arguments(
"--apply",
"--apply-unsafe",
));
} else if !apply && !apply_unsafe {
None
} else if apply && !apply_unsafe {
Some(FixFileMode::SafeFixes)
} else {
Some(FixFileMode::SafeAndUnsafeFixes)
};
let LoadedConfiguration {
configuration: mut fs_configuration,
directory_path: configuration_path,
..
} = load_configuration(&mut session, &cli_options)?
.or_diagnostic(session.app.console, cli_options.verbose)?;
fs_configuration.merge_with(configuration);
// check if support of git ignore files is enabled
let vcs_base_path = configuration_path.or(session.app.fs.working_directory());
store_path_to_ignore_from_vcs(
&mut session,
&mut fs_configuration,
vcs_base_path,
&cli_options,
)?;
let stdin = if let Some(stdin_file_path) = stdin_file_path {
let console = &mut session.app.console;
let input_code = console.read();
if let Some(input_code) = input_code {
let path = PathBuf::from(stdin_file_path);
Some((path, input_code))
} else {
// we provided the argument without a piped stdin, we bail
return Err(CliDiagnostic::missing_argument("stdin", "lint"));
}
} else {
None
};
session
.app
.workspace
.update_settings(UpdateSettingsParams {
configuration: fs_configuration,
})?;
execute_mode(
Execution::new(TraversalMode::Lint {
fix_file_mode,
stdin,
}),
session,
&cli_options,
paths,
)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/commands/mod.rs | crates/rome_cli/src/commands/mod.rs | use crate::cli_options::{cli_options, CliOptions, ColorsArg};
use crate::VERSION;
use bpaf::Bpaf;
use rome_service::configuration::vcs::VcsConfiguration;
use rome_service::configuration::{
configuration, files_configuration, formatter_configuration, javascript::javascript_formatter,
vcs::vcs_configuration, FilesConfiguration, FormatterConfiguration, JavascriptFormatter,
};
use rome_service::Configuration;
use std::ffi::OsString;
pub(crate) mod check;
pub(crate) mod ci;
pub(crate) mod daemon;
pub(crate) mod format;
pub(crate) mod init;
pub(crate) mod lint;
pub(crate) mod migrate;
pub(crate) mod rage;
pub(crate) mod version;
#[derive(Debug, Clone, Bpaf)]
#[bpaf(options, version(VERSION))]
/// Rome official CLI. Use it to check the health of your project or run it to check single files.
pub enum RomeCommand {
/// Shows the Rome version information and quit
#[bpaf(command)]
Version(#[bpaf(external(cli_options), hide_usage)] CliOptions),
#[bpaf(command)]
/// Prints information for debugging
Rage(#[bpaf(external(cli_options), hide_usage)] CliOptions),
/// Start the Rome daemon server process
#[bpaf(command)]
Start,
/// Stop the Rome daemon server process
#[bpaf(command)]
Stop,
/// Run various checks on a set of files.
#[bpaf(command)]
Check {
/// Apply safe fixes, formatting
#[bpaf(long("apply"), switch)]
apply: bool,
/// Apply safe fixes and unsafe fixes, formatting and import sorting
#[bpaf(long("apply-unsafe"), switch)]
apply_unsafe: bool,
/// Allow to enable or disable the formatter check.
#[bpaf(
long("formatter-enabled"),
argument("true|false"),
optional,
hide_usage
)]
formatter_enabled: Option<bool>,
/// Allow to enable or disable the linter check.
#[bpaf(long("linter-enabled"), argument("true|false"), optional, hide_usage)]
linter_enabled: Option<bool>,
/// Allow to enable or disable the organize imports.
#[bpaf(
long("organize-imports-enabled"),
argument("true|false"),
optional,
hide_usage
)]
organize_imports_enabled: Option<bool>,
#[bpaf(external, hide_usage, optional)]
configuration: Option<Configuration>,
#[bpaf(external, hide_usage)]
cli_options: CliOptions,
/// A file name with its extension to pass when reading from standard in, e.g. echo 'let a;' | rome check --stdin-file-path=file.js"
#[bpaf(long("stdin-file-path"), argument("PATH"), hide_usage)]
stdin_file_path: Option<String>,
/// Single file, single path or list of paths
#[bpaf(positional("PATH"), many)]
paths: Vec<OsString>,
},
/// Run various checks on a set of files.
#[bpaf(command)]
Lint {
/// Apply safe fixes, formatting
#[bpaf(long("apply"), switch)]
apply: bool,
/// Apply safe fixes and unsafe fixes, formatting and import sorting
#[bpaf(long("apply-unsafe"), switch)]
apply_unsafe: bool,
#[bpaf(external, hide_usage, optional)]
configuration: Option<Configuration>,
#[bpaf(external, hide_usage)]
cli_options: CliOptions,
/// A file name with its extension to pass when reading from standard in, e.g. echo 'let a;' | rome lint --stdin-file-path=file.js"
#[bpaf(long("stdin-file-path"), argument("PATH"), hide_usage)]
stdin_file_path: Option<String>,
/// Single file, single path or list of paths
#[bpaf(positional("PATH"), many)]
paths: Vec<OsString>,
},
/// Run the formatter on a set of files.
#[bpaf(command)]
Format {
#[bpaf(external, optional, hide_usage)]
formatter_configuration: Option<FormatterConfiguration>,
#[bpaf(external, optional, hide_usage)]
javascript_formatter: Option<JavascriptFormatter>,
#[bpaf(external, optional, hide_usage)]
vcs_configuration: Option<VcsConfiguration>,
#[bpaf(external, optional, hide_usage)]
files_configuration: Option<FilesConfiguration>,
/// A file name with its extension to pass when reading from standard in, e.g. echo 'let a;' | rome format --stdin-file-path=file.js".
#[bpaf(long("stdin-file-path"), argument("PATH"), hide_usage)]
stdin_file_path: Option<String>,
#[bpaf(external, hide_usage)]
cli_options: CliOptions,
/// Writes formatted files to file system.
#[bpaf(switch)]
write: bool,
/// Single file, single path or list of paths.
#[bpaf(positional("PATH"), many)]
paths: Vec<OsString>,
},
/// Command to use in CI environments. Run various checks of a set of files.
#[bpaf(command)]
Ci {
/// Allow to enable or disable the formatter check.
#[bpaf(long("formatter-enabled"), argument("true|false"), optional)]
formatter_enabled: Option<bool>,
/// Allow to enable or disable the linter check.
#[bpaf(long("linter-enabled"), argument("true|false"), optional)]
linter_enabled: Option<bool>,
/// Allow to enable or disable the organize imports.
#[bpaf(long("organize-imports-enabled"), argument("true|false"), optional)]
organize_imports_enabled: Option<bool>,
#[bpaf(external, hide_usage)]
configuration: Configuration,
#[bpaf(external, hide_usage)]
cli_options: CliOptions,
/// Single file, single path or list of paths
#[bpaf(positional("PATH"), many)]
paths: Vec<OsString>,
},
/// Bootstraps a new rome project. Creates a configuration file with some defaults.
#[bpaf(command)]
Init,
/// Acts as a server for the Language Server Protocol over stdin/stdout
#[bpaf(command("lsp-proxy"))]
LspProxy(#[bpaf(external(cli_options))] CliOptions),
/// It updates the configuration when there are breaking changes
#[bpaf(command)]
Migrate(
#[bpaf(external(cli_options), hide_usage)] CliOptions,
/// Writes the new configuration file to disk
#[bpaf(long("write"), switch)]
bool,
),
#[bpaf(command("__run_server"), hide)]
RunServer {
#[bpaf(long("stop-on-disconnect"), hide_usage)]
stop_on_disconnect: bool,
},
#[bpaf(command("__print_socket"), hide)]
PrintSocket,
}
impl RomeCommand {
pub const fn get_color(&self) -> Option<&ColorsArg> {
match self {
RomeCommand::Version(cli_options) => cli_options.colors.as_ref(),
RomeCommand::Rage(cli_options) => cli_options.colors.as_ref(),
RomeCommand::Start => None,
RomeCommand::Stop => None,
RomeCommand::Check { cli_options, .. } => cli_options.colors.as_ref(),
RomeCommand::Lint { cli_options, .. } => cli_options.colors.as_ref(),
RomeCommand::Ci { cli_options, .. } => cli_options.colors.as_ref(),
RomeCommand::Format { cli_options, .. } => cli_options.colors.as_ref(),
RomeCommand::Init => None,
RomeCommand::LspProxy(cli_options) => cli_options.colors.as_ref(),
RomeCommand::Migrate(cli_options, _) => cli_options.colors.as_ref(),
RomeCommand::RunServer { .. } => None,
RomeCommand::PrintSocket => None,
}
}
pub const fn should_use_server(&self) -> bool {
match self {
RomeCommand::Version(cli_options) => cli_options.use_server,
RomeCommand::Rage(cli_options) => cli_options.use_server,
RomeCommand::Start => false,
RomeCommand::Stop => false,
RomeCommand::Check { cli_options, .. } => cli_options.use_server,
RomeCommand::Lint { cli_options, .. } => cli_options.use_server,
RomeCommand::Ci { cli_options, .. } => cli_options.use_server,
RomeCommand::Format { cli_options, .. } => cli_options.use_server,
RomeCommand::Init => false,
RomeCommand::LspProxy(cli_options) => cli_options.use_server,
RomeCommand::Migrate(cli_options, _) => cli_options.use_server,
RomeCommand::RunServer { .. } => false,
RomeCommand::PrintSocket => false,
}
}
pub const fn has_metrics(&self) -> bool {
false
}
pub fn is_verbose(&self) -> bool {
match self {
RomeCommand::Version(_) => false,
RomeCommand::Rage(_) => false,
RomeCommand::Start => false,
RomeCommand::Stop => false,
RomeCommand::Check { cli_options, .. } => cli_options.verbose,
RomeCommand::Lint { cli_options, .. } => cli_options.verbose,
RomeCommand::Format { cli_options, .. } => cli_options.verbose,
RomeCommand::Ci { cli_options, .. } => cli_options.verbose,
RomeCommand::Init => false,
RomeCommand::LspProxy(cli_options) => cli_options.verbose,
RomeCommand::Migrate(cli_options, _) => cli_options.verbose,
RomeCommand::RunServer { .. } => false,
RomeCommand::PrintSocket => false,
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/commands/format.rs | crates/rome_cli/src/commands/format.rs | use crate::cli_options::CliOptions;
use crate::configuration::{load_configuration, LoadedConfiguration};
use crate::execute::ReportMode;
use crate::vcs::store_path_to_ignore_from_vcs;
use crate::{execute_mode, CliDiagnostic, CliSession, Execution, TraversalMode};
use rome_service::configuration::vcs::VcsConfiguration;
use rome_service::configuration::{FilesConfiguration, FormatterConfiguration};
use rome_service::workspace::UpdateSettingsParams;
use rome_service::{JavascriptFormatter, MergeWith};
use std::ffi::OsString;
use std::path::PathBuf;
pub(crate) struct FormatCommandPayload {
pub(crate) javascript_formatter: Option<JavascriptFormatter>,
pub(crate) formatter_configuration: Option<FormatterConfiguration>,
pub(crate) vcs_configuration: Option<VcsConfiguration>,
pub(crate) files_configuration: Option<FilesConfiguration>,
pub(crate) stdin_file_path: Option<String>,
pub(crate) write: bool,
pub(crate) cli_options: CliOptions,
pub(crate) paths: Vec<OsString>,
}
/// Handler for the "format" command of the Rome CLI
pub(crate) fn format(
mut session: CliSession,
payload: FormatCommandPayload,
) -> Result<(), CliDiagnostic> {
let FormatCommandPayload {
javascript_formatter,
formatter_configuration,
vcs_configuration,
paths,
cli_options,
stdin_file_path,
files_configuration,
write,
} = payload;
let LoadedConfiguration {
mut configuration,
directory_path: configuration_path,
..
} = load_configuration(&mut session, &cli_options)?
.or_diagnostic(session.app.console, cli_options.verbose)?;
configuration.merge_with(javascript_formatter);
configuration.merge_with(formatter_configuration);
configuration.merge_with(vcs_configuration);
configuration.merge_with(files_configuration);
// check if support of git ignore files is enabled
let vcs_base_path = configuration_path.or(session.app.fs.working_directory());
store_path_to_ignore_from_vcs(
&mut session,
&mut configuration,
vcs_base_path,
&cli_options,
)?;
session
.app
.workspace
.update_settings(UpdateSettingsParams { configuration })?;
let stdin = if let Some(stdin_file_path) = stdin_file_path {
let console = &mut session.app.console;
let input_code = console.read();
if let Some(input_code) = input_code {
let path = PathBuf::from(stdin_file_path);
Some((path, input_code))
} else {
// we provided the argument without a piped stdin, we bail
return Err(CliDiagnostic::missing_argument("stdin", "format"));
}
} else {
None
};
let execution = if cli_options.json {
Execution::with_report(
TraversalMode::Format {
ignore_errors: cli_options.skip_errors,
write,
stdin,
},
ReportMode::Json,
)
} else {
Execution::new(TraversalMode::Format {
ignore_errors: cli_options.skip_errors,
write,
stdin,
})
};
execute_mode(execution, session, &cli_options, paths)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/commands/init.rs | crates/rome_cli/src/commands/init.rs | use crate::{CliDiagnostic, CliSession};
use rome_console::{markup, ConsoleExt, HorizontalLine};
use rome_service::configuration::Configuration;
use rome_service::create_config;
pub(crate) fn init(mut session: CliSession) -> Result<(), CliDiagnostic> {
let fs = &mut session.app.fs;
create_config(fs, Configuration::default())?;
session.app.console.log(markup! {
"\n"<Inverse>"Welcome to Rome! Let's get you started..."</Inverse>"
"<Info><Emphasis>"Files created "</Emphasis></Info>{HorizontalLine::new(106)}"
"<Dim>"- "</Dim><Emphasis>"rome.json: "</Emphasis>"Your project configuration. Documentation: "<Hyperlink href="https://rome.tools/configuration">"https://rome.tools/configuration"</Hyperlink>"
"<Info><Emphasis>"Next Steps "</Emphasis></Info>{HorizontalLine::new(109)}"
"<Dim>"1."</Dim>" "<Emphasis>"Setup an editor extension"</Emphasis>"
Get live errors as you type and format when you save. Learn more: "<Hyperlink href="https://rome.tools/editors">"https://rome.tools/editors"</Hyperlink>"
"<Dim>"2."</Dim>" "<Emphasis>"Try a command"</Emphasis>"
"<Italic>"rome ci"</Italic>" checks for lint errors and verifies formatting. Run " <Italic>"rome --help"</Italic>" for a full list of commands and options.
"<Dim>"3."</Dim>" "<Emphasis>"Read the documentation"</Emphasis>"
Our website serves as a comprehensive source of guides and documentation: "<Hyperlink href="https://docs.rome.tools">"https://docs.rome.tools"</Hyperlink>"
"<Dim>"4."</Dim>" "<Emphasis>"Get involved in the community"</Emphasis>"
Ask questions, get support, or contribute by participating on GitHub ("<Hyperlink href="https://github.com/rome/tools">"https://github.com/rome/tools"</Hyperlink>"),
or join our community Discord ("<Hyperlink href="https://discord.gg/rome">"https://discord.gg/rome"</Hyperlink>")"
});
Ok(())
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/commands/daemon.rs | crates/rome_cli/src/commands/daemon.rs | use crate::{
open_transport,
service::{self, ensure_daemon, open_socket, run_daemon},
CliDiagnostic, CliSession,
};
use rome_console::{markup, ConsoleExt};
use rome_lsp::ServerFactory;
use rome_service::{workspace::WorkspaceClient, TransportError, WorkspaceError};
use std::{env, fs, path::PathBuf};
use tokio::io;
use tokio::runtime::Runtime;
use tracing::subscriber::Interest;
use tracing::{debug_span, metadata::LevelFilter, Instrument, Metadata};
use tracing_subscriber::{
layer::{Context, Filter},
prelude::*,
registry, Layer,
};
use tracing_tree::HierarchicalLayer;
pub(crate) fn start(session: CliSession) -> Result<(), CliDiagnostic> {
let rt = Runtime::new()?;
let did_spawn = rt.block_on(ensure_daemon(false))?;
if did_spawn {
session.app.console.log(markup! {
"The Rome server was successfully started"
});
} else {
session.app.console.log(markup! {
"The Rome server was already running"
});
}
Ok(())
}
pub(crate) fn stop(session: CliSession) -> Result<(), CliDiagnostic> {
let rt = Runtime::new()?;
if let Some(transport) = open_transport(rt)? {
let client = WorkspaceClient::new(transport)?;
match client.shutdown() {
// The `ChannelClosed` error is expected since the server can
// shutdown before sending a response
Ok(()) | Err(WorkspaceError::TransportError(TransportError::ChannelClosed)) => {}
Err(err) => return Err(CliDiagnostic::from(err)),
};
session.app.console.log(markup! {
"The Rome server was successfully stopped"
});
} else {
session.app.console.log(markup! {
"The Rome server was not running"
});
}
Ok(())
}
pub(crate) fn run_server(stop_on_disconnect: bool) -> Result<(), CliDiagnostic> {
setup_tracing_subscriber();
let rt = Runtime::new()?;
let factory = ServerFactory::new(stop_on_disconnect);
let cancellation = factory.cancellation();
let span = debug_span!("Running Server", pid = std::process::id());
rt.block_on(async move {
tokio::select! {
res = run_daemon(factory).instrument(span) => {
match res {
Ok(never) => match never {},
Err(err) => Err(err.into()),
}
}
_ = cancellation.notified() => {
tracing::info!("Received shutdown signal");
Ok(())
}
}
})
}
pub(crate) fn print_socket() -> Result<(), CliDiagnostic> {
let rt = Runtime::new()?;
rt.block_on(service::print_socket())?;
Ok(())
}
pub(crate) fn lsp_proxy() -> Result<(), CliDiagnostic> {
let rt = Runtime::new()?;
rt.block_on(start_lsp_proxy(&rt))?;
Ok(())
}
/// Start a proxy process.
/// Receives a process via `stdin` and then copy the content to the LSP socket.
/// Copy to the process on `stdout` when the LSP responds to a message
async fn start_lsp_proxy(rt: &Runtime) -> Result<(), CliDiagnostic> {
ensure_daemon(true).await?;
match open_socket().await? {
Some((mut owned_read_half, mut owned_write_half)) => {
// forward stdin to socket
let mut stdin = io::stdin();
let input_handle = rt.spawn(async move {
loop {
match io::copy(&mut stdin, &mut owned_write_half).await {
Ok(b) => {
if b == 0 {
return Ok(());
}
}
Err(err) => return Err(err),
};
}
});
// receive socket response to stdout
let mut stdout = io::stdout();
let out_put_handle = rt.spawn(async move {
loop {
match io::copy(&mut owned_read_half, &mut stdout).await {
Ok(b) => {
if b == 0 {
return Ok(());
}
}
Err(err) => return Err(err),
};
}
});
let _ = input_handle.await;
let _ = out_put_handle.await;
Ok(())
}
None => Ok(()),
}
}
const fn log_file_name_prefix() -> &'static str {
"server.log"
}
pub(crate) fn read_most_recent_log_file() -> io::Result<Option<String>> {
let logs_dir = rome_log_dir();
let most_recent = fs::read_dir(logs_dir)?
.flatten()
.filter(|file| file.file_type().map_or(false, |ty| ty.is_file()))
.filter_map(|file| {
match file
.file_name()
.to_str()?
.split_once(log_file_name_prefix())
{
Some((_, date_part)) if date_part.split('-').count() == 4 => Some(file.path()),
_ => None,
}
})
.max();
match most_recent {
Some(file) => Ok(Some(fs::read_to_string(file)?)),
None => Ok(None),
}
}
/// Setup the [tracing]-based logging system for the server
/// The events received by the subscriber are filtered at the `info` level,
/// then printed using the [HierarchicalLayer] layer, and the resulting text
/// is written to log files rotated on a hourly basis (in
/// `rome-logs/server.log.yyyy-MM-dd-HH` files inside the system temporary
/// directory)
fn setup_tracing_subscriber() {
let file_appender = tracing_appender::rolling::hourly(rome_log_dir(), log_file_name_prefix());
registry()
.with(
HierarchicalLayer::default()
.with_indent_lines(true)
.with_indent_amount(2)
.with_bracketed_fields(true)
.with_targets(true)
.with_ansi(false)
.with_writer(file_appender)
.with_filter(LoggingFilter),
)
.init();
}
pub(super) fn rome_log_dir() -> PathBuf {
match env::var_os("ROME_LOG_DIR") {
Some(directory) => PathBuf::from(directory),
None => env::temp_dir().join("rome-logs"),
}
}
/// Tracing filter enabling:
/// - All spans and events at level info or higher
/// - All spans and events at level debug in crates whose name starts with `rome`
struct LoggingFilter;
/// Tracing filter used for spans emitted by `rome*` crates
const SELF_FILTER: LevelFilter = if cfg!(debug_assertions) {
LevelFilter::TRACE
} else {
LevelFilter::DEBUG
};
impl LoggingFilter {
fn is_enabled(&self, meta: &Metadata<'_>) -> bool {
let filter = if meta.target().starts_with("rome") {
SELF_FILTER
} else {
LevelFilter::INFO
};
meta.level() <= &filter
}
}
impl<S> Filter<S> for LoggingFilter {
fn enabled(&self, meta: &Metadata<'_>, _cx: &Context<'_, S>) -> bool {
self.is_enabled(meta)
}
fn callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest {
if self.is_enabled(meta) {
Interest::always()
} else {
Interest::never()
}
}
fn max_level_hint(&self) -> Option<LevelFilter> {
Some(SELF_FILTER)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/reports/mod.rs | crates/rome_cli/src/reports/mod.rs | pub mod formatter;
use crate::reports::formatter::{FormatterReportFileDetail, FormatterReportSummary};
use formatter::FormatterReport;
use rome_diagnostics::{Category, Severity};
use rome_service::WorkspaceError;
use serde::Serialize;
use std::collections::HashMap;
#[derive(Debug, Default, Serialize)]
pub struct Report {
/// Information related to the formatter
formatter: FormatterReport,
/// Diagnostics tracked during a generic traversal
///
/// The key is the path of the file where the diagnostics occurred
diagnostics: HashMap<String, ReportErrorKind>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ReportErrorKind {
Diagnostic(ReportDiagnostic),
Diff(ReportDiff),
}
/// Information computed from a [diagnostic][rome_diagnostics::Diagnostic]
#[derive(Debug, Serialize)]
pub struct ReportDiagnostic {
/// Severity of the [diagnostic][rome_diagnostics::Diagnostic]
pub severity: Severity,
/// The code of the [diagnostic][rome_diagnostics::Diagnostic]
pub code: Option<&'static Category>,
/// The title of the [diagnostic][rome_diagnostics::Diagnostic]
pub title: String,
}
/// Information computed from a diff result
#[derive(Debug, Serialize)]
pub struct ReportDiff {
/// The severity fo the diff
pub severity: Severity,
/// How was the code before the command
pub before: String,
/// How is the code after the command
pub after: String,
}
impl Default for ReportDiagnostic {
fn default() -> Self {
Self {
severity: Severity::Error,
code: None,
title: String::new(),
}
}
}
#[derive(Debug)]
pub enum ReportKind {
Formatter(String, FormatterReportFileDetail),
Error(String, ReportErrorKind),
}
impl Report {
/// Creates or updates a stat
pub fn push_detail_report(&mut self, stat: ReportKind) {
match stat {
ReportKind::Formatter(path, stat) => {
self.formatter.insert_file_content(path, stat);
}
ReportKind::Error(path, error) => {
self.diagnostics.insert(path, error);
}
}
}
/// It tracks a generic diagnostic
pub fn push_error(&mut self, path: String, err: ReportErrorKind) {
self.diagnostics.insert(path, err);
}
pub fn set_formatter_summary(&mut self, summary: FormatterReportSummary) {
self.formatter.set_summary(summary);
}
pub fn as_serialized_reports(&self) -> Result<String, WorkspaceError> {
serde_json::to_string(&self)
.map_err(|err| WorkspaceError::report_not_serializable(err.to_string()))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/reports/formatter.rs | crates/rome_cli/src/reports/formatter.rs | use serde::Serialize;
use std::collections::HashMap;
#[derive(Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FormatterReport {
/// Useful information of the execution
summary: Option<FormatterReportSummary>,
/// The key is the path of the file
files: HashMap<String, FormatterReportFileDetail>,
}
impl FormatterReport {
pub(crate) fn insert_file_content(&mut self, path: String, detail: FormatterReportFileDetail) {
self.files.insert(path, detail);
}
pub(crate) fn set_summary(&mut self, summary: FormatterReportSummary) {
self.summary = Some(summary);
}
}
#[derive(Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FormatterReportSummary {
files_compared: Option<usize>,
files_written: Option<usize>,
}
impl FormatterReportSummary {
/// how many files were compared
pub(crate) fn set_files_compared(&mut self, files_compared: usize) {
self.files_compared = Some(files_compared)
}
/// how many files were written
pub(crate) fn set_files_written(&mut self, files_written: usize) {
self.files_written = Some(files_written)
}
}
#[derive(Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FormatterReportFileDetail {
/// The new content emitted by the formatter
pub formatted_content: Option<String>,
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/execute/std_in.rs | crates/rome_cli/src/execute/std_in.rs | //! In here, there are the operations that run via standard input
//!
use crate::execute::diagnostics::{ContentDiffAdvice, FormatDiffDiagnostic};
use crate::execute::Execution;
use crate::{CliDiagnostic, CliSession};
use rome_console::{markup, ConsoleExt};
use rome_diagnostics::PrintDiagnostic;
use rome_fs::RomePath;
use rome_service::workspace::{
ChangeFileParams, FeatureName, FeaturesBuilder, FixFileParams, FormatFileParams, Language,
OpenFileParams, OrganizeImportsParams, PullDiagnosticsParams, RuleCategories,
SupportsFeatureParams,
};
use std::borrow::Cow;
pub(crate) fn run<'a>(
session: CliSession,
mode: &'a Execution,
rome_path: RomePath,
content: &'a str,
) -> Result<(), CliDiagnostic> {
let workspace = &*session.app.workspace;
let console = &mut *session.app.console;
let mut version = 0;
if mode.is_format() {
let file_features = workspace.file_features(SupportsFeatureParams {
path: rome_path.clone(),
feature: FeaturesBuilder::new().with_formatter().build(),
})?;
if file_features.supports_for(&FeatureName::Format) {
workspace.open_file(OpenFileParams {
path: rome_path.clone(),
version: 0,
content: content.into(),
language_hint: Language::default(),
})?;
let printed = workspace.format_file(FormatFileParams { path: rome_path })?;
console.append(markup! {
{printed.as_code()}
});
} else {
console.append(markup! {
{content}
});
console.error(markup!{
<Warn>"The content was not formatted because the formatter is currently disabled."</Warn>
})
}
} else if mode.is_check() || mode.is_lint() {
let mut diagnostics = Vec::new();
let mut new_content = Cow::Borrowed(content);
workspace.open_file(OpenFileParams {
path: rome_path.clone(),
version: 0,
content: content.into(),
language_hint: Language::default(),
})?;
// apply fix file of the linter
let file_features = workspace.file_features(SupportsFeatureParams {
path: rome_path.clone(),
feature: FeaturesBuilder::new()
.with_linter()
.with_organize_imports()
.with_formatter()
.build(),
})?;
if let Some(fix_file_mode) = mode.as_fix_file_mode() {
if file_features.supports_for(&FeatureName::Lint) {
let fix_file_result = workspace.fix_file(FixFileParams {
fix_file_mode: *fix_file_mode,
path: rome_path.clone(),
should_format: mode.is_check()
&& file_features.supports_for(&FeatureName::Format),
})?;
if fix_file_result.code != new_content {
version += 1;
workspace.change_file(ChangeFileParams {
content: fix_file_result.code.clone(),
path: rome_path.clone(),
version,
})?;
new_content = Cow::Owned(fix_file_result.code);
}
}
if file_features.supports_for(&FeatureName::OrganizeImports) && mode.is_check() {
let result = workspace.organize_imports(OrganizeImportsParams {
path: rome_path.clone(),
})?;
if result.code != new_content {
version += 1;
workspace.change_file(ChangeFileParams {
content: result.code.clone(),
path: rome_path.clone(),
version,
})?;
new_content = Cow::Owned(result.code);
}
}
}
if !mode.is_check_apply_unsafe() {
let result = workspace.pull_diagnostics(PullDiagnosticsParams {
categories: RuleCategories::LINT | RuleCategories::SYNTAX,
path: rome_path.clone(),
max_diagnostics: mode.max_diagnostics.into(),
})?;
diagnostics.extend(result.diagnostics);
}
if file_features.supports_for(&FeatureName::Format) && mode.is_check() {
let printed = workspace.format_file(FormatFileParams {
path: rome_path.clone(),
})?;
if mode.is_check_apply() || mode.is_check_apply_unsafe() {
if printed.as_code() != new_content {
new_content = Cow::Owned(printed.into_code());
}
} else {
let diagnostic = FormatDiffDiagnostic {
file_name: rome_path.display().to_string(),
diff: ContentDiffAdvice {
new: printed.as_code().to_string(),
old: content.to_string(),
},
};
diagnostics.push(rome_diagnostics::serde::Diagnostic::new(diagnostic));
}
}
match new_content {
Cow::Borrowed(_) => {}
Cow::Owned(new_content) => {
console.append(markup! {
{new_content}
});
}
}
if !diagnostics.is_empty() {
for diag in diagnostics {
console.error(markup! {
{PrintDiagnostic::simple(&diag)}
})
}
}
}
Ok(())
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/execute/diagnostics.rs | crates/rome_cli/src/execute/diagnostics.rs | use rome_diagnostics::adapters::{IoError, StdError};
use rome_diagnostics::{Advices, Category, Diagnostic, DiagnosticExt, Error, Severity, Visit};
use rome_text_edit::TextEdit;
use std::io;
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "format",
message = "File content differs from formatting output"
)]
pub(crate) struct CIFormatDiffDiagnostic {
#[location(resource)]
pub(crate) file_name: String,
#[advice]
pub(crate) diff: ContentDiffAdvice,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "organizeImports",
message = "Import statements differs from the output"
)]
pub(crate) struct CIOrganizeImportsDiffDiagnostic {
#[location(resource)]
pub(crate) file_name: String,
#[advice]
pub(crate) diff: ContentDiffAdvice,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "format",
severity = Information,
message = "Formatter would have printed the following content:"
)]
pub(crate) struct FormatDiffDiagnostic {
#[location(resource)]
pub(crate) file_name: String,
#[advice]
pub(crate) diff: ContentDiffAdvice,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "organizeImports",
severity = Information,
message = "Import statements could be sorted:"
)]
pub(crate) struct OrganizeImportsDiffDiagnostic {
#[location(resource)]
pub(crate) file_name: String,
#[advice]
pub(crate) diff: ContentDiffAdvice,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "migrate",
severity = Information,
message = "Configuration file can be updated."
)]
pub(crate) struct MigrateDiffDiagnostic {
#[location(resource)]
pub(crate) file_name: String,
#[advice]
pub(crate) diff: ContentDiffAdvice,
}
#[derive(Debug)]
pub(crate) struct ContentDiffAdvice {
pub(crate) old: String,
pub(crate) new: String,
}
impl Advices for ContentDiffAdvice {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
let diff = TextEdit::from_unicode_words(&self.old, &self.new);
visitor.record_diff(&diff)
}
}
#[derive(Debug, Diagnostic)]
pub(crate) struct TraversalDiagnostic<'a> {
#[location(resource)]
pub(crate) file_name: Option<&'a str>,
#[severity]
pub(crate) severity: Severity,
#[category]
pub(crate) category: &'static Category,
#[message]
#[description]
pub(crate) message: &'a str,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(category = "internalError/panic", tags(INTERNAL))]
pub(crate) struct PanicDiagnostic {
#[description]
#[message]
pub(crate) message: String,
}
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "files/missingHandler",
message = "Rome doesn't know how to process this file",
severity = Warning
)]
pub(crate) struct UnhandledDiagnostic;
#[derive(Debug, Diagnostic)]
#[diagnostic(category = "parse", message = "Skipped file with syntax errors")]
pub(crate) struct SkippedDiagnostic;
/// Extension trait for turning [Display]-able error types into [TraversalError]
pub(crate) trait ResultExt {
type Result;
fn with_file_path_and_code(
self,
file_path: String,
code: &'static Category,
) -> Result<Self::Result, Error>;
}
impl<T, E> ResultExt for Result<T, E>
where
E: std::error::Error + Send + Sync + 'static,
{
type Result = T;
fn with_file_path_and_code(
self,
file_path: String,
code: &'static Category,
) -> Result<Self::Result, Error> {
self.map_err(move |err| {
StdError::from(err)
.with_category(code)
.with_file_path(file_path)
})
}
}
/// Extension trait for turning [io::Error] into [Error]
pub(crate) trait ResultIoExt: ResultExt {
fn with_file_path(self, file_path: String) -> Result<Self::Result, Error>;
}
impl<T> ResultIoExt for io::Result<T> {
fn with_file_path(self, file_path: String) -> Result<Self::Result, Error> {
self.map_err(|error| IoError::from(error).with_file_path(file_path))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/execute/migrate.rs | crates/rome_cli/src/execute/migrate.rs | use crate::execute::diagnostics::{ContentDiffAdvice, MigrateDiffDiagnostic};
use crate::{CliDiagnostic, CliSession};
use rome_console::{markup, ConsoleExt};
use rome_diagnostics::{category, PrintDiagnostic};
use rome_fs::OpenOptions;
use rome_json_parser::JsonParserOptions;
use rome_json_syntax::JsonRoot;
use rome_migrate::{migrate_configuration, ControlFlow};
use rome_rowan::AstNode;
use rome_service::workspace::FixAction;
use std::borrow::Cow;
use std::path::PathBuf;
pub(crate) fn run(
session: CliSession,
write: bool,
configuration_path: PathBuf,
verbose: bool,
) -> Result<(), CliDiagnostic> {
let fs = &*session.app.fs;
let open_options = if write {
OpenOptions::default().write(true)
} else {
OpenOptions::default().read(true)
};
let mut configuration_file =
fs.open_with_options(configuration_path.as_path(), open_options)?;
let mut configuration_content = String::new();
configuration_file.read_to_string(&mut configuration_content)?;
let parsed = rome_json_parser::parse_json(&configuration_content, JsonParserOptions::default());
let mut errors = 0;
let mut tree = parsed.tree();
let mut actions = Vec::new();
loop {
let (action, _) = migrate_configuration(
&tree.value().unwrap(),
configuration_path.as_path(),
|signal| {
let current_diagnostic = signal.diagnostic();
if current_diagnostic.is_some() {
errors += 1;
}
if let Some(action) = signal.actions().next() {
return ControlFlow::Break(action);
}
ControlFlow::Continue(())
},
);
match action {
Some(action) => {
if let Some((range, _)) = action.mutation.as_text_edits() {
tree = match JsonRoot::cast(action.mutation.commit()) {
Some(tree) => tree,
None => return Err(CliDiagnostic::check_error(category!("migrate"))),
};
actions.push(FixAction {
rule_name: action
.rule_name
.map(|(group, rule)| (Cow::Borrowed(group), Cow::Borrowed(rule))),
range,
});
}
}
None => {
break;
}
}
}
let console = &mut *session.app.console;
let new_configuration_content = tree.to_string();
if configuration_content != new_configuration_content {
if write {
configuration_file.set_content(tree.to_string().as_bytes())?;
console.log(markup!{
<Info>"The configuration "<Emphasis>{{configuration_path.display().to_string()}}</Emphasis>" has been successfully migrated"</Info>
})
} else {
let file_name = configuration_path.display().to_string();
let diagnostic = MigrateDiffDiagnostic {
file_name,
diff: ContentDiffAdvice {
old: configuration_content,
new: new_configuration_content,
},
};
console.error(markup! {
{if verbose { PrintDiagnostic::verbose(&diagnostic) } else { PrintDiagnostic::simple(&diagnostic) }}
});
}
} else {
console.log(markup! {
<Info>
"Your configuration file is up to date."
</Info>
})
}
Ok(())
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/execute/mod.rs | crates/rome_cli/src/execute/mod.rs | mod diagnostics;
mod migrate;
mod process_file;
mod std_in;
mod traverse;
use crate::cli_options::CliOptions;
use crate::execute::traverse::traverse;
use crate::{CliDiagnostic, CliSession};
use rome_diagnostics::{category, Category, MAXIMUM_DISPLAYABLE_DIAGNOSTICS};
use rome_fs::RomePath;
use rome_service::workspace::{FeatureName, FixFileMode};
use std::ffi::OsString;
use std::fmt::{Display, Formatter};
use std::path::PathBuf;
/// Useful information during the traversal of files and virtual content
pub(crate) struct Execution {
/// How the information should be collected and reported
report_mode: ReportMode,
/// The modality of execution of the traversal
traversal_mode: TraversalMode,
/// The maximum number of diagnostics that can be printed in console
max_diagnostics: u16,
}
impl Execution {
pub(crate) fn as_feature_name(&self) -> FeatureName {
match self.traversal_mode {
TraversalMode::Format { .. } => FeatureName::Format,
_ => FeatureName::Lint,
}
}
}
#[derive(Debug)]
pub(crate) enum TraversalMode {
/// This mode is enabled when running the command `rome check`
Check {
/// The type of fixes that should be applied when analyzing a file.
///
/// It's [None] if the `check` command is called without `--apply` or `--apply-suggested`
/// arguments.
fix_file_mode: Option<FixFileMode>,
/// An optional tuple.
/// 1. The virtual path to the file
/// 2. The content of the file
stdin: Option<(PathBuf, String)>,
},
/// This mode is enabled when running the command `rome lint`
Lint {
/// The type of fixes that should be applied when analyzing a file.
///
/// It's [None] if the `check` command is called without `--apply` or `--apply-suggested`
/// arguments.
fix_file_mode: Option<FixFileMode>,
/// An optional tuple.
/// 1. The virtual path to the file
/// 2. The content of the file
stdin: Option<(PathBuf, String)>,
},
/// This mode is enabled when running the command `rome ci`
CI,
/// This mode is enabled when running the command `rome format`
Format {
/// It ignores parse errors
ignore_errors: bool,
/// It writes the new content on file
write: bool,
/// An optional tuple.
/// 1. The virtual path to the file
/// 2. The content of the file
stdin: Option<(PathBuf, String)>,
},
/// This mode is enabled when running the command `rome migrate`
Migrate {
write: bool,
configuration_path: PathBuf,
},
}
impl Display for TraversalMode {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
TraversalMode::Check { .. } => write!(f, "check"),
TraversalMode::CI { .. } => write!(f, "ci"),
TraversalMode::Format { .. } => write!(f, "format"),
TraversalMode::Migrate { .. } => write!(f, "migrate"),
TraversalMode::Lint { .. } => write!(f, "lint"),
}
}
}
/// Tells to the execution of the traversal how the information should be reported
#[derive(Copy, Clone, Default)]
pub(crate) enum ReportMode {
/// Reports information straight to the console, it's the default mode
#[default]
Terminal,
/// Reports information in JSON format
Json,
}
impl Execution {
pub(crate) fn new(mode: TraversalMode) -> Self {
Self {
report_mode: ReportMode::default(),
traversal_mode: mode,
max_diagnostics: MAXIMUM_DISPLAYABLE_DIAGNOSTICS,
}
}
/// Creates an instance of [Execution] by passing [traversal mode](TraversalMode) and [report mode](ReportMode)
pub(crate) fn with_report(traversal_mode: TraversalMode, report_mode: ReportMode) -> Self {
Self {
traversal_mode,
report_mode,
max_diagnostics: MAXIMUM_DISPLAYABLE_DIAGNOSTICS,
}
}
/// Tells if the reporting is happening straight to terminal
pub(crate) fn should_report_to_terminal(&self) -> bool {
matches!(self.report_mode, ReportMode::Terminal)
}
pub(crate) fn traversal_mode(&self) -> &TraversalMode {
&self.traversal_mode
}
pub(crate) fn get_max_diagnostics(&self) -> u16 {
self.max_diagnostics
}
/// `true` only when running the traversal in [TraversalMode::Check] and `should_fix` is `true`
pub(crate) fn as_fix_file_mode(&self) -> Option<&FixFileMode> {
match &self.traversal_mode {
TraversalMode::Check { fix_file_mode, .. }
| TraversalMode::Lint { fix_file_mode, .. } => fix_file_mode.as_ref(),
TraversalMode::Format { .. } | TraversalMode::CI | TraversalMode::Migrate { .. } => {
None
}
}
}
pub(crate) fn as_diagnostic_category(&self) -> &'static Category {
match self.traversal_mode {
TraversalMode::Check { .. } => category!("check"),
TraversalMode::Lint { .. } => category!("lint"),
TraversalMode::CI => category!("ci"),
TraversalMode::Format { .. } => category!("format"),
TraversalMode::Migrate { .. } => category!("migrate"),
}
}
pub(crate) const fn is_ci(&self) -> bool {
matches!(self.traversal_mode, TraversalMode::CI { .. })
}
pub(crate) const fn is_check(&self) -> bool {
matches!(self.traversal_mode, TraversalMode::Check { .. })
}
pub(crate) const fn is_lint(&self) -> bool {
matches!(self.traversal_mode, TraversalMode::Lint { .. })
}
pub(crate) const fn is_check_apply(&self) -> bool {
matches!(
self.traversal_mode,
TraversalMode::Check {
fix_file_mode: Some(FixFileMode::SafeFixes),
..
}
)
}
pub(crate) const fn is_check_apply_unsafe(&self) -> bool {
matches!(
self.traversal_mode,
TraversalMode::Check {
fix_file_mode: Some(FixFileMode::SafeAndUnsafeFixes),
..
}
)
}
pub(crate) const fn is_format(&self) -> bool {
matches!(self.traversal_mode, TraversalMode::Format { .. })
}
/// Whether the traversal mode requires write access to files
pub(crate) const fn requires_write_access(&self) -> bool {
match self.traversal_mode {
TraversalMode::Check { fix_file_mode, .. }
| TraversalMode::Lint { fix_file_mode, .. } => fix_file_mode.is_some(),
TraversalMode::CI => false,
TraversalMode::Format { write, .. } => write,
TraversalMode::Migrate { write: dry_run, .. } => dry_run,
}
}
pub(crate) fn as_stdin_file(&self) -> Option<&(PathBuf, String)> {
match &self.traversal_mode {
TraversalMode::Format { stdin, .. }
| TraversalMode::Lint { stdin, .. }
| TraversalMode::Check { stdin, .. } => stdin.as_ref(),
TraversalMode::CI { .. } | TraversalMode::Migrate { .. } => None,
}
}
}
/// Based on the [mode](ExecutionMode), the function might launch a traversal of the file system
/// or handles the stdin file.
pub(crate) fn execute_mode(
mut mode: Execution,
session: CliSession,
cli_options: &CliOptions,
paths: Vec<OsString>,
) -> Result<(), CliDiagnostic> {
if cli_options.max_diagnostics > MAXIMUM_DISPLAYABLE_DIAGNOSTICS {
return Err(CliDiagnostic::overflown_argument(
"--max-diagnostics",
MAXIMUM_DISPLAYABLE_DIAGNOSTICS,
));
}
mode.max_diagnostics = cli_options.max_diagnostics;
// don't do any traversal if there's some content coming from stdin
if let Some((path, content)) = mode.as_stdin_file() {
let rome_path = RomePath::new(path);
std_in::run(session, &mode, rome_path, content.as_str())
} else if let TraversalMode::Migrate {
write,
configuration_path,
} = mode.traversal_mode
{
migrate::run(session, write, configuration_path, cli_options.verbose)
} else {
traverse(mode, session, cli_options, paths)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/execute/traverse.rs | crates/rome_cli/src/execute/traverse.rs | use super::process_file::{process_file, DiffKind, FileStatus, Message};
use crate::cli_options::CliOptions;
use crate::execute::diagnostics::{
CIFormatDiffDiagnostic, CIOrganizeImportsDiffDiagnostic, ContentDiffAdvice,
FormatDiffDiagnostic, OrganizeImportsDiffDiagnostic, PanicDiagnostic,
};
use crate::{
CliDiagnostic, CliSession, Execution, FormatterReportFileDetail, FormatterReportSummary,
Report, ReportDiagnostic, ReportDiff, ReportErrorKind, ReportKind, TraversalMode,
};
use crossbeam::{
channel::{unbounded, Receiver, Sender},
select,
};
use rome_console::{fmt, markup, Console, ConsoleExt};
use rome_diagnostics::{
adapters::StdError, category, DiagnosticExt, Error, PrintDescription, PrintDiagnostic,
Resource, Severity,
};
use rome_fs::{FileSystem, PathInterner, RomePath};
use rome_fs::{TraversalContext, TraversalScope};
use rome_service::workspace::{FeaturesBuilder, IsPathIgnoredParams};
use rome_service::{
workspace::{FeatureName, SupportsFeatureParams},
Workspace, WorkspaceError,
};
use std::collections::HashSet;
use std::{
ffi::OsString,
io,
panic::catch_unwind,
path::{Path, PathBuf},
sync::{
atomic::{AtomicU16, AtomicUsize, Ordering},
Once,
},
thread,
time::{Duration, Instant},
};
struct CheckResult {
count: usize,
duration: Duration,
errors: usize,
}
impl fmt::Display for CheckResult {
fn fmt(&self, fmt: &mut fmt::Formatter) -> io::Result<()> {
markup!(<Info>"Checked "{self.count}" file(s) in "{self.duration}</Info>).fmt(fmt)?;
if self.errors > 0 {
markup!("\n"<Error>"Found "{self.errors}" error(s)"</Error>).fmt(fmt)?
}
Ok(())
}
}
///
pub(crate) fn traverse(
execution: Execution,
session: CliSession,
cli_options: &CliOptions,
inputs: Vec<OsString>,
) -> Result<(), CliDiagnostic> {
init_thread_pool();
if inputs.is_empty() && execution.as_stdin_file().is_none() {
return Err(CliDiagnostic::missing_argument(
"<INPUT>",
format!("{}", execution.traversal_mode),
));
}
let (interner, recv_files) = PathInterner::new();
let (send_msgs, recv_msgs) = unbounded();
let (sender_reports, recv_reports) = unbounded();
let processed = AtomicUsize::new(0);
let skipped = AtomicUsize::new(0);
let fs = &*session.app.fs;
let workspace = &*session.app.workspace;
let console = &mut *session.app.console;
let max_diagnostics = execution.get_max_diagnostics();
let remaining_diagnostics = AtomicU16::new(max_diagnostics);
let mut errors: usize = 0;
let mut warnings: usize = 0;
let mut report = Report::default();
let duration = thread::scope(|s| {
thread::Builder::new()
.name(String::from("rome::console"))
.spawn_scoped(s, || {
process_messages(ProcessMessagesOptions {
execution: &execution,
console,
recv_reports,
recv_files,
recv_msgs,
max_diagnostics,
remaining_diagnostics: &remaining_diagnostics,
errors: &mut errors,
report: &mut report,
verbose: cli_options.verbose,
warnings: &mut warnings,
});
})
.expect("failed to spawn console thread");
// The traversal context is scoped to ensure all the channels it
// contains are properly closed once the traversal finishes
traverse_inputs(
fs,
inputs,
&TraversalOptions {
fs,
workspace,
execution: &execution,
interner,
processed: &processed,
skipped: &skipped,
messages: send_msgs,
sender_reports,
remaining_diagnostics: &remaining_diagnostics,
},
)
});
let count = processed.load(Ordering::Relaxed);
let skipped = skipped.load(Ordering::Relaxed);
if execution.should_report_to_terminal() {
match execution.traversal_mode() {
TraversalMode::Check { .. } | TraversalMode::Lint { .. } => {
if execution.as_fix_file_mode().is_some() {
console.log(markup! {
<Info>"Fixed "{count}" file(s) in "{duration}</Info>
});
} else {
console.log(markup!({
CheckResult {
count,
duration,
errors,
}
}));
}
}
TraversalMode::CI { .. } => {
console.log(markup!({
CheckResult {
count,
duration,
errors,
}
}));
}
TraversalMode::Format { write: false, .. } => {
console.log(markup! {
<Info>"Compared "{count}" file(s) in "{duration}</Info>
});
}
TraversalMode::Format { write: true, .. } => {
console.log(markup! {
<Info>"Formatted "{count}" file(s) in "{duration}</Info>
});
}
TraversalMode::Migrate { write: false, .. } => {
console.log(markup! {
<Info>"Checked your configuration file in "{duration}</Info>
});
}
TraversalMode::Migrate { write: true, .. } => {
console.log(markup! {
<Info>"Migrated your configuration file in "{duration}</Info>
});
}
}
} else {
if let TraversalMode::Format { write, .. } = execution.traversal_mode() {
let mut summary = FormatterReportSummary::default();
if *write {
summary.set_files_written(count);
} else {
summary.set_files_compared(count);
}
report.set_formatter_summary(summary);
}
let to_print = report.as_serialized_reports()?;
console.log(markup! {
{to_print}
});
return Ok(());
}
if skipped > 0 {
console.log(markup! {
<Warn>"Skipped "{skipped}" file(s)"</Warn>
});
}
let should_exit_on_warnings = warnings > 0 && cli_options.error_on_warnings;
// Processing emitted error diagnostics, exit with a non-zero code
if count.saturating_sub(skipped) == 0 && !cli_options.no_errors_on_unmatched {
Err(CliDiagnostic::no_files_processed())
} else if errors > 0 || should_exit_on_warnings {
let category = execution.as_diagnostic_category();
if should_exit_on_warnings {
if execution.is_check_apply() {
Err(CliDiagnostic::apply_warnings(category))
} else {
Err(CliDiagnostic::check_warnings(category))
}
} else if execution.is_check_apply() {
Err(CliDiagnostic::apply_error(category))
} else {
Err(CliDiagnostic::check_error(category))
}
} else {
Ok(())
}
}
/// This function will setup the global Rayon thread pool the first time it's called
///
/// This is currently only used to assign friendly debug names to the threads of the pool
fn init_thread_pool() {
static INIT_ONCE: Once = Once::new();
INIT_ONCE.call_once(|| {
rayon::ThreadPoolBuilder::new()
.thread_name(|index| format!("rome::worker_{index}"))
.build_global()
.expect("failed to initialize the global thread pool");
});
}
/// Initiate the filesystem traversal tasks with the provided input paths and
/// run it to completion, returning the duration of the process
fn traverse_inputs(fs: &dyn FileSystem, inputs: Vec<OsString>, ctx: &TraversalOptions) -> Duration {
let start = Instant::now();
fs.traversal(Box::new(move |scope: &dyn TraversalScope| {
for input in inputs {
scope.spawn(ctx, PathBuf::from(input));
}
}));
start.elapsed()
}
struct ProcessMessagesOptions<'ctx> {
/// Execution of the traversal
execution: &'ctx Execution,
/// Mutable reference to the [console](Console)
console: &'ctx mut dyn Console,
/// Receiver channel for reporting statistics
recv_reports: Receiver<ReportKind>,
/// Receiver channel that expects info when a file is processed
recv_files: Receiver<PathBuf>,
/// Receiver channel that expects info when a message is sent
recv_msgs: Receiver<Message>,
/// The maximum number of diagnostics the console thread is allowed to print
max_diagnostics: u16,
/// The approximate number of diagnostics the console will print before
/// folding the rest into the "skipped diagnostics" counter
remaining_diagnostics: &'ctx AtomicU16,
/// Mutable reference to a boolean flag tracking whether the console thread
/// printed any error-level message
errors: &'ctx mut usize,
/// Mutable reference to a boolean flag tracking whether the console thread
/// printed any warnings-level message
warnings: &'ctx mut usize,
/// Mutable handle to a [Report] instance the console thread should write
/// stats into
report: &'ctx mut Report,
/// Whether the console thread should print diagnostics in verbose mode
verbose: bool,
}
/// This thread receives [Message]s from the workers through the `recv_msgs`
/// and `recv_files` channels and handles them based on [Execution]
fn process_messages(options: ProcessMessagesOptions) {
let ProcessMessagesOptions {
execution: mode,
console,
recv_reports,
recv_files,
recv_msgs,
max_diagnostics,
remaining_diagnostics,
errors,
report,
verbose,
warnings,
} = options;
let mut paths: HashSet<String> = HashSet::new();
let mut printed_diagnostics: u16 = 0;
let mut not_printed_diagnostics = 0;
let mut total_skipped_suggested_fixes = 0;
let mut is_msg_open = true;
let mut is_report_open = true;
let mut diagnostics_to_print = vec![];
while is_msg_open || is_report_open {
let msg = select! {
recv(recv_msgs) -> msg => match msg {
Ok(msg) => msg,
Err(_) => {
is_msg_open = false;
continue;
},
},
recv(recv_reports) -> stat => {
match stat {
Ok(stat) => {
report.push_detail_report(stat);
}
Err(_) => {
is_report_open = false;
},
}
continue;
}
};
match msg {
Message::SkippedFixes {
skipped_suggested_fixes,
} => {
total_skipped_suggested_fixes += skipped_suggested_fixes;
}
Message::ApplyError(error) => {
*errors += 1;
let should_print = printed_diagnostics < max_diagnostics;
if should_print {
printed_diagnostics += 1;
remaining_diagnostics.store(
max_diagnostics.saturating_sub(printed_diagnostics),
Ordering::Relaxed,
);
} else {
not_printed_diagnostics += 1;
}
if mode.should_report_to_terminal() && should_print {
diagnostics_to_print.push(Error::from(error));
}
}
Message::Error(mut err) => {
let location = err.location();
if err.severity() == Severity::Warning {
*warnings += 1;
}
if let Some(Resource::File(file_path)) = location.resource.as_ref() {
// Retrieves the file name from the file ID cache, if it's a miss
// flush entries from the interner channel until it's found
let file_name = match paths.get(*file_path) {
Some(path) => Some(path),
None => loop {
match recv_files.recv() {
Ok(path) => {
paths.insert(path.display().to_string());
if path.display().to_string() == *file_path {
break paths.get(&path.display().to_string());
}
}
// In case the channel disconnected without sending
// the path we need, print the error without a file
// name (normally this should never happen)
Err(_) => break None,
}
},
};
if let Some(path) = file_name {
err = err.with_file_path(path.as_str());
}
}
let should_print = printed_diagnostics < max_diagnostics;
if should_print {
printed_diagnostics += 1;
remaining_diagnostics.store(
max_diagnostics.saturating_sub(printed_diagnostics),
Ordering::Relaxed,
);
} else {
not_printed_diagnostics += 1;
}
if mode.should_report_to_terminal() {
if should_print {
diagnostics_to_print.push(err);
}
} else {
let location = err.location();
let path = match &location.resource {
Some(Resource::File(file)) => Some(*file),
_ => None,
};
let file_name = path.unwrap_or("<unknown>");
let title = PrintDescription(&err).to_string();
let code = err.category().and_then(|code| code.name().parse().ok());
report.push_detail_report(ReportKind::Error(
file_name.to_string(),
ReportErrorKind::Diagnostic(ReportDiagnostic {
code,
title,
severity: err.severity(),
}),
));
}
}
Message::Diagnostics {
name,
content,
diagnostics,
skipped_diagnostics,
} => {
not_printed_diagnostics += skipped_diagnostics;
// is CI mode we want to print all the diagnostics
if mode.is_ci() {
for diag in diagnostics {
if diag.severity() == Severity::Error {
*errors += 1;
}
let diag = diag.with_file_path(&name).with_file_source_code(&content);
diagnostics_to_print.push(diag);
}
} else {
for diag in diagnostics {
let severity = diag.severity();
if severity == Severity::Error {
*errors += 1;
}
if severity == Severity::Warning {
*warnings += 1;
}
let should_print = printed_diagnostics < max_diagnostics;
if should_print {
printed_diagnostics += 1;
remaining_diagnostics.store(
max_diagnostics.saturating_sub(printed_diagnostics),
Ordering::Relaxed,
);
} else {
not_printed_diagnostics += 1;
}
if mode.should_report_to_terminal() {
if should_print {
let diag =
diag.with_file_path(&name).with_file_source_code(&content);
diagnostics_to_print.push(diag)
}
} else {
report.push_detail_report(ReportKind::Error(
name.to_string(),
ReportErrorKind::Diagnostic(ReportDiagnostic {
code: diag.category().and_then(|code| code.name().parse().ok()),
title: String::from("test here"),
severity,
}),
));
}
}
}
}
Message::Diff {
file_name,
old,
new,
diff_kind,
} => {
if mode.is_ci() {
// A diff is an error in CI mode
*errors += 1;
}
let should_print = printed_diagnostics < max_diagnostics;
if should_print {
printed_diagnostics += 1;
remaining_diagnostics.store(
max_diagnostics.saturating_sub(printed_diagnostics),
Ordering::Relaxed,
);
} else {
not_printed_diagnostics += 1;
}
if mode.should_report_to_terminal() {
if should_print {
if mode.is_ci() {
match diff_kind {
DiffKind::Format => {
let diag = CIFormatDiffDiagnostic {
file_name: file_name.clone(),
diff: ContentDiffAdvice {
old: old.clone(),
new: new.clone(),
},
};
diagnostics_to_print.push(Error::from(diag))
}
DiffKind::OrganizeImports => {
let diag = CIOrganizeImportsDiffDiagnostic {
file_name: file_name.clone(),
diff: ContentDiffAdvice {
old: old.clone(),
new: new.clone(),
},
};
diagnostics_to_print.push(Error::from(diag))
}
};
} else {
match diff_kind {
DiffKind::Format => {
let diag = FormatDiffDiagnostic {
file_name: file_name.clone(),
diff: ContentDiffAdvice {
old: old.clone(),
new: new.clone(),
},
};
diagnostics_to_print.push(Error::from(diag))
}
DiffKind::OrganizeImports => {
let diag = OrganizeImportsDiffDiagnostic {
file_name: file_name.clone(),
diff: ContentDiffAdvice {
old: old.clone(),
new: new.clone(),
},
};
diagnostics_to_print.push(Error::from(diag))
}
};
}
}
} else {
report.push_detail_report(ReportKind::Error(
file_name,
ReportErrorKind::Diff(ReportDiff {
before: old,
after: new,
severity: Severity::Error,
}),
));
}
}
}
}
for diagnostic in diagnostics_to_print {
console.error(markup! {
{if verbose { PrintDiagnostic::verbose(&diagnostic) } else { PrintDiagnostic::simple(&diagnostic) }}
});
}
if mode.is_check() && total_skipped_suggested_fixes > 0 {
console.log(markup! {
<Warn>"Skipped "{total_skipped_suggested_fixes}" suggested fixes.\n"</Warn>
<Info>"If you wish to apply the suggested (unsafe) fixes, use the command "<Emphasis>"rome check --apply-unsafe\n"</Emphasis></Info>
})
}
if !mode.is_ci() && not_printed_diagnostics > 0 {
console.log(markup! {
<Warn>"The number of diagnostics exceeds the number allowed by Rome.\n"</Warn>
<Info>"Diagnostics not shown: "</Info><Emphasis>{not_printed_diagnostics}</Emphasis><Info>"."</Info>
})
}
}
/// Context object shared between directory traversal tasks
pub(crate) struct TraversalOptions<'ctx, 'app> {
/// Shared instance of [FileSystem]
pub(crate) fs: &'app dyn FileSystem,
/// Instance of [Workspace] used by this instance of the CLI
pub(crate) workspace: &'ctx dyn Workspace,
/// Determines how the files should be processed
pub(crate) execution: &'ctx Execution,
/// File paths interner cache used by the filesystem traversal
interner: PathInterner,
/// Shared atomic counter storing the number of processed files
processed: &'ctx AtomicUsize,
/// Shared atomic counter storing the number of skipped files
skipped: &'ctx AtomicUsize,
/// Channel sending messages to the display thread
pub(crate) messages: Sender<Message>,
/// Channel sending reports to the reports thread
sender_reports: Sender<ReportKind>,
/// The approximate number of diagnostics the console will print before
/// folding the rest into the "skipped diagnostics" counter
pub(crate) remaining_diagnostics: &'ctx AtomicU16,
}
impl<'ctx, 'app> TraversalOptions<'ctx, 'app> {
pub(crate) fn increment_processed(&self) {
self.processed.fetch_add(1, Ordering::Relaxed);
}
/// Send a message to the display thread
pub(crate) fn push_message(&self, msg: impl Into<Message>) {
self.messages.send(msg.into()).ok();
}
pub(crate) fn push_format_stat(&self, path: String, stat: FormatterReportFileDetail) {
self.sender_reports
.send(ReportKind::Formatter(path, stat))
.ok();
}
pub(crate) fn miss_handler_err(&self, err: WorkspaceError, rome_path: &RomePath) {
self.push_diagnostic(
StdError::from(err)
.with_category(category!("files/missingHandler"))
.with_file_path(rome_path.display().to_string()),
);
}
}
impl<'ctx, 'app> TraversalContext for TraversalOptions<'ctx, 'app> {
fn interner(&self) -> &PathInterner {
&self.interner
}
fn push_diagnostic(&self, error: Error) {
self.push_message(error);
}
fn can_handle(&self, rome_path: &RomePath) -> bool {
if rome_path.is_dir() {
let can_handle = !self
.workspace
.is_path_ignored(IsPathIgnoredParams {
rome_path: rome_path.clone(),
feature: self.execution.as_feature_name(),
})
.unwrap_or_else(|err| {
self.push_diagnostic(err.into());
false
});
return can_handle;
}
let file_features = self.workspace.file_features(SupportsFeatureParams {
path: rome_path.clone(),
feature: FeaturesBuilder::new()
.with_linter()
.with_formatter()
.with_organize_imports()
.build(),
});
let file_features = match file_features {
Ok(file_features) => file_features,
Err(err) => {
self.miss_handler_err(err, rome_path);
return false;
}
};
match self.execution.traversal_mode() {
TraversalMode::Check { .. } => {
file_features.supports_for(&FeatureName::Lint)
|| file_features.supports_for(&FeatureName::Format)
|| file_features.supports_for(&FeatureName::OrganizeImports)
}
TraversalMode::CI { .. } => {
file_features.supports_for(&FeatureName::Lint)
|| file_features.supports_for(&FeatureName::Format)
|| file_features.supports_for(&FeatureName::OrganizeImports)
}
TraversalMode::Format { .. } => file_features.supports_for(&FeatureName::Format),
TraversalMode::Lint { .. } => file_features.supports_for(&FeatureName::Lint),
// Imagine if Rome can't handle its own configuration file...
TraversalMode::Migrate { .. } => true,
}
}
fn handle_file(&self, path: &Path) {
handle_file(self, path)
}
}
/// This function wraps the [process_file] function implementing the traversal
/// in a [catch_unwind] block and emit diagnostics in case of error (either the
/// traversal function returns Err or panics)
fn handle_file(ctx: &TraversalOptions, path: &Path) {
match catch_unwind(move || process_file(ctx, path)) {
Ok(Ok(FileStatus::Success)) => {}
Ok(Ok(FileStatus::Message(msg))) => {
ctx.push_message(msg);
}
Ok(Ok(FileStatus::Ignored)) => {}
Ok(Err(err)) => {
ctx.skipped.fetch_add(1, Ordering::Relaxed);
ctx.push_message(err);
}
Err(err) => {
let message = match err.downcast::<String>() {
Ok(msg) => format!("processing panicked: {msg}"),
Err(err) => match err.downcast::<&'static str>() {
Ok(msg) => format!("processing panicked: {msg}"),
Err(_) => String::from("processing panicked"),
},
};
ctx.push_message(
PanicDiagnostic { message }.with_file_path(path.display().to_string()),
);
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/execute/process_file.rs | crates/rome_cli/src/execute/process_file.rs | mod check;
mod format;
mod lint;
mod organize_imports;
mod workspace_file;
use crate::execute::diagnostics::{ResultExt, UnhandledDiagnostic};
use crate::execute::process_file::check::check_file;
use crate::execute::process_file::format::format;
use crate::execute::process_file::lint::lint;
use crate::execute::traverse::TraversalOptions;
use crate::execute::TraversalMode;
use crate::CliDiagnostic;
use rome_diagnostics::{category, DiagnosticExt, Error};
use rome_fs::RomePath;
use rome_service::workspace::{FeatureName, FeaturesBuilder, SupportKind, SupportsFeatureParams};
use std::marker::PhantomData;
use std::ops::Deref;
use std::path::Path;
#[derive(Debug)]
pub(crate) enum FileStatus {
Success,
Message(Message),
Ignored,
}
/// Wrapper type for messages that can be printed during the traversal process
#[derive(Debug)]
pub(crate) enum Message {
SkippedFixes {
/// Suggested fixes skipped during the lint traversal
skipped_suggested_fixes: u32,
},
ApplyError(CliDiagnostic),
Error(Error),
Diagnostics {
name: String,
content: String,
diagnostics: Vec<Error>,
skipped_diagnostics: u64,
},
Diff {
file_name: String,
old: String,
new: String,
diff_kind: DiffKind,
},
}
impl Message {
pub(crate) const fn is_diagnostic(&self) -> bool {
matches!(self, Message::Diff { .. } | Message::Diagnostics { .. })
}
}
#[derive(Debug)]
pub(crate) enum DiffKind {
Format,
OrganizeImports,
}
impl<D> From<D> for Message
where
Error: From<D>,
D: std::fmt::Debug,
{
fn from(err: D) -> Self {
Self::Error(Error::from(err))
}
}
/// The return type for [process_file], with the following semantics:
/// - `Ok(Success)` means the operation was successful (the file is added to
/// the `processed` counter)
/// - `Ok(Message(_))` means the operation was successful but a message still
/// needs to be printed (eg. the diff when not in CI or write mode)
/// - `Ok(Ignored)` means the file was ignored (the file is not added to the
/// `processed` or `skipped` counters)
/// - `Err(_)` means the operation failed and the file should be added to the
/// `skipped` counter
pub(crate) type FileResult = Result<FileStatus, Message>;
/// Data structure that allows to pass [TraversalOptions] to multiple consumers, bypassing the
/// compiler constraints set by the lifetimes of the [TraversalOptions]
pub(crate) struct SharedTraversalOptions<'ctx, 'app> {
inner: &'app TraversalOptions<'ctx, 'app>,
_p: PhantomData<&'app ()>,
}
impl<'ctx, 'app> SharedTraversalOptions<'ctx, 'app> {
fn new(t: &'app TraversalOptions<'ctx, 'app>) -> Self {
Self {
_p: PhantomData::default(),
inner: t,
}
}
}
impl<'ctx, 'app> Deref for SharedTraversalOptions<'ctx, 'app> {
type Target = TraversalOptions<'ctx, 'app>;
fn deref(&self) -> &Self::Target {
self.inner
}
}
/// This function performs the actual processing: it reads the file from disk
/// and parse it; analyze and / or format it; then it either fails if error
/// diagnostics were emitted, or compare the formatted code with the original
/// content of the file and emit a diff or write the new content to the disk if
/// write mode is enabled
pub(crate) fn process_file(ctx: &TraversalOptions, path: &Path) -> FileResult {
tracing::trace_span!("process_file", path = ?path).in_scope(move || {
let rome_path = RomePath::new(path);
let file_features = ctx
.workspace
.file_features(SupportsFeatureParams {
path: rome_path,
feature: FeaturesBuilder::new()
.with_formatter()
.with_linter()
.with_organize_imports()
.build(),
})
.with_file_path_and_code(
path.display().to_string(),
category!("files/missingHandler"),
)?;
let unsupported_reason = match ctx.execution.traversal_mode() {
TraversalMode::Check { .. } => file_features
.support_kind_for(&FeatureName::Lint)
.and_then(|support_kind| {
if support_kind.is_not_enabled() {
Some(support_kind)
} else {
None
}
})
.and(
file_features
.support_kind_for(&FeatureName::Format)
.and_then(|support_kind| {
if support_kind.is_not_enabled() {
Some(support_kind)
} else {
None
}
}),
)
.and(
file_features
.support_kind_for(&FeatureName::OrganizeImports)
.and_then(|support_kind| {
if support_kind.is_not_enabled() {
Some(support_kind)
} else {
None
}
}),
),
TraversalMode::CI { .. } => file_features
.support_kind_for(&FeatureName::Lint)
.and_then(|support_kind| {
if support_kind.is_not_enabled() {
Some(support_kind)
} else {
None
}
})
.and(
file_features
.support_kind_for(&FeatureName::Format)
.and_then(|support_kind| {
if support_kind.is_not_enabled() {
Some(support_kind)
} else {
None
}
}),
)
.and(
file_features
.support_kind_for(&FeatureName::OrganizeImports)
.and_then(|support_kind| {
if support_kind.is_not_enabled() {
Some(support_kind)
} else {
None
}
}),
),
TraversalMode::Format { .. } => file_features.support_kind_for(&FeatureName::Format),
TraversalMode::Lint { .. } => file_features.support_kind_for(&FeatureName::Lint),
TraversalMode::Migrate { .. } => None,
};
if let Some(reason) = unsupported_reason {
match reason {
SupportKind::FileNotSupported => {
return Err(Message::from(
UnhandledDiagnostic.with_file_path(path.display().to_string()),
))
}
SupportKind::FeatureNotEnabled | SupportKind::Ignored => {
return Ok(FileStatus::Ignored)
}
SupportKind::Supported => {}
};
}
let shared_context = &SharedTraversalOptions::new(ctx);
ctx.increment_processed();
match ctx.execution.traversal_mode {
TraversalMode::Lint { .. } => {
// the unsupported case should be handled already at this point
lint(shared_context, path)
}
TraversalMode::Format { .. } => {
// the unsupported case should be handled already at this point
format(shared_context, path)
}
TraversalMode::Check { .. } => {
check_file(shared_context, path, &file_features, category!("check"))
}
TraversalMode::CI => check_file(shared_context, path, &file_features, category!("ci")),
TraversalMode::Migrate { .. } => {
unreachable!("The migration should not be called for this file")
}
}
})
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/execute/process_file/workspace_file.rs | crates/rome_cli/src/execute/process_file/workspace_file.rs | use crate::execute::diagnostics::{ResultExt, ResultIoExt};
use crate::execute::process_file::SharedTraversalOptions;
use rome_diagnostics::{category, Error};
use rome_fs::{File, OpenOptions, RomePath};
use rome_service::file_handlers::Language;
use rome_service::workspace::{FileGuard, OpenFileParams};
use rome_service::{Workspace, WorkspaceError};
use std::path::{Path, PathBuf};
/// Small wrapper that holds information and operations around the current processed file
pub(crate) struct WorkspaceFile<'ctx, 'app> {
guard: FileGuard<'app, dyn Workspace + 'ctx>,
file: Box<dyn File>,
pub(crate) path: PathBuf,
}
impl<'ctx, 'app> WorkspaceFile<'ctx, 'app> {
/// It attempts to read the file from disk, creating a [FileGuard] and
/// saving these information internally
pub(crate) fn new(
ctx: &SharedTraversalOptions<'ctx, 'app>,
path: &Path,
) -> Result<Self, Error> {
let rome_path = RomePath::new(path);
let open_options = OpenOptions::default()
.read(true)
.write(ctx.execution.requires_write_access());
let mut file = ctx
.fs
.open_with_options(path, open_options)
.with_file_path(path.display().to_string())?;
let mut input = String::new();
file.read_to_string(&mut input)
.with_file_path(path.display().to_string())?;
let guard = FileGuard::open(
ctx.workspace,
OpenFileParams {
path: rome_path,
version: 0,
content: input.clone(),
language_hint: Language::default(),
},
)
.with_file_path_and_code(path.display().to_string(), category!("internalError/fs"))?;
Ok(Self {
file,
guard,
path: PathBuf::from(path),
})
}
pub(crate) fn guard(&self) -> &FileGuard<'app, dyn Workspace + 'ctx> {
&self.guard
}
pub(crate) fn input(&self) -> Result<String, WorkspaceError> {
self.guard().get_file_content()
}
/// It updates the workspace file with `new_content`
pub(crate) fn update_file(&mut self, new_content: impl Into<String>) -> Result<(), Error> {
let new_content = new_content.into();
self.file
.set_content(new_content.as_bytes())
.with_file_path(self.path.display().to_string())?;
self.guard
.change_file(self.file.file_version(), new_content)?;
Ok(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/execute/process_file/check.rs | crates/rome_cli/src/execute/process_file/check.rs | use crate::execute::process_file::format::format_with_guard;
use crate::execute::process_file::lint::lint_with_guard;
use crate::execute::process_file::organize_imports::organize_imports_with_guard;
use crate::execute::process_file::workspace_file::WorkspaceFile;
use crate::execute::process_file::{FileResult, FileStatus, Message, SharedTraversalOptions};
use crate::CliDiagnostic;
use rome_diagnostics::Category;
use rome_service::workspace::{FeatureName, FileFeaturesResult};
use std::path::Path;
pub(crate) fn check_file<'ctx>(
ctx: &'ctx SharedTraversalOptions<'ctx, '_>,
path: &Path,
file_features: &'ctx FileFeaturesResult,
category: &'static Category,
) -> FileResult {
let mut has_errors = false;
let mut workspace_file = WorkspaceFile::new(ctx, path)?;
if file_features.supports_for(&FeatureName::Lint) {
let lint_result = lint_with_guard(ctx, &mut workspace_file);
match lint_result {
Ok(status) => {
if let FileStatus::Message(msg) = status {
if msg.is_diagnostic() {
has_errors = true
}
ctx.push_message(msg);
}
}
Err(err) => {
ctx.push_message(err);
has_errors = true;
}
}
}
if file_features.supports_for(&FeatureName::OrganizeImports) {
let organize_imports_result = organize_imports_with_guard(ctx, &mut workspace_file);
match organize_imports_result {
Ok(status) => {
if let FileStatus::Message(msg) = status {
if msg.is_diagnostic() {
has_errors = true
}
ctx.push_message(msg);
}
}
Err(err) => {
ctx.push_message(err);
has_errors = true;
}
}
}
if file_features.supports_for(&FeatureName::Format) {
let format_result = format_with_guard(ctx, &mut workspace_file);
match format_result {
Ok(status) => {
if let FileStatus::Message(msg) = status {
if msg.is_diagnostic() {
has_errors = true
}
ctx.push_message(msg);
}
}
Err(err) => {
ctx.push_message(err);
has_errors = true;
}
}
}
if has_errors {
if ctx.execution.is_check_apply() || ctx.execution.is_check_apply_unsafe() {
Ok(FileStatus::Message(Message::ApplyError(
CliDiagnostic::file_apply_error(path.display().to_string(), category),
)))
} else {
Ok(FileStatus::Message(Message::ApplyError(
CliDiagnostic::check_error(category),
)))
}
} else {
Ok(FileStatus::Success)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/execute/process_file/lint.rs | crates/rome_cli/src/execute/process_file/lint.rs | use crate::execute::diagnostics::ResultExt;
use crate::execute::process_file::workspace_file::WorkspaceFile;
use crate::execute::process_file::{FileResult, FileStatus, Message, SharedTraversalOptions};
use crate::CliDiagnostic;
use rome_diagnostics::{category, Error};
use rome_service::workspace::RuleCategories;
use std::path::Path;
use std::sync::atomic::Ordering;
/// Lints a single file and returns a [FileResult]
pub(crate) fn lint<'ctx>(ctx: &'ctx SharedTraversalOptions<'ctx, '_>, path: &Path) -> FileResult {
let mut workspace_file = WorkspaceFile::new(ctx, path)?;
lint_with_guard(ctx, &mut workspace_file)
}
pub(crate) fn lint_with_guard<'ctx>(
ctx: &'ctx SharedTraversalOptions<'ctx, '_>,
workspace_file: &mut WorkspaceFile,
) -> FileResult {
let mut errors = 0;
let mut input = workspace_file.input()?;
if let Some(fix_mode) = ctx.execution.as_fix_file_mode() {
let fixed = workspace_file
.guard()
.fix_file(*fix_mode, false)
.with_file_path_and_code(
workspace_file.path.display().to_string(),
category!("lint"),
)?;
ctx.push_message(Message::SkippedFixes {
skipped_suggested_fixes: fixed.skipped_suggested_fixes,
});
if fixed.code != input {
workspace_file.update_file(fixed.code)?;
input = workspace_file.input()?;
}
errors = fixed.errors;
}
let max_diagnostics = ctx.remaining_diagnostics.load(Ordering::Relaxed);
let pull_diagnostics_result = workspace_file
.guard()
.pull_diagnostics(RuleCategories::LINT, max_diagnostics.into())
.with_file_path_and_code(workspace_file.path.display().to_string(), category!("lint"))?;
let no_diagnostics = pull_diagnostics_result.diagnostics.is_empty()
&& pull_diagnostics_result.skipped_diagnostics == 0;
errors += pull_diagnostics_result.errors;
if !no_diagnostics {
ctx.push_message(Message::Diagnostics {
name: workspace_file.path.display().to_string(),
content: input,
diagnostics: pull_diagnostics_result
.diagnostics
.into_iter()
.map(Error::from)
.collect(),
skipped_diagnostics: pull_diagnostics_result.skipped_diagnostics,
});
}
if errors > 0 {
Ok(FileStatus::Message(Message::ApplyError(
CliDiagnostic::file_apply_error(
workspace_file.path.display().to_string(),
category!("lint"),
),
)))
} else {
Ok(FileStatus::Success)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/execute/process_file/organize_imports.rs | crates/rome_cli/src/execute/process_file/organize_imports.rs | use crate::execute::diagnostics::ResultExt;
use crate::execute::process_file::workspace_file::WorkspaceFile;
use crate::execute::process_file::{
DiffKind, FileResult, FileStatus, Message, SharedTraversalOptions,
};
use rome_diagnostics::category;
/// Lints a single file and returns a [FileResult]
pub(crate) fn organize_imports_with_guard<'ctx>(
ctx: &'ctx SharedTraversalOptions<'ctx, '_>,
workspace_file: &mut WorkspaceFile,
) -> FileResult {
let sorted = workspace_file
.guard()
.organize_imports()
.with_file_path_and_code(
workspace_file.path.display().to_string(),
category!("organizeImports"),
)?;
let input = workspace_file.input()?;
if sorted.code != input {
if ctx.execution.is_check_apply_unsafe() {
workspace_file.update_file(sorted.code)?;
} else {
return Ok(FileStatus::Message(Message::Diff {
file_name: workspace_file.path.display().to_string(),
old: input,
new: sorted.code,
diff_kind: DiffKind::OrganizeImports,
}));
}
}
Ok(FileStatus::Success)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/src/execute/process_file/format.rs | crates/rome_cli/src/execute/process_file/format.rs | use crate::execute::diagnostics::{ResultExt, SkippedDiagnostic};
use crate::execute::process_file::workspace_file::WorkspaceFile;
use crate::execute::process_file::{
DiffKind, FileResult, FileStatus, Message, SharedTraversalOptions,
};
use crate::execute::TraversalMode;
use crate::FormatterReportFileDetail;
use rome_diagnostics::{category, DiagnosticExt};
use rome_service::workspace::RuleCategories;
use std::path::Path;
use std::sync::atomic::Ordering;
pub(crate) fn format<'ctx>(ctx: &'ctx SharedTraversalOptions<'ctx, '_>, path: &Path) -> FileResult {
let mut workspace_file = WorkspaceFile::new(ctx, path)?;
format_with_guard(ctx, &mut workspace_file)
}
pub(crate) fn format_with_guard<'ctx>(
ctx: &'ctx SharedTraversalOptions<'ctx, '_>,
workspace_file: &mut WorkspaceFile,
) -> FileResult {
let max_diagnostics = ctx.remaining_diagnostics.load(Ordering::Relaxed);
let diagnostics_result = workspace_file
.guard()
.pull_diagnostics(RuleCategories::SYNTAX, max_diagnostics.into())
.with_file_path_and_code(
workspace_file.path.display().to_string(),
category!("format"),
)?;
let input = workspace_file.input()?;
let (should_write, ignore_errors) = match ctx.execution.traversal_mode {
TraversalMode::Format {
write,
ignore_errors,
..
} => (write, ignore_errors),
_ => (
ctx.execution.is_check_apply() || ctx.execution.is_check_apply_unsafe(),
false,
),
};
if diagnostics_result.errors > 0 && ignore_errors {
return Err(Message::from(
SkippedDiagnostic.with_file_path(workspace_file.path.display().to_string()),
));
}
let printed = workspace_file
.guard()
.format_file()
.with_file_path_and_code(
workspace_file.path.display().to_string(),
category!("format"),
)?;
let output = printed.into_code();
// NOTE: ignoring the
if ignore_errors {
return Ok(FileStatus::Ignored);
}
if output != input {
if should_write {
workspace_file.update_file(output)?;
} else {
if !ctx.execution.should_report_to_terminal() {
ctx.push_format_stat(
workspace_file.path.display().to_string(),
FormatterReportFileDetail {
formatted_content: Some(output.clone()),
},
)
}
return Ok(FileStatus::Message(Message::Diff {
file_name: workspace_file.path.display().to_string(),
old: input,
new: output,
diff_kind: DiffKind::Format,
}));
}
}
Ok(FileStatus::Success)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/tests/main.rs | crates/rome_cli/tests/main.rs | mod cases;
mod commands;
mod configs;
#[cfg(test)]
mod snap_test;
#[cfg(test)]
use snap_test::assert_cli_snapshot;
use bpaf::ParseFailure;
use std::path::Path;
use rome_cli::{rome_command, CliDiagnostic, CliSession};
use rome_console::{markup, BufferConsole, Console, ConsoleExt};
use rome_fs::{FileSystem, MemoryFileSystem};
use rome_service::{App, DynRef};
const UNFORMATTED: &str = " statement( ) ";
const FORMATTED: &str = "statement();\n";
const PARSE_ERROR: &str = "if\n";
const LINT_ERROR: &str = "for(;true;);\n";
const CUSTOM_FORMAT_BEFORE: &str = r#"
function f() {
return { something }
}
"#;
mod help {
use super::*;
use bpaf::Args;
#[test]
fn unknown_command() {
let mut console = BufferConsole::default();
let mut fs = MemoryFileSystem::default();
let result = run_cli(
DynRef::Borrowed(&mut fs),
&mut console,
Args::from([("unknown"), ("--help")].as_slice()),
);
assert!(result.is_ok(), "run_cli returned {result:?}");
}
}
mod main {
use super::*;
use bpaf::Args;
#[test]
fn unknown_command() {
let mut console = BufferConsole::default();
let mut fs = MemoryFileSystem::default();
let result = run_cli(
DynRef::Borrowed(&mut fs),
&mut console,
Args::from([("unknown")].as_slice()),
);
assert!(result.is_err(), "run_cli returned {result:?}");
}
#[test]
fn unexpected_argument() {
let mut console = BufferConsole::default();
let mut fs = MemoryFileSystem::default();
let result = run_cli(
DynRef::Borrowed(&mut fs),
&mut console,
Args::from([("format"), ("--unknown"), ("file.js")].as_slice()),
);
assert!(result.is_err(), "run_cli returned {result:?}");
}
#[test]
fn empty_arguments() {
let mut console = BufferConsole::default();
let mut fs = MemoryFileSystem::default();
let result = run_cli(
DynRef::Borrowed(&mut fs),
&mut console,
Args::from([("format")].as_slice()),
);
assert!(result.is_err(), "run_cli returned {result:?}");
}
#[test]
fn missing_argument() {
let mut console = BufferConsole::default();
let mut fs = MemoryFileSystem::default();
let result = run_cli(
DynRef::Borrowed(&mut fs),
&mut console,
Args::from([("format"), ("--write")].as_slice()),
);
assert!(result.is_err(), "run_cli returned {result:?}");
}
#[test]
fn incorrect_value() {
let mut console = BufferConsole::default();
let mut fs = MemoryFileSystem::default();
let result = run_cli(
DynRef::Borrowed(&mut fs),
&mut console,
Args::from([("check"), ("--max-diagnostics=foo")].as_slice()),
);
assert!(result.is_err(), "run_cli returned {result:?}");
}
#[test]
fn overflow_value() {
let mut console = BufferConsole::default();
let mut fs = MemoryFileSystem::default();
let result = run_cli(
DynRef::Borrowed(&mut fs),
&mut console,
Args::from([("check"), ("--max-diagnostics=500")].as_slice()),
);
assert!(result.is_err(), "run_cli returned {result:?}");
}
//
// #[test]
// fn no_colors() {
// let mut args = Args::from([("--colors=off")]);
// let result = color_from_arguments(&mut args);
//
// assert!(result.is_ok(), "run_cli returned {result:?}");
// }
//
// #[test]
// fn force_colors() {
// let mut args = Args::from([("--colors=force")]);
// let result = color_from_arguments(&mut args);
//
// assert!(result.is_ok(), "run_cli returned {result:?}");
// }
//
// #[test]
// fn invalid_colors() {
// let mut args = Args::from([("--colors=other")]);
// let result = color_from_arguments(&mut args);
// assert!(result.is_err(), "run_cli returned {result:?}");
// }
}
mod configuration {
use super::*;
use crate::configs::{
CONFIG_ALL_FIELDS, CONFIG_BAD_LINE_WIDTH, CONFIG_INCORRECT_GLOBALS,
CONFIG_INCORRECT_GLOBALS_V2, CONFIG_LINTER_WRONG_RULE,
};
use crate::snap_test::SnapshotPayload;
use bpaf::Args;
use rome_console::BufferConsole;
use rome_fs::MemoryFileSystem;
use rome_service::DynRef;
use std::path::Path;
#[test]
fn correct_root() {
let mut fs = MemoryFileSystem::default();
let mut console = BufferConsole::default();
let file_path = Path::new("rome.json");
fs.insert(file_path.into(), CONFIG_ALL_FIELDS.as_bytes());
let result = run_cli(
DynRef::Borrowed(&mut fs),
&mut console,
Args::from([("format"), ("file.js")].as_slice()),
);
assert!(result.is_err(), "run_cli returned {result:?}");
assert_cli_snapshot(SnapshotPayload::new(
module_path!(),
"correct_root",
fs,
console,
result,
));
}
#[test]
fn line_width_error() {
let mut fs = MemoryFileSystem::default();
let mut console = BufferConsole::default();
let file_path = Path::new("rome.json");
fs.insert(file_path.into(), CONFIG_BAD_LINE_WIDTH.as_bytes());
let result = run_cli(
DynRef::Borrowed(&mut fs),
&mut console,
Args::from([("format"), ("file.js")].as_slice()),
);
assert!(result.is_err(), "run_cli returned {result:?}");
assert_cli_snapshot(SnapshotPayload::new(
module_path!(),
"line_width_error",
fs,
console,
result,
));
}
#[test]
fn incorrect_rule_name() {
let mut fs = MemoryFileSystem::default();
let mut console = BufferConsole::default();
let file_path = Path::new("rome.json");
fs.insert(file_path.into(), CONFIG_LINTER_WRONG_RULE.as_bytes());
let result = run_cli(
DynRef::Borrowed(&mut fs),
&mut console,
Args::from([("check"), ("file.js")].as_slice()),
);
assert!(result.is_err(), "run_cli returned {result:?}");
assert_cli_snapshot(SnapshotPayload::new(
module_path!(),
"incorrect_rule_name",
fs,
console,
result,
));
}
#[test]
fn incorrect_globals() {
let mut fs = MemoryFileSystem::default();
let mut console = BufferConsole::default();
let file_path = Path::new("rome.json");
fs.insert(file_path.into(), CONFIG_INCORRECT_GLOBALS.as_bytes());
let result = run_cli(
DynRef::Borrowed(&mut fs),
&mut console,
Args::from([("check"), ("file.js")].as_slice()),
);
assert!(result.is_err(), "run_cli returned {result:?}");
assert_cli_snapshot(SnapshotPayload::new(
module_path!(),
"incorrect_globals",
fs,
console,
result,
));
}
#[test]
fn ignore_globals() {
let mut fs = MemoryFileSystem::default();
let mut console = BufferConsole::default();
fs.insert(
Path::new("rome.json").into(),
CONFIG_INCORRECT_GLOBALS_V2.as_bytes(),
);
fs.insert(Path::new("file.js").into(), UNFORMATTED.as_bytes());
let result = run_cli(
DynRef::Borrowed(&mut fs),
&mut console,
Args::from([("check"), ("file.js")].as_slice()),
);
assert!(result.is_err(), "run_cli returned {result:?}");
}
}
mod reporter_json {
use super::*;
use crate::snap_test::SnapshotPayload;
use crate::UNFORMATTED;
use bpaf::Args;
use rome_fs::FileSystemExt;
#[test]
fn reports_formatter_check_mode() {
let mut fs = MemoryFileSystem::default();
let mut console = BufferConsole::default();
let file_path = Path::new("format.js");
fs.insert(file_path.into(), UNFORMATTED.as_bytes());
let result = run_cli(
DynRef::Borrowed(&mut fs),
&mut console,
Args::from(
[
("format"),
("--json"),
file_path.as_os_str().to_str().unwrap(),
]
.as_slice(),
),
);
eprintln!("{:?}", console.out_buffer);
assert!(result.is_ok(), "run_cli returned {result:?}");
let mut file = fs
.open(file_path)
.expect("formatting target file was removed by the CLI");
let mut content = String::new();
file.read_to_string(&mut content)
.expect("failed to read file from memory FS");
assert_eq!(content, UNFORMATTED);
assert_eq!(console.out_buffer.len(), 1);
drop(file);
assert_cli_snapshot(SnapshotPayload::new(
module_path!(),
"reports_formatter_check_mode",
fs,
console,
result,
));
}
#[test]
fn reports_formatter_write() {
let mut fs = MemoryFileSystem::default();
let mut console = BufferConsole::default();
let file_path = Path::new("format.js");
fs.insert(file_path.into(), UNFORMATTED.as_bytes());
let result = run_cli(
DynRef::Borrowed(&mut fs),
&mut console,
Args::from(
[
"format",
"--write",
"--json",
file_path.as_os_str().to_str().unwrap(),
]
.as_slice(),
),
);
assert!(result.is_ok(), "run_cli returned {result:?}");
let mut file = fs
.open(file_path)
.expect("formatting target file was removed by the CLI");
let mut content = String::new();
file.read_to_string(&mut content)
.expect("failed to read file from memory FS");
assert_eq!(content, FORMATTED);
assert_eq!(console.out_buffer.len(), 1);
drop(file);
assert_cli_snapshot(SnapshotPayload::new(
module_path!(),
"reports_formatter_write",
fs,
console,
result,
));
}
}
/// Create an [App] instance using the provided [FileSystem] and [Console]
/// instance, and using an in-process "remote" instance of the workspace
pub(crate) fn run_cli<'app>(
fs: DynRef<'app, dyn FileSystem>,
console: &'app mut dyn Console,
args: bpaf::Args,
) -> Result<(), CliDiagnostic> {
use rome_cli::SocketTransport;
use rome_lsp::ServerFactory;
use rome_service::{workspace, WorkspaceRef};
use tokio::{
io::{duplex, split},
runtime::Runtime,
};
let factory = ServerFactory::default();
let connection = factory.create();
let runtime = Runtime::new().expect("failed to create runtime");
let (client, server) = duplex(4096);
let (stdin, stdout) = split(server);
runtime.spawn(connection.accept(stdin, stdout));
let (client_read, client_write) = split(client);
let transport = SocketTransport::open(runtime, client_read, client_write);
let workspace = workspace::client(transport).unwrap();
let app = App::new(fs, console, WorkspaceRef::Owned(workspace));
let mut session = CliSession { app };
let command = rome_command().run_inner(args);
match command {
Ok(command) => session.run(command),
Err(failure) => {
if let ParseFailure::Stdout(help, _) = &failure {
let console = &mut session.app.console;
console.log(markup! {{help.to_string()}});
Ok(())
} else {
Err(CliDiagnostic::parse_error_bpaf(failure))
}
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_cli/tests/configs.rs | crates/rome_cli/tests/configs.rs | pub const CONFIG_FORMAT: &str = r#"{
"formatter": {
"enabled": true,
"lineWidth": 160,
"indentStyle": "space",
"indentSize": 6
}
}
"#;
pub const CONFIG_INIT_DEFAULT: &str = r#"{
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
}
}
}
"#;
pub const CONFIG_INIT_DEFAULT_WHEN_INSTALLED: &str = r#"{
"$schema": "./node_modules/rome/configuration_schema.json",
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
}
}
}
"#;
pub const CONFIG_DISABLED_FORMATTER: &str = r#"{
"formatter": {
"enabled": false
}
}
"#;
pub const CONFIG_ALL_FIELDS: &str = r#"{
"formatter": {
"enabled": true,
"formatWithErrors": true,
"indentStyle": "tab",
"indentSize": 2,
"lineWidth": 80
},
"linter": {
"enabled": true,
"rules": {
"complexity": {
"useSimplifiedLogicExpression": "warn"
},
"style": {
"useTemplate": {
"level": "error"
}
},
"correctness": {
"noUnreachable": "off"
},
"suspicious": {
"noCatchAssign": "error",
"noLabelVar": {
"level": "warn"
}
}
}
},
"javascript": {
"globals": ["$"],
"formatter": {
"quoteStyle": "double",
"jsxQuoteStyle": "double",
"quoteProperties": "asNeeded"
}
}
}"#;
pub const CONFIG_BAD_LINE_WIDTH: &str = r#"{
"formatter": {
"lineWidth": 500
}
}"#;
pub const CONFIG_LINTER_DISABLED: &str = r#"{
"linter": {
"enabled": false
}
}"#;
pub const CONFIG_LINTER_WRONG_RULE: &str = r#"{
"linter": {
"enabled": true,
"rules": {
"correctness": {
"foo_rule": "off"
},
"style": {
"what_the_hell": "off"
}
}
}
}"#;
pub const CONFIG_INCORRECT_GLOBALS: &str = r#"{
"linter": {
"enabled": false
},
"javascript": {
"globals": [false]
}
}"#;
pub const CONFIG_LINTER_SUPPRESSED_RULE: &str = r#"{
"linter": {
"rules": {
"recommended": true,
"suspicious": {
"noDebugger": "off"
}
}
}
}"#;
pub const CONFIG_LINTER_SUPPRESSED_GROUP: &str = r#"{
"linter": {
"rules": {
"recommended": true,
"suspicious": {
"recommended": false
}
}
}
}"#;
pub const CONFIG_LINTER_DOWNGRADE_DIAGNOSTIC: &str = r#"{
"linter": {
"rules": {
"recommended": true,
"suspicious": {
"noDebugger": "warn"
}
}
}
}"#;
pub const CONFIG_LINTER_UPGRADE_DIAGNOSTIC: &str = r#"{
"linter": {
"rules": {
"recommended": true,
"style": {
"noNegationElse": "error"
}
}
}
}"#;
pub const CONFIG_RECOMMENDED_GROUP: &str = r#"{
"linter": {
"rules": {
"recommended": false,
"correctness": {
"recommended": true
}
}
}
}"#;
pub const CONFIG_INCORRECT_GLOBALS_V2: &str = r#"{
"javascript": {
"formatter": {
"quoteStyle": "single"
}
}
}"#;
pub const CONFIG_ISSUE_3175_1: &str = r#"{
"formatter": {
"indentStyle": "space",
"indentSize": 2,
"lineWidth": 120
}
}"#;
pub const CONFIG_ISSUE_3175_2: &str = r#"{
"javascript": {
"formatter": {
"quoteStyle": "single"
}
}
}"#;
pub const CONFIG_FORMATTER_IGNORED_FILES: &str = r#"{
"formatter": {
"enabled": true,
"ignore": ["test.js"]
}
}
"#;
pub const CONFIG_FORMATTER_AND_FILES_IGNORE: &str = r#"{
"files": {
"ignore": ["test1.js"]
},
"formatter": {
"enabled": true,
"ignore": ["test2.js"]
}
}"#;
pub const CONFIG_FORMATTER_IGNORED_DIRECTORIES: &str = r#"{
"formatter": {
"ignore": [
"test1.js",
"./test2.js",
"./test3/**/*",
"/test4/**/*",
"test5/**/*",
"**/test6/*.js",
"*.test7.js"
]
}
}
"#;
pub const CONFIG_LINTER_IGNORED_FILES: &str = r#"{
"linter": {
"enabled": true,
"ignore": ["test.js"]
}
}
"#;
pub const CONFIG_LINTER_AND_FILES_IGNORE: &str = r#"{
"files": {
"ignore": ["test1.js"]
},
"linter": {
"enabled": true,
"ignore": ["test2.js"]
}
}"#;
pub const CONFIG_FILE_SIZE_LIMIT: &str = r#"{
"files": {
"maxSize": 16
}
}"#;
pub const CONFIG_IGNORE_SYMLINK: &str = r#"{
"files": {
"ignore": [
"symlink_testcase2/**/*.ts"
]
}
}"#;
| 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.