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_service/src/configuration/parse/json/json_configuration.rs | crates/rome_service/src/configuration/parse/json/json_configuration.rs | use crate::configuration::json::{JsonConfiguration, JsonParser};
use rome_deserialize::json::{has_only_known_keys, VisitJsonNode};
use rome_deserialize::{DeserializationDiagnostic, VisitNode};
use rome_json_syntax::{JsonLanguage, JsonSyntaxNode};
use rome_rowan::SyntaxNode;
impl VisitJsonNode for JsonConfiguration {}
impl VisitNode<JsonLanguage> for JsonConfiguration {
fn visit_member_name(
&mut self,
node: &JsonSyntaxNode,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
has_only_known_keys(node, JsonConfiguration::KNOWN_KEYS, diagnostics)
}
fn visit_map(
&mut self,
key: &SyntaxNode<JsonLanguage>,
value: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let (name, value) = self.get_key_and_value(key, value, diagnostics)?;
let name_text = name.text();
if let "parser" = name_text {
let mut parser = JsonParser::default();
self.map_to_object(&value, name_text, &mut parser, diagnostics)?;
self.parser = Some(parser);
}
Some(())
}
}
impl VisitJsonNode for JsonParser {}
impl VisitNode<JsonLanguage> for JsonParser {
fn visit_member_name(
&mut self,
node: &JsonSyntaxNode,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
has_only_known_keys(node, JsonParser::KNOWN_KEYS, diagnostics)
}
fn visit_map(
&mut self,
key: &SyntaxNode<JsonLanguage>,
value: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let (name, value) = self.get_key_and_value(key, value, diagnostics)?;
let name_text = name.text();
if name_text == "allowComments" {
self.allow_comments = self.map_to_boolean(&value, name_text, diagnostics);
}
Some(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_service/src/configuration/parse/json/vcs.rs | crates/rome_service/src/configuration/parse/json/vcs.rs | use crate::configuration::vcs::{VcsClientKind, VcsConfiguration};
use rome_console::markup;
use rome_deserialize::json::{has_only_known_keys, with_only_known_variants, VisitJsonNode};
use rome_deserialize::{DeserializationDiagnostic, VisitNode};
use rome_json_syntax::{AnyJsonValue, JsonLanguage};
use rome_rowan::{AstNode, SyntaxNode};
impl VisitJsonNode for VcsConfiguration {}
impl VisitNode<JsonLanguage> for VcsConfiguration {
fn visit_member_name(
&mut self,
node: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
has_only_known_keys(node, VcsConfiguration::KNOWN_KEYS, diagnostics)
}
fn visit_map(
&mut self,
key: &SyntaxNode<JsonLanguage>,
value: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let (name, value) = self.get_key_and_value(key, value, diagnostics)?;
let name_text = name.text();
match name_text {
"clientKind" => {
let mut client_kind = VcsClientKind::default();
self.map_to_known_string(&value, name_text, &mut client_kind, diagnostics)?;
self.client_kind = Some(client_kind);
}
"enabled" => {
self.enabled = self.map_to_boolean(&value, name_text, diagnostics);
}
"useIgnoreFile" => {
self.use_ignore_file = self.map_to_boolean(&value, name_text, diagnostics);
}
"root" => {
self.root = self.map_to_string(&value, name_text, diagnostics);
}
_ => {}
}
Some(())
}
}
impl VisitJsonNode for VcsClientKind {}
impl VisitNode<JsonLanguage> for VcsClientKind {
fn visit_member_value(
&mut self,
node: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let node = with_only_known_variants(node, VcsClientKind::KNOWN_VALUES, diagnostics)?;
if node.inner_string_text().ok()?.text() == "git" {
*self = VcsClientKind::Git;
}
Some(())
}
}
pub(crate) fn validate_vcs_configuration(
node: &AnyJsonValue,
configuration: &mut VcsConfiguration,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) {
if configuration.client_kind.is_none() && !configuration.is_disabled() {
diagnostics.push(
DeserializationDiagnostic::new(markup! {
"You enabled the VCS integration, but you didn't specify a client."
})
.with_range(node.range())
.with_note("Rome will disable the VCS integration until the issue is fixed."),
);
configuration.enabled = Some(false);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_service/src/configuration/parse/json/organize_imports.rs | crates/rome_service/src/configuration/parse/json/organize_imports.rs | use crate::configuration::organize_imports::OrganizeImports;
use rome_deserialize::json::{has_only_known_keys, VisitJsonNode};
use rome_deserialize::{DeserializationDiagnostic, StringSet, VisitNode};
use rome_json_syntax::{JsonLanguage, JsonSyntaxNode};
use rome_rowan::SyntaxNode;
impl VisitJsonNode for OrganizeImports {}
impl VisitNode<JsonLanguage> for OrganizeImports {
fn visit_member_name(
&mut self,
node: &JsonSyntaxNode,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
has_only_known_keys(node, &["enabled", "ignore"], diagnostics)
}
fn visit_map(
&mut self,
key: &SyntaxNode<JsonLanguage>,
value: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let (name, value) = self.get_key_and_value(key, value, diagnostics)?;
let name_text = name.text();
match name_text {
"enabled" => {
self.enabled = self.map_to_boolean(&value, name_text, diagnostics);
}
"ignore" => {
self.ignore = self
.map_to_index_set_string(&value, name_text, diagnostics)
.map(StringSet::new);
}
_ => {}
}
Some(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_service/src/configuration/parse/json/mod.rs | crates/rome_service/src/configuration/parse/json/mod.rs | //! This module is responsible to parse the configuration from a JSON format
//!
mod configuration;
mod files;
mod formatter;
mod javascript;
mod json_configuration;
mod linter;
mod organize_imports;
mod rules;
mod vcs;
use crate::Configuration;
use rome_deserialize::json::{JsonDeserialize, VisitJsonNode};
use rome_deserialize::DeserializationDiagnostic;
use rome_json_syntax::{AnyJsonValue, JsonRoot};
use rome_rowan::AstNode;
impl JsonDeserialize for Configuration {
fn deserialize_from_ast(
root: &JsonRoot,
visitor: &mut impl VisitJsonNode,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let value = root.value().ok()?;
match value {
AnyJsonValue::JsonObjectValue(node) => {
for element in node.json_member_list() {
let element = element.ok()?;
let member_name = element.name().ok()?;
let member_value = element.value().ok()?;
visitor.visit_map(member_name.syntax(), member_value.syntax(), diagnostics)?;
}
Some(())
}
_ => {
diagnostics.push(
DeserializationDiagnostic::new("The configuration should be an object")
.with_range(root.range()),
);
None
}
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_service/src/configuration/parse/json/files.rs | crates/rome_service/src/configuration/parse/json/files.rs | use crate::configuration::FilesConfiguration;
use rome_deserialize::json::{has_only_known_keys, VisitJsonNode};
use rome_deserialize::{DeserializationDiagnostic, StringSet, VisitNode};
use rome_json_syntax::JsonLanguage;
use rome_rowan::SyntaxNode;
use std::num::NonZeroU64;
impl VisitJsonNode for FilesConfiguration {}
impl VisitNode<JsonLanguage> for FilesConfiguration {
fn visit_member_name(
&mut self,
node: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
has_only_known_keys(node, FilesConfiguration::KNOWN_KEYS, diagnostics)
}
fn visit_map(
&mut self,
key: &SyntaxNode<JsonLanguage>,
value: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let (name, value) = self.get_key_and_value(key, value, diagnostics)?;
let name_text = name.text();
match name_text {
"maxSize" => {
self.max_size =
NonZeroU64::new(self.map_to_u64(&value, name_text, u64::MAX, diagnostics)?);
}
"ignore" => {
self.ignore = self
.map_to_index_set_string(&value, name_text, diagnostics)
.map(StringSet::new);
}
"ignoreUnknown" => {
self.ignore_unknown = self.map_to_boolean(&value, name_text, diagnostics);
}
_ => {}
}
Some(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_service/src/configuration/parse/json/rules.rs | crates/rome_service/src/configuration/parse/json/rules.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use crate::configuration::linter::*;
use crate::configuration::parse::json::linter::are_recommended_and_all_correct;
use crate::Rules;
use rome_deserialize::json::{has_only_known_keys, VisitJsonNode};
use rome_deserialize::{DeserializationDiagnostic, VisitNode};
use rome_json_syntax::{AnyJsonValue, JsonLanguage};
use rome_rowan::{AstNode, SyntaxNode};
impl VisitJsonNode for Rules {}
impl VisitNode<JsonLanguage> for Rules {
fn visit_member_name(
&mut self,
node: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
has_only_known_keys(
node,
&[
"recommended",
"all",
"a11y",
"complexity",
"correctness",
"nursery",
"performance",
"security",
"style",
"suspicious",
],
diagnostics,
)
}
fn visit_map(
&mut self,
key: &SyntaxNode<JsonLanguage>,
value: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let (name, value) = self.get_key_and_value(key, value, diagnostics)?;
let name_text = name.text();
match name_text {
"recommended" => {
self.recommended = Some(self.map_to_boolean(&value, name_text, diagnostics)?);
}
"all" => {
self.all = Some(self.map_to_boolean(&value, name_text, diagnostics)?);
}
"a11y" => {
let mut visitor = A11y::default();
if are_recommended_and_all_correct(&value, name_text, diagnostics)? {
self.map_to_object(&value, name_text, &mut visitor, diagnostics)?;
self.a11y = Some(visitor);
}
}
"complexity" => {
let mut visitor = Complexity::default();
if are_recommended_and_all_correct(&value, name_text, diagnostics)? {
self.map_to_object(&value, name_text, &mut visitor, diagnostics)?;
self.complexity = Some(visitor);
}
}
"correctness" => {
let mut visitor = Correctness::default();
if are_recommended_and_all_correct(&value, name_text, diagnostics)? {
self.map_to_object(&value, name_text, &mut visitor, diagnostics)?;
self.correctness = Some(visitor);
}
}
"nursery" => {
let mut visitor = Nursery::default();
if are_recommended_and_all_correct(&value, name_text, diagnostics)? {
self.map_to_object(&value, name_text, &mut visitor, diagnostics)?;
self.nursery = Some(visitor);
}
}
"performance" => {
let mut visitor = Performance::default();
if are_recommended_and_all_correct(&value, name_text, diagnostics)? {
self.map_to_object(&value, name_text, &mut visitor, diagnostics)?;
self.performance = Some(visitor);
}
}
"security" => {
let mut visitor = Security::default();
if are_recommended_and_all_correct(&value, name_text, diagnostics)? {
self.map_to_object(&value, name_text, &mut visitor, diagnostics)?;
self.security = Some(visitor);
}
}
"style" => {
let mut visitor = Style::default();
if are_recommended_and_all_correct(&value, name_text, diagnostics)? {
self.map_to_object(&value, name_text, &mut visitor, diagnostics)?;
self.style = Some(visitor);
}
}
"suspicious" => {
let mut visitor = Suspicious::default();
if are_recommended_and_all_correct(&value, name_text, diagnostics)? {
self.map_to_object(&value, name_text, &mut visitor, diagnostics)?;
self.suspicious = Some(visitor);
}
}
_ => {}
}
Some(())
}
}
impl VisitJsonNode for A11y {}
impl VisitNode<JsonLanguage> for A11y {
fn visit_member_name(
&mut self,
node: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
has_only_known_keys(
node,
&[
"recommended",
"all",
"noAccessKey",
"noAutofocus",
"noBlankTarget",
"noDistractingElements",
"noHeaderScope",
"noNoninteractiveElementToInteractiveRole",
"noPositiveTabindex",
"noRedundantAlt",
"noSvgWithoutTitle",
"useAltText",
"useAnchorContent",
"useAriaPropsForRole",
"useButtonType",
"useHeadingContent",
"useHtmlLang",
"useIframeTitle",
"useKeyWithClickEvents",
"useKeyWithMouseEvents",
"useMediaCaption",
"useValidAnchor",
"useValidAriaProps",
"useValidLang",
],
diagnostics,
)
}
fn visit_map(
&mut self,
key: &SyntaxNode<JsonLanguage>,
value: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let (name, value) = self.get_key_and_value(key, value, diagnostics)?;
let name_text = name.text();
match name_text {
"recommended" => {
self.recommended = Some(self.map_to_boolean(&value, name_text, diagnostics)?);
}
"all" => {
self.all = Some(self.map_to_boolean(&value, name_text, diagnostics)?);
}
"noAccessKey" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.no_access_key = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"noAccessKey",
diagnostics,
)?;
self.no_access_key = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"noAutofocus" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.no_autofocus = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"noAutofocus",
diagnostics,
)?;
self.no_autofocus = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"noBlankTarget" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.no_blank_target = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"noBlankTarget",
diagnostics,
)?;
self.no_blank_target = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"noDistractingElements" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.no_distracting_elements = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"noDistractingElements",
diagnostics,
)?;
self.no_distracting_elements = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"noHeaderScope" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.no_header_scope = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"noHeaderScope",
diagnostics,
)?;
self.no_header_scope = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"noNoninteractiveElementToInteractiveRole" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.no_noninteractive_element_to_interactive_role = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"noNoninteractiveElementToInteractiveRole",
diagnostics,
)?;
self.no_noninteractive_element_to_interactive_role = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"noPositiveTabindex" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.no_positive_tabindex = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"noPositiveTabindex",
diagnostics,
)?;
self.no_positive_tabindex = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"noRedundantAlt" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.no_redundant_alt = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"noRedundantAlt",
diagnostics,
)?;
self.no_redundant_alt = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"noSvgWithoutTitle" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.no_svg_without_title = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"noSvgWithoutTitle",
diagnostics,
)?;
self.no_svg_without_title = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"useAltText" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.use_alt_text = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"useAltText",
diagnostics,
)?;
self.use_alt_text = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"useAnchorContent" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.use_anchor_content = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"useAnchorContent",
diagnostics,
)?;
self.use_anchor_content = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"useAriaPropsForRole" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.use_aria_props_for_role = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"useAriaPropsForRole",
diagnostics,
)?;
self.use_aria_props_for_role = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"useButtonType" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.use_button_type = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"useButtonType",
diagnostics,
)?;
self.use_button_type = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"useHeadingContent" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.use_heading_content = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"useHeadingContent",
diagnostics,
)?;
self.use_heading_content = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"useHtmlLang" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.use_html_lang = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"useHtmlLang",
diagnostics,
)?;
self.use_html_lang = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"useIframeTitle" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.use_iframe_title = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"useIframeTitle",
diagnostics,
)?;
self.use_iframe_title = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"useKeyWithClickEvents" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.use_key_with_click_events = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"useKeyWithClickEvents",
diagnostics,
)?;
self.use_key_with_click_events = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"useKeyWithMouseEvents" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.use_key_with_mouse_events = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"useKeyWithMouseEvents",
diagnostics,
)?;
self.use_key_with_mouse_events = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"useMediaCaption" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.use_media_caption = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"useMediaCaption",
diagnostics,
)?;
self.use_media_caption = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"useValidAnchor" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.use_valid_anchor = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"useValidAnchor",
diagnostics,
)?;
self.use_valid_anchor = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"useValidAriaProps" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.use_valid_aria_props = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"useValidAriaProps",
diagnostics,
)?;
self.use_valid_aria_props = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"useValidLang" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.use_valid_lang = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"useValidLang",
diagnostics,
)?;
self.use_valid_lang = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
_ => {}
}
Some(())
}
}
impl VisitJsonNode for Complexity {}
impl VisitNode<JsonLanguage> for Complexity {
fn visit_member_name(
&mut self,
node: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
has_only_known_keys(
node,
&[
"recommended",
"all",
"noExtraBooleanCast",
"noForEach",
"noMultipleSpacesInRegularExpressionLiterals",
"noUselessCatch",
"noUselessConstructor",
"noUselessFragments",
"noUselessLabel",
"noUselessRename",
"noUselessSwitchCase",
"noUselessTypeConstraint",
"noWith",
"useFlatMap",
"useLiteralKeys",
"useOptionalChain",
"useSimpleNumberKeys",
"useSimplifiedLogicExpression",
],
diagnostics,
)
}
fn visit_map(
&mut self,
key: &SyntaxNode<JsonLanguage>,
value: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let (name, value) = self.get_key_and_value(key, value, diagnostics)?;
let name_text = name.text();
match name_text {
"recommended" => {
self.recommended = Some(self.map_to_boolean(&value, name_text, diagnostics)?);
}
"all" => {
self.all = Some(self.map_to_boolean(&value, name_text, diagnostics)?);
}
"noExtraBooleanCast" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
self.no_extra_boolean_cast = Some(configuration);
}
AnyJsonValue::JsonObjectValue(_) => {
let mut rule_configuration = RuleConfiguration::default();
rule_configuration.map_rule_configuration(
&value,
name_text,
"noExtraBooleanCast",
diagnostics,
)?;
self.no_extra_boolean_cast = Some(rule_configuration);
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"object or string",
value.range(),
));
}
},
"noForEach" => match value {
AnyJsonValue::JsonStringValue(_) => {
let mut configuration = RuleConfiguration::default();
self.map_to_known_string(&value, name_text, &mut configuration, diagnostics)?;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_service/src/configuration/parse/json/formatter.rs | crates/rome_service/src/configuration/parse/json/formatter.rs | use crate::configuration::{FormatterConfiguration, PlainIndentStyle};
use rome_console::markup;
use rome_deserialize::json::{has_only_known_keys, with_only_known_variants, VisitJsonNode};
use rome_deserialize::{DeserializationDiagnostic, StringSet, VisitNode};
use rome_formatter::LineWidth;
use rome_json_syntax::{JsonLanguage, JsonSyntaxNode};
use rome_rowan::{AstNode, SyntaxNode};
impl VisitJsonNode for FormatterConfiguration {}
impl VisitNode<JsonLanguage> for FormatterConfiguration {
fn visit_member_name(
&mut self,
node: &JsonSyntaxNode,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
has_only_known_keys(node, FormatterConfiguration::KNOWN_KEYS, diagnostics)
}
fn visit_map(
&mut self,
key: &SyntaxNode<JsonLanguage>,
value: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let (name, value) = self.get_key_and_value(key, value, diagnostics)?;
let name_text = name.text();
match name_text {
"formatWithErrors" => {
self.format_with_errors = self.map_to_boolean(&value, name_text, diagnostics);
}
"enabled" => {
self.enabled = self.map_to_boolean(&value, name_text, diagnostics);
}
"ignore" => {
self.ignore = self
.map_to_index_set_string(&value, name_text, diagnostics)
.map(StringSet::new);
}
"indentStyle" => {
let mut indent_style = PlainIndentStyle::default();
self.map_to_known_string(&value, name_text, &mut indent_style, diagnostics)?;
self.indent_style = Some(indent_style);
}
"indentSize" => {
self.indent_size = self.map_to_u8(&value, name_text, u8::MAX, diagnostics);
}
"lineWidth" => {
let line_width = self.map_to_u16(&value, name_text, LineWidth::MAX, diagnostics)?;
self.line_width = Some(match LineWidth::try_from(line_width) {
Ok(result) => result,
Err(err) => {
diagnostics.push(
DeserializationDiagnostic::new(err.to_string())
.with_range(value.range())
.with_note(
markup! {"Maximum value accepted is "{{LineWidth::MAX}}},
),
);
LineWidth::default()
}
});
}
_ => {}
}
Some(())
}
}
impl VisitNode<JsonLanguage> for PlainIndentStyle {
fn visit_member_value(
&mut self,
node: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let node = with_only_known_variants(node, PlainIndentStyle::KNOWN_VALUES, diagnostics)?;
if node.inner_string_text().ok()? == "space" {
*self = PlainIndentStyle::Space;
} else {
*self = PlainIndentStyle::Tab;
}
Some(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_service/src/configuration/linter/mod.rs | crates/rome_service/src/configuration/linter/mod.rs | #[rustfmt::skip]
mod rules;
pub use crate::configuration::linter::rules::{rules, Rules};
use crate::configuration::merge::MergeWith;
use crate::settings::LinterSettings;
use crate::{ConfigurationDiagnostic, MatchOptions, Matcher, WorkspaceError};
use bpaf::Bpaf;
use rome_deserialize::StringSet;
use rome_diagnostics::Severity;
use rome_js_analyze::options::{possible_options, PossibleOptions};
pub use rules::*;
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::str::FromStr;
#[derive(Deserialize, Serialize, Debug, Clone, Bpaf)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct LinterConfiguration {
/// if `false`, it disables the feature and the linter won't be executed. `true` by default
#[serde(skip_serializing_if = "Option::is_none")]
#[bpaf(hide)]
pub enabled: Option<bool>,
/// List of rules
#[serde(skip_serializing_if = "Option::is_none")]
#[bpaf(external, optional, hide)]
pub rules: Option<Rules>,
/// A list of Unix shell style patterns. The formatter will ignore files/folders that will
/// match these patterns.
#[serde(skip_serializing_if = "Option::is_none")]
#[bpaf(hide)]
pub ignore: Option<StringSet>,
}
impl MergeWith<LinterConfiguration> for LinterConfiguration {
fn merge_with(&mut self, other: LinterConfiguration) {
if let Some(enabled) = other.enabled {
self.enabled = Some(enabled);
}
}
}
impl LinterConfiguration {
pub const fn is_disabled(&self) -> bool {
matches!(self.enabled, Some(false))
}
pub(crate) const KNOWN_KEYS: &'static [&'static str] = &["enabled", "rules", "ignore"];
}
impl Default for LinterConfiguration {
fn default() -> Self {
Self {
enabled: Some(true),
rules: Some(Rules::default()),
ignore: None,
}
}
}
impl TryFrom<LinterConfiguration> for LinterSettings {
type Error = WorkspaceError;
fn try_from(conf: LinterConfiguration) -> Result<Self, Self::Error> {
let mut matcher = Matcher::new(MatchOptions {
case_sensitive: true,
require_literal_leading_dot: false,
require_literal_separator: false,
});
if let Some(ignore) = conf.ignore {
for pattern in ignore.index_set() {
matcher.add_pattern(pattern).map_err(|err| {
WorkspaceError::Configuration(
ConfigurationDiagnostic::new_invalid_ignore_pattern(
pattern.to_string(),
err.msg.to_string(),
),
)
})?;
}
}
Ok(Self {
enabled: conf.enabled.unwrap_or_default(),
rules: conf.rules,
ignored_files: matcher,
})
}
}
#[derive(Deserialize, Serialize, Debug, Clone, Bpaf)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields, untagged)]
pub enum RuleConfiguration {
Plain(RulePlainConfiguration),
WithOptions(RuleWithOptions),
}
impl FromStr for RuleConfiguration {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let result = RulePlainConfiguration::from_str(s)?;
Ok(Self::Plain(result))
}
}
impl RuleConfiguration {
pub fn is_err(&self) -> bool {
if let Self::WithOptions(rule) = self {
rule.level == RulePlainConfiguration::Error
} else {
matches!(self, Self::Plain(RulePlainConfiguration::Error))
}
}
pub fn is_disabled(&self) -> bool {
if let Self::WithOptions(rule) = self {
rule.level == RulePlainConfiguration::Off
} else {
matches!(self, Self::Plain(RulePlainConfiguration::Off))
}
}
pub fn is_enabled(&self) -> bool {
!self.is_disabled()
}
}
impl Default for RuleConfiguration {
fn default() -> Self {
Self::Plain(RulePlainConfiguration::Error)
}
}
impl From<&RuleConfiguration> for Severity {
fn from(conf: &RuleConfiguration) -> Self {
match conf {
RuleConfiguration::Plain(p) => p.into(),
RuleConfiguration::WithOptions(conf) => {
let level = &conf.level;
level.into()
}
}
}
}
impl From<&RulePlainConfiguration> for Severity {
fn from(conf: &RulePlainConfiguration) -> Self {
match conf {
RulePlainConfiguration::Warn => Severity::Warning,
RulePlainConfiguration::Error => Severity::Error,
_ => unreachable!("the rule is turned off, it should not step in here"),
}
}
}
#[derive(Default, Deserialize, Serialize, Debug, Eq, PartialEq, Clone, Bpaf)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum RulePlainConfiguration {
#[default]
Warn,
Error,
Off,
}
impl RulePlainConfiguration {
pub(crate) const KNOWN_KEYS: &'static [&'static str] = &["warn", "error", "off"];
}
impl FromStr for RulePlainConfiguration {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"warn" => Ok(Self::Warn),
"error" => Ok(Self::Error),
"off" => Ok(Self::Off),
_ => Err("Invalid configuration for rule".to_string()),
}
}
}
#[derive(Default, Deserialize, Serialize, Debug, Clone, Bpaf)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RuleWithOptions {
pub level: RulePlainConfiguration,
#[serde(skip_serializing_if = "Option::is_none")]
#[bpaf(external(possible_options), hide, optional)]
pub options: Option<PossibleOptions>,
}
impl FromStr for RuleWithOptions {
type Err = String;
fn from_str(_s: &str) -> Result<Self, Self::Err> {
Ok(Self {
level: RulePlainConfiguration::default(),
options: None,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_service/src/configuration/linter/rules.rs | crates/rome_service/src/configuration/linter/rules.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use crate::RuleConfiguration;
use bpaf::Bpaf;
use indexmap::IndexSet;
use rome_analyze::RuleFilter;
use rome_diagnostics::{Category, Severity};
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, Debug, Clone, Bpaf)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Rules {
#[doc = r" It enables the lint rules recommended by Rome. `true` by default."]
#[serde(skip_serializing_if = "Option::is_none")]
#[bpaf(hide)]
pub recommended: Option<bool>,
#[doc = r" It enables ALL rules. The rules that belong to `nursery` won't be enabled."]
#[serde(skip_serializing_if = "Option::is_none")]
#[bpaf(hide)]
pub all: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
#[bpaf(external, hide, optional)]
pub a11y: Option<A11y>,
#[serde(skip_serializing_if = "Option::is_none")]
#[bpaf(external, hide, optional)]
pub complexity: Option<Complexity>,
#[serde(skip_serializing_if = "Option::is_none")]
#[bpaf(external, hide, optional)]
pub correctness: Option<Correctness>,
#[serde(skip_serializing_if = "Option::is_none")]
#[bpaf(external, hide, optional)]
pub nursery: Option<Nursery>,
#[serde(skip_serializing_if = "Option::is_none")]
#[bpaf(external, hide, optional)]
pub performance: Option<Performance>,
#[serde(skip_serializing_if = "Option::is_none")]
#[bpaf(external, hide, optional)]
pub security: Option<Security>,
#[serde(skip_serializing_if = "Option::is_none")]
#[bpaf(external, hide, optional)]
pub style: Option<Style>,
#[serde(skip_serializing_if = "Option::is_none")]
#[bpaf(external, hide, optional)]
pub suspicious: Option<Suspicious>,
}
impl Default for Rules {
fn default() -> Self {
Self {
recommended: Some(true),
all: None,
a11y: None,
complexity: None,
correctness: None,
nursery: None,
performance: None,
security: None,
style: None,
suspicious: None,
}
}
}
impl Rules {
#[doc = r" Checks if the code coming from [rome_diagnostics::Diagnostic] corresponds to a rule."]
#[doc = r" Usually the code is built like {category}/{rule_name}"]
pub fn matches_diagnostic_code<'a>(
&self,
category: Option<&'a str>,
rule_name: Option<&'a str>,
) -> Option<(&'a str, &'a str)> {
match (category, rule_name) {
(Some(category), Some(rule_name)) => match category {
"a11y" => A11y::has_rule(rule_name).then_some((category, rule_name)),
"complexity" => Complexity::has_rule(rule_name).then_some((category, rule_name)),
"correctness" => Correctness::has_rule(rule_name).then_some((category, rule_name)),
"nursery" => Nursery::has_rule(rule_name).then_some((category, rule_name)),
"performance" => Performance::has_rule(rule_name).then_some((category, rule_name)),
"security" => Security::has_rule(rule_name).then_some((category, rule_name)),
"style" => Style::has_rule(rule_name).then_some((category, rule_name)),
"suspicious" => Suspicious::has_rule(rule_name).then_some((category, rule_name)),
_ => None,
},
_ => None,
}
}
#[doc = r" Given a category coming from [Diagnostic](rome_diagnostics::Diagnostic), this function returns"]
#[doc = r" the [Severity](rome_diagnostics::Severity) associated to the rule, if the configuration changed it."]
#[doc = r""]
#[doc = r" If not, the function returns [None]."]
pub fn get_severity_from_code(&self, category: &Category) -> Option<Severity> {
let mut split_code = category.name().split('/');
let _lint = split_code.next();
debug_assert_eq!(_lint, Some("lint"));
let group = split_code.next();
let rule_name = split_code.next();
if let Some((group, rule_name)) = self.matches_diagnostic_code(group, rule_name) {
let severity = match group {
"a11y" => self
.a11y
.as_ref()
.and_then(|a11y| a11y.get_rule_configuration(rule_name))
.map(|rule_setting| rule_setting.into())
.unwrap_or_else(|| {
if A11y::is_recommended_rule(rule_name) {
Severity::Error
} else {
Severity::Warning
}
}),
"complexity" => self
.complexity
.as_ref()
.and_then(|complexity| complexity.get_rule_configuration(rule_name))
.map(|rule_setting| rule_setting.into())
.unwrap_or_else(|| {
if Complexity::is_recommended_rule(rule_name) {
Severity::Error
} else {
Severity::Warning
}
}),
"correctness" => self
.correctness
.as_ref()
.and_then(|correctness| correctness.get_rule_configuration(rule_name))
.map(|rule_setting| rule_setting.into())
.unwrap_or_else(|| {
if Correctness::is_recommended_rule(rule_name) {
Severity::Error
} else {
Severity::Warning
}
}),
"nursery" => self
.nursery
.as_ref()
.and_then(|nursery| nursery.get_rule_configuration(rule_name))
.map(|rule_setting| rule_setting.into())
.unwrap_or_else(|| {
if Nursery::is_recommended_rule(rule_name) {
Severity::Error
} else {
Severity::Warning
}
}),
"performance" => self
.performance
.as_ref()
.and_then(|performance| performance.get_rule_configuration(rule_name))
.map(|rule_setting| rule_setting.into())
.unwrap_or_else(|| {
if Performance::is_recommended_rule(rule_name) {
Severity::Error
} else {
Severity::Warning
}
}),
"security" => self
.security
.as_ref()
.and_then(|security| security.get_rule_configuration(rule_name))
.map(|rule_setting| rule_setting.into())
.unwrap_or_else(|| {
if Security::is_recommended_rule(rule_name) {
Severity::Error
} else {
Severity::Warning
}
}),
"style" => self
.style
.as_ref()
.and_then(|style| style.get_rule_configuration(rule_name))
.map(|rule_setting| rule_setting.into())
.unwrap_or_else(|| {
if Style::is_recommended_rule(rule_name) {
Severity::Error
} else {
Severity::Warning
}
}),
"suspicious" => self
.suspicious
.as_ref()
.and_then(|suspicious| suspicious.get_rule_configuration(rule_name))
.map(|rule_setting| rule_setting.into())
.unwrap_or_else(|| {
if Suspicious::is_recommended_rule(rule_name) {
Severity::Error
} else {
Severity::Warning
}
}),
_ => unreachable!("this group should not exist, found {}", group),
};
Some(severity)
} else {
None
}
}
pub(crate) const fn is_recommended(&self) -> bool { !matches!(self.recommended, Some(false)) }
pub(crate) const fn is_all(&self) -> bool { matches!(self.all, Some(true)) }
pub(crate) const fn is_not_all(&self) -> bool { matches!(self.all, Some(false)) }
#[doc = r" It returns a tuple of filters. The first element of the tuple are the enabled rules,"]
#[doc = r" while the second element are the disabled rules."]
#[doc = r""]
#[doc = r" Only one element of the tuple is [Some] at the time."]
#[doc = r""]
#[doc = r" The enabled rules are calculated from the difference with the disabled rules."]
pub fn as_enabled_rules(&self) -> IndexSet<RuleFilter> {
let mut enabled_rules = IndexSet::new();
let mut disabled_rules = IndexSet::new();
if let Some(group) = self.a11y.as_ref() {
group.collect_preset_rules(
self.is_recommended(),
&mut enabled_rules,
&mut disabled_rules,
);
enabled_rules.extend(&group.get_enabled_rules());
disabled_rules.extend(&group.get_disabled_rules());
} else if self.is_all() {
enabled_rules.extend(A11y::all_rules_as_filters());
} else if self.is_not_all() {
disabled_rules.extend(A11y::all_rules_as_filters());
} else if self.is_recommended() {
enabled_rules.extend(A11y::recommended_rules_as_filters());
}
if let Some(group) = self.complexity.as_ref() {
group.collect_preset_rules(
self.is_recommended(),
&mut enabled_rules,
&mut disabled_rules,
);
enabled_rules.extend(&group.get_enabled_rules());
disabled_rules.extend(&group.get_disabled_rules());
} else if self.is_all() {
enabled_rules.extend(Complexity::all_rules_as_filters());
} else if self.is_not_all() {
disabled_rules.extend(Complexity::all_rules_as_filters());
} else if self.is_recommended() {
enabled_rules.extend(Complexity::recommended_rules_as_filters());
}
if let Some(group) = self.correctness.as_ref() {
group.collect_preset_rules(
self.is_recommended(),
&mut enabled_rules,
&mut disabled_rules,
);
enabled_rules.extend(&group.get_enabled_rules());
disabled_rules.extend(&group.get_disabled_rules());
} else if self.is_all() {
enabled_rules.extend(Correctness::all_rules_as_filters());
} else if self.is_not_all() {
disabled_rules.extend(Correctness::all_rules_as_filters());
} else if self.is_recommended() {
enabled_rules.extend(Correctness::recommended_rules_as_filters());
}
if let Some(group) = self.nursery.as_ref() {
group.collect_preset_rules(
self.is_recommended(),
&mut enabled_rules,
&mut disabled_rules,
);
enabled_rules.extend(&group.get_enabled_rules());
disabled_rules.extend(&group.get_disabled_rules());
} else if self.is_all() {
enabled_rules.extend(Nursery::all_rules_as_filters());
} else if self.is_not_all() {
disabled_rules.extend(Nursery::all_rules_as_filters());
} else if self.is_recommended() && rome_flags::is_unstable() {
enabled_rules.extend(Nursery::recommended_rules_as_filters());
}
if let Some(group) = self.performance.as_ref() {
group.collect_preset_rules(
self.is_recommended(),
&mut enabled_rules,
&mut disabled_rules,
);
enabled_rules.extend(&group.get_enabled_rules());
disabled_rules.extend(&group.get_disabled_rules());
} else if self.is_all() {
enabled_rules.extend(Performance::all_rules_as_filters());
} else if self.is_not_all() {
disabled_rules.extend(Performance::all_rules_as_filters());
} else if self.is_recommended() {
enabled_rules.extend(Performance::recommended_rules_as_filters());
}
if let Some(group) = self.security.as_ref() {
group.collect_preset_rules(
self.is_recommended(),
&mut enabled_rules,
&mut disabled_rules,
);
enabled_rules.extend(&group.get_enabled_rules());
disabled_rules.extend(&group.get_disabled_rules());
} else if self.is_all() {
enabled_rules.extend(Security::all_rules_as_filters());
} else if self.is_not_all() {
disabled_rules.extend(Security::all_rules_as_filters());
} else if self.is_recommended() {
enabled_rules.extend(Security::recommended_rules_as_filters());
}
if let Some(group) = self.style.as_ref() {
group.collect_preset_rules(
self.is_recommended(),
&mut enabled_rules,
&mut disabled_rules,
);
enabled_rules.extend(&group.get_enabled_rules());
disabled_rules.extend(&group.get_disabled_rules());
} else if self.is_all() {
enabled_rules.extend(Style::all_rules_as_filters());
} else if self.is_not_all() {
disabled_rules.extend(Style::all_rules_as_filters());
} else if self.is_recommended() {
enabled_rules.extend(Style::recommended_rules_as_filters());
}
if let Some(group) = self.suspicious.as_ref() {
group.collect_preset_rules(
self.is_recommended(),
&mut enabled_rules,
&mut disabled_rules,
);
enabled_rules.extend(&group.get_enabled_rules());
disabled_rules.extend(&group.get_disabled_rules());
} else if self.is_all() {
enabled_rules.extend(Suspicious::all_rules_as_filters());
} else if self.is_not_all() {
disabled_rules.extend(Suspicious::all_rules_as_filters());
} else if self.is_recommended() {
enabled_rules.extend(Suspicious::recommended_rules_as_filters());
}
enabled_rules.difference(&disabled_rules).cloned().collect()
}
}
#[derive(Deserialize, Default, Serialize, Debug, Clone, Bpaf)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", default)]
#[doc = r" A list of rules that belong to this group"]
pub struct A11y {
#[doc = r" It enables the recommended rules for this group"]
#[serde(skip_serializing_if = "Option::is_none")]
#[bpaf(hide)]
pub recommended: Option<bool>,
#[doc = r" It enables ALL rules for this group."]
#[serde(skip_serializing_if = "Option::is_none")]
#[bpaf(hide)]
pub all: Option<bool>,
#[doc = "Enforce that the accessKey attribute is not used on any HTML element."]
#[bpaf(long("no-access-key"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub no_access_key: Option<RuleConfiguration>,
#[doc = "Enforce that autoFocus prop is not used on elements."]
#[bpaf(long("no-autofocus"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub no_autofocus: Option<RuleConfiguration>,
#[doc = "Disallow target=\"_blank\" attribute without rel=\"noreferrer\""]
#[bpaf(long("no-blank-target"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub no_blank_target: Option<RuleConfiguration>,
#[doc = "Enforces that no distracting elements are used."]
#[bpaf(
long("no-distracting-elements"),
argument("on|off|warn"),
optional,
hide
)]
#[serde(skip_serializing_if = "Option::is_none")]
pub no_distracting_elements: Option<RuleConfiguration>,
#[doc = "The scope prop should be used only on <th> elements."]
#[bpaf(long("no-header-scope"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub no_header_scope: Option<RuleConfiguration>,
#[doc = "Enforce that interactive ARIA roles are not assigned to non-interactive HTML elements."]
#[bpaf(
long("no-noninteractive-element-to-interactive-role"),
argument("on|off|warn"),
optional,
hide
)]
#[serde(skip_serializing_if = "Option::is_none")]
pub no_noninteractive_element_to_interactive_role: Option<RuleConfiguration>,
#[doc = "Prevent the usage of positive integers on tabIndex property"]
#[bpaf(long("no-positive-tabindex"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub no_positive_tabindex: Option<RuleConfiguration>,
#[doc = "Enforce img alt prop does not contain the word \"image\", \"picture\", or \"photo\"."]
#[bpaf(long("no-redundant-alt"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub no_redundant_alt: Option<RuleConfiguration>,
#[doc = "Enforces the usage of the title element for the svg element."]
#[bpaf(long("no-svg-without-title"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub no_svg_without_title: Option<RuleConfiguration>,
#[doc = "Enforce that all elements that require alternative text have meaningful information to relay back to the end user."]
#[bpaf(long("use-alt-text"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub use_alt_text: Option<RuleConfiguration>,
#[doc = "Enforce that anchors have content and that the content is accessible to screen readers."]
#[bpaf(long("use-anchor-content"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub use_anchor_content: Option<RuleConfiguration>,
#[doc = "Enforce that elements with ARIA roles must have all required ARIA attributes for that role."]
#[bpaf(
long("use-aria-props-for-role"),
argument("on|off|warn"),
optional,
hide
)]
#[serde(skip_serializing_if = "Option::is_none")]
pub use_aria_props_for_role: Option<RuleConfiguration>,
#[doc = "Enforces the usage of the attribute type for the element button"]
#[bpaf(long("use-button-type"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub use_button_type: Option<RuleConfiguration>,
#[doc = "Enforce that heading elements (h1, h2, etc.) have content and that the content is accessible to screen readers. Accessible means that it is not hidden using the aria-hidden prop."]
#[bpaf(long("use-heading-content"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub use_heading_content: Option<RuleConfiguration>,
#[doc = "Enforce that html element has lang attribute."]
#[bpaf(long("use-html-lang"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub use_html_lang: Option<RuleConfiguration>,
#[doc = "Enforces the usage of the attribute title for the element iframe."]
#[bpaf(long("use-iframe-title"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub use_iframe_title: Option<RuleConfiguration>,
#[doc = "Enforce onClick is accompanied by at least one of the following: onKeyUp, onKeyDown, onKeyPress."]
#[bpaf(
long("use-key-with-click-events"),
argument("on|off|warn"),
optional,
hide
)]
#[serde(skip_serializing_if = "Option::is_none")]
pub use_key_with_click_events: Option<RuleConfiguration>,
#[doc = "Enforce onMouseOver / onMouseOut are accompanied by onFocus / onBlur."]
#[bpaf(
long("use-key-with-mouse-events"),
argument("on|off|warn"),
optional,
hide
)]
#[serde(skip_serializing_if = "Option::is_none")]
pub use_key_with_mouse_events: Option<RuleConfiguration>,
#[doc = "Enforces that audio and video elements must have a track for captions."]
#[bpaf(long("use-media-caption"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub use_media_caption: Option<RuleConfiguration>,
#[doc = "Enforce that all anchors are valid, and they are navigable elements."]
#[bpaf(long("use-valid-anchor"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub use_valid_anchor: Option<RuleConfiguration>,
#[doc = "Ensures that ARIA properties aria-* are all valid."]
#[bpaf(long("use-valid-aria-props"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub use_valid_aria_props: Option<RuleConfiguration>,
#[doc = "Ensure that the attribute passed to the lang attribute is a correct ISO language and/or country."]
#[bpaf(long("use-valid-lang"), argument("on|off|warn"), optional, hide)]
#[serde(skip_serializing_if = "Option::is_none")]
pub use_valid_lang: Option<RuleConfiguration>,
}
impl A11y {
const GROUP_NAME: &'static str = "a11y";
pub(crate) const GROUP_RULES: [&'static str; 22] = [
"noAccessKey",
"noAutofocus",
"noBlankTarget",
"noDistractingElements",
"noHeaderScope",
"noNoninteractiveElementToInteractiveRole",
"noPositiveTabindex",
"noRedundantAlt",
"noSvgWithoutTitle",
"useAltText",
"useAnchorContent",
"useAriaPropsForRole",
"useButtonType",
"useHeadingContent",
"useHtmlLang",
"useIframeTitle",
"useKeyWithClickEvents",
"useKeyWithMouseEvents",
"useMediaCaption",
"useValidAnchor",
"useValidAriaProps",
"useValidLang",
];
const RECOMMENDED_RULES: [&'static str; 20] = [
"noAutofocus",
"noBlankTarget",
"noDistractingElements",
"noHeaderScope",
"noNoninteractiveElementToInteractiveRole",
"noPositiveTabindex",
"noRedundantAlt",
"noSvgWithoutTitle",
"useAltText",
"useAnchorContent",
"useAriaPropsForRole",
"useButtonType",
"useHtmlLang",
"useIframeTitle",
"useKeyWithClickEvents",
"useKeyWithMouseEvents",
"useMediaCaption",
"useValidAnchor",
"useValidAriaProps",
"useValidLang",
];
const RECOMMENDED_RULES_AS_FILTERS: [RuleFilter<'static>; 20] = [
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[1]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[2]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[3]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[4]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[5]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[6]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[7]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[8]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[9]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[10]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[11]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[12]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[14]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[15]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[16]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[17]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[18]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[19]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[20]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[21]),
];
const ALL_RULES_AS_FILTERS: [RuleFilter<'static>; 22] = [
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[0]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[1]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[2]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[3]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[4]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[5]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[6]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[7]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[8]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[9]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[10]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[11]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[12]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[13]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[14]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[15]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[16]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[17]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[18]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[19]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[20]),
RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[21]),
];
#[doc = r" Retrieves the recommended rules"]
pub(crate) fn is_recommended(&self) -> bool { matches!(self.recommended, Some(true)) }
pub(crate) const fn is_not_recommended(&self) -> bool {
matches!(self.recommended, Some(false))
}
pub(crate) fn is_all(&self) -> bool { matches!(self.all, Some(true)) }
pub(crate) fn is_not_all(&self) -> bool { matches!(self.all, Some(false)) }
pub(crate) fn get_enabled_rules(&self) -> IndexSet<RuleFilter> {
let mut index_set = IndexSet::new();
if let Some(rule) = self.no_access_key.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[0]));
}
}
if let Some(rule) = self.no_autofocus.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[1]));
}
}
if let Some(rule) = self.no_blank_target.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[2]));
}
}
if let Some(rule) = self.no_distracting_elements.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[3]));
}
}
if let Some(rule) = self.no_header_scope.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[4]));
}
}
if let Some(rule) = self.no_noninteractive_element_to_interactive_role.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[5]));
}
}
if let Some(rule) = self.no_positive_tabindex.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[6]));
}
}
if let Some(rule) = self.no_redundant_alt.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[7]));
}
}
if let Some(rule) = self.no_svg_without_title.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[8]));
}
}
if let Some(rule) = self.use_alt_text.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[9]));
}
}
if let Some(rule) = self.use_anchor_content.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[10]));
}
}
if let Some(rule) = self.use_aria_props_for_role.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[11]));
}
}
if let Some(rule) = self.use_button_type.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[12]));
}
}
if let Some(rule) = self.use_heading_content.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[13]));
}
}
if let Some(rule) = self.use_html_lang.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[14]));
}
}
if let Some(rule) = self.use_iframe_title.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[15]));
}
}
if let Some(rule) = self.use_key_with_click_events.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[16]));
}
}
if let Some(rule) = self.use_key_with_mouse_events.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[17]));
}
}
if let Some(rule) = self.use_media_caption.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[18]));
}
}
if let Some(rule) = self.use_valid_anchor.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[19]));
}
}
if let Some(rule) = self.use_valid_aria_props.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[20]));
}
}
if let Some(rule) = self.use_valid_lang.as_ref() {
if rule.is_enabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[21]));
}
}
index_set
}
pub(crate) fn get_disabled_rules(&self) -> IndexSet<RuleFilter> {
let mut index_set = IndexSet::new();
if let Some(rule) = self.no_access_key.as_ref() {
if rule.is_disabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[0]));
}
}
if let Some(rule) = self.no_autofocus.as_ref() {
if rule.is_disabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[1]));
}
}
if let Some(rule) = self.no_blank_target.as_ref() {
if rule.is_disabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[2]));
}
}
if let Some(rule) = self.no_distracting_elements.as_ref() {
if rule.is_disabled() {
index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[3]));
}
}
if let Some(rule) = self.no_header_scope.as_ref() {
if rule.is_disabled() {
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_service/src/file_handlers/javascript.rs | crates/rome_service/src/file_handlers/javascript.rs | use super::{
AnalyzerCapabilities, DebugCapabilities, ExtensionHandler, FormatterCapabilities, LintParams,
LintResults, Mime, ParserCapabilities,
};
use crate::configuration::to_analyzer_configuration;
use crate::file_handlers::{is_diagnostic_error, Features, FixAllParams, Language as LanguageId};
use crate::workspace::OrganizeImportsResult;
use crate::{
settings::{FormatSettings, Language, LanguageSettings, LanguagesSettings, SettingsHandle},
workspace::{
CodeAction, FixAction, FixFileMode, FixFileResult, GetSyntaxTreeResult, PullActionsResult,
RenameResult,
},
Rules, WorkspaceError,
};
use indexmap::IndexSet;
use rome_analyze::{
AnalysisFilter, AnalyzerOptions, ControlFlow, GroupCategory, Never, QueryMatch,
RegistryVisitor, RuleCategories, RuleCategory, RuleFilter, RuleGroup,
};
use rome_diagnostics::{category, Applicability, Diagnostic, DiagnosticExt, Severity};
use rome_formatter::{FormatError, Printed};
use rome_fs::RomePath;
use rome_js_analyze::utils::rename::{RenameError, RenameSymbolExtensions};
use rome_js_analyze::{
analyze, analyze_with_inspect_matcher, visit_registry, ControlFlowGraph, RuleError,
};
use rome_js_formatter::context::{
trailing_comma::TrailingComma, ArrowParentheses, QuoteProperties, QuoteStyle, Semicolons,
};
use rome_js_formatter::{context::JsFormatOptions, format_node};
use rome_js_parser::JsParserOptions;
use rome_js_semantic::{semantic_model, SemanticModelOptions};
use rome_js_syntax::{
AnyJsRoot, JsFileSource, JsLanguage, JsSyntaxNode, TextRange, TextSize, TokenAtOffset,
};
use rome_parser::AnyParse;
use rome_rowan::{AstNode, BatchMutationExt, Direction, FileSource, NodeCache};
use std::borrow::Cow;
use std::ffi::OsStr;
use std::fmt::Debug;
use std::path::PathBuf;
use tracing::{debug, trace};
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct JsFormatterSettings {
pub quote_style: Option<QuoteStyle>,
pub jsx_quote_style: Option<QuoteStyle>,
pub quote_properties: Option<QuoteProperties>,
pub trailing_comma: Option<TrailingComma>,
pub semicolons: Option<Semicolons>,
pub arrow_parentheses: Option<ArrowParentheses>,
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct JsParserSettings {
pub parse_class_parameter_decorators: bool,
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct JsonParserSettings {
pub allow_comments: bool,
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct JsLinterSettings {
pub globals: Vec<String>,
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct JsOrganizeImportsSettings {}
impl Language for JsLanguage {
type FormatterSettings = JsFormatterSettings;
type LinterSettings = JsLinterSettings;
type FormatOptions = JsFormatOptions;
type OrganizeImportsSettings = JsOrganizeImportsSettings;
type ParserSettings = JsParserSettings;
fn lookup_settings(languages: &LanguagesSettings) -> &LanguageSettings<Self> {
&languages.javascript
}
fn resolve_format_options(
global: &FormatSettings,
language: &JsFormatterSettings,
path: &RomePath,
) -> JsFormatOptions {
JsFormatOptions::new(path.as_path().try_into().unwrap_or_default())
.with_indent_style(global.indent_style.unwrap_or_default())
.with_line_width(global.line_width.unwrap_or_default())
.with_quote_style(language.quote_style.unwrap_or_default())
.with_jsx_quote_style(language.jsx_quote_style.unwrap_or_default())
.with_quote_properties(language.quote_properties.unwrap_or_default())
.with_trailing_comma(language.trailing_comma.unwrap_or_default())
.with_semicolons(language.semicolons.unwrap_or_default())
.with_arrow_parentheses(language.arrow_parentheses.unwrap_or_default())
}
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct JsFileHandler;
impl ExtensionHandler for JsFileHandler {
fn language(&self) -> super::Language {
super::Language::JavaScript
}
fn mime(&self) -> Mime {
Mime::Javascript
}
fn may_use_tabs(&self) -> bool {
true
}
fn capabilities(&self) -> super::Capabilities {
super::Capabilities {
parser: ParserCapabilities { parse: Some(parse) },
debug: DebugCapabilities {
debug_syntax_tree: Some(debug_syntax_tree),
debug_control_flow: Some(debug_control_flow),
debug_formatter_ir: Some(debug_formatter_ir),
},
analyzer: AnalyzerCapabilities {
lint: Some(lint),
code_actions: Some(code_actions),
fix_all: Some(fix_all),
rename: Some(rename),
organize_imports: Some(organize_imports),
},
formatter: FormatterCapabilities {
format: Some(format),
format_range: Some(format_range),
format_on_type: Some(format_on_type),
},
}
}
}
fn extension_error(path: &RomePath) -> WorkspaceError {
let language = Features::get_language(path).or(LanguageId::from_path(path));
WorkspaceError::source_file_not_supported(
language,
path.clone().display().to_string(),
path.clone()
.extension()
.and_then(OsStr::to_str)
.map(|s| s.to_string()),
)
}
fn parse(
rome_path: &RomePath,
language_hint: LanguageId,
text: &str,
settings: SettingsHandle,
cache: &mut NodeCache,
) -> AnyParse {
let source_type =
JsFileSource::try_from(rome_path.as_path()).unwrap_or_else(|_| match language_hint {
LanguageId::JavaScriptReact => JsFileSource::jsx(),
LanguageId::TypeScript => JsFileSource::ts(),
LanguageId::TypeScriptReact => JsFileSource::tsx(),
_ => JsFileSource::js_module(),
});
let settings = &settings.as_ref().languages.javascript.parser;
let options = JsParserOptions {
parse_class_parameter_decorators: settings.parse_class_parameter_decorators,
};
let parse = rome_js_parser::parse_js_with_cache(text, source_type, options, cache);
let root = parse.syntax();
let diagnostics = parse.into_diagnostics();
AnyParse::new(
// SAFETY: the parser should always return a root node
root.as_send().unwrap(),
diagnostics,
source_type.as_any_file_source(),
)
}
fn debug_syntax_tree(_rome_path: &RomePath, parse: AnyParse) -> GetSyntaxTreeResult {
let syntax: JsSyntaxNode = parse.syntax();
let tree: AnyJsRoot = parse.tree();
GetSyntaxTreeResult {
cst: format!("{syntax:#?}"),
ast: format!("{tree:#?}"),
}
}
fn debug_control_flow(parse: AnyParse, cursor: TextSize) -> String {
let mut control_flow_graph = None;
let filter = AnalysisFilter {
categories: RuleCategories::LINT,
enabled_rules: Some(&[RuleFilter::Rule("correctness", "noUnreachable")]),
..AnalysisFilter::default()
};
let options = AnalyzerOptions::default();
analyze_with_inspect_matcher(
&parse.tree(),
filter,
|match_params| {
let cfg = match match_params.query.downcast_ref::<ControlFlowGraph>() {
Some(cfg) => cfg,
_ => return,
};
let range = cfg.text_range();
if !range.contains(cursor) {
return;
}
match &control_flow_graph {
None => {
control_flow_graph = Some((cfg.graph.to_string(), range));
}
Some((_, prev_range)) => {
if range.len() < prev_range.len() {
control_flow_graph = Some((cfg.graph.to_string(), range));
}
}
}
},
&options,
JsFileSource::default(),
|_| ControlFlow::<Never>::Continue(()),
);
control_flow_graph.map(|(cfg, _)| cfg).unwrap_or_default()
}
fn debug_formatter_ir(
rome_path: &RomePath,
parse: AnyParse,
settings: SettingsHandle,
) -> Result<String, WorkspaceError> {
let options = settings.format_options::<JsLanguage>(rome_path);
let tree = parse.syntax();
let formatted = format_node(options, &tree)?;
let root_element = formatted.into_document();
Ok(root_element.to_string())
}
fn lint(params: LintParams) -> LintResults {
let Ok(file_source) = params
.parse
.file_source(params.path) else {
return LintResults {
errors: 0,
diagnostics: vec![],
skipped_diagnostics: 0
}
};
let tree = params.parse.tree();
let mut diagnostics = params.parse.into_diagnostics();
let analyzer_options =
compute_analyzer_options(¶ms.settings, PathBuf::from(params.path.as_path()));
let mut diagnostic_count = diagnostics.len() as u64;
let mut errors = diagnostics
.iter()
.filter(|diag| diag.severity() <= Severity::Error)
.count();
let has_lint = params.filter.categories.contains(RuleCategories::LINT);
let (_, analyze_diagnostics) = analyze(
&tree,
params.filter,
&analyzer_options,
file_source,
|signal| {
if let Some(mut diagnostic) = signal.diagnostic() {
// Do not report unused suppression comment diagnostics if this is a syntax-only analyzer pass
if !has_lint && diagnostic.category() == Some(category!("suppressions/unused")) {
return ControlFlow::<Never>::Continue(());
}
diagnostic_count += 1;
// We do now check if the severity of the diagnostics should be changed.
// The configuration allows to change the severity of the diagnostics emitted by rules.
let severity = diagnostic
.category()
.filter(|category| category.name().starts_with("lint/"))
.map(|category| {
params
.rules
.and_then(|rules| rules.get_severity_from_code(category))
.unwrap_or(Severity::Warning)
})
.unwrap_or_else(|| diagnostic.severity());
if severity >= Severity::Error {
errors += 1;
}
if diagnostic_count <= params.max_diagnostics {
for action in signal.actions() {
if !action.is_suppression() {
diagnostic = diagnostic.add_code_suggestion(action.into());
}
}
let error = diagnostic.with_severity(severity);
diagnostics.push(rome_diagnostics::serde::Diagnostic::new(error));
}
}
ControlFlow::<Never>::Continue(())
},
);
diagnostics.extend(
analyze_diagnostics
.into_iter()
.map(rome_diagnostics::serde::Diagnostic::new)
.collect::<Vec<_>>(),
);
let skipped_diagnostics = diagnostic_count.saturating_sub(diagnostics.len() as u64);
LintResults {
diagnostics,
errors,
skipped_diagnostics,
}
}
struct ActionsVisitor<'a> {
enabled_rules: Vec<RuleFilter<'a>>,
}
impl RegistryVisitor<JsLanguage> for ActionsVisitor<'_> {
fn record_category<C: GroupCategory<Language = JsLanguage>>(&mut self) {
if matches!(C::CATEGORY, RuleCategory::Action) {
C::record_groups(self);
}
}
fn record_group<G: RuleGroup<Language = JsLanguage>>(&mut self) {
G::record_rules(self)
}
fn record_rule<R>(&mut self)
where
R: rome_analyze::Rule + 'static,
R::Query: rome_analyze::Queryable<Language = JsLanguage>,
<R::Query as rome_analyze::Queryable>::Output: Clone,
{
self.enabled_rules.push(RuleFilter::Rule(
<R::Group as RuleGroup>::NAME,
R::METADATA.name,
));
}
}
#[tracing::instrument(level = "debug", skip(parse))]
fn code_actions(
parse: AnyParse,
range: TextRange,
rules: Option<&Rules>,
settings: SettingsHandle,
path: &RomePath,
) -> PullActionsResult {
let tree = parse.tree();
let mut actions = Vec::new();
let mut enabled_rules = vec![];
if settings.as_ref().organize_imports.enabled {
enabled_rules.push(RuleFilter::Rule("correctness", "organizeImports"));
}
if let Some(rules) = rules {
let rules = rules.as_enabled_rules().into_iter().collect();
// The rules in the assist category do not have configuration entries,
// always add them all to the enabled rules list
let mut visitor = ActionsVisitor {
enabled_rules: rules,
};
visit_registry(&mut visitor);
enabled_rules.extend(visitor.enabled_rules);
}
let mut filter = if !enabled_rules.is_empty() {
AnalysisFilter::from_enabled_rules(Some(enabled_rules.as_slice()))
} else {
AnalysisFilter::default()
};
filter.categories = RuleCategories::SYNTAX | RuleCategories::LINT;
if settings.as_ref().organize_imports.enabled {
filter.categories |= RuleCategories::ACTION;
}
filter.range = Some(range);
trace!("Filter applied for code actions: {:?}", &filter);
let analyzer_options = compute_analyzer_options(&settings, PathBuf::from(path.as_path()));
let Ok(source_type) = parse.file_source(path) else {
return PullActionsResult {
actions: vec![]
}
};
analyze(&tree, filter, &analyzer_options, source_type, |signal| {
actions.extend(signal.actions().into_code_action_iter().map(|item| {
CodeAction {
category: item.category.clone(),
rule_name: item
.rule_name
.map(|(group, name)| (Cow::Borrowed(group), Cow::Borrowed(name))),
suggestion: item.suggestion,
}
}));
ControlFlow::<Never>::Continue(())
});
PullActionsResult { actions }
}
/// If applies all the safe fixes to the given syntax tree.
///
/// If `indent_style` is [Some], it means that the formatting should be applied at the end
fn fix_all(params: FixAllParams) -> Result<FixFileResult, WorkspaceError> {
let FixAllParams {
parse,
rules,
fix_file_mode,
settings,
should_format,
rome_path,
} = params;
let file_source = parse
.file_source(rome_path)
.map_err(|_| extension_error(params.rome_path))?;
let mut tree: AnyJsRoot = parse.tree();
let mut actions = Vec::new();
let enabled_rules: Option<Vec<RuleFilter>> = if let Some(rules) = rules {
let enabled: IndexSet<RuleFilter> = rules.as_enabled_rules();
Some(enabled.into_iter().collect())
} else {
None
};
let mut filter = match &enabled_rules {
Some(rules) => AnalysisFilter::from_enabled_rules(Some(rules.as_slice())),
_ => AnalysisFilter::default(),
};
filter.categories = RuleCategories::SYNTAX | RuleCategories::LINT;
let mut skipped_suggested_fixes = 0;
let mut errors: u16 = 0;
let analyzer_options = compute_analyzer_options(&settings, PathBuf::from(rome_path.as_path()));
loop {
let (action, _) = analyze(&tree, filter, &analyzer_options, file_source, |signal| {
let current_diagnostic = signal.diagnostic();
if let Some(diagnostic) = current_diagnostic.as_ref() {
if is_diagnostic_error(diagnostic, params.rules) {
errors += 1;
}
}
for action in signal.actions() {
// suppression actions should not be part of the fixes (safe or suggested)
if action.is_suppression() {
continue;
}
match fix_file_mode {
FixFileMode::SafeFixes => {
if action.applicability == Applicability::MaybeIncorrect {
skipped_suggested_fixes += 1;
}
if action.applicability == Applicability::Always {
errors = errors.saturating_sub(1);
return ControlFlow::Break(action);
}
}
FixFileMode::SafeAndUnsafeFixes => {
if matches!(
action.applicability,
Applicability::Always | Applicability::MaybeIncorrect
) {
errors = errors.saturating_sub(1);
return ControlFlow::Break(action);
}
}
}
}
ControlFlow::Continue(())
});
match action {
Some(action) => {
if let Some((range, _)) = action.mutation.as_text_edits() {
tree = match AnyJsRoot::cast(action.mutation.commit()) {
Some(tree) => tree,
None => {
return Err(WorkspaceError::RuleError(
RuleError::ReplacedRootWithNonRootError {
rule_name: action.rule_name.map(|(group, rule)| {
(Cow::Borrowed(group), Cow::Borrowed(rule))
}),
},
))
}
};
actions.push(FixAction {
rule_name: action
.rule_name
.map(|(group, rule)| (Cow::Borrowed(group), Cow::Borrowed(rule))),
range,
});
}
}
None => {
let code = if should_format {
format_node(
settings.format_options::<JsLanguage>(rome_path),
tree.syntax(),
)?
.print()?
.into_code()
} else {
tree.syntax().to_string()
};
return Ok(FixFileResult {
code,
skipped_suggested_fixes,
actions,
errors: errors.into(),
});
}
}
}
}
#[tracing::instrument(level = "debug", skip(parse))]
fn format(
rome_path: &RomePath,
parse: AnyParse,
settings: SettingsHandle,
) -> Result<Printed, WorkspaceError> {
let options = settings.format_options::<JsLanguage>(rome_path);
debug!("Format with the following options: \n{}", options);
let tree = parse.syntax();
let formatted = format_node(options, &tree)?;
match formatted.print() {
Ok(printed) => Ok(printed),
Err(error) => Err(WorkspaceError::FormatError(error.into())),
}
}
fn format_range(
rome_path: &RomePath,
parse: AnyParse,
settings: SettingsHandle,
range: TextRange,
) -> Result<Printed, WorkspaceError> {
let options = settings.format_options::<JsLanguage>(rome_path);
let tree = parse.syntax();
let printed = rome_js_formatter::format_range(options, &tree, range)?;
Ok(printed)
}
fn format_on_type(
rome_path: &RomePath,
parse: AnyParse,
settings: SettingsHandle,
offset: TextSize,
) -> Result<Printed, WorkspaceError> {
let options = settings.format_options::<JsLanguage>(rome_path);
let tree = parse.syntax();
let range = tree.text_range();
if offset < range.start() || offset > range.end() {
return Err(WorkspaceError::FormatError(FormatError::RangeError {
input: TextRange::at(offset, TextSize::from(0)),
tree: range,
}));
}
let token = match tree.token_at_offset(offset) {
// File is empty, do nothing
TokenAtOffset::None => panic!("empty file"),
TokenAtOffset::Single(token) => token,
// The cursor should be right after the closing character that was just typed,
// select the previous token as the correct one
TokenAtOffset::Between(token, _) => token,
};
let root_node = match token.parent() {
Some(node) => node,
None => panic!("found a token with no parent"),
};
let printed = rome_js_formatter::format_sub_tree(options, &root_node)?;
Ok(printed)
}
fn rename(
_rome_path: &RomePath,
parse: AnyParse,
symbol_at: TextSize,
new_name: String,
) -> Result<RenameResult, WorkspaceError> {
let root = parse.tree();
let model = semantic_model(&root, SemanticModelOptions::default());
if let Some(node) = parse
.syntax()
.descendants_tokens(Direction::Next)
.find(|token| token.text_range().contains(symbol_at))
.and_then(|token| token.parent())
{
let original_name = node.text_trimmed();
let range = node.text_range();
match node.try_into() {
Ok(node) => {
let mut batch = root.begin();
let result = batch.rename_any_renamable_node(&model, node, &new_name);
if !result {
Err(WorkspaceError::RenameError(RenameError::CannotBeRenamed {
original_name: original_name.to_string(),
original_range: range,
new_name,
}))
} else {
let (range, indels) = batch.as_text_edits().unwrap_or_default();
Ok(RenameResult { range, indels })
}
}
Err(err) => Err(WorkspaceError::RenameError(err)),
}
} else {
Err(WorkspaceError::RenameError(
RenameError::CannotFindDeclaration(new_name),
))
}
}
fn organize_imports(parse: AnyParse) -> Result<OrganizeImportsResult, WorkspaceError> {
let mut tree: AnyJsRoot = parse.tree();
let filter = AnalysisFilter {
enabled_rules: Some(&[RuleFilter::Rule("correctness", "organizeImports")]),
categories: RuleCategories::ACTION,
..AnalysisFilter::default()
};
let (action, _) = analyze(
&tree,
filter,
&AnalyzerOptions::default(),
JsFileSource::default(),
|signal| {
for action in signal.actions() {
if action.is_suppression() {
continue;
}
return ControlFlow::Break(action);
}
ControlFlow::Continue(())
},
);
if let Some(action) = action {
tree = match AnyJsRoot::cast(action.mutation.commit()) {
Some(tree) => tree,
None => {
return Err(WorkspaceError::RuleError(
RuleError::ReplacedRootWithNonRootError {
rule_name: action
.rule_name
.map(|(group, rule)| (Cow::Borrowed(group), Cow::Borrowed(rule))),
},
))
}
};
Ok(OrganizeImportsResult {
code: tree.syntax().to_string(),
})
} else {
Ok(OrganizeImportsResult {
code: tree.syntax().to_string(),
})
}
}
fn compute_analyzer_options(settings: &SettingsHandle, file_path: PathBuf) -> AnalyzerOptions {
let configuration = to_analyzer_configuration(
settings.as_ref().linter(),
&settings.as_ref().languages,
|settings| {
if let Some(globals) = settings.javascript.globals.as_ref() {
globals
.iter()
.map(|global| global.to_string())
.collect::<Vec<_>>()
} else {
vec![]
}
},
);
AnalyzerOptions {
configuration,
file_path,
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_service/src/file_handlers/unknown.rs | crates/rome_service/src/file_handlers/unknown.rs | use super::ExtensionHandler;
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct UnknownFileHandler {}
impl ExtensionHandler for UnknownFileHandler {
fn language(&self) -> super::Language {
super::Language::Unknown
}
fn mime(&self) -> super::Mime {
super::Mime::Text
}
fn may_use_tabs(&self) -> bool {
true
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_service/src/file_handlers/json.rs | crates/rome_service/src/file_handlers/json.rs | use super::{ExtensionHandler, Mime};
use crate::configuration::to_analyzer_configuration;
use crate::file_handlers::javascript::JsonParserSettings;
use crate::file_handlers::{
AnalyzerCapabilities, Capabilities, FixAllParams, FormatterCapabilities, LintParams,
LintResults, ParserCapabilities,
};
use crate::file_handlers::{DebugCapabilities, Language as LanguageId};
use crate::settings::{
FormatSettings, Language, LanguageSettings, LanguagesSettings, SettingsHandle,
};
use crate::workspace::{
FixFileResult, GetSyntaxTreeResult, OrganizeImportsResult, PullActionsResult,
};
use crate::{Configuration, Rules, WorkspaceError};
use rome_analyze::{AnalyzerOptions, ControlFlow, Never, RuleCategories};
use rome_deserialize::json::deserialize_from_json_ast;
use rome_diagnostics::{category, Diagnostic, DiagnosticExt, Severity};
use rome_formatter::{FormatError, Printed};
use rome_fs::{RomePath, CONFIG_NAME};
use rome_json_analyze::analyze;
use rome_json_formatter::context::JsonFormatOptions;
use rome_json_formatter::format_node;
use rome_json_parser::JsonParserOptions;
use rome_json_syntax::{JsonFileSource, JsonLanguage, JsonRoot, JsonSyntaxNode};
use rome_parser::AnyParse;
use rome_rowan::{AstNode, FileSource, NodeCache};
use rome_rowan::{TextRange, TextSize, TokenAtOffset};
use std::path::{Path, PathBuf};
impl Language for JsonLanguage {
type FormatterSettings = ();
type LinterSettings = ();
type OrganizeImportsSettings = ();
type FormatOptions = JsonFormatOptions;
type ParserSettings = JsonParserSettings;
fn lookup_settings(language: &LanguagesSettings) -> &LanguageSettings<Self> {
&language.json
}
fn resolve_format_options(
global: &FormatSettings,
_language: &Self::FormatterSettings,
_path: &RomePath,
) -> Self::FormatOptions {
JsonFormatOptions::default()
.with_indent_style(global.indent_style.unwrap_or_default())
.with_line_width(global.line_width.unwrap_or_default())
}
}
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct JsonFileHandler;
impl ExtensionHandler for JsonFileHandler {
fn language(&self) -> super::Language {
super::Language::Json
}
fn mime(&self) -> super::Mime {
Mime::Json
}
fn may_use_tabs(&self) -> bool {
true
}
fn capabilities(&self) -> Capabilities {
Capabilities {
parser: ParserCapabilities { parse: Some(parse) },
debug: DebugCapabilities {
debug_syntax_tree: Some(debug_syntax_tree),
debug_control_flow: None,
debug_formatter_ir: Some(debug_formatter_ir),
},
analyzer: AnalyzerCapabilities {
lint: Some(lint),
code_actions: Some(code_actions),
rename: None,
fix_all: Some(fix_all),
organize_imports: Some(organize_imports),
},
formatter: FormatterCapabilities {
format: Some(format),
format_range: Some(format_range),
format_on_type: Some(format_on_type),
},
}
}
}
fn is_file_allowed_as_jsonc(path: &Path) -> bool {
path.file_name()
.and_then(|f| f.to_str())
.map(|f| super::Language::ALLOWED_FILES.contains(&f))
// default is false
.unwrap_or_default()
}
fn parse(
rome_path: &RomePath,
language_hint: LanguageId,
text: &str,
settings: SettingsHandle,
cache: &mut NodeCache,
) -> AnyParse {
let parser = &settings.as_ref().languages.json.parser;
let source_type =
JsonFileSource::try_from(rome_path.as_path()).unwrap_or_else(|_| match language_hint {
LanguageId::Json => JsonFileSource::json(),
LanguageId::Jsonc => JsonFileSource::jsonc(),
_ => JsonFileSource::json(),
});
let options: JsonParserOptions = JsonParserOptions {
allow_comments: parser.allow_comments
|| source_type.is_jsonc()
|| is_file_allowed_as_jsonc(rome_path),
};
let parse = rome_json_parser::parse_json_with_cache(text, cache, options);
let root = parse.syntax();
let diagnostics = parse.into_diagnostics();
AnyParse::new(
// SAFETY: the parser should always return a root node
root.as_send().unwrap(),
diagnostics,
source_type.as_any_file_source(),
)
}
fn debug_syntax_tree(_rome_path: &RomePath, parse: AnyParse) -> GetSyntaxTreeResult {
let syntax: JsonSyntaxNode = parse.syntax();
let tree: JsonRoot = parse.tree();
GetSyntaxTreeResult {
cst: format!("{syntax:#?}"),
ast: format!("{tree:#?}"),
}
}
fn debug_formatter_ir(
rome_path: &RomePath,
parse: AnyParse,
settings: SettingsHandle,
) -> Result<String, WorkspaceError> {
let options = settings.format_options::<JsonLanguage>(rome_path);
let tree = parse.syntax();
let formatted = format_node(options, &tree)?;
let root_element = formatted.into_document();
Ok(root_element.to_string())
}
#[tracing::instrument(level = "debug", skip(parse))]
fn format(
rome_path: &RomePath,
parse: AnyParse,
settings: SettingsHandle,
) -> Result<Printed, WorkspaceError> {
let options = settings.format_options::<JsonLanguage>(rome_path);
tracing::debug!("Format with the following options: \n{}", options);
let tree = parse.syntax();
let formatted = format_node(options, &tree)?;
match formatted.print() {
Ok(printed) => Ok(printed),
Err(error) => Err(WorkspaceError::FormatError(error.into())),
}
}
fn format_range(
rome_path: &RomePath,
parse: AnyParse,
settings: SettingsHandle,
range: TextRange,
) -> Result<Printed, WorkspaceError> {
let options = settings.format_options::<JsonLanguage>(rome_path);
let tree = parse.syntax();
let printed = rome_json_formatter::format_range(options, &tree, range)?;
Ok(printed)
}
fn format_on_type(
rome_path: &RomePath,
parse: AnyParse,
settings: SettingsHandle,
offset: TextSize,
) -> Result<Printed, WorkspaceError> {
let options = settings.format_options::<JsonLanguage>(rome_path);
let tree = parse.syntax();
let range = tree.text_range();
if offset < range.start() || offset > range.end() {
return Err(WorkspaceError::FormatError(FormatError::RangeError {
input: TextRange::at(offset, TextSize::from(0)),
tree: range,
}));
}
let token = match tree.token_at_offset(offset) {
// File is empty, do nothing
TokenAtOffset::None => panic!("empty file"),
TokenAtOffset::Single(token) => token,
// The cursor should be right after the closing character that was just typed,
// select the previous token as the correct one
TokenAtOffset::Between(token, _) => token,
};
let root_node = match token.parent() {
Some(node) => node,
None => panic!("found a token with no parent"),
};
let printed = rome_json_formatter::format_sub_tree(options, &root_node)?;
Ok(printed)
}
fn lint(params: LintParams) -> LintResults {
tracing::debug_span!("lint").in_scope(move || {
let root: JsonRoot = params.parse.tree();
let mut diagnostics = params.parse.into_diagnostics();
// if we're parsing the `rome.json` file, we deserialize it, so we can emit diagnostics for
// malformed configuration
if params.path.ends_with(CONFIG_NAME) {
let deserialized = deserialize_from_json_ast::<Configuration>(&root);
diagnostics.extend(
deserialized
.into_diagnostics()
.into_iter()
.map(rome_diagnostics::serde::Diagnostic::new)
.collect::<Vec<_>>(),
);
}
let mut diagnostic_count = diagnostics.len() as u64;
let mut errors = diagnostics
.iter()
.filter(|diag| diag.severity() <= Severity::Error)
.count();
let skipped_diagnostics = diagnostic_count - diagnostics.len() as u64;
let has_lint = params.filter.categories.contains(RuleCategories::LINT);
let analyzer_options =
compute_analyzer_options(¶ms.settings, PathBuf::from(params.path.as_path()));
let (_, analyze_diagnostics) = analyze(
&root.value().unwrap(),
params.filter,
&analyzer_options,
|signal| {
if let Some(mut diagnostic) = signal.diagnostic() {
// Do not report unused suppression comment diagnostics if this is a syntax-only analyzer pass
if !has_lint && diagnostic.category() == Some(category!("suppressions/unused"))
{
return ControlFlow::<Never>::Continue(());
}
diagnostic_count += 1;
// We do now check if the severity of the diagnostics should be changed.
// The configuration allows to change the severity of the diagnostics emitted by rules.
let severity = diagnostic
.category()
.filter(|category| category.name().starts_with("lint/"))
.map(|category| {
params
.rules
.and_then(|rules| rules.get_severity_from_code(category))
.unwrap_or(Severity::Warning)
})
.unwrap_or_else(|| diagnostic.severity());
if severity <= Severity::Error {
errors += 1;
}
if diagnostic_count <= params.max_diagnostics {
for action in signal.actions() {
if !action.is_suppression() {
diagnostic = diagnostic.add_code_suggestion(action.into());
}
}
let error = diagnostic.with_severity(severity);
diagnostics.push(rome_diagnostics::serde::Diagnostic::new(error));
}
}
ControlFlow::<Never>::Continue(())
},
);
diagnostics.extend(
analyze_diagnostics
.into_iter()
.map(rome_diagnostics::serde::Diagnostic::new)
.collect::<Vec<_>>(),
);
LintResults {
diagnostics,
errors,
skipped_diagnostics,
}
})
}
fn code_actions(
_parse: AnyParse,
_range: TextRange,
_rules: Option<&Rules>,
_settings: SettingsHandle,
_path: &RomePath,
) -> PullActionsResult {
PullActionsResult {
actions: Vec::new(),
}
}
fn fix_all(params: FixAllParams) -> Result<FixFileResult, WorkspaceError> {
let tree: JsonRoot = params.parse.tree();
Ok(FixFileResult {
actions: vec![],
errors: 0,
skipped_suggested_fixes: 0,
code: tree.syntax().to_string(),
})
}
fn organize_imports(parse: AnyParse) -> Result<OrganizeImportsResult, WorkspaceError> {
Ok(OrganizeImportsResult {
code: parse.syntax::<JsonLanguage>().to_string(),
})
}
fn compute_analyzer_options(settings: &SettingsHandle, file_path: PathBuf) -> AnalyzerOptions {
let configuration = to_analyzer_configuration(
settings.as_ref().linter(),
&settings.as_ref().languages,
|_| vec![],
);
AnalyzerOptions {
configuration,
file_path,
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_service/src/file_handlers/mod.rs | crates/rome_service/src/file_handlers/mod.rs | use self::{javascript::JsFileHandler, json::JsonFileHandler, unknown::UnknownFileHandler};
use crate::workspace::{FixFileMode, OrganizeImportsResult};
use crate::{
settings::SettingsHandle,
workspace::{FixFileResult, GetSyntaxTreeResult, PullActionsResult, RenameResult},
Rules, WorkspaceError,
};
pub use javascript::JsFormatterSettings;
use rome_analyze::{AnalysisFilter, AnalyzerDiagnostic};
use rome_console::fmt::Formatter;
use rome_console::markup;
use rome_diagnostics::{Diagnostic, Severity};
use rome_formatter::Printed;
use rome_fs::RomePath;
use rome_js_syntax::{TextRange, TextSize};
use rome_parser::AnyParse;
use rome_rowan::NodeCache;
use std::ffi::OsStr;
use std::path::Path;
mod javascript;
mod json;
mod unknown;
/// Supported languages by Rome
#[derive(Clone, Copy, Debug, Eq, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum Language {
/// JavaScript
JavaScript,
/// JSX
JavaScriptReact,
/// TypeScript
TypeScript,
/// TSX
TypeScriptReact,
/// JSON
Json,
/// JSONC
Jsonc,
/// Any language that is not supported
#[default]
Unknown,
}
impl Language {
/// Files that can be bypassed, because correctly handled by the JSON parser
pub(crate) const ALLOWED_FILES: &'static [&'static str; 13] = &[
"typescript.json",
"tslint.json",
"babel.config.json",
".babelrc.json",
".ember-cli",
"typedoc.json",
".eslintrc.json",
".eslintrc",
".jsfmtrc",
".jshintrc",
".swcrc",
".hintrc",
".babelrc",
];
/// Returns the language corresponding to this file extension
pub fn from_extension(s: &str) -> Self {
match s.to_lowercase().as_str() {
"js" | "mjs" | "cjs" => Language::JavaScript,
"jsx" => Language::JavaScriptReact,
"ts" | "mts" | "cts" => Language::TypeScript,
"tsx" => Language::TypeScriptReact,
"json" => Language::Json,
"jsonc" => Language::Jsonc,
_ => Language::Unknown,
}
}
pub fn from_known_filename(s: &str) -> Self {
if Self::ALLOWED_FILES.contains(&s.to_lowercase().as_str()) {
Language::Jsonc
} else {
Language::Unknown
}
}
/// Returns the language corresponding to the file path
pub fn from_path(path: &Path) -> Self {
path.extension()
.and_then(|path| path.to_str())
.map(Language::from_extension)
.unwrap_or(Language::Unknown)
}
/// Returns the language corresponding to this language ID
///
/// See the [microsoft spec] <https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentItem>
/// for a list of language identifiers
///
/// [microsoft spec]: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentItem
pub fn from_language_id(s: &str) -> Self {
match s.to_lowercase().as_str() {
"javascript" => Language::JavaScript,
"typescript" => Language::TypeScript,
"javascriptreact" => Language::JavaScriptReact,
"typescriptreact" => Language::TypeScriptReact,
"json" => Language::Json,
"jsonc" => Language::Jsonc,
_ => Language::Unknown,
}
}
/// Returns the language if it's not unknown, otherwise returns `other`.
///
/// # Examples
///
/// ```
/// # use rome_service::workspace::Language;
/// let x = Language::JavaScript;
/// let y = Language::Unknown;
/// assert_eq!(x.or(y), Language::JavaScript);
///
/// let x = Language::Unknown;
/// let y = Language::JavaScript;
/// assert_eq!(x.or(y), Language::JavaScript);
///
/// let x = Language::JavaScript;
/// let y = Language::Json;
/// assert_eq!(x.or(y), Language::JavaScript);
///
/// let x = Language::Unknown;
/// let y = Language::Unknown;
/// assert_eq!(x.or(y), Language::Unknown);
/// ```
pub fn or(self, other: Language) -> Language {
if self != Language::Unknown {
self
} else {
other
}
}
}
impl rome_console::fmt::Display for Language {
fn fmt(&self, fmt: &mut Formatter) -> std::io::Result<()> {
match self {
Language::JavaScript => fmt.write_markup(markup! { "JavaScript" }),
Language::JavaScriptReact => fmt.write_markup(markup! { "JSX" }),
Language::TypeScript => fmt.write_markup(markup! { "TypeScript" }),
Language::TypeScriptReact => fmt.write_markup(markup! { "TSX" }),
Language::Json => fmt.write_markup(markup! { "JSON" }),
Language::Jsonc => fmt.write_markup(markup! { "JSONC" }),
Language::Unknown => fmt.write_markup(markup! { "Unknown" }),
}
}
}
// TODO: The Css variant is unused at the moment
#[allow(dead_code)]
pub(crate) enum Mime {
Javascript,
Json,
Css,
Text,
}
impl std::fmt::Display for Mime {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Mime::Css => write!(f, "text/css"),
Mime::Json => write!(f, "application/json"),
Mime::Javascript => write!(f, "application/javascript"),
Mime::Text => write!(f, "text/plain"),
}
}
}
impl rome_console::fmt::Display for Mime {
fn fmt(&self, f: &mut Formatter<'_>) -> std::io::Result<()> {
write!(f, "{self}")
}
}
pub struct FixAllParams<'a> {
pub(crate) parse: AnyParse,
pub(crate) rules: Option<&'a Rules>,
pub(crate) fix_file_mode: FixFileMode,
pub(crate) settings: SettingsHandle<'a>,
/// Whether it should format the code action
pub(crate) should_format: bool,
pub(crate) rome_path: &'a RomePath,
}
#[derive(Default)]
/// The list of capabilities that are available for a language
pub struct Capabilities {
pub(crate) parser: ParserCapabilities,
pub(crate) debug: DebugCapabilities,
pub(crate) analyzer: AnalyzerCapabilities,
pub(crate) formatter: FormatterCapabilities,
}
type Parse = fn(&RomePath, Language, &str, SettingsHandle, &mut NodeCache) -> AnyParse;
#[derive(Default)]
pub struct ParserCapabilities {
/// Parse a file
pub(crate) parse: Option<Parse>,
}
type DebugSyntaxTree = fn(&RomePath, AnyParse) -> GetSyntaxTreeResult;
type DebugControlFlow = fn(AnyParse, TextSize) -> String;
type DebugFormatterIR = fn(&RomePath, AnyParse, SettingsHandle) -> Result<String, WorkspaceError>;
#[derive(Default)]
pub struct DebugCapabilities {
/// Prints the syntax tree
pub(crate) debug_syntax_tree: Option<DebugSyntaxTree>,
/// Prints the control flow graph
pub(crate) debug_control_flow: Option<DebugControlFlow>,
/// Prints the formatter IR
pub(crate) debug_formatter_ir: Option<DebugFormatterIR>,
}
pub(crate) struct LintParams<'a> {
pub(crate) parse: AnyParse,
pub(crate) filter: AnalysisFilter<'a>,
pub(crate) rules: Option<&'a Rules>,
pub(crate) settings: SettingsHandle<'a>,
pub(crate) max_diagnostics: u64,
pub(crate) path: &'a RomePath,
}
pub(crate) struct LintResults {
pub(crate) diagnostics: Vec<rome_diagnostics::serde::Diagnostic>,
pub(crate) errors: usize,
pub(crate) skipped_diagnostics: u64,
}
type Lint = fn(LintParams) -> LintResults;
type CodeActions =
fn(AnyParse, TextRange, Option<&Rules>, SettingsHandle, &RomePath) -> PullActionsResult;
type FixAll = fn(FixAllParams) -> Result<FixFileResult, WorkspaceError>;
type Rename = fn(&RomePath, AnyParse, TextSize, String) -> Result<RenameResult, WorkspaceError>;
type OrganizeImports = fn(AnyParse) -> Result<OrganizeImportsResult, WorkspaceError>;
#[derive(Default)]
pub struct AnalyzerCapabilities {
/// It lints a file
pub(crate) lint: Option<Lint>,
/// It extracts code actions for a file
pub(crate) code_actions: Option<CodeActions>,
/// Applies fixes to a file
pub(crate) fix_all: Option<FixAll>,
/// It renames a binding inside a file
pub(crate) rename: Option<Rename>,
/// It organize imports
pub(crate) organize_imports: Option<OrganizeImports>,
}
type Format = fn(&RomePath, AnyParse, SettingsHandle) -> Result<Printed, WorkspaceError>;
type FormatRange =
fn(&RomePath, AnyParse, SettingsHandle, TextRange) -> Result<Printed, WorkspaceError>;
type FormatOnType =
fn(&RomePath, AnyParse, SettingsHandle, TextSize) -> Result<Printed, WorkspaceError>;
#[derive(Default)]
pub(crate) struct FormatterCapabilities {
/// It formats a file
pub(crate) format: Option<Format>,
/// It formats a portion of text of a file
pub(crate) format_range: Option<FormatRange>,
/// It formats a file while typing
pub(crate) format_on_type: Option<FormatOnType>,
}
/// Main trait to use to add a new language to Rome
pub(crate) trait ExtensionHandler {
/// The language of the file. It can be a super language.
/// For example, a ".js" file can have [Language::Ts]
fn language(&self) -> Language;
/// MIME types used to identify a certain language
fn mime(&self) -> Mime;
/// A file that can support tabs inside its content
fn may_use_tabs(&self) -> bool {
true
}
/// Capabilities that can applied to a file
fn capabilities(&self) -> Capabilities {
Capabilities::default()
}
/// How a file should be treated. Usually an asset doesn't posses a parser.
///
/// An image should me parked as asset.
fn is_asset(&self) -> bool {
false
}
}
/// Features available for each language
pub(crate) struct Features {
js: JsFileHandler,
json: JsonFileHandler,
unknown: UnknownFileHandler,
}
impl Features {
pub(crate) fn new() -> Self {
Features {
js: JsFileHandler {},
json: JsonFileHandler {},
unknown: UnknownFileHandler::default(),
}
}
/// Return a [Language] from a string
pub(crate) fn get_language(rome_path: &RomePath) -> Language {
rome_path
.extension()
.and_then(OsStr::to_str)
.map(Language::from_extension)
.or(rome_path
.file_name()
.and_then(OsStr::to_str)
.map(Language::from_known_filename))
.unwrap_or_default()
}
/// Returns the [Capabilities] associated with a [RomePath]
pub(crate) fn get_capabilities(
&self,
rome_path: &RomePath,
language_hint: Language,
) -> Capabilities {
match Self::get_language(rome_path).or(language_hint) {
Language::JavaScript
| Language::JavaScriptReact
| Language::TypeScript
| Language::TypeScriptReact => self.js.capabilities(),
Language::Json | Language::Jsonc => self.json.capabilities(),
Language::Unknown => self.unknown.capabilities(),
}
}
}
/// Checks whether a diagnostic coming from the analyzer is an [error](Severity::Error)
///
/// The function checks the diagnostic against the current configured rules.
pub(crate) fn is_diagnostic_error(
diagnostic: &'_ AnalyzerDiagnostic,
rules: Option<&'_ Rules>,
) -> bool {
let severity = diagnostic
.category()
.filter(|category| category.name().starts_with("lint/"))
.map(|category| {
rules
.and_then(|rules| rules.get_severity_from_code(category))
.unwrap_or(Severity::Warning)
})
.unwrap_or_else(|| diagnostic.severity());
severity >= Severity::Error
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_service/tests/workspace.rs | crates/rome_service/tests/workspace.rs | use rome_fs::RomePath;
use rome_js_syntax::TextSize;
use rome_service::workspace::{server, FileGuard, Language, OpenFileParams};
#[test]
fn debug_control_flow() {
const SOURCE: &str = "function test () { return; }";
const GRAPH: &str = "flowchart TB
block_0[\"<b>block_0</b><br/>Return(JS_RETURN_STATEMENT 19..26)<br/>Return\"]
";
let workspace = server();
let file = FileGuard::open(
workspace.as_ref(),
OpenFileParams {
path: RomePath::new("file.js"),
content: SOURCE.into(),
version: 0,
language_hint: Language::JavaScript,
},
)
.unwrap();
let cfg = file.get_control_flow_graph(TextSize::from(20)).unwrap();
assert_eq!(cfg, GRAPH);
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_service/tests/spec_tests.rs | crates/rome_service/tests/spec_tests.rs | use rome_deserialize::json::deserialize_from_json_str;
use rome_diagnostics::{print_diagnostic_to_string, DiagnosticExt};
use rome_json_parser::JsonParserOptions;
use rome_service::Configuration;
use std::ffi::OsStr;
use std::fs::read_to_string;
use std::path::Path;
tests_macros::gen_tests! {"tests/invalid/*.{json}", crate::run_invalid_configurations, "module"}
fn run_invalid_configurations(input: &'static str, _: &str, _: &str, _: &str) {
let input_file = Path::new(input);
let file_name = input_file.file_name().and_then(OsStr::to_str).unwrap();
let extension = input_file.extension().and_then(OsStr::to_str).unwrap();
let input_code = read_to_string(input_file)
.unwrap_or_else(|err| panic!("failed to read {:?}: {:?}", input_file, err));
let result = match extension {
"json" => deserialize_from_json_str::<Configuration>(
input_code.as_str(),
JsonParserOptions::default(),
),
"jsonc" => deserialize_from_json_str::<Configuration>(
input_code.as_str(),
JsonParserOptions::default().with_allow_comments(),
),
_ => {
panic!("Extension not supported");
}
};
assert!(
result.has_errors(),
"This test should have diagnostics, but it doesn't have any"
);
let result = result
.into_diagnostics()
.into_iter()
.map(|diagnostic| {
print_diagnostic_to_string(
&diagnostic
.with_file_path(file_name)
.with_file_source_code(input_code.as_str()),
)
})
.collect::<Vec<_>>()
.join("\n\n");
insta::with_settings!({
prepend_module_to_snapshot => false,
snapshot_path => input_file.parent().unwrap(),
}, {
insta::assert_snapshot!(file_name, result, file_name);
});
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/shared_traits.rs | crates/rome_formatter/shared_traits.rs | // Code that must be included in every language specific formatter crate. Redefining these types
// in every formatter crate is necessary because of Rust's orphan rule that prohibits implementing
// unowned traits (traits defined in this file) on unowned types (node types)
/// Used to get an object that knows how to format this object.
pub(crate) trait AsFormat<Context> {
type Format<'a>: rome_formatter::Format<Context>
where
Self: 'a;
/// Returns an object that is able to format this object.
fn format(&self) -> Self::Format<'_>;
}
/// Implement [AsFormat] for references to types that implement [AsFormat].
impl<T, C> AsFormat<C> for &T
where
T: AsFormat<C>,
{
type Format<'a> = T::Format<'a> where Self: 'a;
fn format(&self) -> Self::Format<'_> {
AsFormat::format(&**self)
}
}
/// Implement [AsFormat] for [SyntaxResult] where `T` implements [AsFormat].
///
/// Useful to format mandatory AST fields without having to unwrap the value first.
impl<T, C> AsFormat<C> for rome_rowan::SyntaxResult<T>
where
T: AsFormat<C>,
{
type Format<'a> = rome_rowan::SyntaxResult<T::Format<'a>> where Self: 'a;
fn format(&self) -> Self::Format<'_> {
match self {
Ok(value) => Ok(value.format()),
Err(err) => Err(*err),
}
}
}
/// Implement [AsFormat] for [Option] when `T` implements [AsFormat]
///
/// Allows to call format on optional AST fields without having to unwrap the field first.
impl<T, C> AsFormat<C> for Option<T>
where
T: AsFormat<C>,
{
type Format<'a> = Option<T::Format<'a>> where Self: 'a;
fn format(&self) -> Self::Format<'_> {
self.as_ref().map(|value| value.format())
}
}
/// Used to convert this object into an object that can be formatted.
///
/// The difference to [AsFormat] is that this trait takes ownership of `self`.
pub(crate) trait IntoFormat<Context> {
type Format: rome_formatter::Format<Context>;
fn into_format(self) -> Self::Format;
}
impl<T, Context> IntoFormat<Context> for rome_rowan::SyntaxResult<T>
where
T: IntoFormat<Context>,
{
type Format = rome_rowan::SyntaxResult<T::Format>;
fn into_format(self) -> Self::Format {
self.map(IntoFormat::into_format)
}
}
/// Implement [IntoFormat] for [Option] when `T` implements [IntoFormat]
///
/// Allows to call format on optional AST fields without having to unwrap the field first.
impl<T, Context> IntoFormat<Context> for Option<T>
where
T: IntoFormat<Context>,
{
type Format = Option<T::Format>;
fn into_format(self) -> Self::Format {
self.map(IntoFormat::into_format)
}
}
/// Formatting specific [Iterator] extensions
pub(crate) trait FormattedIterExt {
/// Converts every item to an object that knows how to format it.
fn formatted<Context>(self) -> FormattedIter<Self, Self::Item, Context>
where
Self: Iterator + Sized,
Self::Item: IntoFormat<Context>,
{
FormattedIter {
inner: self,
options: std::marker::PhantomData,
}
}
}
impl<I> FormattedIterExt for I where I: std::iter::Iterator {}
pub(crate) struct FormattedIter<Iter, Item, Context>
where
Iter: Iterator<Item = Item>,
{
inner: Iter,
options: std::marker::PhantomData<Context>,
}
impl<Iter, Item, Context> std::iter::Iterator for FormattedIter<Iter, Item, Context>
where
Iter: Iterator<Item = Item>,
Item: IntoFormat<Context>,
{
type Item = Item::Format;
fn next(&mut self) -> Option<Self::Item> {
Some(self.inner.next()?.into_format())
}
}
impl<Iter, Item, Context> std::iter::FusedIterator for FormattedIter<Iter, Item, Context>
where
Iter: std::iter::FusedIterator<Item = Item>,
Item: IntoFormat<Context>,
{
}
impl<Iter, Item, Context> std::iter::ExactSizeIterator for FormattedIter<Iter, Item, Context>
where
Iter: Iterator<Item = Item> + std::iter::ExactSizeIterator,
Item: IntoFormat<Context>,
{
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/source_map.rs | crates/rome_formatter/src/source_map.rs | use crate::{Printed, SourceMarker, TextRange};
use rome_rowan::TextLen;
use rome_rowan::{Language, SyntaxNode, TextSize};
use rustc_hash::FxHashMap;
use std::cmp::Ordering;
use std::iter::FusedIterator;
/// A source map for mapping positions of a pre-processed tree back to the locations in the source tree.
///
/// This is not a generic purpose source map but instead focused on supporting the case where
/// a language removes or re-orders nodes that would otherwise complicate the formatting logic.
/// A common use case for pre-processing is the removal of all parenthesized nodes.
/// Removing parenthesized nodes simplifies the formatting logic when it has different behaviour
/// depending if a child or parent is of a specific node kind. Performing such a test with parenthesized
/// nodes present in the source code means that the formatting logic has to skip over all parenthesized nodes
/// until it finds the first non-parenthesized node and then test if that node is of the expected kind.
///
/// This source map implementation supports removing tokens or re-structuring nodes
/// without changing the order of the tokens in the tree (requires no source map).
///
/// The following section uses parentheses as a concrete example to explain the functionality of the source map.
/// However, the source map implementation isn't restricted to removing parentheses only, it supports mapping
/// transformed to source position for any use case where a transform deletes text from the source tree.
///
/// ## Position Mapping
///
/// The source map internally tracks all the ranges that have been deleted from the source code sorted by the start of the deleted range.
/// It further stores the absolute count of deleted bytes preceding a range. The deleted range together
/// with the absolute count allows to re-compute the source location for every transformed location
/// and has the benefit that it requires significantly fewer memory
/// than source maps that use a source to destination position marker for every token.
///
/// ## Map Node Ranges
///
/// Only having the deleted ranges to resolve the original text of a node isn't sufficient.
/// Resolving the original text of a node is needed when formatting a node as verbatim, either because
/// formatting the node failed because of a syntax error, or formatting is suppressed with a `rome-ignore format:` comment.
///
/// ```text
/// // Source // Transformed
/// (a+b) + (c + d) a + b + c + d;
/// ```
///
/// Using the above example, the following source ranges should be returned when quering with the transformed ranges:
///
/// * `a` -> `a`: Should not include the leading `(`
/// * `b` -> `b`: Should not include the trailing `)`
/// * `a + b` -> `(a + b)`: Should include the leading `(` and trailing `)`.
/// * `a + b + c + d` -> `(a + b) + (c + d)`: Should include the fist `(` token and the last `)` token because the expression statement
/// fully encloses the `a + b` and `c + d` nodes.
///
/// This is why the source map also tracks the mapped trimmed ranges for every node.
#[derive(Debug, Clone)]
pub struct TransformSourceMap {
source_text: SourceText,
/// The mappings stored in increasing order
deleted_ranges: Vec<DeletedRange>,
/// Key: Start or end position of node for which the trimmed range should be extended
/// Value: The trimmed range.
mapped_node_ranges: FxHashMap<TextSize, TrimmedNodeRangeMapping>,
}
impl TransformSourceMap {
/// Returns the text of the source document as it was before the transformation.
pub fn source(&self) -> &SourceText {
&self.source_text
}
/// Maps a range of the transformed document to a range in the source document.
///
/// Complexity: `O(log(n))`
pub fn source_range(&self, transformed_range: TextRange) -> TextRange {
let range = TextRange::new(
self.source_offset(transformed_range.start(), RangePosition::Start),
self.source_offset(transformed_range.end(), RangePosition::End),
);
debug_assert!(range.end() <= self.source_text.text.text_len() - self.source_text.offset, "Mapped range {:?} exceeds the length of the source document {:?}. Please check if the passed `transformed_range` is a range of the transformed tree and not of the source tree, and that it belongs to the tree for which the source map was created for.", range, self.source_text.text.text_len() - self.source_text.offset);
range
}
/// Maps the trimmed range of the transformed node to the trimmed range in the source document.
///
/// Average Complexity: `O(log(n))`
pub fn trimmed_source_range<L: Language>(&self, node: &SyntaxNode<L>) -> TextRange {
self.trimmed_source_range_from_transformed_range(node.text_trimmed_range())
}
fn resolve_trimmed_range(&self, mut source_range: TextRange) -> TextRange {
let start_mapping = self.mapped_node_ranges.get(&source_range.start());
if let Some(mapping) = start_mapping {
// If the queried node fully encloses the original range of the node, then extend the range
if source_range.contains_range(mapping.original_range) {
source_range = TextRange::new(mapping.extended_range.start(), source_range.end());
}
}
let end_mapping = self.mapped_node_ranges.get(&source_range.end());
if let Some(mapping) = end_mapping {
// If the queried node fully encloses the original range of the node, then extend the range
if source_range.contains_range(mapping.original_range) {
source_range = TextRange::new(source_range.start(), mapping.extended_range.end());
}
}
source_range
}
fn trimmed_source_range_from_transformed_range(
&self,
transformed_range: TextRange,
) -> TextRange {
let source_range = self.source_range(transformed_range);
let mut mapped_range = source_range;
loop {
let resolved = self.resolve_trimmed_range(mapped_range);
if resolved == mapped_range {
break resolved;
} else {
mapped_range = resolved;
}
}
}
/// Returns the source text of the trimmed range of `node`.
pub fn trimmed_source_text<L: Language>(&self, node: &SyntaxNode<L>) -> &str {
let range = self.trimmed_source_range(node);
self.source().text_slice(range)
}
/// Returns an iterator over all deleted ranges in increasing order by their start position.
pub fn deleted_ranges(&self) -> DeletedRanges {
DeletedRanges {
source_text: self.source(),
deleted_ranges: self.deleted_ranges.iter(),
}
}
#[cfg(test)]
fn trimmed_source_text_from_transformed_range(&self, range: TextRange) -> &str {
let range = self.trimmed_source_range_from_transformed_range(range);
self.source().text_slice(range)
}
fn source_offset(&self, transformed_offset: TextSize, position: RangePosition) -> TextSize {
let index = self
.deleted_ranges
.binary_search_by_key(&transformed_offset, |range| range.transformed_start());
let range = match index {
Ok(index) => Some(&self.deleted_ranges[index]),
Err(index) => {
if index == 0 {
None
} else {
self.deleted_ranges.get(index - 1)
}
}
};
self.source_offset_with_range(transformed_offset, position, range)
}
fn source_offset_with_range(
&self,
transformed_offset: TextSize,
position: RangePosition,
deleted_range: Option<&DeletedRange>,
) -> TextSize {
match deleted_range {
Some(range) => {
debug_assert!(
range.transformed_start() <= transformed_offset,
"Transformed start {:?} must be less than or equal to transformed offset {:?}.",
range.transformed_start(),
transformed_offset
);
// Transformed position directly falls onto a position where a deleted range starts or ends (depending on the position)
// For example when querying: `a` in `(a)` or (a + b)`, or `b`
if range.transformed_start() == transformed_offset {
match position {
RangePosition::Start => range.source_end(),
// `a)`, deleted range is right after the token. That's why `source_start` is the offset
// that truncates the `)` and `source_end` includes it
RangePosition::End => range.source_start(),
}
}
// The position falls outside of a position that has a leading/trailing deleted range.
// For example, if you get the position of `+` in `(a + b)`.
// That means, the trimmed and non-trimmed offsets are the same
else {
let transformed_delta = transformed_offset - range.transformed_start();
range.source_start() + range.len() + transformed_delta
}
}
None => transformed_offset,
}
}
/// Maps the source code positions relative to the transformed tree of `printed` to the location
/// in the original, untransformed source code.
///
/// The printer creates a source map that allows mapping positions from the newly formatted document
/// back to the locations of the tree. However, the source positions stored in [crate::FormatElement::DynamicText]
/// and [crate::FormatElement::LocatedTokenText] are relative to the transformed tree
/// and not the original tree passed to [crate::format_node].
///
/// This function re-maps the positions from the positions in the transformed tree back to the positions
/// in the original, untransformed tree.
pub fn map_printed(&self, mut printed: Printed) -> Printed {
self.map_markers(&mut printed.sourcemap);
printed
}
/// Maps the printers source map marker to the source positions.
fn map_markers(&self, markers: &mut [SourceMarker]) {
if self.deleted_ranges.is_empty() {
return;
}
let mut previous_marker: Option<SourceMarker> = None;
let mut next_range_index = 0;
for marker in markers {
// It's not guaranteed that markers are sorted by source location (line suffix comments).
// It can, therefore, be necessary to navigate backwards again.
// In this case, do a binary search for the index of the next deleted range (`O(log(n)`).
let out_of_order_marker =
previous_marker.map_or(false, |previous| previous.source > marker.source);
if out_of_order_marker {
let index = self
.deleted_ranges
.binary_search_by_key(&marker.source, |range| range.transformed_start());
match index {
// Direct match
Ok(index) => {
next_range_index = index + 1;
}
Err(index) => next_range_index = index,
}
} else {
// Find the range for this mapping. In most cases this is a no-op or only involves a single step
// because markers are most of the time in increasing source order.
while next_range_index < self.deleted_ranges.len() {
let next_range = &self.deleted_ranges[next_range_index];
if next_range.transformed_start() > marker.source {
break;
}
next_range_index += 1;
}
}
previous_marker = Some(*marker);
let current_range = if next_range_index == 0 {
None
} else {
self.deleted_ranges.get(next_range_index - 1)
};
let source =
self.source_offset_with_range(marker.source, RangePosition::Start, current_range);
marker.source = source;
}
}
}
/// The transform function builds the source map by iterating over all tokens and pushing source text in the builder.
/// This correctly builds up the source text for the sub-tree, but the offsets are incorrect if the root isn't at the start of the document.
/// The struct wraps a String and the offset in the document of the formatting node to get correct text slice.
#[derive(Debug, Default, Clone)]
pub struct SourceText {
text: String,
offset: TextSize,
}
impl SourceText {
pub fn with_source(text: String) -> Self {
Self {
text,
..Default::default()
}
}
pub fn with_offset(offset: TextSize) -> Self {
Self {
offset,
..Default::default()
}
}
pub fn text_slice(&self, range: TextRange) -> &str {
debug_assert!(
range.start() >= self.offset,
"Range {:?} should be bigger than offset {:?}.",
range,
self.offset
);
&self.text[range - self.offset]
}
pub fn push_str(&mut self, string: &str) {
self.text.push_str(string)
}
}
#[derive(Debug, Copy, Clone)]
struct TrimmedNodeRangeMapping {
/// The original trimmed range of the node.
///
/// ```javascript
/// (a + b)
/// ```
///
/// `1..6` `a + b`
original_range: TextRange,
/// The range to which the trimmed range of the node should be extended
/// ```javascript
/// (a + b)
/// ```
///
/// `0..7` for `a + b` if its range should also include the parenthesized range.
extended_range: TextRange,
}
#[derive(Copy, Clone, Debug)]
enum RangePosition {
Start,
End,
}
/// Stores the information about a range in the source document that isn't present in the transformed document
/// and provides means to map the transformed position back to the source position.
///
/// # Examples
///
/// ```javascript
/// (a + b)
/// ```
///
/// A transform that removes the parentheses from the above expression removes the ranges `0..1` (`(` token)
/// and `6..7` (`)` token) and the source map creates one [DeletedRange] for each:
///
/// ```text
/// DeletedRange {
/// source_range: 0..1,
/// total_length_preceding_deleted_ranges: 0,
/// },
/// DeletedRange {
/// source_range: 6..7,
/// total_length_preceding_deleted_ranges: 1,
/// }
/// ```
///
/// The first range indicates that the range `0..1` for the `(` token has been removed. The second range
/// indicates that the range `6..7` for the `)` token has been removed and it stores that, up to this point,
/// but not including, 1 more byte has been removed.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
struct DeletedRange {
/// The range in the source document of the bytes that have been omitted from the transformed document.
source_range: TextRange,
/// The accumulated count of all removed bytes up to (but not including) the start of this range.
total_length_preceding_deleted_ranges: TextSize,
}
impl DeletedRange {
fn new(source_range: TextRange, total_length_preceding_deleted_ranges: TextSize) -> Self {
debug_assert!(source_range.start() >= total_length_preceding_deleted_ranges, "The total number of deleted bytes ({:?}) can not exceed the offset from the start in the source document ({:?}). This is a bug in the source map implementation.", total_length_preceding_deleted_ranges, source_range.start());
Self {
source_range,
total_length_preceding_deleted_ranges,
}
}
/// The number of deleted characters starting from [source offset](DeletedRange::source_start).
fn len(&self) -> TextSize {
self.source_range.len()
}
/// The start position in bytes in the source document of the omitted sequence in the transformed document.
fn source_start(&self) -> TextSize {
self.source_range.start()
}
/// The end position in bytes in the source document of the omitted sequence in the transformed document.
fn source_end(&self) -> TextSize {
self.source_range.end()
}
/// Returns the byte position of [DeleteRange::source_start] in the transformed document.
fn transformed_start(&self) -> TextSize {
self.source_range.start() - self.total_length_preceding_deleted_ranges
}
}
/// Builder for creating a source map.
#[derive(Debug, Default)]
pub struct TransformSourceMapBuilder {
/// The original source text of the tree before it was transformed.
source_text: SourceText,
/// The mappings in increasing order by transformed offset.
deleted_ranges: Vec<TextRange>,
/// The keys are a position in the source map where a trimmed node starts or ends.
/// The values are the metadata about a trimmed node range
mapped_node_ranges: FxHashMap<TextSize, TrimmedNodeRangeMapping>,
}
impl TransformSourceMapBuilder {
/// Creates a new builder.
pub fn new() -> Self {
Self {
..Default::default()
}
}
pub fn with_offset(offset: TextSize) -> Self {
Self {
source_text: SourceText::with_offset(offset),
..Default::default()
}
}
/// Creates a new builder for a document with the given source.
pub fn with_source(source: String) -> Self {
Self {
source_text: SourceText::with_source(source),
..Default::default()
}
}
/// Appends `text` to the source text of the original document.
pub fn push_source_text(&mut self, text: &str) {
self.source_text.push_str(text);
}
/// Adds a new mapping for a deleted character range.
pub fn add_deleted_range(&mut self, source_range: TextRange) {
self.deleted_ranges.push(source_range);
}
/// Adds a mapping to widen a nodes trimmed range.
///
/// The formatter uses the trimmed range when formatting a node in verbatim either because the node
/// failed to format because of a syntax error or because it's formatting is suppressed with a `rome-ignore format:` comment.
///
/// This method adds a mapping to widen a nodes trimmed range to enclose another range instead. This is
/// e.g. useful when removing parentheses around expressions where `(/* comment */ a /* comment */)` because
/// the trimmed range of `a` should now enclose the full range including the `(` and `)` tokens to ensure
/// that the parentheses are retained when printing that node in verbatim style.
pub fn extend_trimmed_node_range(
&mut self,
original_range: TextRange,
extended_range: TextRange,
) {
let mapping = TrimmedNodeRangeMapping {
original_range,
extended_range,
};
self.mapped_node_ranges
.insert(original_range.start(), mapping);
self.mapped_node_ranges
.insert(original_range.end(), mapping);
}
/// Creates a source map that performs single position lookups in `O(log(n))`.
pub fn finish(mut self) -> TransformSourceMap {
let mut merged_mappings = Vec::with_capacity(self.deleted_ranges.len());
if !self.deleted_ranges.is_empty() {
self.deleted_ranges
.sort_by(|a, b| match a.start().cmp(&b.start()) {
Ordering::Equal => a.end().cmp(&b.end()),
ordering => ordering,
});
let mut last_mapping = DeletedRange::new(
// SAFETY: Safe because of the not empty check above
self.deleted_ranges[0],
TextSize::default(),
);
let mut transformed_offset = last_mapping.len();
for range in self.deleted_ranges.drain(1..) {
// Merge adjacent ranges to ensure there's only ever a single mapping starting at the same transformed offset.
if last_mapping.source_range.end() == range.start() {
last_mapping.source_range = last_mapping.source_range.cover(range);
} else {
merged_mappings.push(last_mapping);
last_mapping = DeletedRange::new(range, transformed_offset);
}
transformed_offset += range.len();
}
merged_mappings.push(last_mapping);
}
TransformSourceMap {
source_text: self.source_text,
deleted_ranges: merged_mappings,
mapped_node_ranges: self.mapped_node_ranges,
}
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct DeletedRangeEntry<'a> {
/// The start position of the removed range in the source document
pub source: TextSize,
/// The position in the transformed document where the removed range would have been (but is not, because it was removed)
pub transformed: TextSize,
/// The text of the removed range
pub text: &'a str,
}
/// Iterator over all removed ranges in a document.
///
/// Returns the ranges in increased order by their start position.
pub struct DeletedRanges<'a> {
source_text: &'a SourceText,
/// The mappings stored in increasing order
deleted_ranges: std::slice::Iter<'a, DeletedRange>,
}
impl<'a> Iterator for DeletedRanges<'a> {
type Item = DeletedRangeEntry<'a>;
fn next(&mut self) -> Option<Self::Item> {
let next = self.deleted_ranges.next()?;
Some(DeletedRangeEntry {
source: next.source_range.start(),
transformed: next.transformed_start(),
text: self.source_text.text_slice(next.source_range),
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.deleted_ranges.size_hint()
}
fn last(self) -> Option<Self::Item>
where
Self: Sized,
{
let last = self.deleted_ranges.last()?;
Some(DeletedRangeEntry {
source: last.source_range.start(),
transformed: last.transformed_start(),
text: self.source_text.text_slice(last.source_range),
})
}
}
impl DoubleEndedIterator for DeletedRanges<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
let back = self.deleted_ranges.next_back()?;
Some(DeletedRangeEntry {
source: back.source_range.start(),
transformed: back.transformed_start(),
text: self.source_text.text_slice(back.source_range),
})
}
}
impl FusedIterator for DeletedRanges<'_> {}
impl ExactSizeIterator for DeletedRanges<'_> {}
#[cfg(test)]
mod tests {
use crate::source_map::DeletedRangeEntry;
use crate::{TextRange, TextSize, TransformSourceMapBuilder};
use rome_rowan::raw_language::{RawLanguageKind, RawSyntaxTreeBuilder};
#[test]
fn range_mapping() {
let mut cst_builder = RawSyntaxTreeBuilder::new();
cst_builder.start_node(RawLanguageKind::ROOT);
// The shape of the tree doesn't matter for the test case
cst_builder.token(RawLanguageKind::STRING_TOKEN, "(a + (((b + c)) + d)) + e");
cst_builder.finish_node();
let root = cst_builder.finish();
let mut builder = TransformSourceMapBuilder::new();
builder.push_source_text(&root.text().to_string());
// Add mappings for all removed parentheses.
// `(`
builder.add_deleted_range(TextRange::new(TextSize::from(0), TextSize::from(1)));
// `(((`
builder.add_deleted_range(TextRange::new(TextSize::from(5), TextSize::from(6)));
// Ranges can be added out of order
builder.add_deleted_range(TextRange::new(TextSize::from(7), TextSize::from(8)));
builder.add_deleted_range(TextRange::new(TextSize::from(6), TextSize::from(7)));
// `))`
builder.add_deleted_range(TextRange::new(TextSize::from(13), TextSize::from(14)));
builder.add_deleted_range(TextRange::new(TextSize::from(14), TextSize::from(15)));
// `))`
builder.add_deleted_range(TextRange::new(TextSize::from(19), TextSize::from(20)));
builder.add_deleted_range(TextRange::new(TextSize::from(20), TextSize::from(21)));
let source_map = builder.finish();
// The following mapping assume the tranformed string to be (including whitespace):
// "a + b + c + d + e";
// `a`
assert_eq!(
source_map.source_range(TextRange::new(TextSize::from(0), TextSize::from(1))),
TextRange::new(TextSize::from(1), TextSize::from(2))
);
// `b`
assert_eq!(
source_map.source_range(TextRange::new(TextSize::from(4), TextSize::from(5))),
TextRange::new(TextSize::from(8), TextSize::from(9))
);
// `c`
assert_eq!(
source_map.source_range(TextRange::new(TextSize::from(8), TextSize::from(9))),
TextRange::new(TextSize::from(12), TextSize::from(13))
);
// `d`
assert_eq!(
source_map.source_range(TextRange::new(TextSize::from(12), TextSize::from(13))),
TextRange::new(TextSize::from(18), TextSize::from(19))
);
// `e`
assert_eq!(
source_map.source_range(TextRange::new(TextSize::from(16), TextSize::from(17))),
TextRange::new(TextSize::from(24), TextSize::from(25))
);
}
#[test]
fn trimmed_range() {
// Build up a tree for `((a))`
// Don't mind the unknown nodes, it doesn't really matter what the nodes are.
let mut cst_builder = RawSyntaxTreeBuilder::new();
cst_builder.start_node(RawLanguageKind::ROOT);
cst_builder.start_node(RawLanguageKind::BOGUS);
cst_builder.token(RawLanguageKind::STRING_TOKEN, "(");
cst_builder.start_node(RawLanguageKind::BOGUS);
cst_builder.token(RawLanguageKind::BOGUS, "(");
cst_builder.start_node(RawLanguageKind::LITERAL_EXPRESSION);
cst_builder.token(RawLanguageKind::STRING_TOKEN, "a");
cst_builder.finish_node();
cst_builder.token(RawLanguageKind::BOGUS, ")");
cst_builder.finish_node();
cst_builder.token(RawLanguageKind::BOGUS, ")");
cst_builder.finish_node();
cst_builder.token(RawLanguageKind::BOGUS, ";");
cst_builder.finish_node();
let root = cst_builder.finish();
assert_eq!(&root.text(), "((a));");
let mut bogus = root
.descendants()
.filter(|node| node.kind() == RawLanguageKind::BOGUS);
// `((a))`
let outer = bogus.next().unwrap();
// `(a)`
let inner = bogus.next().unwrap();
// `a`
let expression = root
.descendants()
.find(|node| node.kind() == RawLanguageKind::LITERAL_EXPRESSION)
.unwrap();
let mut builder = TransformSourceMapBuilder::new();
builder.push_source_text(&root.text().to_string());
// Add mappings for all removed parentheses.
builder.add_deleted_range(TextRange::new(TextSize::from(0), TextSize::from(2)));
builder.add_deleted_range(TextRange::new(TextSize::from(3), TextSize::from(5)));
// Extend `a` to the range of `(a)`
builder
.extend_trimmed_node_range(expression.text_trimmed_range(), inner.text_trimmed_range());
// Extend `(a)` to the range of `((a))`
builder.extend_trimmed_node_range(inner.text_trimmed_range(), outer.text_trimmed_range());
let source_map = builder.finish();
// Query `a`
assert_eq!(
source_map.trimmed_source_text_from_transformed_range(TextRange::new(
TextSize::from(0),
TextSize::from(1)
)),
"((a))"
);
// Query `a;` expression
assert_eq!(
source_map.trimmed_source_text_from_transformed_range(TextRange::new(
TextSize::from(0),
TextSize::from(2)
)),
"((a));"
);
}
#[test]
fn deleted_ranges() {
let mut cst_builder = RawSyntaxTreeBuilder::new();
cst_builder.start_node(RawLanguageKind::ROOT);
// The shape of the tree doesn't matter for the test case
cst_builder.token(RawLanguageKind::STRING_TOKEN, "(a + (((b + c)) + d)) + e");
cst_builder.finish_node();
let root = cst_builder.finish();
let mut builder = TransformSourceMapBuilder::new();
builder.push_source_text(&root.text().to_string());
// Add mappings for all removed parentheses.
// `(`
builder.add_deleted_range(TextRange::new(TextSize::from(0), TextSize::from(1)));
// `(((`
builder.add_deleted_range(TextRange::new(TextSize::from(5), TextSize::from(6)));
// Ranges can be added out of order
builder.add_deleted_range(TextRange::new(TextSize::from(7), TextSize::from(8)));
builder.add_deleted_range(TextRange::new(TextSize::from(6), TextSize::from(7)));
// `))`
builder.add_deleted_range(TextRange::new(TextSize::from(13), TextSize::from(14)));
builder.add_deleted_range(TextRange::new(TextSize::from(14), TextSize::from(15)));
// `))`
builder.add_deleted_range(TextRange::new(TextSize::from(19), TextSize::from(20)));
builder.add_deleted_range(TextRange::new(TextSize::from(20), TextSize::from(21)));
let source_map = builder.finish();
let deleted_ranges = source_map.deleted_ranges().collect::<Vec<_>>();
assert_eq!(
deleted_ranges,
vec![
DeletedRangeEntry {
source: TextSize::from(0),
transformed: TextSize::from(0),
text: "("
},
DeletedRangeEntry {
source: TextSize::from(5),
transformed: TextSize::from(4),
text: "((("
},
DeletedRangeEntry {
source: TextSize::from(13),
transformed: TextSize::from(9),
text: "))"
},
DeletedRangeEntry {
source: TextSize::from(19),
transformed: TextSize::from(13),
text: "))"
},
]
);
assert_eq!(
source_map.deleted_ranges().last(),
Some(DeletedRangeEntry {
source: TextSize::from(19),
transformed: TextSize::from(13),
text: "))"
})
);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/diagnostics.rs | crates/rome_formatter/src/diagnostics.rs | use crate::prelude::TagKind;
use rome_console::fmt::Formatter;
use rome_console::markup;
use rome_diagnostics::{category, Category, Diagnostic, DiagnosticTags, Location, Severity};
use rome_rowan::{SyntaxError, TextRange};
use std::error::Error;
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// Series of errors encountered during formatting
pub enum FormatError {
/// In case a node can't be formatted because it either misses a require child element or
/// a child is present that should not (e.g. a trailing comma after a rest element).
SyntaxError,
/// In case range formatting failed because the provided range was larger
/// than the formatted syntax tree
RangeError { input: TextRange, tree: TextRange },
/// In case printing the document failed because it has an invalid structure.
InvalidDocument(InvalidDocumentError),
/// Formatting failed because some content encountered a situation where a layout
/// choice by an enclosing [crate::Format] resulted in a poor layout for a child [crate::Format].
///
/// It's up to an enclosing [crate::Format] to handle the error and pick another layout.
/// This error should not be raised if there's no outer [crate::Format] handling the poor layout error,
/// avoiding that formatting of the whole document fails.
PoorLayout,
}
impl std::fmt::Display for FormatError {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FormatError::SyntaxError => fmt.write_str("syntax error"),
FormatError::RangeError { input, tree } => std::write!(
fmt,
"formatting range {input:?} is larger than syntax tree {tree:?}"
),
FormatError::InvalidDocument(error) => std::write!(fmt, "Invalid document: {error}\n\n This is an internal Rome error. Please report if necessary."),
FormatError::PoorLayout => {
std::write!(fmt, "Poor layout: The formatter wasn't able to pick a good layout for your document. This is an internal Rome error. Please report if necessary.")
}
}
}
}
impl Error for FormatError {}
impl From<SyntaxError> for FormatError {
fn from(error: SyntaxError) -> Self {
FormatError::from(&error)
}
}
impl From<&SyntaxError> for FormatError {
fn from(syntax_error: &SyntaxError) -> Self {
match syntax_error {
SyntaxError::MissingRequiredChild => FormatError::SyntaxError,
}
}
}
impl From<PrintError> for FormatError {
fn from(error: PrintError) -> Self {
FormatError::from(&error)
}
}
impl From<&PrintError> for FormatError {
fn from(error: &PrintError) -> Self {
match error {
PrintError::InvalidDocument(reason) => FormatError::InvalidDocument(*reason),
}
}
}
impl Diagnostic for FormatError {
fn location(&self) -> Location<'_> {
Location::builder().build()
}
fn severity(&self) -> Severity {
Severity::Error
}
fn tags(&self) -> DiagnosticTags {
match self {
FormatError::SyntaxError => DiagnosticTags::empty(),
FormatError::RangeError { .. } => DiagnosticTags::empty(),
FormatError::InvalidDocument(_) => DiagnosticTags::INTERNAL,
FormatError::PoorLayout => DiagnosticTags::INTERNAL,
}
}
fn description(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self, fmt)
}
fn category(&self) -> Option<&'static Category> {
Some(category!("format"))
}
fn message(
&self,
fmt: &mut rome_diagnostics::console::fmt::Formatter<'_>,
) -> std::io::Result<()> {
match self {
FormatError::SyntaxError => fmt.write_str("Syntax error."),
FormatError::RangeError { input, tree } => std::write!(
fmt,
"Formatting range {input:?} is larger than syntax tree {tree:?}"
),
FormatError::InvalidDocument(error) => std::write!(fmt, "Invalid document: {error}"),
FormatError::PoorLayout => {
std::write!(fmt, "Poor layout: The formatter wasn't able to pick a good layout for your document.")
}
}
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum InvalidDocumentError {
/// Mismatching start/end kinds
///
/// ```plain
/// StartIndent
/// ...
/// EndGroup
/// ```
StartEndTagMismatch {
start_kind: TagKind,
end_kind: TagKind,
},
/// End tag without a corresponding start tag.
///
/// ```plain
/// Text
/// EndGroup
/// ```
StartTagMissing { kind: TagKind },
/// Expected a specific start tag but instead is:
/// * at the end of the document
/// * at another start tag
/// * at an end tag
ExpectedStart {
expected_start: TagKind,
actual: ActualStart,
},
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ActualStart {
/// The actual element is not a tag.
Content,
/// The actual element was a start tag of another kind.
Start(TagKind),
/// The actual element is an end tag instead of a start tag.
End(TagKind),
/// Reached the end of the document
EndOfDocument,
}
impl std::fmt::Display for InvalidDocumentError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
InvalidDocumentError::StartEndTagMismatch {
start_kind,
end_kind,
} => {
std::write!(
f,
"Expected end tag of kind {start_kind:?} but found {end_kind:?}."
)
}
InvalidDocumentError::StartTagMissing { kind } => {
std::write!(f, "End tag of kind {kind:?} without matching start tag.")
}
InvalidDocumentError::ExpectedStart {
expected_start,
actual,
} => {
match actual {
ActualStart::EndOfDocument => {
std::write!(f, "Expected start tag of kind {expected_start:?} but at the end of document.")
}
ActualStart::Start(start) => {
std::write!(f, "Expected start tag of kind {expected_start:?} but found start tag of kind {start:?}.")
}
ActualStart::End(end) => {
std::write!(f, "Expected start tag of kind {expected_start:?} but found end tag of kind {end:?}.")
}
ActualStart::Content => {
std::write!(f, "Expected start tag of kind {expected_start:?} but found non-tag element.")
}
}
}
}
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PrintError {
InvalidDocument(InvalidDocumentError),
}
impl Error for PrintError {}
impl std::fmt::Display for PrintError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PrintError::InvalidDocument(inner) => {
std::write!(f, "Invalid document: {inner}")
}
}
}
}
impl Diagnostic for PrintError {
fn category(&self) -> Option<&'static Category> {
Some(category!("format"))
}
fn severity(&self) -> Severity {
Severity::Error
}
fn message(&self, fmt: &mut Formatter<'_>) -> std::io::Result<()> {
match self {
PrintError::InvalidDocument(inner) => {
let inner = format!("{}", inner);
fmt.write_markup(markup! {
"Invalid document: "{{inner}}
})
}
}
}
}
#[cfg(test)]
mod test {
use crate::diagnostics::{ActualStart, InvalidDocumentError};
use crate::prelude::{FormatError, TagKind};
use rome_diagnostics::{print_diagnostic_to_string, DiagnosticExt, Error};
use rome_js_syntax::TextRange;
fn snap_diagnostic(test_name: &str, diagnostic: Error) {
let content = print_diagnostic_to_string(&diagnostic);
insta::with_settings!({
prepend_module_to_snapshot => false,
}, {
insta::assert_snapshot!(test_name, content);
});
}
#[test]
fn formatter_syntax_error() {
snap_diagnostic(
"formatter_syntax_error",
FormatError::SyntaxError.with_file_path("example.js"),
)
}
#[test]
fn poor_layout() {
snap_diagnostic(
"poor_layout",
FormatError::PoorLayout.with_file_path("example.js"),
)
}
#[test]
fn invalid_document() {
snap_diagnostic(
"invalid_document",
FormatError::InvalidDocument(InvalidDocumentError::ExpectedStart {
expected_start: TagKind::Align,
actual: ActualStart::Start(TagKind::ConditionalContent),
})
.with_file_path("example.js"),
)
}
#[test]
fn range_error() {
snap_diagnostic(
"range_error",
FormatError::RangeError {
input: TextRange::new(7.into(), 10.into()),
tree: TextRange::new(0.into(), 5.into()),
}
.with_file_path("example.js"),
)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/prelude.rs | crates/rome_formatter/src/prelude.rs | pub use crate::builders::*;
pub use crate::format_element::*;
pub use crate::format_extensions::{MemoizeFormat, Memoized};
pub use crate::formatter::Formatter;
pub use crate::printer::PrinterOptions;
pub use crate::trivia::{
format_dangling_comments, format_leading_comments, format_only_if_breaks, format_removed,
format_replaced, format_trailing_comments, format_trimmed_token,
};
pub use crate::diagnostics::FormatError;
pub use crate::format_element::document::Document;
pub use crate::format_element::tag::{LabelId, Tag, TagKind};
pub use crate::verbatim::{
format_bogus_node, format_or_verbatim, format_suppressed_node, format_verbatim_node,
};
pub use crate::{
best_fitting, dbg_write, format, format_args, write, Buffer as _, BufferExtensions, Format,
Format as _, FormatResult, FormatRule, FormatWithRule as _, SimpleFormatContext,
};
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/lib.rs | crates/rome_formatter/src/lib.rs | //! Infrastructure for code formatting
//!
//! This module defines [FormatElement], an IR to format code documents and provides a mean to print
//! such a document to a string. Objects that know how to format themselves implement the [Format] trait.
//!
//! ## Formatting Traits
//!
//! * [Format]: Implemented by objects that can be formatted.
//! * [FormatRule]: Rule that knows how to format an object of another type. Necessary in the situation where
//! it's necessary to implement [Format] on an object from another crate. This module defines the
//! [FormatRefWithRule] and [FormatOwnedWithRule] structs to pass an item with its corresponding rule.
//! * [FormatWithRule] implemented by objects that know how to format another type. Useful for implementing
//! some reusable formatting logic inside of this module if the type itself doesn't implement [Format]
//!
//! ## Formatting Macros
//!
//! This crate defines two macros to construct the IR. These are inspired by Rust's `fmt` macros
//! * [`format!`]: Formats a formatable object
//! * [`format_args!`]: Concatenates a sequence of Format objects.
//! * [`write!`]: Writes a sequence of formatable objects into an output buffer.
#![deny(rustdoc::broken_intra_doc_links)]
mod arguments;
mod buffer;
mod builders;
pub mod comments;
pub mod diagnostics;
pub mod format_element;
mod format_extensions;
pub mod formatter;
pub mod group_id;
pub mod macros;
pub mod prelude;
#[cfg(debug_assertions)]
pub mod printed_tokens;
pub mod printer;
pub mod separated;
mod source_map;
pub mod token;
pub mod trivia;
mod verbatim;
use crate::formatter::Formatter;
use crate::group_id::UniqueGroupIdBuilder;
use crate::prelude::TagKind;
use std::fmt::Debug;
use crate::format_element::document::Document;
#[cfg(debug_assertions)]
use crate::printed_tokens::PrintedTokens;
use crate::printer::{Printer, PrinterOptions};
pub use arguments::{Argument, Arguments};
pub use buffer::{
Buffer, BufferExtensions, BufferSnapshot, Inspect, PreambleBuffer, RemoveSoftLinesBuffer,
VecBuffer,
};
pub use builders::BestFitting;
use crate::builders::syntax_token_cow_slice;
use crate::comments::{CommentStyle, Comments, SourceComment};
pub use crate::diagnostics::{ActualStart, FormatError, InvalidDocumentError, PrintError};
use crate::trivia::{format_skipped_token_trivia, format_trimmed_token};
pub use format_element::{normalize_newlines, FormatElement, LINE_TERMINATORS};
pub use group_id::GroupId;
use rome_rowan::{
Language, NodeOrToken, SyntaxElement, SyntaxNode, SyntaxResult, SyntaxToken, SyntaxTriviaPiece,
TextLen, TextRange, TextSize, TokenAtOffset,
};
pub use source_map::{TransformSourceMap, TransformSourceMapBuilder};
use std::marker::PhantomData;
use std::num::ParseIntError;
use std::str::FromStr;
#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)
)]
#[derive(Default)]
pub enum IndentStyle {
/// Tab
#[default]
Tab,
/// Space, with its quantity
Space(u8),
}
impl IndentStyle {
pub const DEFAULT_SPACES: u8 = 2;
/// Returns `true` if this is an [IndentStyle::Tab].
pub const fn is_tab(&self) -> bool {
matches!(self, IndentStyle::Tab)
}
/// Returns `true` if this is an [IndentStyle::Space].
pub const fn is_space(&self) -> bool {
matches!(self, IndentStyle::Space(_))
}
}
impl FromStr for IndentStyle {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"tab" | "Tabs" => Ok(Self::Tab),
"space" | "Spaces" => Ok(Self::Space(IndentStyle::DEFAULT_SPACES)),
// TODO: replace this error with a diagnostic
_ => Err("Value not supported for IndentStyle"),
}
}
}
impl std::fmt::Display for IndentStyle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
IndentStyle::Tab => std::write!(f, "Tab"),
IndentStyle::Space(size) => std::write!(f, "Spaces, size: {}", size),
}
}
}
/// Validated value for the `line_width` formatter options
///
/// The allowed range of values is 1..=320
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema),
serde(rename_all = "camelCase")
)]
pub struct LineWidth(u16);
impl LineWidth {
/// Maximum allowed value for a valid [LineWidth]
pub const MAX: u16 = 320;
/// Return the numeric value for this [LineWidth]
pub fn value(&self) -> u16 {
self.0
}
}
impl Default for LineWidth {
fn default() -> Self {
Self(80)
}
}
/// Error type returned when parsing a [LineWidth] from a string fails
pub enum ParseLineWidthError {
/// The string could not be parsed as a valid [u16]
ParseError(ParseIntError),
/// The [u16] value of the string is not a valid [LineWidth]
TryFromIntError(LineWidthFromIntError),
}
impl Debug for ParseLineWidthError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self, f)
}
}
impl std::fmt::Display for ParseLineWidthError {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ParseLineWidthError::ParseError(err) => std::fmt::Display::fmt(err, fmt),
ParseLineWidthError::TryFromIntError(err) => std::fmt::Display::fmt(err, fmt),
}
}
}
impl FromStr for LineWidth {
type Err = ParseLineWidthError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let value = u16::from_str(s).map_err(ParseLineWidthError::ParseError)?;
let value = Self::try_from(value).map_err(ParseLineWidthError::TryFromIntError)?;
Ok(value)
}
}
/// Error type returned when converting a u16 to a [LineWidth] fails
#[derive(Clone, Copy, Debug)]
pub struct LineWidthFromIntError(pub u16);
impl TryFrom<u16> for LineWidth {
type Error = LineWidthFromIntError;
fn try_from(value: u16) -> Result<Self, Self::Error> {
if value > 0 && value <= Self::MAX {
Ok(Self(value))
} else {
Err(LineWidthFromIntError(value))
}
}
}
impl std::fmt::Display for LineWidthFromIntError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(
f,
"The line width exceeds the maximum value ({})",
LineWidth::MAX
)
}
}
impl From<LineWidth> for u16 {
fn from(value: LineWidth) -> Self {
value.0
}
}
/// Context object storing data relevant when formatting an object.
pub trait FormatContext {
type Options: FormatOptions;
/// Returns the formatting options
fn options(&self) -> &Self::Options;
/// Returns [None] if the CST has not been pre-processed.
///
/// Returns [Some] if the CST has been pre-processed to simplify formatting.
/// The source map can be used to map positions of the formatted nodes back to their original
/// source locations or to resolve the source text.
fn source_map(&self) -> Option<&TransformSourceMap>;
}
/// Options customizing how the source code should be formatted.
pub trait FormatOptions {
/// The indent style.
fn indent_style(&self) -> IndentStyle;
/// What's the max width of a line. Defaults to 80.
fn line_width(&self) -> LineWidth;
/// Derives the print options from the these format options
fn as_print_options(&self) -> PrinterOptions;
}
/// The [CstFormatContext] is an extension of the CST unaware [FormatContext] and must be implemented
/// by every language.
///
/// The context customizes the comments formatting and stores the comments of the CST.
pub trait CstFormatContext: FormatContext {
type Language: Language;
type Style: CommentStyle<Language = Self::Language>;
/// Rule for formatting comments.
type CommentRule: FormatRule<SourceComment<Self::Language>, Context = Self> + Default;
/// Returns a reference to the program's comments.
fn comments(&self) -> &Comments<Self::Language>;
}
#[derive(Debug, Default, Eq, PartialEq)]
pub struct SimpleFormatContext {
options: SimpleFormatOptions,
}
impl SimpleFormatContext {
pub fn new(options: SimpleFormatOptions) -> Self {
Self { options }
}
}
impl FormatContext for SimpleFormatContext {
type Options = SimpleFormatOptions;
fn options(&self) -> &Self::Options {
&self.options
}
fn source_map(&self) -> Option<&TransformSourceMap> {
None
}
}
#[derive(Debug, Default, Eq, PartialEq)]
pub struct SimpleFormatOptions {
pub indent_style: IndentStyle,
pub line_width: LineWidth,
}
impl FormatOptions for SimpleFormatOptions {
fn indent_style(&self) -> IndentStyle {
self.indent_style
}
fn line_width(&self) -> LineWidth {
self.line_width
}
fn as_print_options(&self) -> PrinterOptions {
PrinterOptions::default()
.with_indent(self.indent_style)
.with_print_width(self.line_width.into())
}
}
/// Lightweight sourcemap marker between source and output tokens
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)
)]
pub struct SourceMarker {
/// Position of the marker in the original source
pub source: TextSize,
/// Position of the marker in the output code
pub dest: TextSize,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Formatted<Context> {
document: Document,
context: Context,
}
impl<Context> Formatted<Context> {
pub fn new(document: Document, context: Context) -> Self {
Self { document, context }
}
/// Returns the context used during formatting.
pub fn context(&self) -> &Context {
&self.context
}
/// Returns the formatted document.
pub fn document(&self) -> &Document {
&self.document
}
/// Consumes `self` and returns the formatted document.
pub fn into_document(self) -> Document {
self.document
}
}
impl<Context> Formatted<Context>
where
Context: FormatContext,
{
pub fn print(&self) -> PrintResult<Printed> {
let print_options = self.context.options().as_print_options();
let printed = Printer::new(print_options).print(&self.document)?;
let printed = match self.context.source_map() {
Some(source_map) => source_map.map_printed(printed),
None => printed,
};
Ok(printed)
}
pub fn print_with_indent(&self, indent: u16) -> PrintResult<Printed> {
let print_options = self.context.options().as_print_options();
let printed = Printer::new(print_options).print_with_indent(&self.document, indent)?;
let printed = match self.context.source_map() {
Some(source_map) => source_map.map_printed(printed),
None => printed,
};
Ok(printed)
}
}
pub type PrintResult<T> = Result<T, PrintError>;
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)
)]
pub struct Printed {
code: String,
range: Option<TextRange>,
sourcemap: Vec<SourceMarker>,
verbatim_ranges: Vec<TextRange>,
}
impl Printed {
pub fn new(
code: String,
range: Option<TextRange>,
sourcemap: Vec<SourceMarker>,
verbatim_source: Vec<TextRange>,
) -> Self {
Self {
code,
range,
sourcemap,
verbatim_ranges: verbatim_source,
}
}
/// Construct an empty formatter result
pub fn new_empty() -> Self {
Self {
code: String::new(),
range: None,
sourcemap: Vec::new(),
verbatim_ranges: Vec::new(),
}
}
/// Range of the input source file covered by this formatted code,
/// or None if the entire file is covered in this instance
pub fn range(&self) -> Option<TextRange> {
self.range
}
/// Returns a list of [SourceMarker] mapping byte positions
/// in the output string to the input source code.
/// It's not guaranteed that the markers are sorted by source position.
pub fn sourcemap(&self) -> &[SourceMarker] {
&self.sourcemap
}
/// Returns a list of [SourceMarker] mapping byte positions
/// in the output string to the input source code, consuming the result
pub fn into_sourcemap(self) -> Vec<SourceMarker> {
self.sourcemap
}
/// Takes the list of [SourceMarker] mapping byte positions in the output string
/// to the input source code.
pub fn take_sourcemap(&mut self) -> Vec<SourceMarker> {
std::mem::take(&mut self.sourcemap)
}
/// Access the resulting code, borrowing the result
pub fn as_code(&self) -> &str {
&self.code
}
/// Access the resulting code, consuming the result
pub fn into_code(self) -> String {
self.code
}
/// The text in the formatted code that has been formatted as verbatim.
pub fn verbatim(&self) -> impl Iterator<Item = (TextRange, &str)> {
self.verbatim_ranges
.iter()
.map(|range| (*range, &self.code[*range]))
}
/// Ranges of the formatted code that have been formatted as verbatim.
pub fn verbatim_ranges(&self) -> &[TextRange] {
&self.verbatim_ranges
}
/// Takes the ranges of nodes that have been formatted as verbatim, replacing them with an empty list.
pub fn take_verbatim_ranges(&mut self) -> Vec<TextRange> {
std::mem::take(&mut self.verbatim_ranges)
}
}
/// Public return type of the formatter
pub type FormatResult<F> = Result<F, FormatError>;
/// Formatting trait for types that can create a formatted representation. The `rome_formatter` equivalent
/// to [std::fmt::Display].
///
/// ## Example
/// Implementing `Format` for a custom struct
///
/// ```
/// use rome_formatter::{format, write, IndentStyle, LineWidth};
/// use rome_formatter::prelude::*;
/// use rome_rowan::TextSize;
///
/// struct Paragraph(String);
///
/// impl Format<SimpleFormatContext> for Paragraph {
/// fn fmt(&self, f: &mut Formatter<SimpleFormatContext>) -> FormatResult<()> {
/// write!(f, [
/// hard_line_break(),
/// dynamic_text(&self.0, TextSize::from(0)),
/// hard_line_break(),
/// ])
/// }
/// }
///
/// # fn main() -> FormatResult<()> {
/// let paragraph = Paragraph(String::from("test"));
/// let formatted = format!(SimpleFormatContext::default(), [paragraph])?;
///
/// assert_eq!("test\n", formatted.print()?.as_code());
/// # Ok(())
/// # }
/// ```
pub trait Format<Context> {
/// Formats the object using the given formatter.
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()>;
}
impl<T, Context> Format<Context> for &T
where
T: ?Sized + Format<Context>,
{
#[inline(always)]
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
Format::fmt(&**self, f)
}
}
impl<T, Context> Format<Context> for &mut T
where
T: ?Sized + Format<Context>,
{
#[inline(always)]
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
Format::fmt(&**self, f)
}
}
impl<T, Context> Format<Context> for Option<T>
where
T: Format<Context>,
{
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
match self {
Some(value) => value.fmt(f),
None => Ok(()),
}
}
}
impl<T, Context> Format<Context> for SyntaxResult<T>
where
T: Format<Context>,
{
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
match self {
Ok(value) => value.fmt(f),
Err(err) => Err(err.into()),
}
}
}
impl<Context> Format<Context> for () {
#[inline]
fn fmt(&self, _: &mut Formatter<Context>) -> FormatResult<()> {
// Intentionally left empty
Ok(())
}
}
/// Rule that knows how to format an object of type `T`.
///
/// Implementing [Format] on the object itself is preferred over implementing [FormatRule] but
/// this isn't possible inside of a dependent crate for external type.
///
/// For example, the `rome_js_formatter` crate isn't able to implement [Format] on `JsIfStatement`
/// because both the [Format] trait and `JsIfStatement` are external types (Rust's orphan rule).
///
/// That's why the `rome_js_formatter` crate must define a new-type that implements the formatting
/// of `JsIfStatement`.
pub trait FormatRule<T> {
type Context;
fn fmt(&self, item: &T, f: &mut Formatter<Self::Context>) -> FormatResult<()>;
}
/// Default implementation for formatting a token
pub struct FormatToken<C> {
context: PhantomData<C>,
}
impl<C> Default for FormatToken<C> {
fn default() -> Self {
Self {
context: PhantomData,
}
}
}
impl<C> FormatRule<SyntaxToken<C::Language>> for FormatToken<C>
where
C: CstFormatContext,
C::Language: 'static,
{
type Context = C;
fn fmt(
&self,
token: &SyntaxToken<C::Language>,
f: &mut Formatter<Self::Context>,
) -> FormatResult<()> {
f.state_mut().track_token(token);
crate::write!(
f,
[
format_skipped_token_trivia(token),
format_trimmed_token(token),
]
)
}
}
/// Rule that supports customizing how it formats an object of type `T`.
pub trait FormatRuleWithOptions<T>: FormatRule<T> {
type Options;
/// Returns a new rule that uses the given options to format an object.
fn with_options(self, options: Self::Options) -> Self;
}
/// Trait for an object that formats an object with a specified rule.
///
/// Gives access to the underlying item.
///
/// Useful in situation where a type itself doesn't implement [Format] (e.g. because of Rust's orphan rule)
/// but you want to implement some common formatting logic.
///
/// ## Examples
///
/// This can be useful if you want to format a `SyntaxNode` inside rome_formatter.. `SyntaxNode` doesn't implement [Format]
/// itself but the language specific crate implements `AsFormat` and `IntoFormat` for it and the returned [Format]
/// implement [FormatWithRule].
///
/// ```ignore
/// use rome_formatter::prelude::*;
/// use rome_formatter::{format, Formatted, FormatWithRule};
/// use rome_rowan::{Language, SyntaxNode};
/// fn format_node<L: Language, F: FormatWithRule<SimpleFormatContext, Item=SyntaxNode<L>>>(node: F) -> FormatResult<Formatted<SimpleFormatContext>> {
/// let formatted = format!(SimpleFormatContext::default(), [node]);
/// let syntax = node.item();
/// // Do something with syntax
/// formatted;
/// }
/// ```
pub trait FormatWithRule<Context>: Format<Context> {
type Item;
/// Returns the associated item
fn item(&self) -> &Self::Item;
}
/// Formats the referenced `item` with the specified rule.
#[derive(Debug, Copy, Clone)]
pub struct FormatRefWithRule<'a, T, R>
where
R: FormatRule<T>,
{
item: &'a T,
rule: R,
}
impl<'a, T, R> FormatRefWithRule<'a, T, R>
where
R: FormatRule<T>,
{
pub fn new(item: &'a T, rule: R) -> Self {
Self { item, rule }
}
}
impl<T, R, O> FormatRefWithRule<'_, T, R>
where
R: FormatRuleWithOptions<T, Options = O>,
{
pub fn with_options(mut self, options: O) -> Self {
self.rule = self.rule.with_options(options);
self
}
}
impl<T, R> FormatWithRule<R::Context> for FormatRefWithRule<'_, T, R>
where
R: FormatRule<T>,
{
type Item = T;
fn item(&self) -> &Self::Item {
self.item
}
}
impl<T, R> Format<R::Context> for FormatRefWithRule<'_, T, R>
where
R: FormatRule<T>,
{
#[inline(always)]
fn fmt(&self, f: &mut Formatter<R::Context>) -> FormatResult<()> {
self.rule.fmt(self.item, f)
}
}
/// Formats the `item` with the specified rule.
#[derive(Debug, Clone)]
pub struct FormatOwnedWithRule<T, R>
where
R: FormatRule<T>,
{
item: T,
rule: R,
}
impl<T, R> FormatOwnedWithRule<T, R>
where
R: FormatRule<T>,
{
pub fn new(item: T, rule: R) -> Self {
Self { item, rule }
}
pub fn with_item(mut self, item: T) -> Self {
self.item = item;
self
}
pub fn into_item(self) -> T {
self.item
}
}
impl<T, R> Format<R::Context> for FormatOwnedWithRule<T, R>
where
R: FormatRule<T>,
{
#[inline(always)]
fn fmt(&self, f: &mut Formatter<R::Context>) -> FormatResult<()> {
self.rule.fmt(&self.item, f)
}
}
impl<T, R, O> FormatOwnedWithRule<T, R>
where
R: FormatRuleWithOptions<T, Options = O>,
{
pub fn with_options(mut self, options: O) -> Self {
self.rule = self.rule.with_options(options);
self
}
}
impl<T, R> FormatWithRule<R::Context> for FormatOwnedWithRule<T, R>
where
R: FormatRule<T>,
{
type Item = T;
fn item(&self) -> &Self::Item {
&self.item
}
}
/// The `write` function takes a target buffer and an `Arguments` struct that can be precompiled with the `format_args!` macro.
///
/// The arguments will be formatted in-order into the output buffer provided.
///
/// # Examples
///
/// ```
/// use rome_formatter::prelude::*;
/// use rome_formatter::{VecBuffer, format_args, FormatState, write, Formatted};
///
/// # fn main() -> FormatResult<()> {
/// let mut state = FormatState::new(SimpleFormatContext::default());
/// let mut buffer = VecBuffer::new(&mut state);
///
/// write!(&mut buffer, [format_args!(text("Hello World"))])?;
///
/// let formatted = Formatted::new(Document::from(buffer.into_vec()), SimpleFormatContext::default());
///
/// assert_eq!("Hello World", formatted.print()?.as_code());
/// # Ok(())
/// # }
/// ```
///
/// Please note that using [`write!`] might be preferable. Example:
///
/// ```
/// use rome_formatter::prelude::*;
/// use rome_formatter::{VecBuffer, format_args, FormatState, write, Formatted};
///
/// # fn main() -> FormatResult<()> {
/// let mut state = FormatState::new(SimpleFormatContext::default());
/// let mut buffer = VecBuffer::new(&mut state);
///
/// write!(&mut buffer, [text("Hello World")])?;
///
/// let formatted = Formatted::new(Document::from(buffer.into_vec()), SimpleFormatContext::default());
///
/// assert_eq!("Hello World", formatted.print()?.as_code());
/// # Ok(())
/// # }
/// ```
///
#[inline(always)]
pub fn write<Context>(
output: &mut dyn Buffer<Context = Context>,
args: Arguments<Context>,
) -> FormatResult<()> {
let mut f = Formatter::new(output);
f.write_fmt(args)
}
/// The `format` function takes an [`Arguments`] struct and returns the resulting formatting IR.
///
/// The [`Arguments`] instance can be created with the [`format_args!`].
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use rome_formatter::prelude::*;
/// use rome_formatter::{format, format_args};
///
/// # fn main() -> FormatResult<()> {
/// let formatted = format!(SimpleFormatContext::default(), [&format_args!(text("test"))])?;
/// assert_eq!("test", formatted.print()?.as_code());
/// # Ok(())
/// # }
/// ```
///
/// Please note that using [`format!`] might be preferable. Example:
///
/// ```
/// use rome_formatter::prelude::*;
/// use rome_formatter::{format};
///
/// # fn main() -> FormatResult<()> {
/// let formatted = format!(SimpleFormatContext::default(), [text("test")])?;
/// assert_eq!("test", formatted.print()?.as_code());
/// # Ok(())
/// # }
/// ```
pub fn format<Context>(
context: Context,
arguments: Arguments<Context>,
) -> FormatResult<Formatted<Context>>
where
Context: FormatContext,
{
let mut state = FormatState::new(context);
let mut buffer = VecBuffer::with_capacity(arguments.items().len(), &mut state);
buffer.write_fmt(arguments)?;
let mut document = Document::from(buffer.into_vec());
document.propagate_expand();
Ok(Formatted::new(document, state.into_context()))
}
/// Entry point for formatting a [SyntaxNode] for a specific language.
pub trait FormatLanguage {
type SyntaxLanguage: Language;
/// The type of the formatting context
type Context: CstFormatContext<Language = Self::SyntaxLanguage>;
/// The rule type that can format a [SyntaxNode] of this language
type FormatRule: FormatRule<SyntaxNode<Self::SyntaxLanguage>, Context = Self::Context> + Default;
/// Performs an optional pre-processing of the tree. This can be useful to remove nodes
/// that otherwise complicate formatting.
///
/// Return [None] if the tree shouldn't be processed. Return [Some] with the transformed
/// tree and the source map otherwise.
fn transform(
&self,
_root: &SyntaxNode<Self::SyntaxLanguage>,
) -> Option<(SyntaxNode<Self::SyntaxLanguage>, TransformSourceMap)> {
None
}
/// This is used to select appropriate "root nodes" for the
/// range formatting process: for instance in JavaScript the function returns
/// true for statement and declaration nodes, to ensure the entire statement
/// gets formatted instead of the smallest sub-expression that fits the range
fn is_range_formatting_node(&self, _node: &SyntaxNode<Self::SyntaxLanguage>) -> bool {
true
}
/// Returns the formatting options
fn options(&self) -> &<Self::Context as FormatContext>::Options;
/// Creates the [FormatContext] with the given `source map` and `comments`
fn create_context(
self,
root: &SyntaxNode<Self::SyntaxLanguage>,
source_map: Option<TransformSourceMap>,
) -> Self::Context;
}
/// Formats a syntax node file based on its features.
///
/// It returns a [Formatted] result, which the user can use to override a file.
pub fn format_node<L: FormatLanguage>(
root: &SyntaxNode<L::SyntaxLanguage>,
language: L,
) -> FormatResult<Formatted<L::Context>> {
tracing::trace_span!("format_node").in_scope(move || {
let (root, source_map) = match language.transform(&root.clone()) {
Some((transformed, source_map)) => {
// we don't need to insert the node back if it has the same offset
if &transformed == root {
(transformed, Some(source_map))
} else {
match root
.ancestors()
// ancestors() always returns self as the first element of the iterator.
.skip(1)
.last()
{
// current root node is the topmost node we don't need to insert the transformed node back
None => (transformed, Some(source_map)),
Some(top_root) => {
// we have to return transformed node back into subtree
let transformed_range = transformed.text_range();
let root_range = root.text_range();
let transformed_root = top_root
.replace_child(root.clone().into(), transformed.into())
// SAFETY: Calling `unwrap` is safe because we know that `root` is part of the `top_root` subtree.
.unwrap();
let transformed = transformed_root.covering_element(TextRange::new(
root_range.start(),
root_range.start() + transformed_range.len(),
));
let node = match transformed {
NodeOrToken::Node(node) => node,
NodeOrToken::Token(token) => {
// if we get a token we need to get the parent node
token.parent().unwrap_or(transformed_root)
}
};
(node, Some(source_map))
}
}
}
}
None => (root.clone(), None),
};
let context = language.create_context(&root, source_map);
let format_node = FormatRefWithRule::new(&root, L::FormatRule::default());
let mut state = FormatState::new(context);
let mut buffer = VecBuffer::new(&mut state);
write!(buffer, [format_node])?;
let mut document = Document::from(buffer.into_vec());
document.propagate_expand();
state.assert_formatted_all_tokens(&root);
let context = state.into_context();
let comments = context.comments();
comments.assert_checked_all_suppressions(&root);
comments.assert_formatted_all_comments();
Ok(Formatted::new(document, context))
})
}
/// Returns the [TextRange] for this [SyntaxElement] with the leading and
/// trailing whitespace trimmed (but keeping comments or skipped trivias)
fn text_non_whitespace_range<E, L>(elem: &E) -> TextRange
where
E: Into<SyntaxElement<L>> + Clone,
L: Language,
{
let elem: SyntaxElement<L> = elem.clone().into();
let start = elem
.leading_trivia()
.into_iter()
.flat_map(|trivia| trivia.pieces())
.find_map(|piece| {
if piece.is_whitespace() || piece.is_newline() {
None
} else {
Some(piece.text_range().start())
}
})
.unwrap_or_else(|| elem.text_trimmed_range().start());
let end = elem
.trailing_trivia()
.into_iter()
.flat_map(|trivia| trivia.pieces().rev())
.find_map(|piece| {
if piece.is_whitespace() || piece.is_newline() {
None
} else {
Some(piece.text_range().end())
}
})
.unwrap_or_else(|| elem.text_trimmed_range().end());
TextRange::new(start, end)
}
/// Formats a range within a file, supported by Rome
///
/// This runs a simple heuristic to determine the initial indentation
/// level of the node based on the provided [FormatContext], which
/// must match currently the current initial of the file. Additionally,
/// because the reformatting happens only locally the resulting code
/// will be indented with the same level as the original selection,
/// even if it's a mismatch from the rest of the block the selection is in
///
/// It returns a [Formatted] result with a range corresponding to the
/// range of the input that was effectively overwritten by the formatter
pub fn format_range<Language: FormatLanguage>(
root: &SyntaxNode<Language::SyntaxLanguage>,
mut range: TextRange,
language: Language,
) -> FormatResult<Printed> {
if range.is_empty() {
return Ok(Printed::new(
String::new(),
Some(range),
Vec::new(),
Vec::new(),
));
}
let root_range = root.text_range();
if range.start() < root_range.start() || range.end() > root_range.end() {
return Err(FormatError::RangeError {
input: range,
tree: root_range,
});
}
// Find the tokens corresponding to the start and end of the range
let start_token = root.token_at_offset(range.start());
let end_token = root.token_at_offset(range.end());
// If these tokens were not found this means either:
// 1. The input [SyntaxNode] was empty
// 2. The input node was not the root [SyntaxNode] of the file
// In the first case we can return an empty result immediately,
// otherwise default to the first and last tokens in the root node
let mut start_token = match start_token {
// If the start of the range lies between two tokens,
// start at the rightmost one
TokenAtOffset::Between(_, token) => token,
TokenAtOffset::Single(token) => token,
TokenAtOffset::None => match root.first_token() {
Some(token) => token,
// root node is empty
None => return Ok(Printed::new_empty()),
},
};
let mut end_token = match end_token {
// If the end of the range lies between two tokens,
// end at the leftmost one
TokenAtOffset::Between(token, _) => token,
TokenAtOffset::Single(token) => token,
TokenAtOffset::None => match root.last_token() {
Some(token) => token,
// root node is empty
None => return Ok(Printed::new_empty()),
},
};
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/comments.rs | crates/rome_formatter/src/comments.rs | //! Types for extracting and representing comments of a syntax tree.
//!
//! Most programming languages support comments allowing programmers to document their programs. Comments are different from other syntaxes because programming languages allow comments in almost any position, giving programmers great flexibility on where they can write comments:
//!
//! ```ignore
//! /**
//! * Documentation comment
//! */
//! async /* comment */ function Test () // line comment
//! {/*inline*/}
//! ```
//!
//! However, this flexibility makes formatting comments challenging because:
//! * The formatter must consistently place comments so that re-formatting the output yields the same result and does not create invalid syntax (line comments).
//! * It is essential that formatters place comments close to the syntax the programmer intended to document. However, the lack of rules regarding where comments are allowed and what syntax they document requires the use of heuristics to infer the documented syntax.
//!
//! This module strikes a balance between placing comments as closely as possible to their source location and reducing the complexity of formatting comments. It does so by associating comments per node rather than a token. This greatly reduces the combinations of possible comment positions but turns out to be, in practice, sufficiently precise to keep comments close to their source location.
//!
//! ## Node comments
//!
//! Comments are associated per node but get further distinguished on their location related to that node:
//!
//! ### Leading Comments
//!
//! A comment at the start of a node
//!
//! ```ignore
//! // Leading comment of the statement
//! console.log("test");
//!
//! [/* leading comment of identifier */ a ];
//! ```
//!
//! ### Dangling Comments
//!
//! A comment that is neither at the start nor the end of a node
//!
//! ```ignore
//! [/* in between the brackets */ ];
//! async /* between keywords */ function Test () {}
//! ```
//!
//! ### Trailing Comments
//!
//! A comment at the end of a node
//!
//! ```ignore
//! [a /* trailing comment of a */, b, c];
//! [
//! a // trailing comment of a
//! ]
//! ```
//!
//! ## Limitations
//! Limiting the placement of comments to leading, dangling, or trailing node comments reduces complexity inside the formatter but means, that the formatter's possibility of where comments can be formatted depends on the AST structure.
//!
//! For example, the continue statement in JavaScript is defined as:
//!
//! ```ungram
//! JsContinueStatement =
//! 'continue'
//! (label: 'ident')?
//! ';'?
//! ```
//!
//! but a programmer may decide to add a comment in front or after the label:
//!
//! ```ignore
//! continue /* comment 1 */ label;
//! continue label /* comment 2*/; /* trailing */
//! ```
//!
//! Because all children of the `continue` statement are tokens, it is only possible to make the comments leading, dangling, or trailing comments of the `continue` statement. But this results in a loss of information as the formatting code can no longer distinguish if a comment appeared before or after the label and, thus, has to format them the same way.
//!
//! This hasn't shown to be a significant limitation today but the infrastructure could be extended to support a `label` on [`SourceComment`] that allows to further categorise comments.
//!
mod builder;
mod map;
use self::{builder::CommentsBuilderVisitor, map::CommentsMap};
use crate::formatter::Formatter;
use crate::{buffer::Buffer, write};
use crate::{CstFormatContext, FormatResult, FormatRule, TextSize, TransformSourceMap};
use rome_rowan::syntax::SyntaxElementKey;
use rome_rowan::{Language, SyntaxNode, SyntaxToken, SyntaxTriviaPieceComments};
use rustc_hash::FxHashSet;
#[cfg(debug_assertions)]
use std::cell::{Cell, RefCell};
use std::marker::PhantomData;
use std::rc::Rc;
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum CommentKind {
/// An inline comment that can appear between any two tokens and doesn't contain any line breaks.
///
/// ## Examples
///
/// ```ignore
/// a /* test */
/// ```
InlineBlock,
/// A block comment that can appear between any two tokens and contains at least one line break.
///
/// ## Examples
///
/// ```javascript
/// /* first line
/// * more content on the second line
/// */
/// ```
Block,
/// A line comment that appears at the end of the line.
///
/// ## Examples
///
/// ```ignore
/// a // test
/// ```
Line,
}
impl CommentKind {
pub const fn is_line(&self) -> bool {
matches!(self, CommentKind::Line)
}
pub const fn is_block(&self) -> bool {
matches!(self, CommentKind::Block)
}
pub const fn is_inline_block(&self) -> bool {
matches!(self, CommentKind::InlineBlock)
}
/// Returns `true` for comments that can appear inline between any two tokens.
///
/// ## Examples
///
/// ```rust
/// use rome_formatter::comments::CommentKind;
///
/// // Block and InlineBlock comments can appear inline
/// assert!(CommentKind::Block.is_inline());
/// assert!(CommentKind::InlineBlock.is_inline());
///
/// // But not line comments
/// assert!(!CommentKind::Line.is_inline())
/// ```
pub const fn is_inline(&self) -> bool {
matches!(self, CommentKind::InlineBlock | CommentKind::Block)
}
}
/// A comment in the source document.
#[derive(Debug, Clone)]
pub struct SourceComment<L: Language> {
/// The number of lines appearing before this comment
pub(crate) lines_before: u32,
pub(crate) lines_after: u32,
/// The comment piece
pub(crate) piece: SyntaxTriviaPieceComments<L>,
/// The kind of the comment.
pub(crate) kind: CommentKind,
/// Whether the comment has been formatted or not.
#[cfg(debug_assertions)]
pub(crate) formatted: Cell<bool>,
}
impl<L: Language> SourceComment<L> {
/// Returns the underlining comment trivia piece
pub fn piece(&self) -> &SyntaxTriviaPieceComments<L> {
&self.piece
}
/// The number of lines between this comment and the **previous** token or comment.
///
/// # Examples
///
/// ## Same line
///
/// ```ignore
/// a // end of line
/// ```
///
/// Returns `0` because there's no line break between the token `a` and the comment.
///
/// ## Own Line
///
/// ```ignore
/// a;
///
/// /* comment */
/// ```
///
/// Returns `2` because there are two line breaks between the token `a` and the comment.
pub fn lines_before(&self) -> u32 {
self.lines_before
}
/// The number of line breaks right after this comment.
///
/// # Examples
///
/// ## End of line
///
/// ```ignore
/// a; // comment
///
/// b;
/// ```
///
/// Returns `2` because there are two line breaks between the comment and the token `b`.
///
/// ## Same line
///
/// ```ignore
/// a;
/// /* comment */ b;
/// ```
///
/// Returns `0` because there are no line breaks between the comment and the token `b`.
pub fn lines_after(&self) -> u32 {
self.lines_after
}
/// The kind of the comment
pub fn kind(&self) -> CommentKind {
self.kind
}
#[cfg(not(debug_assertions))]
#[inline(always)]
pub fn mark_formatted(&self) {}
/// Marks the comment as formatted
#[cfg(debug_assertions)]
pub fn mark_formatted(&self) {
self.formatted.set(true)
}
}
/// A comment decorated with additional information about its surrounding context in the source document.
///
/// Used by [CommentStyle::place_comment] to determine if this should become a [leading](self#leading-comments), [dangling](self#dangling-comments), or [trailing](self#trailing-comments) comment.
#[derive(Debug, Clone)]
pub struct DecoratedComment<L: Language> {
enclosing: SyntaxNode<L>,
preceding: Option<SyntaxNode<L>>,
following: Option<SyntaxNode<L>>,
following_token: Option<SyntaxToken<L>>,
text_position: CommentTextPosition,
lines_before: u32,
lines_after: u32,
comment: SyntaxTriviaPieceComments<L>,
kind: CommentKind,
}
impl<L: Language> DecoratedComment<L> {
/// The closest parent node that fully encloses the comment.
///
/// A node encloses a comment when the comment is between two of its direct children (ignoring lists).
///
/// # Examples
///
/// ```ignore
/// [a, /* comment */ b]
/// ```
///
/// The enclosing node is the array expression and not the identifier `b` because
/// `a` and `b` are children of the array expression and `comment` is a comment between the two nodes.
pub fn enclosing_node(&self) -> &SyntaxNode<L> {
&self.enclosing
}
/// Returns the comment piece.
pub fn piece(&self) -> &SyntaxTriviaPieceComments<L> {
&self.comment
}
/// Returns the node preceding the comment.
///
/// The direct child node (ignoring lists) of the [`enclosing_node`](DecoratedComment::enclosing_node) that precedes this comment.
///
/// Returns [None] if the [`enclosing_node`](DecoratedComment::enclosing_node) only consists of tokens or if
/// all preceding children of the [`enclosing_node`](DecoratedComment::enclosing_node) have been tokens.
///
/// The Preceding node is guaranteed to be a sibling of [`following_node`](DecoratedComment::following_node).
///
/// # Examples
///
/// ## Preceding tokens only
///
/// ```ignore
/// [/* comment */]
/// ```
/// Returns [None] because the comment has no preceding node, only a preceding `[` token.
///
/// ## Preceding node
///
/// ```ignore
/// [a /* comment */, b]
/// ```
///
/// Returns `Some(a)` because `a` directly precedes the comment.
///
/// ## Preceding token and node
///
/// ```ignore
/// [a, /* comment */]
/// ```
///
/// Returns `Some(a)` because `a` is the preceding node of `comment`. The presence of the `,` token
/// doesn't change that.
pub fn preceding_node(&self) -> Option<&SyntaxNode<L>> {
self.preceding.as_ref()
}
/// Takes the [`preceding_node`](DecoratedComment::preceding_node) and replaces it with [None].
fn take_preceding_node(&mut self) -> Option<SyntaxNode<L>> {
self.preceding.take()
}
/// Returns the node following the comment.
///
/// The direct child node (ignoring lists) of the [`enclosing_node`](DecoratedComment::enclosing_node) that follows this comment.
///
/// Returns [None] if the [`enclosing_node`](DecoratedComment::enclosing_node) only consists of tokens or if
/// all children children of the [`enclosing_node`](DecoratedComment::enclosing_node) following this comment are tokens.
///
/// The following node is guaranteed to be a sibling of [`preceding_node`](DecoratedComment::preceding_node).
///
/// # Examples
///
/// ## Following tokens only
///
/// ```ignore
/// [ /* comment */ ]
/// ```
///
/// Returns [None] because there's no node following the comment, only the `]` token.
///
/// ## Following node
///
/// ```ignore
/// [ /* comment */ a ]
/// ```
///
/// Returns `Some(a)` because `a` is the node directly following the comment.
///
/// ## Following token and node
///
/// ```ignore
/// async /* comment */ function test() {}
/// ```
///
/// Returns `Some(test)` because the `test` identifier is the first node following `comment`.
///
/// ## Following parenthesized expression
///
/// ```ignore
/// !(
/// a /* comment */
/// );
/// b
/// ```
///
/// Returns `None` because `comment` is enclosed inside the parenthesized expression and it has no children
/// following `/* comment */.
pub fn following_node(&self) -> Option<&SyntaxNode<L>> {
self.following.as_ref()
}
/// Takes the [`following_node`](DecoratedComment::following_node) and replaces it with [None].
fn take_following_node(&mut self) -> Option<SyntaxNode<L>> {
self.following.take()
}
/// The number of line breaks between this comment and the **previous** token or comment.
///
/// # Examples
///
/// ## Same line
///
/// ```ignore
/// a // end of line
/// ```
///
/// Returns `0` because there's no line break between the token `a` and the comment.
///
/// ## Own Line
///
/// ```ignore
/// a;
///
/// /* comment */
/// ```
///
/// Returns `2` because there are two line breaks between the token `a` and the comment.
pub fn lines_before(&self) -> u32 {
self.lines_before
}
/// The number of line breaks right after this comment.
///
/// # Examples
///
/// ## End of line
///
/// ```ignore
/// a; // comment
///
/// b;
/// ```
///
/// Returns `2` because there are two line breaks between the comment and the token `b`.
///
/// ## Same line
///
/// ```ignore
/// a;
/// /* comment */ b;
/// ```
///
/// Returns `0` because there are no line breaks between the comment and the token `b`.
pub fn lines_after(&self) -> u32 {
self.lines_after
}
/// Returns the [CommentKind] of the comment.
pub fn kind(&self) -> CommentKind {
self.kind
}
/// The position of the comment in the text.
pub fn text_position(&self) -> CommentTextPosition {
self.text_position
}
/// The next token that comes after this comment. It is possible that other comments are between this comment
/// and the token.
///
/// ```ignore
/// a /* comment */ /* other b */
/// ```
///
/// The `following_token` for both comments is `b` because it's the token coming after the comments.
pub fn following_token(&self) -> Option<&SyntaxToken<L>> {
self.following_token.as_ref()
}
}
impl<L: Language> From<DecoratedComment<L>> for SourceComment<L> {
fn from(decorated: DecoratedComment<L>) -> Self {
Self {
lines_before: decorated.lines_before,
lines_after: decorated.lines_after,
piece: decorated.comment,
kind: decorated.kind,
#[cfg(debug_assertions)]
formatted: Cell::new(false),
}
}
}
/// The position of a comment in the source text.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum CommentTextPosition {
/// A comment that is on the same line as the preceding token and is separated by at least one line break from the following token.
///
/// # Examples
///
/// ## End of line
///
/// ```ignore
/// a; /* this */ // or this
/// b;
/// ```
///
/// Both `/* this */` and `// or this` are end of line comments because both comments are separated by
/// at least one line break from the following token `b`.
///
/// ## Own line
///
/// ```ignore
/// a;
/// /* comment */
/// b;
/// ```
///
/// This is not an end of line comment because it isn't on the same line as the preceding token `a`.
EndOfLine,
/// A Comment that is separated by at least one line break from the preceding token.
///
/// # Examples
///
/// ```ignore
/// a;
/// /* comment */ /* or this */
/// b;
/// ```
///
/// Both comments are own line comments because they are separated by one line break from the preceding
/// token `a`.
OwnLine,
/// A comment that is placed on the same line as the preceding and following token.
///
/// # Examples
///
/// ```ignore
/// a /* comment */ + b
/// ```
SameLine,
}
impl CommentTextPosition {
pub const fn is_same_line(&self) -> bool {
matches!(self, CommentTextPosition::SameLine)
}
pub const fn is_own_line(&self) -> bool {
matches!(self, CommentTextPosition::OwnLine)
}
pub const fn is_end_of_line(&self) -> bool {
matches!(self, CommentTextPosition::EndOfLine)
}
}
#[derive(Debug)]
pub enum CommentPlacement<L: Language> {
/// Makes `comment` a [leading comment](self#leading-comments) of `node`.
Leading {
node: SyntaxNode<L>,
comment: SourceComment<L>,
},
/// Makes `comment` a [trailing comment](self#trailing-comments) of `node`.
Trailing {
node: SyntaxNode<L>,
comment: SourceComment<L>,
},
/// Makes `comment` a [dangling comment](self#dangling-comments) of `node`.
Dangling {
node: SyntaxNode<L>,
comment: SourceComment<L>,
},
/// Uses the default heuristic to determine the placement of the comment.
///
/// # Same line comments
///
/// Makes the comment a...
///
/// * [trailing comment] of the [`preceding_node`] if both the [`following_node`] and [`preceding_node`] are not [None]
/// and the comment and [`preceding_node`] are only separated by a space (there's no token between the comment and [`preceding_node`]).
/// * [leading comment] of the [`following_node`] if the [`following_node`] is not [None]
/// * [trailing comment] of the [`preceding_node`] if the [`preceding_node`] is not [None]
/// * [dangling comment] of the [`enclosing_node`].
///
/// ## Examples
/// ### Comment with preceding and following nodes
///
/// ```ignore
/// [
/// a, // comment
/// b
/// ]
/// ```
///
/// The comment becomes a [trailing comment] of the node `a`.
///
/// ### Comment with preceding node only
///
/// ```ignore
/// [
/// a // comment
/// ]
/// ```
///
/// The comment becomes a [trailing comment] of the node `a`.
///
/// ### Comment with following node only
///
/// ```ignore
/// [ // comment
/// b
/// ]
/// ```
///
/// The comment becomes a [leading comment] of the node `b`.
///
/// ### Dangling comment
///
/// ```ignore
/// [ // comment
/// ]
/// ```
///
/// The comment becomes a [dangling comment] of the enclosing array expression because both the [`preceding_node`] and [`following_node`] are [None].
///
/// # Own line comments
///
/// Makes the comment a...
///
/// * [leading comment] of the [`following_node`] if the [`following_node`] is not [None]
/// * or a [trailing comment] of the [`preceding_node`] if the [`preceding_node`] is not [None]
/// * or a [dangling comment] of the [`enclosing_node`].
///
/// ## Examples
///
/// ### Comment with leading and preceding nodes
///
/// ```ignore
/// [
/// a,
/// // comment
/// b
/// ]
/// ```
///
/// The comment becomes a [leading comment] of the node `b`.
///
/// ### Comment with preceding node only
///
/// ```ignore
/// [
/// a
/// // comment
/// ]
/// ```
///
/// The comment becomes a [trailing comment] of the node `a`.
///
/// ### Comment with following node only
///
/// ```ignore
/// [
/// // comment
/// b
/// ]
/// ```
///
/// The comment becomes a [leading comment] of the node `b`.
///
/// ### Dangling comment
///
/// ```ignore
/// [
/// // comment
/// ]
/// ```
///
/// The comment becomes a [dangling comment] of the array expression because both [`preceding_node`] and [`following_node`] are [None].
///
///
/// # End of line comments
/// Makes the comment a...
///
/// * [trailing comment] of the [`preceding_node`] if the [`preceding_node`] is not [None]
/// * or a [leading comment] of the [`following_node`] if the [`following_node`] is not [None]
/// * or a [dangling comment] of the [`enclosing_node`].
///
///
/// ## Examples
///
/// ### Comment with leading and preceding nodes
///
/// ```ignore
/// [a /* comment */, b]
/// ```
///
/// The comment becomes a [trailing comment] of the node `a` because there's no token between the node `a` and the `comment`.
///
/// ```ignore
/// [a, /* comment */ b]
/// ```
///
/// The comment becomes a [leading comment] of the node `b` because the node `a` and the comment are separated by a `,` token.
///
/// ### Comment with preceding node only
///
/// ```ignore
/// [a, /* last */ ]
/// ```
///
/// The comment becomes a [trailing comment] of the node `a` because the [`following_node`] is [None].
///
/// ### Comment with following node only
///
/// ```ignore
/// [/* comment */ b]
/// ```
///
/// The comment becomes a [leading comment] of the node `b` because the [`preceding_node`] is [None]
///
/// ### Dangling comment
///
/// ```ignore
/// [/* comment*/]
/// ```
///
/// The comment becomes a [dangling comment] of the array expression because both [`preceding_node`] and [`following_node`] are [None].
///
/// [`preceding_node`]: DecoratedComment::preceding_node
/// [`following_node`]: DecoratedComment::following_node
/// [`enclosing_node`]: DecoratedComment::enclosing_node
/// [trailing comment]: self#trailing-comments
/// [leading comment]: self#leading-comments
/// [dangling comment]: self#dangling-comments
Default(DecoratedComment<L>),
}
impl<L: Language> CommentPlacement<L> {
/// Makes `comment` a [leading comment](self#leading-comments) of `node`.
#[inline]
pub fn leading(node: SyntaxNode<L>, comment: impl Into<SourceComment<L>>) -> Self {
Self::Leading {
node,
comment: comment.into(),
}
}
/// Makes `comment` a [dangling comment](self::dangling-comments) of `node`.
pub fn dangling(node: SyntaxNode<L>, comment: impl Into<SourceComment<L>>) -> Self {
Self::Dangling {
node,
comment: comment.into(),
}
}
/// Makes `comment` a [trailing comment](self::trailing-comments) of `node`.
#[inline]
pub fn trailing(node: SyntaxNode<L>, comment: impl Into<SourceComment<L>>) -> Self {
Self::Trailing {
node,
comment: comment.into(),
}
}
/// Returns the placement if it isn't [CommentPlacement::Default], otherwise calls `f` and returns the result.
#[inline]
pub fn or_else<F>(self, f: F) -> Self
where
F: FnOnce(DecoratedComment<L>) -> CommentPlacement<L>,
{
match self {
CommentPlacement::Default(comment) => f(comment),
placement => placement,
}
}
}
/// Defines how to format comments for a specific [Language].
pub trait CommentStyle: Default {
type Language: Language;
/// Returns `true` if a comment with the given `text` is a `rome-ignore format:` suppression comment.
fn is_suppression(_text: &str) -> bool {
false
}
/// Returns the (kind)[CommentKind] of the comment
fn get_comment_kind(comment: &SyntaxTriviaPieceComments<Self::Language>) -> CommentKind;
/// Determines the placement of `comment`.
///
/// The default implementation returns [CommentPlacement::Default].
fn place_comment(
&self,
comment: DecoratedComment<Self::Language>,
) -> CommentPlacement<Self::Language> {
CommentPlacement::Default(comment)
}
}
/// The comments of a syntax tree stored by node.
///
/// Cloning `comments` is cheap as it only involves bumping a reference counter.
#[derive(Debug, Clone, Default)]
pub struct Comments<L: Language> {
/// The use of a [Rc] is necessary to achieve that [Comments] has a lifetime that is independent from the [crate::Formatter].
/// Having independent lifetimes is necessary to support the use case where a (formattable object)[crate::Format]
/// iterates over all comments, and writes them into the [crate::Formatter] (mutably borrowing the [crate::Formatter] and in turn its context).
///
/// ```block
/// for leading in f.context().comments().leading_comments(node) {
/// ^
/// |- Borrows comments
/// write!(f, [comment(leading.piece.text())])?;
/// ^
/// |- Mutably borrows the formatter, state, context, and comments (if comments aren't cloned)
/// }
/// ```
///
/// Using an `Rc` here allows to cheaply clone [Comments] for these use cases.
data: Rc<CommentsData<L>>,
}
impl<L: Language> Comments<L> {
/// Extracts all the comments from `root` and its descendants nodes.
pub fn from_node<Style>(
root: &SyntaxNode<L>,
style: &Style,
source_map: Option<&TransformSourceMap>,
) -> Self
where
Style: CommentStyle<Language = L>,
{
let builder = CommentsBuilderVisitor::new(style, source_map);
let (comments, skipped) = builder.visit(root);
Self {
data: Rc::new(CommentsData {
root: Some(root.clone()),
is_suppression: Style::is_suppression,
comments,
with_skipped: skipped,
#[cfg(debug_assertions)]
checked_suppressions: RefCell::new(Default::default()),
}),
}
}
/// Returns `true` if the given `node` has any [leading](self#leading-comments) or [trailing](self#trailing-comments) comments.
#[inline]
pub fn has_comments(&self, node: &SyntaxNode<L>) -> bool {
self.data.comments.has(&node.key())
}
/// Returns `true` if the given `node` has any [leading comments](self#leading-comments).
#[inline]
pub fn has_leading_comments(&self, node: &SyntaxNode<L>) -> bool {
!self.leading_comments(node).is_empty()
}
/// Tests if the node has any [leading comments](self#leading-comments) that have a leading line break.
///
/// Corresponds to [CommentTextPosition::OwnLine].
pub fn has_leading_own_line_comment(&self, node: &SyntaxNode<L>) -> bool {
self.leading_comments(node)
.iter()
.any(|comment| comment.lines_after() > 0)
}
/// Returns the `node`'s [leading comments](self#leading-comments).
#[inline]
pub fn leading_comments(&self, node: &SyntaxNode<L>) -> &[SourceComment<L>] {
self.data.comments.leading(&node.key())
}
/// Returns `true` if node has any [dangling comments](self#dangling-comments).
pub fn has_dangling_comments(&self, node: &SyntaxNode<L>) -> bool {
!self.dangling_comments(node).is_empty()
}
/// Returns the [dangling comments](self#dangling-comments) of `node`
pub fn dangling_comments(&self, node: &SyntaxNode<L>) -> &[SourceComment<L>] {
self.data.comments.dangling(&node.key())
}
/// Returns the `node`'s [trailing comments](self#trailing-comments).
#[inline]
pub fn trailing_comments(&self, node: &SyntaxNode<L>) -> &[SourceComment<L>] {
self.data.comments.trailing(&node.key())
}
/// Returns `true` if the node has any [trailing](self#trailing-comments) [line](CommentKind::Line) comment.
pub fn has_trailing_line_comment(&self, node: &SyntaxNode<L>) -> bool {
self.trailing_comments(node)
.iter()
.any(|comment| comment.kind().is_line())
}
/// Returns `true` if the given `node` has any [trailing comments](self#trailing-comments).
#[inline]
pub fn has_trailing_comments(&self, node: &SyntaxNode<L>) -> bool {
!self.trailing_comments(node).is_empty()
}
/// Returns an iterator over the [leading](self#leading-comments) and [trailing comments](self#trailing-comments) of `node`.
pub fn leading_trailing_comments(
&self,
node: &SyntaxNode<L>,
) -> impl Iterator<Item = &SourceComment<L>> {
self.leading_comments(node)
.iter()
.chain(self.trailing_comments(node).iter())
}
/// Returns an iterator over the [leading](self#leading-comments), [dangling](self#dangling-comments), and [trailing](self#trailing) comments of `node`.
pub fn leading_dangling_trailing_comments<'a>(
&'a self,
node: &'a SyntaxNode<L>,
) -> impl Iterator<Item = &SourceComment<L>> + 'a {
self.data.comments.parts(&node.key())
}
/// Returns `true` if that node has skipped token trivia attached.
#[inline]
pub fn has_skipped(&self, token: &SyntaxToken<L>) -> bool {
self.data.with_skipped.contains(&token.key())
}
/// Returns `true` if `node` has a [leading](self#leading-comments), [dangling](self#dangling-comments), or [trailing](self#trailing-comments) suppression comment.
///
/// # Examples
///
/// ```javascript
/// // rome-ignore format: Reason
/// console.log("Test");
/// ```
///
/// Returns `true` for the expression statement but `false` for the call expression because the
/// call expression is nested inside of the expression statement.
pub fn is_suppressed(&self, node: &SyntaxNode<L>) -> bool {
self.mark_suppression_checked(node);
let is_suppression = self.data.is_suppression;
self.leading_dangling_trailing_comments(node)
.any(|comment| is_suppression(comment.piece().text()))
}
#[cfg(not(debug_assertions))]
#[inline(always)]
pub fn mark_suppression_checked(&self, _: &SyntaxNode<L>) {}
/// Marks that it isn't necessary for the given node to check if it has been suppressed or not.
#[cfg(debug_assertions)]
pub fn mark_suppression_checked(&self, node: &SyntaxNode<L>) {
let mut checked_nodes = self.data.checked_suppressions.borrow_mut();
checked_nodes.insert(node.clone());
}
#[cfg(not(debug_assertions))]
#[inline(always)]
pub(crate) fn assert_checked_all_suppressions(&self, _: &SyntaxNode<L>) {}
/// Verifies that [NodeSuppressions::is_suppressed] has been called for every node of `root`.
/// This is a no-op in builds that have the feature `debug_assertions` disabled.
///
/// # Panics
/// If theres any node for which the formatting didn't very if it has a suppression comment.
#[cfg(debug_assertions)]
pub(crate) fn assert_checked_all_suppressions(&self, root: &SyntaxNode<L>) {
use rome_rowan::SyntaxKind;
let checked_nodes = self.data.checked_suppressions.borrow();
for node in root.descendants() {
if node.kind().is_list() || node.kind().is_root() {
continue;
}
if !checked_nodes.contains(&node) {
panic!(
r#"
The following node has been formatted without checking if it has suppression comments.
Ensure that the formatter calls into the node's formatting rule by using `node.format()` or
manually test if the node has a suppression comment using `f.context().comments().is_suppressed(node.syntax())`
if using the node's format rule isn't an option."
Node:
{node:#?}"#
);
}
}
}
#[inline(always)]
#[cfg(not(debug_assertions))]
pub(crate) fn assert_formatted_all_comments(&self) {}
#[cfg(debug_assertions)]
pub(crate) fn assert_formatted_all_comments(&self) {
let has_unformatted_comments = self
.data
.comments
.all_parts()
.any(|comment| !comment.formatted.get());
if has_unformatted_comments {
let mut unformatted_comments = Vec::new();
for node in self
.data
.root
.as_ref()
.expect("Expected root for comments with data")
.descendants()
{
unformatted_comments.extend(self.leading_comments(&node).iter().filter_map(
|comment| {
(!comment.formatted.get()).then_some(DebugComment::Leading {
node: node.clone(),
comment,
})
},
));
unformatted_comments.extend(self.dangling_comments(&node).iter().filter_map(
|comment| {
(!comment.formatted.get()).then_some(DebugComment::Dangling {
node: node.clone(),
comment,
})
},
));
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/format_extensions.rs | crates/rome_formatter/src/format_extensions.rs | use crate::prelude::*;
use std::cell::RefCell;
use std::marker::PhantomData;
use std::ops::Deref;
use crate::Buffer;
/// Utility trait that allows memorizing the output of a [Format].
/// Useful to avoid re-formatting the same object twice.
pub trait MemoizeFormat<Context> {
/// Returns a formattable object that memoizes the result of `Format` by cloning.
/// Mainly useful if the same sub-tree can appear twice in the formatted output because it's
/// used inside of `if_group_breaks` or `if_group_fits_single_line`.
///
/// ```
/// use std::cell::Cell;
/// use rome_formatter::{format, write};
/// use rome_formatter::prelude::*;
/// use rome_rowan::TextSize;
///
/// struct MyFormat {
/// value: Cell<u64>
/// }
///
/// impl MyFormat {
/// pub fn new() -> Self {
/// Self { value: Cell::new(1) }
/// }
/// }
///
/// impl Format<SimpleFormatContext> for MyFormat {
/// fn fmt(&self, f: &mut Formatter<SimpleFormatContext>) -> FormatResult<()> {
/// let value = self.value.get();
/// self.value.set(value + 1);
///
/// write!(f, [dynamic_text(&std::format!("Formatted {value} times."), TextSize::from(0))])
/// }
/// }
///
/// # fn main() -> FormatResult<()> {
/// let normal = MyFormat::new();
///
/// // Calls `format` for everytime the object gets formatted
/// assert_eq!(
/// "Formatted 1 times. Formatted 2 times.",
/// format!(SimpleFormatContext::default(), [normal, space(), normal])?.print()?.as_code()
/// );
///
/// // Memoized memoizes the result and calls `format` only once.
/// let memoized = normal.memoized();
/// assert_eq!(
/// "Formatted 3 times. Formatted 3 times.",
/// format![SimpleFormatContext::default(), [memoized, space(), memoized]]?.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
///
fn memoized(self) -> Memoized<Self, Context>
where
Self: Sized + Format<Context>,
{
Memoized::new(self)
}
}
impl<T, Context> MemoizeFormat<Context> for T where T: Format<Context> {}
/// Memoizes the output of its inner [Format] to avoid re-formatting a potential expensive object.
#[derive(Debug)]
pub struct Memoized<F, Context> {
inner: F,
memory: RefCell<Option<FormatResult<Option<FormatElement>>>>,
options: PhantomData<Context>,
}
impl<F, Context> Memoized<F, Context>
where
F: Format<Context>,
{
fn new(inner: F) -> Self {
Self {
inner,
memory: RefCell::new(None),
options: PhantomData,
}
}
/// Gives access to the memoized content.
///
/// Performs the formatting if the content hasn't been formatted at this point.
///
/// # Example
///
/// Inspect if some memoized content breaks.
///
/// ```rust
/// use std::cell::Cell;
/// use rome_formatter::{format, write};
/// use rome_formatter::prelude::*;
/// use rome_rowan::TextSize;
///
/// #[derive(Default)]
/// struct Counter {
/// value: Cell<u64>
/// }
///
/// impl Format<SimpleFormatContext> for Counter {
/// fn fmt(&self, f: &mut Formatter<SimpleFormatContext>) -> FormatResult<()> {
/// let current = self.value.get();
///
/// write!(f, [
/// text("Count:"),
/// space(),
/// dynamic_text(&std::format!("{current}"), TextSize::default()),
/// hard_line_break()
/// ])?;
///
/// self.value.set(current + 1);
/// Ok(())
/// }
/// }
///
/// # fn main() -> FormatResult<()> {
/// let content = format_with(|f| {
/// let mut counter = Counter::default().memoized();
/// let counter_content = counter.inspect(f)?;
///
/// if counter_content.will_break() {
/// write!(f, [text("Counter:"), block_indent(&counter)])
/// } else {
/// write!(f, [text("Counter:"), counter])
/// }?;
///
/// write!(f, [counter])
/// });
///
///
/// let formatted = format!(SimpleFormatContext::default(), [content])?;
/// assert_eq!("Counter:\n\tCount: 0\nCount: 0\n", formatted.print()?.as_code());
/// # Ok(())
/// # }
///
/// ```
pub fn inspect(&mut self, f: &mut Formatter<Context>) -> FormatResult<&[FormatElement]> {
let result = self
.memory
.get_mut()
.get_or_insert_with(|| f.intern(&self.inner));
match result.as_ref() {
Ok(Some(FormatElement::Interned(interned))) => Ok(interned.deref()),
Ok(Some(other)) => Ok(std::slice::from_ref(other)),
Ok(None) => Ok(&[]),
Err(error) => Err(*error),
}
}
}
impl<F, Context> Format<Context> for Memoized<F, Context>
where
F: Format<Context>,
{
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
let mut memory = self.memory.borrow_mut();
let result = memory.get_or_insert_with(|| f.intern(&self.inner));
match result {
Ok(Some(elements)) => {
f.write_element(elements.clone())?;
Ok(())
}
Ok(None) => Ok(()),
Err(err) => Err(*err),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/arguments.rs | crates/rome_formatter/src/arguments.rs | use super::{Buffer, Format, Formatter};
use crate::FormatResult;
use std::ffi::c_void;
use std::marker::PhantomData;
/// Mono-morphed type to format an object. Used by the [crate::format!], [crate::format_args!], and
/// [crate::write!] macros.
///
/// This struct is similar to a dynamic dispatch (using `dyn Format`) because it stores a pointer to the value.
/// However, it doesn't store the pointer to `dyn Format`'s vtable, instead it statically resolves the function
/// pointer of `Format::format` and stores it in `formatter`.
pub struct Argument<'fmt, Context> {
/// The value to format stored as a raw pointer where `lifetime` stores the value's lifetime.
value: *const c_void,
/// Stores the lifetime of the value. To get the most out of our dear borrow checker.
lifetime: PhantomData<&'fmt ()>,
/// The function pointer to `value`'s `Format::format` method
formatter: fn(*const c_void, &mut Formatter<'_, Context>) -> FormatResult<()>,
}
impl<Context> Clone for Argument<'_, Context> {
fn clone(&self) -> Self {
*self
}
}
impl<Context> Copy for Argument<'_, Context> {}
impl<'fmt, Context> Argument<'fmt, Context> {
/// Called by the [rome_formatter::format_args] macro. Creates a mono-morphed value for formatting
/// an object.
#[doc(hidden)]
#[inline]
pub fn new<F: Format<Context>>(value: &'fmt F) -> Self {
#[inline(always)]
fn formatter<F: Format<Context>, Context>(
ptr: *const c_void,
fmt: &mut Formatter<Context>,
) -> FormatResult<()> {
// SAFETY: Safe because the 'fmt lifetime is captured by the 'lifetime' field.
F::fmt(unsafe { &*(ptr as *const F) }, fmt)
}
Self {
value: value as *const F as *const c_void,
lifetime: PhantomData,
formatter: formatter::<F, Context>,
}
}
/// Formats the value stored by this argument using the given formatter.
#[inline(always)]
pub(super) fn format(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
(self.formatter)(self.value, f)
}
}
/// Sequence of objects that should be formatted in the specified order.
///
/// The [`format_args!`] macro will safely create an instance of this structure.
///
/// You can use the `Arguments<a>` that [`format_args!]` return in `Format` context as seen below.
/// It will call the `format` function for every of it's objects.
///
/// ```rust
/// use rome_formatter::prelude::*;
/// use rome_formatter::{format, format_args};
///
/// # fn main() -> FormatResult<()> {
/// let formatted = format!(SimpleFormatContext::default(), [
/// format_args!(text("a"), space(), text("b"))
/// ])?;
///
/// assert_eq!("a b", formatted.print()?.as_code());
/// # Ok(())
/// # }
/// ```
pub struct Arguments<'fmt, Context>(pub &'fmt [Argument<'fmt, Context>]);
impl<'fmt, Context> Arguments<'fmt, Context> {
#[doc(hidden)]
#[inline(always)]
pub fn new(arguments: &'fmt [Argument<'fmt, Context>]) -> Self {
Self(arguments)
}
/// Returns the arguments
#[inline]
pub(super) fn items(&self) -> &'fmt [Argument<'fmt, Context>] {
self.0
}
}
impl<Context> Copy for Arguments<'_, Context> {}
impl<Context> Clone for Arguments<'_, Context> {
fn clone(&self) -> Self {
Self(self.0)
}
}
impl<Context> Format<Context> for Arguments<'_, Context> {
#[inline(always)]
fn fmt(&self, formatter: &mut Formatter<Context>) -> FormatResult<()> {
formatter.write_fmt(*self)
}
}
impl<Context> std::fmt::Debug for Arguments<'_, Context> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Arguments[...]")
}
}
impl<'fmt, Context> From<&'fmt Argument<'fmt, Context>> for Arguments<'fmt, Context> {
fn from(argument: &'fmt Argument<'fmt, Context>) -> Self {
Arguments::new(std::slice::from_ref(argument))
}
}
#[cfg(test)]
mod tests {
use crate::format_element::tag::Tag;
use crate::prelude::*;
use crate::{format_args, write, FormatState, VecBuffer};
#[test]
fn test_nesting() {
let mut context = FormatState::new(());
let mut buffer = VecBuffer::new(&mut context);
write!(
&mut buffer,
[
text("function"),
space(),
text("a"),
space(),
group(&format_args!(text("("), text(")")))
]
)
.unwrap();
assert_eq!(
buffer.into_vec(),
vec![
FormatElement::StaticText { text: "function" },
FormatElement::Space,
FormatElement::StaticText { text: "a" },
FormatElement::Space,
// Group
FormatElement::Tag(Tag::StartGroup(tag::Group::new())),
FormatElement::StaticText { text: "(" },
FormatElement::StaticText { text: ")" },
FormatElement::Tag(Tag::EndGroup)
]
);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/trivia.rs | crates/rome_formatter/src/trivia.rs | //! Provides builders for comments and skipped token trivia.
use crate::format_element::tag::VerbatimKind;
use crate::prelude::*;
use crate::{
comments::{CommentKind, CommentStyle},
write, Argument, Arguments, CstFormatContext, FormatRefWithRule, GroupId, SourceComment,
TextRange,
};
use rome_rowan::{Language, SyntaxNode, SyntaxToken};
#[cfg(debug_assertions)]
use std::cell::Cell;
/// Formats the leading comments of `node`
pub const fn format_leading_comments<L: Language>(
node: &SyntaxNode<L>,
) -> FormatLeadingComments<L> {
FormatLeadingComments::Node(node)
}
/// Formats the leading comments of a node.
#[derive(Debug, Copy, Clone)]
pub enum FormatLeadingComments<'a, L: Language> {
Node(&'a SyntaxNode<L>),
Comments(&'a [SourceComment<L>]),
}
impl<Context> Format<Context> for FormatLeadingComments<'_, Context::Language>
where
Context: CstFormatContext,
{
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
let comments = f.context().comments().clone();
let leading_comments = match self {
FormatLeadingComments::Node(node) => comments.leading_comments(node),
FormatLeadingComments::Comments(comments) => comments,
};
for comment in leading_comments {
let format_comment = FormatRefWithRule::new(comment, Context::CommentRule::default());
write!(f, [format_comment])?;
match comment.kind() {
CommentKind::Block | CommentKind::InlineBlock => {
match comment.lines_after() {
0 => write!(f, [space()])?,
1 => {
if comment.lines_before() == 0 {
write!(f, [soft_line_break_or_space()])?;
} else {
write!(f, [hard_line_break()])?;
}
}
_ => write!(f, [empty_line()])?,
};
}
CommentKind::Line => match comment.lines_after() {
0 | 1 => write!(f, [hard_line_break()])?,
_ => write!(f, [empty_line()])?,
},
}
comment.mark_formatted()
}
Ok(())
}
}
/// Formats the trailing comments of `node`.
pub const fn format_trailing_comments<L: Language>(
node: &SyntaxNode<L>,
) -> FormatTrailingComments<L> {
FormatTrailingComments::Node(node)
}
/// Formats the trailing comments of `node`
#[derive(Debug, Clone, Copy)]
pub enum FormatTrailingComments<'a, L: Language> {
Node(&'a SyntaxNode<L>),
Comments(&'a [SourceComment<L>]),
}
impl<Context> Format<Context> for FormatTrailingComments<'_, Context::Language>
where
Context: CstFormatContext,
{
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
let comments = f.context().comments().clone();
let trailing_comments = match self {
FormatTrailingComments::Node(node) => comments.trailing_comments(node),
FormatTrailingComments::Comments(comments) => comments,
};
let mut total_lines_before = 0;
for comment in trailing_comments {
total_lines_before += comment.lines_before();
let format_comment = FormatRefWithRule::new(comment, Context::CommentRule::default());
// This allows comments at the end of nested structures:
// {
// x: 1,
// y: 2
// // A comment
// }
// Those kinds of comments are almost always leading comments, but
// here it doesn't go "outside" the block and turns it into a
// trailing comment for `2`. We can simulate the above by checking
// if this a comment on its own line; normal trailing comments are
// always at the end of another expression.
if total_lines_before > 0 {
write!(
f,
[
line_suffix(&format_with(|f| {
match comment.lines_before() {
0 | 1 => write!(f, [hard_line_break()])?,
_ => write!(f, [empty_line()])?,
};
write!(f, [format_comment])
})),
expand_parent()
]
)?;
} else {
let content = format_with(|f| write!(f, [space(), format_comment]));
if comment.kind().is_line() {
write!(f, [line_suffix(&content), expand_parent()])?;
} else {
write!(f, [content])?;
}
}
comment.mark_formatted();
}
Ok(())
}
}
/// Formats the dangling comments of `node`.
pub const fn format_dangling_comments<L: Language>(
node: &SyntaxNode<L>,
) -> FormatDanglingComments<L> {
FormatDanglingComments::Node {
node,
indent: DanglingIndentMode::None,
}
}
/// Formats the dangling trivia of `token`.
pub enum FormatDanglingComments<'a, L: Language> {
Node {
node: &'a SyntaxNode<L>,
indent: DanglingIndentMode,
},
Comments {
comments: &'a [SourceComment<L>],
indent: DanglingIndentMode,
},
}
#[derive(Copy, Clone, Debug)]
pub enum DanglingIndentMode {
/// Writes every comment on its own line and indents them with a block indent.
///
/// # Examples
/// ```ignore
/// [
/// /* comment */
/// ]
///
/// [
/// /* comment */
/// /* multiple */
/// ]
/// ```
Block,
/// Writes every comment on its own line and indents them with a soft line indent.
/// Guarantees to write a line break if the last formatted comment is a [line](CommentKind::Line) comment.
///
/// # Examples
///
/// ```ignore
/// [/* comment */]
///
/// [
/// /* comment */
/// /* other */
/// ]
///
/// [
/// // line
/// ]
/// ```
Soft,
/// Writes every comment on its own line.
None,
}
impl<L: Language> FormatDanglingComments<'_, L> {
/// Indents the comments with a [block](DanglingIndentMode::Block) indent.
pub fn with_block_indent(self) -> Self {
self.with_indent_mode(DanglingIndentMode::Block)
}
/// Indents the comments with a [soft block](DanglingIndentMode::Soft) indent.
pub fn with_soft_block_indent(self) -> Self {
self.with_indent_mode(DanglingIndentMode::Soft)
}
fn with_indent_mode(mut self, mode: DanglingIndentMode) -> Self {
match &mut self {
FormatDanglingComments::Node { indent, .. } => *indent = mode,
FormatDanglingComments::Comments { indent, .. } => *indent = mode,
}
self
}
const fn indent(&self) -> DanglingIndentMode {
match self {
FormatDanglingComments::Node { indent, .. } => *indent,
FormatDanglingComments::Comments { indent, .. } => *indent,
}
}
}
impl<Context> Format<Context> for FormatDanglingComments<'_, Context::Language>
where
Context: CstFormatContext,
{
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
let comments = f.context().comments().clone();
let dangling_comments = match self {
FormatDanglingComments::Node { node, .. } => comments.dangling_comments(node),
FormatDanglingComments::Comments { comments, .. } => *comments,
};
if dangling_comments.is_empty() {
return Ok(());
}
let format_dangling_comments = format_with(|f| {
// Write all comments up to the first skipped token trivia or the token
let mut join = f.join_with(hard_line_break());
for comment in dangling_comments {
let format_comment =
FormatRefWithRule::new(comment, Context::CommentRule::default());
join.entry(&format_comment);
comment.mark_formatted();
}
join.finish()?;
if matches!(self.indent(), DanglingIndentMode::Soft)
&& dangling_comments
.last()
.map_or(false, |comment| comment.kind().is_line())
{
write!(f, [hard_line_break()])?;
}
Ok(())
});
match self.indent() {
DanglingIndentMode::Block => {
write!(f, [block_indent(&format_dangling_comments)])
}
DanglingIndentMode::Soft => {
write!(f, [group(&soft_block_indent(&format_dangling_comments))])
}
DanglingIndentMode::None => {
write!(f, [format_dangling_comments])
}
}
}
}
/// Formats a token without its skipped token trivia
///
/// ## Warning
/// It's your responsibility to format any skipped trivia.
pub const fn format_trimmed_token<L: Language>(token: &SyntaxToken<L>) -> FormatTrimmedToken<L> {
FormatTrimmedToken { token }
}
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub struct FormatTrimmedToken<'a, L: Language> {
token: &'a SyntaxToken<L>,
}
impl<L: Language + 'static, C> Format<C> for FormatTrimmedToken<'_, L>
where
C: CstFormatContext<Language = L>,
{
fn fmt(&self, f: &mut Formatter<C>) -> FormatResult<()> {
let trimmed_range = self.token.text_trimmed_range();
located_token_text(self.token, trimmed_range).fmt(f)
}
}
/// Formats the skipped token trivia of a removed token and marks the token as tracked.
pub const fn format_removed<L>(token: &SyntaxToken<L>) -> FormatRemoved<L>
where
L: Language,
{
FormatRemoved { token }
}
/// Formats the trivia of a token that is present in the source text but should be omitted in the
/// formatted output.
pub struct FormatRemoved<'a, L>
where
L: Language,
{
token: &'a SyntaxToken<L>,
}
impl<C, L> Format<C> for FormatRemoved<'_, L>
where
L: Language + 'static,
C: CstFormatContext<Language = L>,
{
fn fmt(&self, f: &mut Formatter<C>) -> FormatResult<()> {
f.state_mut().track_token(self.token);
write!(f, [format_skipped_token_trivia(self.token)])
}
}
/// Print out a `token` from the original source with a different `content`.
///
/// This will print the skipped token trivia that belong to `token` to `content`;
/// `token` is then marked as consumed by the formatter.
pub fn format_replaced<'a, 'content, L, Context>(
token: &'a SyntaxToken<L>,
content: &'content impl Format<Context>,
) -> FormatReplaced<'a, 'content, L, Context>
where
L: Language,
{
FormatReplaced {
token,
content: Argument::new(content),
}
}
/// Formats a token's skipped token trivia but uses the provided content instead
/// of the token in the formatted output.
#[derive(Copy, Clone)]
pub struct FormatReplaced<'a, 'content, L, C>
where
L: Language,
{
token: &'a SyntaxToken<L>,
content: Argument<'content, C>,
}
impl<L, C> Format<C> for FormatReplaced<'_, '_, L, C>
where
L: Language + 'static,
C: CstFormatContext<Language = L>,
{
fn fmt(&self, f: &mut Formatter<C>) -> FormatResult<()> {
f.state_mut().track_token(self.token);
write!(f, [format_skipped_token_trivia(self.token)])?;
f.write_fmt(Arguments::from(&self.content))
}
}
/// Formats the given token only if the group does break and otherwise retains the token's skipped token trivia.
pub fn format_only_if_breaks<'a, 'content, L, Content, Context>(
token: &'a SyntaxToken<L>,
content: &'content Content,
) -> FormatOnlyIfBreaks<'a, 'content, L, Context>
where
L: Language,
Content: Format<Context>,
{
FormatOnlyIfBreaks {
token,
content: Argument::new(content),
group_id: None,
}
}
/// Formats a token with its skipped token trivia that only gets printed if its enclosing
/// group does break but otherwise gets omitted from the formatted output.
pub struct FormatOnlyIfBreaks<'a, 'content, L, C>
where
L: Language,
{
token: &'a SyntaxToken<L>,
content: Argument<'content, C>,
group_id: Option<GroupId>,
}
impl<'a, 'content, L, C> FormatOnlyIfBreaks<'a, 'content, L, C>
where
L: Language,
{
pub fn with_group_id(mut self, group_id: Option<GroupId>) -> Self {
self.group_id = group_id;
self
}
}
impl<L, C> Format<C> for FormatOnlyIfBreaks<'_, '_, L, C>
where
L: Language + 'static,
C: CstFormatContext<Language = L>,
{
fn fmt(&self, f: &mut Formatter<C>) -> FormatResult<()> {
write!(
f,
[if_group_breaks(&Arguments::from(&self.content)).with_group_id(self.group_id),]
)?;
if f.comments().has_skipped(self.token) {
// Print the trivia otherwise
write!(
f,
[
if_group_fits_on_line(&format_skipped_token_trivia(self.token))
.with_group_id(self.group_id)
]
)?;
}
Ok(())
}
}
/// Formats the skipped token trivia of `token`.
pub const fn format_skipped_token_trivia<L: Language>(
token: &SyntaxToken<L>,
) -> FormatSkippedTokenTrivia<L> {
FormatSkippedTokenTrivia { token }
}
/// Formats the skipped token trivia of `token`.
pub struct FormatSkippedTokenTrivia<'a, L: Language> {
token: &'a SyntaxToken<L>,
}
impl<L: Language> FormatSkippedTokenTrivia<'_, L> {
#[cold]
fn fmt_skipped<Context>(&self, f: &mut Formatter<Context>) -> FormatResult<()>
where
Context: CstFormatContext<Language = L>,
{
// Lines/spaces before the next token/comment
let (mut lines, mut spaces) = match self.token.prev_token() {
Some(token) => {
let mut lines = 0u32;
let mut spaces = 0u32;
for piece in token.trailing_trivia().pieces().rev() {
if piece.is_whitespace() {
spaces += 1;
} else if piece.is_newline() {
spaces = 0;
lines += 1;
} else {
break;
}
}
(lines, spaces)
}
None => (0, 0),
};
// The comments between the last skipped token trivia and the token
let mut dangling_comments = Vec::new();
let mut skipped_range: Option<TextRange> = None;
// Iterate over the remaining pieces to find the full range from the first to the last skipped token trivia.
// Extract the comments between the last skipped token trivia and the token.
for piece in self.token.leading_trivia().pieces() {
if piece.is_whitespace() {
spaces += 1;
continue;
}
if piece.is_newline() {
lines += 1;
spaces = 0;
} else if let Some(comment) = piece.as_comments() {
let source_comment = SourceComment {
kind: Context::Style::get_comment_kind(&comment),
lines_before: lines,
lines_after: 0,
piece: comment,
#[cfg(debug_assertions)]
formatted: Cell::new(true),
};
dangling_comments.push(source_comment);
lines = 0;
spaces = 0;
} else if piece.is_skipped() {
skipped_range = Some(match skipped_range {
Some(range) => range.cover(piece.text_range()),
None => {
if dangling_comments.is_empty() {
match lines {
0 if spaces == 0 => {
// Token had no space to previous token nor any preceding comment. Keep it that way
}
0 => write!(f, [space()])?,
_ => write!(f, [hard_line_break()])?,
};
} else {
match lines {
0 => write!(f, [space()])?,
1 => write!(f, [hard_line_break()])?,
_ => write!(f, [empty_line()])?,
};
}
piece.text_range()
}
});
lines = 0;
spaces = 0;
dangling_comments.clear();
}
}
let skipped_range =
skipped_range.unwrap_or_else(|| TextRange::empty(self.token.text_range().start()));
f.write_element(FormatElement::Tag(Tag::StartVerbatim(
VerbatimKind::Verbatim {
length: skipped_range.len(),
},
)))?;
write!(f, [located_token_text(self.token, skipped_range)])?;
f.write_element(FormatElement::Tag(Tag::EndVerbatim))?;
// Write whitespace separator between skipped/last comment and token
if dangling_comments.is_empty() {
match lines {
0 if spaces == 0 => {
// Don't write a space if there was non in the source document
Ok(())
}
0 => write!(f, [space()]),
_ => write!(f, [hard_line_break()]),
}
} else {
match dangling_comments.first().unwrap().lines_before {
0 => write!(f, [space()])?,
1 => write!(f, [hard_line_break()])?,
_ => write!(f, [empty_line()])?,
}
write!(
f,
[FormatDanglingComments::Comments {
comments: &dangling_comments,
indent: DanglingIndentMode::None
}]
)?;
match lines {
0 => write!(f, [space()]),
_ => write!(f, [hard_line_break()]),
}
}
}
}
impl<Context> Format<Context> for FormatSkippedTokenTrivia<'_, Context::Language>
where
Context: CstFormatContext,
{
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
if f.comments().has_skipped(self.token) {
self.fmt_skipped(f)
} else {
Ok(())
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/builders.rs | crates/rome_formatter/src/builders.rs | use crate::format_element::tag::{Condition, Tag};
use crate::prelude::tag::{DedentMode, GroupMode, LabelId};
use crate::prelude::*;
use crate::{format_element, write, Argument, Arguments, GroupId, TextRange, TextSize};
use crate::{Buffer, VecBuffer};
use rome_rowan::{Language, SyntaxNode, SyntaxToken, TextLen, TokenText};
use std::borrow::Cow;
use std::cell::Cell;
use std::marker::PhantomData;
use std::num::NonZeroU8;
use Tag::*;
/// A line break that only gets printed if the enclosing `Group` doesn't fit on a single line.
/// It's omitted if the enclosing `Group` fits on a single line.
/// A soft line break is identical to a hard line break when not enclosed inside of a `Group`.
///
/// # Examples
///
/// Soft line breaks are omitted if the enclosing `Group` fits on a single line
///
/// ```
/// use rome_formatter::{format, format_args};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let elements = format!(SimpleFormatContext::default(), [
/// group(&format_args![text("a,"), soft_line_break(), text("b")])
/// ])?;
///
/// assert_eq!(
/// "a,b",
/// elements.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
/// See [soft_line_break_or_space] if you want to insert a space between the elements if the enclosing
/// `Group` fits on a single line.
///
/// Soft line breaks are emitted if the enclosing `Group` doesn't fit on a single line
/// ```
/// use rome_formatter::{format, format_args, LineWidth, SimpleFormatOptions};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let context = SimpleFormatContext::new(SimpleFormatOptions {
/// line_width: LineWidth::try_from(10).unwrap(),
/// ..SimpleFormatOptions::default()
/// });
///
/// let elements = format!(context, [
/// group(&format_args![
/// text("a long word,"),
/// soft_line_break(),
/// text("so that the group doesn't fit on a single line"),
/// ])
/// ])?;
///
/// assert_eq!(
/// "a long word,\nso that the group doesn't fit on a single line",
/// elements.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
#[inline]
pub const fn soft_line_break() -> Line {
Line::new(LineMode::Soft)
}
/// A forced line break that are always printed. A hard line break forces any enclosing `Group`
/// to be printed over multiple lines.
///
/// # Examples
///
/// It forces a line break, even if the enclosing `Group` would otherwise fit on a single line.
/// ```
/// use rome_formatter::{format, format_args};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let elements = format!(SimpleFormatContext::default(), [
/// group(&format_args![
/// text("a,"),
/// hard_line_break(),
/// text("b"),
/// hard_line_break()
/// ])
/// ])?;
///
/// assert_eq!(
/// "a,\nb\n",
/// elements.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
#[inline]
pub const fn hard_line_break() -> Line {
Line::new(LineMode::Hard)
}
/// A forced empty line. An empty line inserts enough line breaks in the output for
/// the previous and next element to be separated by an empty line.
///
/// # Examples
///
/// ```
/// use rome_formatter::{format, format_args};
/// use rome_formatter::prelude::*;
///
/// fn main() -> FormatResult<()> {
/// let elements = format!(
/// SimpleFormatContext::default(), [
/// group(&format_args![
/// text("a,"),
/// empty_line(),
/// text("b"),
/// empty_line()
/// ])
/// ])?;
///
/// assert_eq!(
/// "a,\n\nb\n\n",
/// elements.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
#[inline]
pub const fn empty_line() -> Line {
Line::new(LineMode::Empty)
}
/// A line break if the enclosing `Group` doesn't fit on a single line, a space otherwise.
///
/// # Examples
///
/// The line breaks are emitted as spaces if the enclosing `Group` fits on a a single line:
/// ```
/// use rome_formatter::{format, format_args};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let elements = format!(SimpleFormatContext::default(), [
/// group(&format_args![
/// text("a,"),
/// soft_line_break_or_space(),
/// text("b"),
/// ])
/// ])?;
///
/// assert_eq!(
/// "a, b",
/// elements.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
///
/// The printer breaks the lines if the enclosing `Group` doesn't fit on a single line:
/// ```
/// use rome_formatter::{format_args, format, LineWidth, SimpleFormatOptions};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let context = SimpleFormatContext::new(SimpleFormatOptions {
/// line_width: LineWidth::try_from(10).unwrap(),
/// ..SimpleFormatOptions::default()
/// });
///
/// let elements = format!(context, [
/// group(&format_args![
/// text("a long word,"),
/// soft_line_break_or_space(),
/// text("so that the group doesn't fit on a single line"),
/// ])
/// ])?;
///
/// assert_eq!(
/// "a long word,\nso that the group doesn't fit on a single line",
/// elements.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
#[inline]
pub const fn soft_line_break_or_space() -> Line {
Line::new(LineMode::SoftOrSpace)
}
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Line {
mode: LineMode,
}
impl Line {
const fn new(mode: LineMode) -> Self {
Self { mode }
}
}
impl<Context> Format<Context> for Line {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Line(self.mode))
}
}
impl std::fmt::Debug for Line {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Line").field(&self.mode).finish()
}
}
/// Creates a token that gets written as is to the output. Make sure to properly escape the text if
/// it's user generated (e.g. a string and not a language keyword).
///
/// # Line feeds
/// Tokens may contain line breaks but they must use the line feeds (`\n`).
/// The [crate::Printer] converts the line feed characters to the character specified in the [crate::PrinterOptions].
///
/// # Examples
///
/// ```
/// use rome_formatter::format;
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let elements = format!(SimpleFormatContext::default(), [text("Hello World")])?;
///
/// assert_eq!(
/// "Hello World",
/// elements.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
///
/// Printing a string literal as a literal requires that the string literal is properly escaped and
/// enclosed in quotes (depending on the target language).
///
/// ```
/// use rome_formatter::format;
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// // the tab must be encoded as \\t to not literally print a tab character ("Hello{tab}World" vs "Hello\tWorld")
/// let elements = format!(SimpleFormatContext::default(), [text("\"Hello\\tWorld\"")])?;
///
/// assert_eq!(r#""Hello\tWorld""#, elements.print()?.as_code());
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn text(text: &'static str) -> StaticText {
debug_assert_no_newlines(text);
StaticText { text }
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct StaticText {
text: &'static str,
}
impl<Context> Format<Context> for StaticText {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::StaticText { text: self.text })
}
}
impl std::fmt::Debug for StaticText {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::write!(f, "StaticToken({})", self.text)
}
}
/// Creates a text from a dynamic string and a range of the input source
pub fn dynamic_text(text: &str, position: TextSize) -> DynamicText {
debug_assert_no_newlines(text);
DynamicText { text, position }
}
#[derive(Eq, PartialEq)]
pub struct DynamicText<'a> {
text: &'a str,
position: TextSize,
}
impl<Context> Format<Context> for DynamicText<'_> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::DynamicText {
text: self.text.to_string().into_boxed_str(),
source_position: self.position,
})
}
}
impl std::fmt::Debug for DynamicText<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::write!(f, "DynamicToken({})", self.text)
}
}
/// String that is the same as in the input source text if `text` is [`Cow::Borrowed`] or
/// some replaced content if `text` is [`Cow::Owned`].
pub fn syntax_token_cow_slice<'a, L: Language>(
text: Cow<'a, str>,
token: &'a SyntaxToken<L>,
start: TextSize,
) -> SyntaxTokenCowSlice<'a, L> {
debug_assert_no_newlines(&text);
SyntaxTokenCowSlice { text, token, start }
}
pub struct SyntaxTokenCowSlice<'a, L: Language> {
text: Cow<'a, str>,
token: &'a SyntaxToken<L>,
start: TextSize,
}
impl<L: Language, Context> Format<Context> for SyntaxTokenCowSlice<'_, L> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
match &self.text {
Cow::Borrowed(text) => {
let range = TextRange::at(self.start, text.text_len());
debug_assert_eq!(
*text,
&self.token.text()[range - self.token.text_range().start()],
"The borrowed string doesn't match the specified token substring. Does the borrowed string belong to this token and range?"
);
let relative_range = range - self.token.text_range().start();
let slice = self.token.token_text().slice(relative_range);
f.write_element(FormatElement::LocatedTokenText {
slice,
source_position: self.start,
})
}
Cow::Owned(text) => f.write_element(FormatElement::DynamicText {
text: text.to_string().into_boxed_str(),
source_position: self.start,
}),
}
}
}
impl<L: Language> std::fmt::Debug for SyntaxTokenCowSlice<'_, L> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::write!(f, "SyntaxTokenCowSlice({})", self.text)
}
}
/// Copies a source text 1:1 into the output text.
pub fn located_token_text<L: Language>(
token: &SyntaxToken<L>,
range: TextRange,
) -> LocatedTokenText {
let relative_range = range - token.text_range().start();
let slice = token.token_text().slice(relative_range);
debug_assert_no_newlines(&slice);
LocatedTokenText {
text: slice,
source_position: range.start(),
}
}
pub struct LocatedTokenText {
text: TokenText,
source_position: TextSize,
}
impl<Context> Format<Context> for LocatedTokenText {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::LocatedTokenText {
slice: self.text.clone(),
source_position: self.source_position,
})
}
}
impl std::fmt::Debug for LocatedTokenText {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::write!(f, "LocatedTokenText({})", self.text)
}
}
fn debug_assert_no_newlines(text: &str) {
debug_assert!(!text.contains('\r'), "The content '{}' contains an unsupported '\\r' line terminator character but text must only use line feeds '\\n' as line separator. Use '\\n' instead of '\\r' and '\\r\\n' to insert a line break in strings.", text);
}
/// Pushes some content to the end of the current line
///
/// ## Examples
///
/// ```
/// use rome_formatter::{format};
/// use rome_formatter::prelude::*;
///
/// fn main() -> FormatResult<()> {
/// let elements = format!(SimpleFormatContext::default(), [
/// text("a"),
/// line_suffix(&text("c")),
/// text("b")
/// ])?;
///
/// assert_eq!(
/// "abc",
/// elements.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn line_suffix<Content, Context>(inner: &Content) -> LineSuffix<Context>
where
Content: Format<Context>,
{
LineSuffix {
content: Argument::new(inner),
}
}
#[derive(Copy, Clone)]
pub struct LineSuffix<'a, Context> {
content: Argument<'a, Context>,
}
impl<Context> Format<Context> for LineSuffix<'_, Context> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Tag(StartLineSuffix))?;
Arguments::from(&self.content).fmt(f)?;
f.write_element(FormatElement::Tag(EndLineSuffix))
}
}
impl<Context> std::fmt::Debug for LineSuffix<'_, Context> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("LineSuffix").field(&"{{content}}").finish()
}
}
/// Inserts a boundary for line suffixes that forces the printer to print all pending line suffixes.
/// Helpful if a line sufix shouldn't pass a certain point.
///
/// ## Examples
///
/// Forces the line suffix "c" to be printed before the token `d`.
/// ```
/// use rome_formatter::format;
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let elements = format!(SimpleFormatContext::default(), [
/// text("a"),
/// line_suffix(&text("c")),
/// text("b"),
/// line_suffix_boundary(),
/// text("d")
/// ])?;
///
/// assert_eq!(
/// "abc\nd",
/// elements.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
pub const fn line_suffix_boundary() -> LineSuffixBoundary {
LineSuffixBoundary
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct LineSuffixBoundary;
impl<Context> Format<Context> for LineSuffixBoundary {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::LineSuffixBoundary)
}
}
/// Marks some content with a label.
///
/// This does not directly influence how this content will be printed, but some
/// parts of the formatter may inspect the [labelled element](Tag::StartLabelled)
/// using [FormatElements::has_label].
///
/// ## Examples
///
/// ```rust
/// # use rome_formatter::prelude::*;
/// # use rome_formatter::{format, write, LineWidth};
///
/// #[derive(Debug, Copy, Clone)]
/// enum MyLabels {
/// Main
/// }
///
/// impl tag::Label for MyLabels {
/// fn id(&self) -> u64 {
/// *self as u64
/// }
///
/// fn debug_name(&self) -> &'static str {
/// match self {
/// Self::Main => "Main"
/// }
/// }
/// }
///
/// # fn main() -> FormatResult<()> {
/// let formatted = format!(
/// SimpleFormatContext::default(),
/// [format_with(|f| {
/// let mut recording = f.start_recording();
/// write!(recording, [
/// labelled(
/// LabelId::of(MyLabels::Main),
/// &text("'I have a label'")
/// )
/// ])?;
///
/// let recorded = recording.stop();
///
/// let is_labelled = recorded.first().map_or(false, |element| element.has_label(LabelId::of(MyLabels::Main)));
///
/// if is_labelled {
/// write!(f, [text(" has label `Main`")])
/// } else {
/// write!(f, [text(" doesn't have label `Main`")])
/// }
/// })]
/// )?;
///
/// assert_eq!("'I have a label' has label `Main`", formatted.print()?.as_code());
/// # Ok(())
/// # }
/// ```
///
/// ## Alternatives
///
/// Use `Memoized.inspect(f)?.has_label(LabelId::of(MyLabels::Main)` if you need to know if some content breaks that should
/// only be written later.
#[inline]
pub fn labelled<Content, Context>(label_id: LabelId, content: &Content) -> FormatLabelled<Context>
where
Content: Format<Context>,
{
FormatLabelled {
label_id,
content: Argument::new(content),
}
}
#[derive(Copy, Clone)]
pub struct FormatLabelled<'a, Context> {
label_id: LabelId,
content: Argument<'a, Context>,
}
impl<Context> Format<Context> for FormatLabelled<'_, Context> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Tag(StartLabelled(self.label_id)))?;
Arguments::from(&self.content).fmt(f)?;
f.write_element(FormatElement::Tag(EndLabelled))
}
}
impl<Context> std::fmt::Debug for FormatLabelled<'_, Context> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Label")
.field(&self.label_id)
.field(&"{{content}}")
.finish()
}
}
/// Inserts a single space. Allows to separate different tokens.
///
/// # Examples
///
/// ```
/// use rome_formatter::format;
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// // the tab must be encoded as \\t to not literally print a tab character ("Hello{tab}World" vs "Hello\tWorld")
/// let elements = format!(SimpleFormatContext::default(), [text("a"), space(), text("b")])?;
///
/// assert_eq!("a b", elements.print()?.as_code());
/// # Ok(())
/// # }
/// ```
#[inline]
pub const fn space() -> Space {
Space
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct Space;
impl<Context> Format<Context> for Space {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Space)
}
}
/// It adds a level of indentation to the given content
///
/// It doesn't add any line breaks at the edges of the content, meaning that
/// the line breaks have to be manually added.
///
/// This helper should be used only in rare cases, instead you should rely more on
/// [block_indent] and [soft_block_indent]
///
/// # Examples
///
/// ```
/// use rome_formatter::{format, format_args};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let block = format!(SimpleFormatContext::default(), [
/// text("switch {"),
/// block_indent(&format_args![
/// text("default:"),
/// indent(&format_args![
/// // this is where we want to use a
/// hard_line_break(),
/// text("break;"),
/// ])
/// ]),
/// text("}"),
/// ])?;
///
/// assert_eq!(
/// "switch {\n\tdefault:\n\t\tbreak;\n}",
/// block.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn indent<Content, Context>(content: &Content) -> Indent<Context>
where
Content: Format<Context>,
{
Indent {
content: Argument::new(content),
}
}
#[derive(Copy, Clone)]
pub struct Indent<'a, Context> {
content: Argument<'a, Context>,
}
impl<Context> Format<Context> for Indent<'_, Context> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Tag(StartIndent))?;
Arguments::from(&self.content).fmt(f)?;
f.write_element(FormatElement::Tag(EndIndent))
}
}
impl<Context> std::fmt::Debug for Indent<'_, Context> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Indent").field(&"{{content}}").finish()
}
}
/// It reduces the indention for the given content depending on the closest [indent] or [align] parent element.
/// * [align] Undoes the spaces added by [align]
/// * [indent] Reduces the indention level by one
///
/// This is a No-op if the indention level is zero.
///
/// # Examples
///
/// ```
/// use rome_formatter::{format, format_args};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let block = format!(SimpleFormatContext::default(), [
/// text("root"),
/// align(2, &format_args![
/// hard_line_break(),
/// text("aligned"),
/// dedent(&format_args![
/// hard_line_break(),
/// text("not aligned"),
/// ]),
/// dedent(&indent(&format_args![
/// hard_line_break(),
/// text("Indented, not aligned")
/// ]))
/// ]),
/// dedent(&format_args![
/// hard_line_break(),
/// text("Dedent on root level is a no-op.")
/// ])
/// ])?;
///
/// assert_eq!(
/// "root\n aligned\nnot aligned\n\tIndented, not aligned\nDedent on root level is a no-op.",
/// block.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn dedent<Content, Context>(content: &Content) -> Dedent<Context>
where
Content: Format<Context>,
{
Dedent {
content: Argument::new(content),
mode: DedentMode::Level,
}
}
#[derive(Copy, Clone)]
pub struct Dedent<'a, Context> {
content: Argument<'a, Context>,
mode: DedentMode,
}
impl<Context> Format<Context> for Dedent<'_, Context> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Tag(StartDedent(self.mode)))?;
Arguments::from(&self.content).fmt(f)?;
f.write_element(FormatElement::Tag(EndDedent))
}
}
impl<Context> std::fmt::Debug for Dedent<'_, Context> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Dedent").field(&"{{content}}").finish()
}
}
/// It resets the indent document so that the content will be printed at the start of the line.
///
/// # Examples
///
/// ```
/// use rome_formatter::{format, format_args};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let block = format!(SimpleFormatContext::default(), [
/// text("root"),
/// indent(&format_args![
/// hard_line_break(),
/// text("indent level 1"),
/// indent(&format_args![
/// hard_line_break(),
/// text("indent level 2"),
/// align(2, &format_args![
/// hard_line_break(),
/// text("two space align"),
/// dedent_to_root(&format_args![
/// hard_line_break(),
/// text("starts at the beginning of the line")
/// ]),
/// ]),
/// hard_line_break(),
/// text("end indent level 2"),
/// ])
/// ]),
/// ])?;
///
/// assert_eq!(
/// "root\n\tindent level 1\n\t\tindent level 2\n\t\t two space align\nstarts at the beginning of the line\n\t\tend indent level 2",
/// block.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
///
/// ## Prettier
///
/// This resembles the behaviour of Prettier's `align(Number.NEGATIVE_INFINITY, content)` IR element.
#[inline]
pub fn dedent_to_root<Content, Context>(content: &Content) -> Dedent<Context>
where
Content: Format<Context>,
{
Dedent {
content: Argument::new(content),
mode: DedentMode::Root,
}
}
/// Aligns its content by indenting the content by `count` spaces.
///
/// [align] is a variant of `[indent]` that indents its content by a specified number of spaces rather than
/// using the configured indent character (tab or a specified number of spaces).
///
/// You should use [align] when you want to indent a content by a specific number of spaces.
/// Using [indent] is preferred in all other situations as it respects the users preferred indent character.
///
/// # Examples
///
/// ## Tab indention
///
/// ```
/// use std::num::NonZeroU8;
/// use rome_formatter::{format, format_args};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let block = format!(SimpleFormatContext::default(), [
/// text("a"),
/// hard_line_break(),
/// text("?"),
/// space(),
/// align(2, &format_args![
/// text("function () {"),
/// hard_line_break(),
/// text("}"),
/// ]),
/// hard_line_break(),
/// text(":"),
/// space(),
/// align(2, &format_args![
/// text("function () {"),
/// block_indent(&text("console.log('test');")),
/// text("}"),
/// ]),
/// text(";")
/// ])?;
///
/// assert_eq!(
/// "a\n? function () {\n }\n: function () {\n\t\tconsole.log('test');\n };",
/// block.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
///
/// You can see that:
///
/// * the printer indents the function's `}` by two spaces because it is inside of an `align`.
/// * the block `console.log` gets indented by two tabs.
/// This is because `align` increases the indention level by one (same as `indent`)
/// if you nest an `indent` inside an `align`.
/// Meaning that, `align > ... > indent` results in the same indention as `indent > ... > indent`.
///
/// ## Spaces indention
///
/// ```
/// use std::num::NonZeroU8;
/// use rome_formatter::{format, format_args, IndentStyle, SimpleFormatOptions};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let context = SimpleFormatContext::new(SimpleFormatOptions {
/// indent_style: IndentStyle::Space(4),
/// ..SimpleFormatOptions::default()
/// });
///
/// let block = format!(context, [
/// text("a"),
/// hard_line_break(),
/// text("?"),
/// space(),
/// align(2, &format_args![
/// text("function () {"),
/// hard_line_break(),
/// text("}"),
/// ]),
/// hard_line_break(),
/// text(":"),
/// space(),
/// align(2, &format_args![
/// text("function () {"),
/// block_indent(&text("console.log('test');")),
/// text("}"),
/// ]),
/// text(";")
/// ])?;
///
/// assert_eq!(
/// "a\n? function () {\n }\n: function () {\n console.log('test');\n };",
/// block.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
///
/// The printing of `align` differs if using spaces as indention sequence *and* it contains an `indent`.
/// You can see the difference when comparing the indention of the `console.log(...)` expression to the previous example:
///
/// * tab indention: Printer indents the expression with two tabs because the `align` increases the indention level.
/// * space indention: Printer indents the expression by 4 spaces (one indention level) **and** 2 spaces for the align.
pub fn align<Content, Context>(count: u8, content: &Content) -> Align<Context>
where
Content: Format<Context>,
{
Align {
count: NonZeroU8::new(count).expect("Alignment count must be a non-zero number."),
content: Argument::new(content),
}
}
#[derive(Copy, Clone)]
pub struct Align<'a, Context> {
count: NonZeroU8,
content: Argument<'a, Context>,
}
impl<Context> Format<Context> for Align<'_, Context> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
f.write_element(FormatElement::Tag(StartAlign(tag::Align(self.count))))?;
Arguments::from(&self.content).fmt(f)?;
f.write_element(FormatElement::Tag(EndAlign))
}
}
impl<Context> std::fmt::Debug for Align<'_, Context> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Align")
.field("count", &self.count)
.field("content", &"{{content}}")
.finish()
}
}
/// Inserts a hard line break before and after the content and increases the indention level for the content by one.
///
/// Block indents indent a block of code, such as in a function body, and therefore insert a line
/// break before and after the content.
///
/// Doesn't create an indention if the passed in content is [FormatElement.is_empty].
///
/// # Examples
///
/// ```
/// use rome_formatter::{format, format_args};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let block = format![
/// SimpleFormatContext::default(),
/// [
/// text("{"),
/// block_indent(&format_args![
/// text("let a = 10;"),
/// hard_line_break(),
/// text("let c = a + 5;"),
/// ]),
/// text("}"),
/// ]
/// ]?;
///
/// assert_eq!(
/// "{\n\tlet a = 10;\n\tlet c = a + 5;\n}",
/// block.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn block_indent<Context>(content: &impl Format<Context>) -> BlockIndent<Context> {
BlockIndent {
content: Argument::new(content),
mode: IndentMode::Block,
}
}
/// Indents the content by inserting a line break before and after the content and increasing
/// the indention level for the content by one if the enclosing group doesn't fit on a single line.
/// Doesn't change the formatting if the enclosing group fits on a single line.
///
/// # Examples
///
/// Indents the content by one level and puts in new lines if the enclosing `Group` doesn't fit on a single line
///
/// ```
/// use rome_formatter::{format, format_args, LineWidth, SimpleFormatOptions};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let context = SimpleFormatContext::new(SimpleFormatOptions {
/// line_width: LineWidth::try_from(10).unwrap(),
/// ..SimpleFormatOptions::default()
/// });
///
/// let elements = format!(context, [
/// group(&format_args![
/// text("["),
/// soft_block_indent(&format_args![
/// text("'First string',"),
/// soft_line_break_or_space(),
/// text("'second string',"),
/// ]),
/// text("]"),
/// ])
/// ])?;
///
/// assert_eq!(
/// "[\n\t'First string',\n\t'second string',\n]",
/// elements.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
///
/// Doesn't change the formatting if the enclosing `Group` fits on a single line
/// ```
/// use rome_formatter::{format, format_args};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let elements = format!(SimpleFormatContext::default(), [
/// group(&format_args![
/// text("["),
/// soft_block_indent(&format_args![
/// text("5,"),
/// soft_line_break_or_space(),
/// text("10"),
/// ]),
/// text("]"),
/// ])
/// ])?;
///
/// assert_eq!(
/// "[5, 10]",
/// elements.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn soft_block_indent<Context>(content: &impl Format<Context>) -> BlockIndent<Context> {
BlockIndent {
content: Argument::new(content),
mode: IndentMode::Soft,
}
}
/// If the enclosing `Group` doesn't fit on a single line, inserts a line break and indent.
/// Otherwise, just inserts a space.
///
/// Line indents are used to break a single line of code, and therefore only insert a line
/// break before the content and not after the content.
///
/// # Examples
///
/// Indents the content by one level and puts in new lines if the enclosing `Group` doesn't
/// fit on a single line. Otherwise, just inserts a space.
///
/// ```
/// use rome_formatter::{format, format_args, LineWidth, SimpleFormatOptions};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let context = SimpleFormatContext::new(SimpleFormatOptions {
/// line_width: LineWidth::try_from(10).unwrap(),
/// ..SimpleFormatOptions::default()
/// });
///
/// let elements = format!(context, [
/// group(&format_args![
/// text("name"),
/// space(),
/// text("="),
/// soft_line_indent_or_space(&format_args![
/// text("firstName"),
/// space(),
/// text("+"),
/// space(),
/// text("lastName"),
/// ]),
/// ])
/// ])?;
///
/// assert_eq!(
/// "name =\n\tfirstName + lastName",
/// elements.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
///
/// Only adds a space if the enclosing `Group` fits on a single line
/// ```
/// use rome_formatter::{format, format_args};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let elements = format!(SimpleFormatContext::default(), [
/// group(&format_args![
/// text("a"),
/// space(),
/// text("="),
/// soft_line_indent_or_space(&text("10")),
/// ])
/// ])?;
///
/// assert_eq!(
/// "a = 10",
/// elements.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn soft_line_indent_or_space<Context>(content: &impl Format<Context>) -> BlockIndent<Context> {
BlockIndent {
content: Argument::new(content),
mode: IndentMode::SoftLineOrSpace,
}
}
#[derive(Copy, Clone)]
pub struct BlockIndent<'a, Context> {
content: Argument<'a, Context>,
mode: IndentMode,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum IndentMode {
Soft,
Block,
SoftSpace,
SoftLineOrSpace,
}
impl<Context> Format<Context> for BlockIndent<'_, Context> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
let snapshot = f.snapshot();
f.write_element(FormatElement::Tag(StartIndent))?;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/macros.rs | crates/rome_formatter/src/macros.rs | /// Constructs the parameters for other formatting macros.
///
/// This macro functions by taking a list of objects implementing [crate::Format]. It canonicalize the
/// arguments into a single type.
///
/// This macro produces a value of type [crate::Arguments]. This value can be passed to
/// the macros within [crate]. All other formatting macros ([`format!`](crate::format!),
/// [`write!`](crate::write!)) are proxied through this one. This macro avoids heap allocations.
///
/// You can use the [`Arguments`] value that `format_args!` returns in `Format` contexts
/// as seen below.
///
/// ```rust
/// use rome_formatter::{SimpleFormatContext, format, format_args};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let formatted = format!(SimpleFormatContext::default(), [
/// format_args!(text("Hello World"))
/// ])?;
///
/// assert_eq!("Hello World", formatted.print()?.as_code());
/// # Ok(())
/// # }
/// ```
///
/// [`Format`]: crate::Format
/// [`Arguments`]: crate::Arguments
#[macro_export]
macro_rules! format_args {
($($value:expr),+ $(,)?) => {
$crate::Arguments::new(&[
$(
$crate::Argument::new(&$value)
),+
])
}
}
/// Writes formatted data into a buffer.
///
/// This macro accepts a 'buffer' and a list of format arguments. Each argument will be formatted
/// and the result will be passed to the buffer. The writer may be any value with a `write_fmt` method;
/// generally this comes from an implementation of the [crate::Buffer] trait.
///
/// # Examples
///
/// ```rust
/// use rome_formatter::prelude::*;
/// use rome_formatter::{Buffer, FormatState, SimpleFormatContext, VecBuffer, write};
///
/// # fn main() -> FormatResult<()> {
/// let mut state = FormatState::new(SimpleFormatContext::default());
/// let mut buffer = VecBuffer::new(&mut state);
/// write!(&mut buffer, [text("Hello"), space()])?;
/// write!(&mut buffer, [text("World")])?;
///
/// assert_eq!(
/// buffer.into_vec(),
/// vec![
/// FormatElement::StaticText { text: "Hello" },
/// FormatElement::Space,
/// FormatElement::StaticText { text: "World" },
/// ]
/// );
/// # Ok(())
/// # }
/// ```
#[macro_export]
macro_rules! write {
($dst:expr, [$($arg:expr),+ $(,)?]) => {{
let result = $dst.write_fmt($crate::format_args!($($arg),+));
result
}}
}
/// Writes formatted data into the given buffer and prints all written elements for a quick and dirty debugging.
///
/// An example:
///
/// ```rust
/// use rome_formatter::prelude::*;
/// use rome_formatter::{FormatState, VecBuffer};
///
/// # fn main() -> FormatResult<()> {
/// let mut state = FormatState::new(SimpleFormatContext::default());
/// let mut buffer = VecBuffer::new(&mut state);
///
/// dbg_write!(buffer, [text("Hello")])?;
/// // ^-- prints: [src/main.rs:7][0] = StaticToken("Hello")
///
/// assert_eq!(buffer.into_vec(), vec![FormatElement::StaticText { text: "Hello" }]);
/// # Ok(())
/// # }
/// ```
///
/// Note that the macro is intended as debugging tool and therefore you should avoid having
/// uses of it in version control for long periods (other than in tests and similar). Format output
/// from production code is better done with `[write!]`
#[macro_export]
macro_rules! dbg_write {
($dst:expr, [$($arg:expr),+ $(,)?]) => {{
use $crate::BufferExtensions;
let mut count = 0;
let mut inspect = $dst.inspect(|element: &FormatElement| {
std::eprintln!(
"[{}:{}][{}] = {element:#?}",
std::file!(), std::line!(), count
);
count += 1;
});
let result = inspect.write_fmt($crate::format_args!($($arg),+));
result
}}
}
/// Creates the Format IR for a value.
///
/// The first argument `format!` receives is the [crate::FormatContext] that specify how elements must be formatted.
/// Additional parameters passed get formatted by using their [crate::Format] implementation.
///
///
/// ## Examples
///
/// ```
/// use rome_formatter::prelude::*;
/// use rome_formatter::format;
///
/// let formatted = format!(SimpleFormatContext::default(), [text("("), text("a"), text(")")]).unwrap();
///
/// assert_eq!(
/// formatted.into_document(),
/// Document::from(vec![
/// FormatElement::StaticText { text: "(" },
/// FormatElement::StaticText { text: "a" },
/// FormatElement::StaticText { text: ")" },
/// ])
/// );
/// ```
#[macro_export]
macro_rules! format {
($context:expr, [$($arg:expr),+ $(,)?]) => {{
($crate::format($context, $crate::format_args!($($arg),+)))
}}
}
/// Provides multiple different alternatives and the printer picks the first one that fits.
/// Use this as last resort because it requires that the printer must try all variants in the worst case.
/// The passed variants must be in the following order:
/// * First: The variant that takes up most space horizontally
/// * Last: The variant that takes up the least space horizontally by splitting the content over multiple lines.
///
/// ## Examples
///
/// ```
/// use rome_formatter::{Formatted, LineWidth, format, format_args, SimpleFormatOptions};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let formatted = format!(
/// SimpleFormatContext::default(),
/// [
/// text("aVeryLongIdentifier"),
/// best_fitting!(
/// // Everything fits on a single line
/// format_args!(
/// text("("),
/// group(&format_args![
/// text("["),
/// soft_block_indent(&format_args![
/// text("1,"),
/// soft_line_break_or_space(),
/// text("2,"),
/// soft_line_break_or_space(),
/// text("3"),
/// ]),
/// text("]")
/// ]),
/// text(")")
/// ),
///
/// // Breaks after `[`, but prints all elements on a single line
/// format_args!(
/// text("("),
/// text("["),
/// block_indent(&text("1, 2, 3")),
/// text("]"),
/// text(")"),
/// ),
///
/// // Breaks after `[` and prints each element on a single line
/// format_args!(
/// text("("),
/// block_indent(&format_args![
/// text("["),
/// block_indent(&format_args![
/// text("1,"),
/// hard_line_break(),
/// text("2,"),
/// hard_line_break(),
/// text("3"),
/// ]),
/// text("]"),
/// ]),
/// text(")")
/// )
/// )
/// ]
/// )?;
///
/// let document = formatted.into_document();
///
/// // Takes the first variant if everything fits on a single line
/// assert_eq!(
/// "aVeryLongIdentifier([1, 2, 3])",
/// Formatted::new(document.clone(), SimpleFormatContext::default())
/// .print()?
/// .as_code()
/// );
///
/// // It takes the second if the first variant doesn't fit on a single line. The second variant
/// // has some additional line breaks to make sure inner groups don't break
/// assert_eq!(
/// "aVeryLongIdentifier([\n\t1, 2, 3\n])",
/// Formatted::new(document.clone(), SimpleFormatContext::new(SimpleFormatOptions { line_width: 21.try_into().unwrap(), ..SimpleFormatOptions::default() }))
/// .print()?
/// .as_code()
/// );
///
/// // Prints the last option as last resort
/// assert_eq!(
/// "aVeryLongIdentifier(\n\t[\n\t\t1,\n\t\t2,\n\t\t3\n\t]\n)",
/// Formatted::new(document.clone(), SimpleFormatContext::new(SimpleFormatOptions { line_width: 20.try_into().unwrap(), ..SimpleFormatOptions::default() }))
/// .print()?
/// .as_code()
/// );
/// # Ok(())
/// # }
/// ```
///
/// ### Enclosing group with `should_expand: true`
///
/// ```
/// use rome_formatter::{Formatted, LineWidth, format, format_args, SimpleFormatOptions};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let formatted = format!(
/// SimpleFormatContext::default(),
/// [
/// best_fitting!(
/// // Prints the method call on the line but breaks the array.
/// format_args!(
/// text("expect(a).toMatch("),
/// group(&format_args![
/// text("["),
/// soft_block_indent(&format_args![
/// text("1,"),
/// soft_line_break_or_space(),
/// text("2,"),
/// soft_line_break_or_space(),
/// text("3"),
/// ]),
/// text("]")
/// ]).should_expand(true),
/// text(")")
/// ),
///
/// // Breaks after `(`
/// format_args!(
/// text("expect(a).toMatch("),
/// group(&soft_block_indent(
/// &group(&format_args![
/// text("["),
/// soft_block_indent(&format_args![
/// text("1,"),
/// soft_line_break_or_space(),
/// text("2,"),
/// soft_line_break_or_space(),
/// text("3"),
/// ]),
/// text("]")
/// ]).should_expand(true),
/// )).should_expand(true),
/// text(")")
/// ),
/// )
/// ]
/// )?;
///
/// let document = formatted.into_document();
///
/// assert_eq!(
/// "expect(a).toMatch([\n\t1,\n\t2,\n\t3\n])",
/// Formatted::new(document.clone(), SimpleFormatContext::default())
/// .print()?
/// .as_code()
/// );
///
/// # Ok(())
/// # }
/// ```
///
/// The first variant fits because all its content up to the first line break fit on the line without exceeding
/// the configured print width.
///
/// ## Complexity
/// Be mindful of using this IR element as it has a considerable performance penalty:
/// * There are multiple representation for the same content. This results in increased memory usage
/// and traversal time in the printer.
/// * The worst case complexity is that the printer tires each variant. This can result in quadratic
/// complexity if used in nested structures.
///
/// ## Behavior
/// This IR is similar to Prettier's `conditionalGroup`. The printer measures each variant, except the [`MostExpanded`], in [`Flat`] mode
/// to find the first variant that fits and prints this variant in [`Flat`] mode. If no variant fits, then
/// the printer falls back to printing the [`MostExpanded`] variant in `[`Expanded`] mode.
///
/// The definition of *fits* differs to groups in that the printer only tests if it is possible to print
/// the content up to the first non-soft line break without exceeding the configured print width.
/// This definition differs from groups as that non-soft line breaks make group expand.
///
/// [crate::BestFitting] acts as a "break" boundary, meaning that it is considered to fit
///
///
/// [`Flat`]: crate::format_element::PrintMode::Flat
/// [`Expanded`]: crate::format_element::PrintMode::Expanded
/// [`MostExpanded`]: crate::format_element::BestFittingElement::most_expanded
#[macro_export]
macro_rules! best_fitting {
($least_expanded:expr, $($tail:expr),+ $(,)?) => {{
unsafe {
$crate::BestFitting::from_arguments_unchecked($crate::format_args!($least_expanded, $($tail),+))
}
}}
}
#[cfg(test)]
mod tests {
use crate::prelude::*;
use crate::{write, FormatState, SimpleFormatOptions, VecBuffer};
struct TestFormat;
impl Format<()> for TestFormat {
fn fmt(&self, f: &mut Formatter<()>) -> FormatResult<()> {
write!(f, [text("test")])
}
}
#[test]
fn test_single_element() {
let mut state = FormatState::new(());
let mut buffer = VecBuffer::new(&mut state);
write![&mut buffer, [TestFormat]].unwrap();
assert_eq!(
buffer.into_vec(),
vec![FormatElement::StaticText { text: "test" }]
);
}
#[test]
fn test_multiple_elements() {
let mut state = FormatState::new(());
let mut buffer = VecBuffer::new(&mut state);
write![
&mut buffer,
[text("a"), space(), text("simple"), space(), TestFormat]
]
.unwrap();
assert_eq!(
buffer.into_vec(),
vec![
FormatElement::StaticText { text: "a" },
FormatElement::Space,
FormatElement::StaticText { text: "simple" },
FormatElement::Space,
FormatElement::StaticText { text: "test" }
]
);
}
#[test]
fn best_fitting_variants_print_as_lists() {
use crate::prelude::*;
use crate::{format, format_args, Formatted};
// The second variant below should be selected when printing at a width of 30
let formatted_best_fitting = format!(
SimpleFormatContext::default(),
[
text("aVeryLongIdentifier"),
soft_line_break_or_space(),
best_fitting![
format_args![text(
"Something that will not fit on a line with 30 character print width."
)],
format_args![group(&format_args![
text("Start"),
soft_line_break(),
group(&soft_block_indent(&format_args![
text("1,"),
soft_line_break_or_space(),
text("2,"),
soft_line_break_or_space(),
text("3"),
])),
soft_line_break_or_space(),
soft_block_indent(&format_args![
text("1,"),
soft_line_break_or_space(),
text("2,"),
soft_line_break_or_space(),
group(&format_args!(
text("A,"),
soft_line_break_or_space(),
text("B")
)),
soft_line_break_or_space(),
text("3")
]),
soft_line_break_or_space(),
text("End")
])
.should_expand(true)],
format_args!(text("Most"), hard_line_break(), text("Expanded"))
]
]
)
.unwrap();
// This matches the IR above except that the `best_fitting` was replaced with
// the contents of its second variant.
let formatted_normal_list = format!(
SimpleFormatContext::default(),
[
text("aVeryLongIdentifier"),
soft_line_break_or_space(),
format_args![
text("Start"),
soft_line_break(),
&group(&soft_block_indent(&format_args![
text("1,"),
soft_line_break_or_space(),
text("2,"),
soft_line_break_or_space(),
text("3"),
])),
soft_line_break_or_space(),
&soft_block_indent(&format_args![
text("1,"),
soft_line_break_or_space(),
text("2,"),
soft_line_break_or_space(),
group(&format_args!(
text("A,"),
soft_line_break_or_space(),
text("B")
)),
soft_line_break_or_space(),
text("3")
]),
soft_line_break_or_space(),
text("End")
],
]
)
.unwrap();
let best_fitting_code = Formatted::new(
formatted_best_fitting.into_document(),
SimpleFormatContext::new(SimpleFormatOptions {
line_width: 30.try_into().unwrap(),
..SimpleFormatOptions::default()
}),
)
.print()
.expect("Document to be valid")
.as_code()
.to_string();
let normal_list_code = Formatted::new(
formatted_normal_list.into_document(),
SimpleFormatContext::new(SimpleFormatOptions {
line_width: 30.try_into().unwrap(),
..SimpleFormatOptions::default()
}),
)
.print()
.expect("Document to be valid")
.as_code()
.to_string();
// The variant that "fits" will print its contents as if it were a normal list
// outside of a BestFitting element.
assert_eq!(best_fitting_code, normal_list_code);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/group_id.rs | crates/rome_formatter/src/group_id.rs | use std::num::NonZeroU32;
use std::sync::atomic::{AtomicU32, Ordering};
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub struct DebugGroupId {
value: NonZeroU32,
name: &'static str,
}
impl DebugGroupId {
#[allow(unused)]
fn new(value: NonZeroU32, debug_name: &'static str) -> Self {
Self {
value,
name: debug_name,
}
}
}
impl std::fmt::Debug for DebugGroupId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "#{}-{}", self.name, self.value)
}
}
/// Unique identification for a group.
///
/// See [crate::Formatter::group_id] on how to get a unique id.
#[repr(transparent)]
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub struct ReleaseGroupId {
value: NonZeroU32,
}
impl ReleaseGroupId {
/// Creates a new unique group id with the given debug name (only stored in debug builds)
#[allow(unused)]
fn new(value: NonZeroU32, _: &'static str) -> Self {
Self { value }
}
}
impl From<GroupId> for u32 {
fn from(id: GroupId) -> Self {
id.value.get()
}
}
impl std::fmt::Debug for ReleaseGroupId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "#{}", self.value)
}
}
#[cfg(not(debug_assertions))]
pub type GroupId = ReleaseGroupId;
#[cfg(debug_assertions)]
pub type GroupId = DebugGroupId;
/// Builder to construct unique group ids that are unique if created with the same builder.
pub(super) struct UniqueGroupIdBuilder {
next_id: AtomicU32,
}
impl UniqueGroupIdBuilder {
/// Creates a new unique group id with the given debug name.
pub fn group_id(&self, debug_name: &'static str) -> GroupId {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let id = NonZeroU32::new(id).unwrap_or_else(|| panic!("Group ID counter overflowed"));
GroupId::new(id, debug_name)
}
}
impl Default for UniqueGroupIdBuilder {
fn default() -> Self {
UniqueGroupIdBuilder {
// Start with 1 because `GroupId` wraps a `NonZeroU32` to reduce memory usage.
next_id: AtomicU32::new(1),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/verbatim.rs | crates/rome_formatter/src/verbatim.rs | use crate::format_element::tag::VerbatimKind;
use crate::prelude::*;
use crate::trivia::{FormatLeadingComments, FormatTrailingComments};
use crate::{write, CstFormatContext, FormatWithRule};
use rome_rowan::{AstNode, Direction, Language, SyntaxElement, SyntaxNode, TextRange};
/// "Formats" a node according to its original formatting in the source text. Being able to format
/// a node "as is" is useful if a node contains syntax errors. Formatting a node with syntax errors
/// has the risk that Rome misinterprets the structure of the code and formatting it could
/// "mess up" the developers, yet incomplete, work or accidentally introduce new syntax errors.
///
/// You may be inclined to call `node.text` directly. However, using `text` doesn't track the nodes
/// nor its children source mapping information, resulting in incorrect source maps for this subtree.
///
/// These nodes and tokens get tracked as [VerbatimKind::Verbatim], useful to understand
/// if these nodes still need to have their own implementation.
pub fn format_verbatim_node<L: Language>(node: &SyntaxNode<L>) -> FormatVerbatimNode<L> {
FormatVerbatimNode {
node,
kind: VerbatimKind::Verbatim {
length: node.text_range().len(),
},
format_comments: true,
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct FormatVerbatimNode<'node, L: Language> {
node: &'node SyntaxNode<L>,
kind: VerbatimKind,
format_comments: bool,
}
impl<Context> Format<Context> for FormatVerbatimNode<'_, Context::Language>
where
Context: CstFormatContext,
{
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
for element in self.node.descendants_with_tokens(Direction::Next) {
match element {
SyntaxElement::Token(token) => f.state_mut().track_token(&token),
SyntaxElement::Node(node) => {
let comments = f.context().comments();
comments.mark_suppression_checked(&node);
for comment in comments.leading_dangling_trailing_comments(&node) {
comment.mark_formatted();
}
}
}
}
// The trimmed range of a node is its range without any of its leading or trailing trivia.
// Except for nodes that used to be parenthesized, the range than covers the source from the
// `(` to the `)` (the trimmed range of the parenthesized expression, not the inner expression)
let trimmed_source_range = f.context().source_map().map_or_else(
|| self.node.text_trimmed_range(),
|source_map| source_map.trimmed_source_range(self.node),
);
f.write_element(FormatElement::Tag(Tag::StartVerbatim(self.kind)))?;
fn source_range<Context>(f: &Formatter<Context>, range: TextRange) -> TextRange
where
Context: CstFormatContext,
{
f.context()
.source_map()
.map_or_else(|| range, |source_map| source_map.source_range(range))
}
// Format all leading comments that are outside of the node's source range.
if self.format_comments {
let comments = f.context().comments().clone();
let leading_comments = comments.leading_comments(self.node);
let outside_trimmed_range = leading_comments.partition_point(|comment| {
comment.piece().text_range().end() <= trimmed_source_range.start()
});
let (outside_trimmed_range, in_trimmed_range) =
leading_comments.split_at(outside_trimmed_range);
write!(f, [FormatLeadingComments::Comments(outside_trimmed_range)])?;
for comment in in_trimmed_range {
comment.mark_formatted();
}
}
// Find the first skipped token trivia, if any, and include it in the verbatim range because
// the comments only format **up to** but not including skipped token trivia.
let start_source = self
.node
.first_leading_trivia()
.into_iter()
.flat_map(|trivia| trivia.pieces())
.filter(|trivia| trivia.is_skipped())
.map(|trivia| source_range(f, trivia.text_range()).start())
.take_while(|start| *start < trimmed_source_range.start())
.next()
.unwrap_or_else(|| trimmed_source_range.start());
let original_source = f.context().source_map().map_or_else(
|| self.node.text_trimmed().to_string(),
|source_map| {
source_map
.source()
.text_slice(trimmed_source_range.cover_offset(start_source))
.to_string()
},
);
dynamic_text(
&normalize_newlines(&original_source, LINE_TERMINATORS),
self.node.text_trimmed_range().start(),
)
.fmt(f)?;
for comment in f.context().comments().dangling_comments(self.node) {
comment.mark_formatted();
}
// Format all trailing comments that are outside of the trimmed range.
if self.format_comments {
let comments = f.context().comments().clone();
let trailing_comments = comments.trailing_comments(self.node);
let outside_trimmed_range_start = trailing_comments.partition_point(|comment| {
source_range(f, comment.piece().text_range()).end() <= trimmed_source_range.end()
});
let (in_trimmed_range, outside_trimmed_range) =
trailing_comments.split_at(outside_trimmed_range_start);
for comment in in_trimmed_range {
comment.mark_formatted();
}
write!(f, [FormatTrailingComments::Comments(outside_trimmed_range)])?;
}
f.write_element(FormatElement::Tag(Tag::EndVerbatim))
}
}
impl<L: Language> FormatVerbatimNode<'_, L> {
pub fn skip_comments(mut self) -> Self {
self.format_comments = false;
self
}
}
/// Formats bogus nodes. The difference between this method and `format_verbatim` is that this method
/// doesn't track nodes/tokens as [VerbatimKind::Verbatim]. They are just printed as they are.
pub fn format_bogus_node<L: Language>(node: &SyntaxNode<L>) -> FormatVerbatimNode<L> {
FormatVerbatimNode {
node,
kind: VerbatimKind::Bogus,
format_comments: true,
}
}
/// Format a node having formatter suppression comment applied to it
pub fn format_suppressed_node<L: Language>(node: &SyntaxNode<L>) -> FormatVerbatimNode<L> {
FormatVerbatimNode {
node,
kind: VerbatimKind::Suppressed,
format_comments: true,
}
}
/// Formats an object using its [`Format`] implementation but falls back to printing the object as
/// it is in the source document if formatting it returns an [`FormatError::SyntaxError`].
pub const fn format_or_verbatim<F>(inner: F) -> FormatNodeOrVerbatim<F> {
FormatNodeOrVerbatim { inner }
}
/// Formats a node or falls back to verbatim printing if formating this node fails.
#[derive(Copy, Clone)]
pub struct FormatNodeOrVerbatim<F> {
inner: F,
}
impl<F, Context, Item> Format<Context> for FormatNodeOrVerbatim<F>
where
F: FormatWithRule<Context, Item = Item>,
Item: AstNode,
Context: CstFormatContext<Language = Item::Language>,
{
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
let snapshot = Formatter::state_snapshot(f);
match self.inner.fmt(f) {
Ok(result) => Ok(result),
Err(FormatError::SyntaxError) => {
f.restore_state_snapshot(snapshot);
// Lists that yield errors are formatted as they were suppressed nodes.
// Doing so, the formatter formats the nodes/tokens as is.
format_suppressed_node(self.inner.item().syntax()).fmt(f)
}
Err(err) => Err(err),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/buffer.rs | crates/rome_formatter/src/buffer.rs | use super::{write, Arguments, FormatElement};
use crate::format_element::Interned;
use crate::prelude::LineMode;
use crate::{Format, FormatResult, FormatState};
use rustc_hash::FxHashMap;
use std::any::{Any, TypeId};
use std::fmt::Debug;
use std::ops::{Deref, DerefMut};
/// A trait for writing or formatting into [FormatElement]-accepting buffers or streams.
pub trait Buffer {
/// The context used during formatting
type Context;
/// Writes a [crate::FormatElement] into this buffer, returning whether the write succeeded.
///
/// # Errors
/// This function will return an instance of [crate::FormatError] on error.
///
/// # Examples
///
/// ```
/// use rome_formatter::{Buffer, FormatElement, FormatState, SimpleFormatContext, VecBuffer};
///
/// let mut state = FormatState::new(SimpleFormatContext::default());
/// let mut buffer = VecBuffer::new(&mut state);
///
/// buffer.write_element(FormatElement::StaticText { text: "test"}).unwrap();
///
/// assert_eq!(buffer.into_vec(), vec![FormatElement::StaticText { text: "test" }]);
/// ```
///
fn write_element(&mut self, element: FormatElement) -> FormatResult<()>;
/// Returns a slice containing all elements written into this buffer.
///
/// Prefer using [BufferExtensions::start_recording] over accessing [Buffer::elements] directly.
#[doc(hidden)]
fn elements(&self) -> &[FormatElement];
/// Glue for usage of the [`write!`] macro with implementors of this trait.
///
/// This method should generally not be invoked manually, but rather through the [`write!`] macro itself.
///
/// # Examples
///
/// ```
/// use rome_formatter::prelude::*;
/// use rome_formatter::{Buffer, FormatState, SimpleFormatContext, VecBuffer, format_args};
///
/// let mut state = FormatState::new(SimpleFormatContext::default());
/// let mut buffer = VecBuffer::new(&mut state);
///
/// buffer.write_fmt(format_args!(text("Hello World"))).unwrap();
///
/// assert_eq!(buffer.into_vec(), vec![FormatElement::StaticText{ text: "Hello World" }]);
/// ```
fn write_fmt(mut self: &mut Self, arguments: Arguments<Self::Context>) -> FormatResult<()> {
write(&mut self, arguments)
}
/// Returns the formatting state relevant for this formatting session.
fn state(&self) -> &FormatState<Self::Context>;
/// Returns the mutable formatting state relevant for this formatting session.
fn state_mut(&mut self) -> &mut FormatState<Self::Context>;
/// Takes a snapshot of the Buffers state, excluding the formatter state.
fn snapshot(&self) -> BufferSnapshot;
/// Restores the snapshot buffer
///
/// ## Panics
/// If the passed snapshot id is a snapshot of another buffer OR
/// if the snapshot is restored out of order
fn restore_snapshot(&mut self, snapshot: BufferSnapshot);
}
/// Snapshot of a buffer state that can be restored at a later point.
///
/// Used in cases where the formatting of an object fails but a parent formatter knows an alternative
/// strategy on how to format the object that might succeed.
#[derive(Debug)]
pub enum BufferSnapshot {
/// Stores an absolute position of a buffers state, for example, the offset of the last written element.
Position(usize),
/// Generic structure for custom buffers that need to store more complex data. Slightly more
/// expensive because it requires allocating the buffer state on the heap.
Any(Box<dyn Any>),
}
impl BufferSnapshot {
/// Creates a new buffer snapshot that points to the specified position.
pub const fn position(index: usize) -> Self {
Self::Position(index)
}
/// Unwraps the position value.
///
/// # Panics
///
/// If self is not a [`BufferSnapshot::Position`]
pub fn unwrap_position(&self) -> usize {
match self {
BufferSnapshot::Position(index) => *index,
BufferSnapshot::Any(_) => panic!("Tried to unwrap Any snapshot as a position."),
}
}
/// Unwraps the any value.
///
/// # Panics
///
/// If `self` is not a [`BufferSnapshot::Any`].
pub fn unwrap_any<T: 'static>(self) -> T {
match self {
BufferSnapshot::Position(_) => {
panic!("Tried to unwrap Position snapshot as Any snapshot.")
}
BufferSnapshot::Any(value) => match value.downcast::<T>() {
Ok(snapshot) => *snapshot,
Err(err) => {
panic!(
"Tried to unwrap snapshot of type {:?} as {:?}",
err.type_id(),
TypeId::of::<T>()
)
}
},
}
}
}
/// Implements the `[Buffer]` trait for all mutable references of objects implementing [Buffer].
impl<W: Buffer<Context = Context> + ?Sized, Context> Buffer for &mut W {
type Context = Context;
fn write_element(&mut self, element: FormatElement) -> FormatResult<()> {
(**self).write_element(element)
}
fn elements(&self) -> &[FormatElement] {
(**self).elements()
}
fn write_fmt(&mut self, args: Arguments<Context>) -> FormatResult<()> {
(**self).write_fmt(args)
}
fn state(&self) -> &FormatState<Self::Context> {
(**self).state()
}
fn state_mut(&mut self) -> &mut FormatState<Self::Context> {
(**self).state_mut()
}
fn snapshot(&self) -> BufferSnapshot {
(**self).snapshot()
}
fn restore_snapshot(&mut self, snapshot: BufferSnapshot) {
(**self).restore_snapshot(snapshot)
}
}
/// Vector backed [`Buffer`] implementation.
///
/// The buffer writes all elements into the internal elements buffer.
#[derive(Debug)]
pub struct VecBuffer<'a, Context> {
state: &'a mut FormatState<Context>,
elements: Vec<FormatElement>,
}
impl<'a, Context> VecBuffer<'a, Context> {
pub fn new(state: &'a mut FormatState<Context>) -> Self {
Self::new_with_vec(state, Vec::new())
}
pub fn new_with_vec(state: &'a mut FormatState<Context>, elements: Vec<FormatElement>) -> Self {
Self { state, elements }
}
/// Creates a buffer with the specified capacity
pub fn with_capacity(capacity: usize, state: &'a mut FormatState<Context>) -> Self {
Self {
state,
elements: Vec::with_capacity(capacity),
}
}
/// Consumes the buffer and returns the written [`FormatElement]`s as a vector.
pub fn into_vec(self) -> Vec<FormatElement> {
self.elements
}
/// Takes the elements without consuming self
pub fn take_vec(&mut self) -> Vec<FormatElement> {
std::mem::take(&mut self.elements)
}
}
impl<Context> Deref for VecBuffer<'_, Context> {
type Target = [FormatElement];
fn deref(&self) -> &Self::Target {
&self.elements
}
}
impl<Context> DerefMut for VecBuffer<'_, Context> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.elements
}
}
impl<Context> Buffer for VecBuffer<'_, Context> {
type Context = Context;
fn write_element(&mut self, element: FormatElement) -> FormatResult<()> {
self.elements.push(element);
Ok(())
}
fn elements(&self) -> &[FormatElement] {
self
}
fn state(&self) -> &FormatState<Self::Context> {
self.state
}
fn state_mut(&mut self) -> &mut FormatState<Self::Context> {
self.state
}
fn snapshot(&self) -> BufferSnapshot {
BufferSnapshot::position(self.elements.len())
}
fn restore_snapshot(&mut self, snapshot: BufferSnapshot) {
let position = snapshot.unwrap_position();
assert!(
self.elements.len() >= position,
r#"Outdated snapshot. This buffer contains fewer elements than at the time the snapshot was taken.
Make sure that you take and restore the snapshot in order and that this snapshot belongs to the current buffer."#
);
self.elements.truncate(position);
}
}
/// This struct wraps an existing buffer and emits a preamble text when the first text is written.
///
/// This can be useful if you, for example, want to write some content if what gets written next isn't empty.
///
/// # Examples
///
/// ```
/// use rome_formatter::{FormatState, Formatted, PreambleBuffer, SimpleFormatContext, VecBuffer, write};
/// use rome_formatter::prelude::*;
///
/// struct Preamble;
///
/// impl Format<SimpleFormatContext> for Preamble {
/// fn fmt(&self, f: &mut Formatter<SimpleFormatContext>) -> FormatResult<()> {
/// write!(f, [text("# heading"), hard_line_break()])
/// }
/// }
///
/// # fn main() -> FormatResult<()> {
/// let mut state = FormatState::new(SimpleFormatContext::default());
/// let mut buffer = VecBuffer::new(&mut state);
///
/// {
/// let mut with_preamble = PreambleBuffer::new(&mut buffer, Preamble);
///
/// write!(&mut with_preamble, [text("this text will be on a new line")])?;
/// }
///
/// let formatted = Formatted::new(Document::from(buffer.into_vec()), SimpleFormatContext::default());
/// assert_eq!("# heading\nthis text will be on a new line", formatted.print()?.as_code());
///
/// # Ok(())
/// # }
/// ```
///
/// The pre-amble does not get written if no content is written to the buffer.
///
/// ```
/// use rome_formatter::{FormatState, Formatted, PreambleBuffer, SimpleFormatContext, VecBuffer, write};
/// use rome_formatter::prelude::*;
///
/// struct Preamble;
///
/// impl Format<SimpleFormatContext> for Preamble {
/// fn fmt(&self, f: &mut Formatter<SimpleFormatContext>) -> FormatResult<()> {
/// write!(f, [text("# heading"), hard_line_break()])
/// }
/// }
///
/// # fn main() -> FormatResult<()> {
/// let mut state = FormatState::new(SimpleFormatContext::default());
/// let mut buffer = VecBuffer::new(&mut state);
/// {
/// let mut with_preamble = PreambleBuffer::new(&mut buffer, Preamble);
/// }
///
/// let formatted = Formatted::new(Document::from(buffer.into_vec()), SimpleFormatContext::default());
/// assert_eq!("", formatted.print()?.as_code());
/// # Ok(())
/// # }
/// ```
pub struct PreambleBuffer<'buf, Preamble, Context> {
/// The wrapped buffer
inner: &'buf mut dyn Buffer<Context = Context>,
/// The pre-amble to write once the first content gets written to this buffer.
preamble: Preamble,
/// Whether some content (including the pre-amble) has been written at this point.
empty: bool,
}
impl<'buf, Preamble, Context> PreambleBuffer<'buf, Preamble, Context> {
pub fn new(inner: &'buf mut dyn Buffer<Context = Context>, preamble: Preamble) -> Self {
Self {
inner,
preamble,
empty: true,
}
}
/// Returns `true` if the preamble has been written, `false` otherwise.
pub fn did_write_preamble(&self) -> bool {
!self.empty
}
}
impl<Preamble, Context> Buffer for PreambleBuffer<'_, Preamble, Context>
where
Preamble: Format<Context>,
{
type Context = Context;
fn write_element(&mut self, element: FormatElement) -> FormatResult<()> {
if self.empty {
write!(self.inner, [&self.preamble])?;
self.empty = false;
}
self.inner.write_element(element)
}
fn elements(&self) -> &[FormatElement] {
self.inner.elements()
}
fn state(&self) -> &FormatState<Self::Context> {
self.inner.state()
}
fn state_mut(&mut self) -> &mut FormatState<Self::Context> {
self.inner.state_mut()
}
fn snapshot(&self) -> BufferSnapshot {
BufferSnapshot::Any(Box::new(PreambleBufferSnapshot {
inner: self.inner.snapshot(),
empty: self.empty,
}))
}
fn restore_snapshot(&mut self, snapshot: BufferSnapshot) {
let snapshot = snapshot.unwrap_any::<PreambleBufferSnapshot>();
self.empty = snapshot.empty;
self.inner.restore_snapshot(snapshot.inner);
}
}
struct PreambleBufferSnapshot {
inner: BufferSnapshot,
empty: bool,
}
/// Buffer that allows you inspecting elements as they get written to the formatter.
pub struct Inspect<'inner, Context, Inspector> {
inner: &'inner mut dyn Buffer<Context = Context>,
inspector: Inspector,
}
impl<'inner, Context, Inspector> Inspect<'inner, Context, Inspector> {
fn new(inner: &'inner mut dyn Buffer<Context = Context>, inspector: Inspector) -> Self {
Self { inner, inspector }
}
}
impl<'inner, Context, Inspector> Buffer for Inspect<'inner, Context, Inspector>
where
Inspector: FnMut(&FormatElement),
{
type Context = Context;
fn write_element(&mut self, element: FormatElement) -> FormatResult<()> {
(self.inspector)(&element);
self.inner.write_element(element)
}
fn elements(&self) -> &[FormatElement] {
self.inner.elements()
}
fn state(&self) -> &FormatState<Self::Context> {
self.inner.state()
}
fn state_mut(&mut self) -> &mut FormatState<Self::Context> {
self.inner.state_mut()
}
fn snapshot(&self) -> BufferSnapshot {
self.inner.snapshot()
}
fn restore_snapshot(&mut self, snapshot: BufferSnapshot) {
self.inner.restore_snapshot(snapshot)
}
}
/// A Buffer that removes any soft line breaks.
///
/// * Removes [`lines`](FormatElement::Line) with the mode [`Soft`](LineMode::Soft).
/// * Replaces [`lines`](FormatElement::Line) with the mode [`Soft`](LineMode::SoftOrSpace) with a [`Space`](FormatElement::Space)
///
/// # Examples
///
/// ```
/// use rome_formatter::prelude::*;
/// use rome_formatter::{format, write};
///
/// # fn main() -> FormatResult<()> {
/// use rome_formatter::{RemoveSoftLinesBuffer, SimpleFormatContext, VecBuffer};
/// use rome_formatter::prelude::format_with;
/// let formatted = format!(
/// SimpleFormatContext::default(),
/// [format_with(|f| {
/// let mut buffer = RemoveSoftLinesBuffer::new(f);
///
/// write!(
/// buffer,
/// [
/// text("The next soft line or space gets replaced by a space"),
/// soft_line_break_or_space(),
/// text("and the line here"),
/// soft_line_break(),
/// text("is removed entirely.")
/// ]
/// )
/// })]
/// )?;
///
/// assert_eq!(
/// formatted.document().as_ref(),
/// &[
/// FormatElement::StaticText { text: "The next soft line or space gets replaced by a space" },
/// FormatElement::Space,
/// FormatElement::StaticText { text: "and the line here" },
/// FormatElement::StaticText { text: "is removed entirely." }
/// ]
/// );
///
/// # Ok(())
/// # }
/// ```
pub struct RemoveSoftLinesBuffer<'a, Context> {
inner: &'a mut dyn Buffer<Context = Context>,
/// Caches the interned elements after the soft line breaks have been removed.
///
/// The `key` is the [Interned] element as it has been passed to [Self::write_element] or the child of another
/// [Interned] element. The `value` is the matching document of the key where all soft line breaks have been removed.
///
/// It's fine to not snapshot the cache. The worst that can happen is that it holds on interned elements
/// that are now unused. But there's little harm in that and the cache is cleaned when dropping the buffer.
interned_cache: FxHashMap<Interned, Interned>,
}
impl<'a, Context> RemoveSoftLinesBuffer<'a, Context> {
/// Creates a new buffer that removes the soft line breaks before writing them into `buffer`.
pub fn new(inner: &'a mut dyn Buffer<Context = Context>) -> Self {
Self {
inner,
interned_cache: FxHashMap::default(),
}
}
/// Removes the soft line breaks from an interned element.
fn clean_interned(&mut self, interned: &Interned) -> Interned {
clean_interned(interned, &mut self.interned_cache)
}
}
// Extracted to function to avoid monomorphization
fn clean_interned(
interned: &Interned,
interned_cache: &mut FxHashMap<Interned, Interned>,
) -> Interned {
match interned_cache.get(interned) {
Some(cleaned) => cleaned.clone(),
None => {
// Find the first soft line break element or interned element that must be changed
let result = interned
.iter()
.enumerate()
.find_map(|(index, element)| match element {
FormatElement::Line(LineMode::Soft | LineMode::SoftOrSpace) => {
let mut cleaned = Vec::new();
cleaned.extend_from_slice(&interned[..index]);
Some((cleaned, &interned[index..]))
}
FormatElement::Interned(inner) => {
let cleaned_inner = clean_interned(inner, interned_cache);
if &cleaned_inner != inner {
let mut cleaned = Vec::with_capacity(interned.len());
cleaned.extend_from_slice(&interned[..index]);
cleaned.push(FormatElement::Interned(cleaned_inner));
Some((cleaned, &interned[index + 1..]))
} else {
None
}
}
_ => None,
});
let result = match result {
// Copy the whole interned buffer so that becomes possible to change the necessary elements.
Some((mut cleaned, rest)) => {
for element in rest {
let element = match element {
FormatElement::Line(LineMode::Soft) => continue,
FormatElement::Line(LineMode::SoftOrSpace) => FormatElement::Space,
FormatElement::Interned(interned) => {
FormatElement::Interned(clean_interned(interned, interned_cache))
}
element => element.clone(),
};
cleaned.push(element)
}
Interned::new(cleaned)
}
// No change necessary, return existing interned element
None => interned.clone(),
};
interned_cache.insert(interned.clone(), result.clone());
result
}
}
}
impl<Context> Buffer for RemoveSoftLinesBuffer<'_, Context> {
type Context = Context;
fn write_element(&mut self, element: FormatElement) -> FormatResult<()> {
let element = match element {
FormatElement::Line(LineMode::Soft) => return Ok(()),
FormatElement::Line(LineMode::SoftOrSpace) => FormatElement::Space,
FormatElement::Interned(interned) => {
FormatElement::Interned(self.clean_interned(&interned))
}
element => element,
};
self.inner.write_element(element)
}
fn elements(&self) -> &[FormatElement] {
self.inner.elements()
}
fn state(&self) -> &FormatState<Self::Context> {
self.inner.state()
}
fn state_mut(&mut self) -> &mut FormatState<Self::Context> {
self.inner.state_mut()
}
fn snapshot(&self) -> BufferSnapshot {
self.inner.snapshot()
}
fn restore_snapshot(&mut self, snapshot: BufferSnapshot) {
self.inner.restore_snapshot(snapshot)
}
}
pub trait BufferExtensions: Buffer + Sized {
/// Returns a new buffer that calls the passed inspector for every element that gets written to the output
#[must_use]
fn inspect<F>(&mut self, inspector: F) -> Inspect<Self::Context, F>
where
F: FnMut(&FormatElement),
{
Inspect::new(self, inspector)
}
/// Starts a recording that gives you access to all elements that have been written between the start
/// and end of the recording
///
/// #Examples
///
/// ```
/// use std::ops::Deref;
/// use rome_formatter::prelude::*;
/// use rome_formatter::{write, format, SimpleFormatContext};
///
/// # fn main() -> FormatResult<()> {
/// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| {
/// let mut recording = f.start_recording();
///
/// write!(recording, [text("A")])?;
/// write!(recording, [text("B")])?;
///
/// write!(recording, [format_with(|f| write!(f, [text("C"), text("D")]))])?;
///
/// let recorded = recording.stop();
/// assert_eq!(
/// recorded.deref(),
/// &[
/// FormatElement::StaticText{ text: "A" },
/// FormatElement::StaticText{ text: "B" },
/// FormatElement::StaticText{ text: "C" },
/// FormatElement::StaticText{ text: "D" }
/// ]
/// );
///
/// Ok(())
/// })])?;
///
/// assert_eq!(formatted.print()?.as_code(), "ABCD");
/// # Ok(())
/// # }
/// ```
#[must_use]
fn start_recording(&mut self) -> Recording<Self> {
Recording::new(self)
}
/// Writes a sequence of elements into this buffer.
fn write_elements<I>(&mut self, elements: I) -> FormatResult<()>
where
I: IntoIterator<Item = FormatElement>,
{
for element in elements.into_iter() {
self.write_element(element)?;
}
Ok(())
}
}
impl<T> BufferExtensions for T where T: Buffer {}
#[derive(Debug)]
pub struct Recording<'buf, Buffer> {
start: usize,
buffer: &'buf mut Buffer,
}
impl<'buf, B> Recording<'buf, B>
where
B: Buffer,
{
fn new(buffer: &'buf mut B) -> Self {
Self {
start: buffer.elements().len(),
buffer,
}
}
#[inline(always)]
pub fn write_fmt(&mut self, arguments: Arguments<B::Context>) -> FormatResult<()> {
self.buffer.write_fmt(arguments)
}
#[inline(always)]
pub fn write_element(&mut self, element: FormatElement) -> FormatResult<()> {
self.buffer.write_element(element)
}
pub fn stop(self) -> Recorded<'buf> {
let buffer: &'buf B = self.buffer;
let elements = buffer.elements();
let recorded = if self.start > elements.len() {
// May happen if buffer was rewinded.
&[]
} else {
&elements[self.start..]
};
Recorded(recorded)
}
}
#[derive(Debug, Copy, Clone)]
pub struct Recorded<'a>(&'a [FormatElement]);
impl Deref for Recorded<'_> {
type Target = [FormatElement];
fn deref(&self) -> &Self::Target {
self.0
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/formatter.rs | crates/rome_formatter/src/formatter.rs | use crate::buffer::BufferSnapshot;
use crate::builders::{FillBuilder, JoinBuilder, JoinNodesBuilder, Line};
use crate::prelude::*;
use crate::{
Arguments, Buffer, Comments, CstFormatContext, FormatContext, FormatState, FormatStateSnapshot,
GroupId, VecBuffer,
};
/// Handles the formatting of a CST and stores the context how the CST should be formatted (user preferences).
/// The formatter is passed to the [Format] implementation of every node in the CST so that they
/// can use it to format their children.
pub struct Formatter<'buf, Context> {
pub(super) buffer: &'buf mut dyn Buffer<Context = Context>,
}
impl<'buf, Context> Formatter<'buf, Context> {
/// Creates a new context that uses the given formatter context
pub fn new(buffer: &'buf mut (dyn Buffer<Context = Context> + 'buf)) -> Self {
Self { buffer }
}
/// Returns the format options
pub fn options(&self) -> &Context::Options
where
Context: FormatContext,
{
self.context().options()
}
/// Returns the Context specifying how to format the current CST
pub fn context(&self) -> &Context {
self.state().context()
}
/// Returns a mutable reference to the context.
pub fn context_mut(&mut self) -> &mut Context {
self.state_mut().context_mut()
}
/// Creates a new group id that is unique to this document. The passed debug name is used in the
/// [std::fmt::Debug] of the document if this is a debug build.
/// The name is unused for production builds and has no meaning on the equality of two group ids.
pub fn group_id(&self, debug_name: &'static str) -> GroupId {
self.state().group_id(debug_name)
}
/// Joins multiple [Format] together without any separator
///
/// ## Examples
///
/// ```rust
/// use rome_formatter::format;
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| {
/// f.join()
/// .entry(&text("a"))
/// .entry(&space())
/// .entry(&text("+"))
/// .entry(&space())
/// .entry(&text("b"))
/// .finish()
/// })])?;
///
/// assert_eq!(
/// "a + b",
/// formatted.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
pub fn join<'a>(&'a mut self) -> JoinBuilder<'a, 'buf, (), Context> {
JoinBuilder::new(self)
}
/// Joins the objects by placing the specified separator between every two items.
///
/// ## Examples
///
/// Joining different tokens by separating them with a comma and a space.
///
/// ```
/// use rome_formatter::{format, format_args};
/// use rome_formatter::prelude::*;
///
/// # fn main() -> FormatResult<()> {
/// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| {
/// f.join_with(&format_args!(text(","), space()))
/// .entry(&text("1"))
/// .entry(&text("2"))
/// .entry(&text("3"))
/// .entry(&text("4"))
/// .finish()
/// })])?;
///
/// assert_eq!(
/// "1, 2, 3, 4",
/// formatted.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
pub fn join_with<'a, Joiner>(
&'a mut self,
joiner: Joiner,
) -> JoinBuilder<'a, 'buf, Joiner, Context>
where
Joiner: Format<Context>,
{
JoinBuilder::with_separator(self, joiner)
}
/// Specialized version of [crate::Formatter::join_with] for joining SyntaxNodes separated by a space, soft
/// line break or empty line depending on the input file.
///
/// This functions inspects the input source and separates consecutive elements with either
/// a [crate::builders::soft_line_break_or_space] or [crate::builders::empty_line] depending on how many line breaks were
/// separating the elements in the original file.
pub fn join_nodes_with_soft_line<'a>(
&'a mut self,
) -> JoinNodesBuilder<'a, 'buf, Line, Context> {
JoinNodesBuilder::new(soft_line_break_or_space(), self)
}
/// Specialized version of [crate::Formatter::join_with] for joining SyntaxNodes separated by one or more
/// line breaks depending on the input file.
///
/// This functions inspects the input source and separates consecutive elements with either
/// a [crate::builders::hard_line_break] or [crate::builders::empty_line] depending on how many line breaks were separating the
/// elements in the original file.
pub fn join_nodes_with_hardline<'a>(&'a mut self) -> JoinNodesBuilder<'a, 'buf, Line, Context> {
JoinNodesBuilder::new(hard_line_break(), self)
}
/// Concatenates a list of [crate::Format] objects with spaces and line breaks to fit
/// them on as few lines as possible. Each element introduces a conceptual group. The printer
/// first tries to print the item in flat mode but then prints it in expanded mode if it doesn't fit.
///
/// ## Examples
///
/// ```rust
/// use rome_formatter::prelude::*;
/// use rome_formatter::{format, format_args};
///
/// # fn main() -> FormatResult<()> {
/// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| {
/// f.fill()
/// .entry(&soft_line_break_or_space(), &text("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"))
/// .entry(&soft_line_break_or_space(), &text("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"))
/// .entry(&soft_line_break_or_space(), &text("cccccccccccccccccccccccccccccc"))
/// .entry(&soft_line_break_or_space(), &text("dddddddddddddddddddddddddddddd"))
/// .finish()
/// })])?;
///
/// assert_eq!(
/// "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\ncccccccccccccccccccccccccccccc dddddddddddddddddddddddddddddd",
/// formatted.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
///
/// ```rust
/// use rome_formatter::prelude::*;
/// use rome_formatter::{format, format_args};
///
/// # fn main() -> FormatResult<()> {
/// let entries = vec![
/// text("<b>Important: </b>"),
/// text("Please do not commit memory bugs such as segfaults, buffer overflows, etc. otherwise you "),
/// text("<em>will</em>"),
/// text(" be reprimanded")
/// ];
///
/// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| {
/// f.fill().entries(&soft_line_break(), entries.iter()).finish()
/// })])?;
///
/// assert_eq!(
/// &std::format!("<b>Important: </b>\nPlease do not commit memory bugs such as segfaults, buffer overflows, etc. otherwise you \n<em>will</em> be reprimanded"),
/// formatted.print()?.as_code()
/// );
/// # Ok(())
/// # }
/// ```
pub fn fill<'a>(&'a mut self) -> FillBuilder<'a, 'buf, Context> {
FillBuilder::new(self)
}
/// Formats `content` into an interned element without writing it to the formatter's buffer.
pub fn intern(&mut self, content: &dyn Format<Context>) -> FormatResult<Option<FormatElement>> {
let mut buffer = VecBuffer::new(self.state_mut());
crate::write!(&mut buffer, [content])?;
let elements = buffer.into_vec();
Ok(self.intern_vec(elements))
}
pub fn intern_vec(&mut self, mut elements: Vec<FormatElement>) -> Option<FormatElement> {
match elements.len() {
0 => None,
// Doesn't get cheaper than calling clone, use the element directly
// SAFETY: Safe because of the `len == 1` check in the match arm.
1 => Some(elements.pop().unwrap()),
_ => Some(FormatElement::Interned(Interned::new(elements))),
}
}
}
impl<Context> Formatter<'_, Context>
where
Context: FormatContext,
{
/// Take a snapshot of the state of the formatter
#[inline]
pub fn state_snapshot(&self) -> FormatterSnapshot {
FormatterSnapshot {
buffer: self.buffer.snapshot(),
state: self.state().snapshot(),
}
}
#[inline]
/// Restore the state of the formatter to a previous snapshot
pub fn restore_state_snapshot(&mut self, snapshot: FormatterSnapshot) {
self.state_mut().restore_snapshot(snapshot.state);
self.buffer.restore_snapshot(snapshot.buffer);
}
}
impl<Context> Formatter<'_, Context>
where
Context: CstFormatContext,
{
/// Returns the comments from the context.
pub fn comments(&self) -> &Comments<Context::Language> {
self.context().comments()
}
}
impl<Context> Buffer for Formatter<'_, Context> {
type Context = Context;
#[inline(always)]
fn write_element(&mut self, element: FormatElement) -> FormatResult<()> {
self.buffer.write_element(element)
}
fn elements(&self) -> &[FormatElement] {
self.buffer.elements()
}
#[inline(always)]
fn write_fmt(&mut self, arguments: Arguments<Self::Context>) -> FormatResult<()> {
for argument in arguments.items() {
argument.format(self)?;
}
Ok(())
}
fn state(&self) -> &FormatState<Self::Context> {
self.buffer.state()
}
fn state_mut(&mut self) -> &mut FormatState<Self::Context> {
self.buffer.state_mut()
}
fn snapshot(&self) -> BufferSnapshot {
self.buffer.snapshot()
}
fn restore_snapshot(&mut self, snapshot: BufferSnapshot) {
self.buffer.restore_snapshot(snapshot)
}
}
/// Snapshot of the formatter state used to handle backtracking if
/// errors are encountered in the formatting process and the formatter
/// has to fallback to printing raw tokens
///
/// In practice this only saves the set of printed tokens in debug
/// mode and compiled to nothing in release mode
pub struct FormatterSnapshot {
buffer: BufferSnapshot,
state: FormatStateSnapshot,
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/format_element.rs | crates/rome_formatter/src/format_element.rs | pub mod document;
pub mod tag;
use crate::format_element::tag::{LabelId, Tag};
use std::borrow::Cow;
use crate::{TagKind, TextSize};
#[cfg(target_pointer_width = "64")]
use rome_rowan::static_assert;
use rome_rowan::TokenText;
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::rc::Rc;
/// Language agnostic IR for formatting source code.
///
/// Use the helper functions like [crate::builders::space], [crate::builders::soft_line_break] etc. defined in this file to create elements.
#[derive(Clone, Eq, PartialEq)]
pub enum FormatElement {
/// A space token, see [crate::builders::space] for documentation.
Space,
/// A new line, see [crate::builders::soft_line_break], [crate::builders::hard_line_break], and [crate::builders::soft_line_break_or_space] for documentation.
Line(LineMode),
/// Forces the parent group to print in expanded mode.
ExpandParent,
/// Token constructed by the formatter from a static string
StaticText { text: &'static str },
/// Token constructed from the input source as a dynamic
/// string with its start position in the input document.
DynamicText {
/// There's no need for the text to be mutable, using `Box<str>` safes 8 bytes over `String`.
text: Box<str>,
/// The start position of the dynamic token in the unformatted source code
source_position: TextSize,
},
/// A token for a text that is taken as is from the source code (input text and formatted representation are identical).
/// Implementing by taking a slice from a `SyntaxToken` to avoid allocating a new string.
LocatedTokenText {
/// The start position of the token in the unformatted source code
source_position: TextSize,
/// The token text
slice: TokenText,
},
/// Prevents that line suffixes move past this boundary. Forces the printer to print any pending
/// line suffixes, potentially by inserting a hard line break.
LineSuffixBoundary,
/// An interned format element. Useful when the same content must be emitted multiple times to avoid
/// deep cloning the IR when using the `best_fitting!` macro or `if_group_fits_on_line` and `if_group_breaks`.
Interned(Interned),
/// A list of different variants representing the same content. The printer picks the best fitting content.
/// Line breaks inside of a best fitting don't propagate to parent groups.
BestFitting(BestFittingElement),
/// A [Tag] that marks the start/end of some content to which some special formatting is applied.
Tag(Tag),
}
impl std::fmt::Debug for FormatElement {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
FormatElement::Space => write!(fmt, "Space"),
FormatElement::Line(mode) => fmt.debug_tuple("Line").field(mode).finish(),
FormatElement::ExpandParent => write!(fmt, "ExpandParent"),
FormatElement::StaticText { text } => {
fmt.debug_tuple("StaticText").field(text).finish()
}
FormatElement::DynamicText { text, .. } => {
fmt.debug_tuple("DynamicText").field(text).finish()
}
FormatElement::LocatedTokenText { slice, .. } => {
fmt.debug_tuple("LocatedTokenText").field(slice).finish()
}
FormatElement::LineSuffixBoundary => write!(fmt, "LineSuffixBoundary"),
FormatElement::BestFitting(best_fitting) => {
fmt.debug_tuple("BestFitting").field(&best_fitting).finish()
}
FormatElement::Interned(interned) => {
fmt.debug_list().entries(interned.deref()).finish()
}
FormatElement::Tag(tag) => fmt.debug_tuple("Tag").field(tag).finish(),
}
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum LineMode {
/// See [crate::builders::soft_line_break_or_space] for documentation.
SoftOrSpace,
/// See [crate::builders::soft_line_break] for documentation.
Soft,
/// See [crate::builders::hard_line_break] for documentation.
Hard,
/// See [crate::builders::empty_line] for documentation.
Empty,
}
impl LineMode {
pub const fn is_hard(&self) -> bool {
matches!(self, LineMode::Hard)
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum PrintMode {
/// Omits any soft line breaks
Flat,
/// Prints soft line breaks as line breaks
Expanded,
}
impl PrintMode {
pub const fn is_flat(&self) -> bool {
matches!(self, PrintMode::Flat)
}
pub const fn is_expanded(&self) -> bool {
matches!(self, PrintMode::Expanded)
}
}
#[derive(Clone)]
pub struct Interned(Rc<[FormatElement]>);
impl Interned {
pub(super) fn new(content: Vec<FormatElement>) -> Self {
Self(content.into())
}
}
impl PartialEq for Interned {
fn eq(&self, other: &Interned) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for Interned {}
impl Hash for Interned {
fn hash<H>(&self, hasher: &mut H)
where
H: Hasher,
{
Rc::as_ptr(&self.0).hash(hasher);
}
}
impl std::fmt::Debug for Interned {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl Deref for Interned {
type Target = [FormatElement];
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
const LINE_SEPARATOR: char = '\u{2028}';
const PARAGRAPH_SEPARATOR: char = '\u{2029}';
pub const LINE_TERMINATORS: [char; 3] = ['\r', LINE_SEPARATOR, PARAGRAPH_SEPARATOR];
/// Replace the line terminators matching the provided list with "\n"
/// since its the only line break type supported by the printer
pub fn normalize_newlines<const N: usize>(text: &str, terminators: [char; N]) -> Cow<str> {
let mut result = String::new();
let mut last_end = 0;
for (start, part) in text.match_indices(terminators) {
result.push_str(&text[last_end..start]);
result.push('\n');
last_end = start + part.len();
// If the current character is \r and the
// next is \n, skip over the entire sequence
if part == "\r" && text[last_end..].starts_with('\n') {
last_end += 1;
}
}
// If the result is empty no line terminators were matched,
// return the entire input text without allocating a new String
if result.is_empty() {
Cow::Borrowed(text)
} else {
result.push_str(&text[last_end..text.len()]);
Cow::Owned(result)
}
}
impl FormatElement {
/// Returns `true` if self is a [FormatElement::Tag]
pub const fn is_tag(&self) -> bool {
matches!(self, FormatElement::Tag(_))
}
/// Returns `true` if self is a [FormatElement::Tag] and [Tag::is_start] is `true`.
pub const fn is_start_tag(&self) -> bool {
match self {
FormatElement::Tag(tag) => tag.is_start(),
_ => false,
}
}
/// Returns `true` if self is a [FormatElement::Tag] and [Tag::is_end] is `true`.
pub const fn is_end_tag(&self) -> bool {
match self {
FormatElement::Tag(tag) => tag.is_end(),
_ => false,
}
}
pub const fn is_text(&self) -> bool {
matches!(
self,
FormatElement::LocatedTokenText { .. }
| FormatElement::DynamicText { .. }
| FormatElement::StaticText { .. }
)
}
pub const fn is_space(&self) -> bool {
matches!(self, FormatElement::Space)
}
}
impl FormatElements for FormatElement {
fn will_break(&self) -> bool {
match self {
FormatElement::ExpandParent => true,
FormatElement::Tag(Tag::StartGroup(group)) => !group.mode().is_flat(),
FormatElement::Line(line_mode) => matches!(line_mode, LineMode::Hard | LineMode::Empty),
FormatElement::StaticText { text } => text.contains('\n'),
FormatElement::DynamicText { text, .. } => text.contains('\n'),
FormatElement::LocatedTokenText { slice, .. } => slice.contains('\n'),
FormatElement::Interned(interned) => interned.will_break(),
// Traverse into the most flat version because the content is guaranteed to expand when even
// the most flat version contains some content that forces a break.
FormatElement::BestFitting(best_fitting) => best_fitting.most_flat().will_break(),
FormatElement::LineSuffixBoundary | FormatElement::Space | FormatElement::Tag(_) => {
false
}
}
}
fn has_label(&self, label_id: LabelId) -> bool {
match self {
FormatElement::Tag(Tag::StartLabelled(actual)) => *actual == label_id,
FormatElement::Interned(interned) => interned.deref().has_label(label_id),
_ => false,
}
}
fn start_tag(&self, _: TagKind) -> Option<&Tag> {
None
}
fn end_tag(&self, kind: TagKind) -> Option<&Tag> {
match self {
FormatElement::Tag(tag) if tag.kind() == kind && tag.is_end() => Some(tag),
_ => None,
}
}
}
/// Provides the printer with different representations for the same element so that the printer
/// can pick the best fitting variant.
///
/// Best fitting is defined as the variant that takes the most horizontal space but fits on the line.
#[derive(Clone, Eq, PartialEq)]
pub struct BestFittingElement {
/// The different variants for this element.
/// The first element is the one that takes up the most space horizontally (the most flat),
/// The last element takes up the least space horizontally (but most horizontal space).
variants: Box<[Box<[FormatElement]>]>,
}
impl BestFittingElement {
/// Creates a new best fitting IR with the given variants. The method itself isn't unsafe
/// but it is to discourage people from using it because the printer will panic if
/// the slice doesn't contain at least the least and most expanded variants.
///
/// You're looking for a way to create a `BestFitting` object, use the `best_fitting![least_expanded, most_expanded]` macro.
///
/// ## Safety
/// The slice must contain at least two variants.
#[doc(hidden)]
pub unsafe fn from_vec_unchecked(variants: Vec<Box<[FormatElement]>>) -> Self {
debug_assert!(
variants.len() >= 2,
"Requires at least the least expanded and most expanded variants"
);
Self {
variants: variants.into_boxed_slice(),
}
}
/// Returns the most expanded variant
pub fn most_expanded(&self) -> &[FormatElement] {
self.variants.last().expect(
"Most contain at least two elements, as guaranteed by the best fitting builder.",
)
}
pub fn variants(&self) -> &[Box<[FormatElement]>] {
&self.variants
}
/// Returns the least expanded variant
pub fn most_flat(&self) -> &[FormatElement] {
self.variants.first().expect(
"Most contain at least two elements, as guaranteed by the best fitting builder.",
)
}
}
impl std::fmt::Debug for BestFittingElement {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_list().entries(&*self.variants).finish()
}
}
pub trait FormatElements {
/// Returns true if this [FormatElement] is guaranteed to break across multiple lines by the printer.
/// This is the case if this format element recursively contains a:
/// * [crate::builders::empty_line] or [crate::builders::hard_line_break]
/// * A token containing '\n'
///
/// Use this with caution, this is only a heuristic and the printer may print the element over multiple
/// lines if this element is part of a group and the group doesn't fit on a single line.
fn will_break(&self) -> bool;
/// Returns true if the element has the given label.
fn has_label(&self, label: LabelId) -> bool;
/// Returns the start tag of `kind` if:
/// * the last element is an end tag of `kind`.
/// * there's a matching start tag in this document (may not be true if this slice is an interned element and the `start` is in the document storing the interned element).
fn start_tag(&self, kind: TagKind) -> Option<&Tag>;
/// Returns the end tag if:
/// * the last element is an end tag of `kind`
fn end_tag(&self, kind: TagKind) -> Option<&Tag>;
}
#[cfg(test)]
mod tests {
use crate::format_element::{normalize_newlines, LINE_TERMINATORS};
#[test]
fn test_normalize_newlines() {
assert_eq!(normalize_newlines("a\nb", LINE_TERMINATORS), "a\nb");
assert_eq!(normalize_newlines("a\n\n\nb", LINE_TERMINATORS), "a\n\n\nb");
assert_eq!(normalize_newlines("a\rb", LINE_TERMINATORS), "a\nb");
assert_eq!(normalize_newlines("a\r\nb", LINE_TERMINATORS), "a\nb");
assert_eq!(
normalize_newlines("a\r\n\r\n\r\nb", LINE_TERMINATORS),
"a\n\n\nb"
);
assert_eq!(normalize_newlines("a\u{2028}b", LINE_TERMINATORS), "a\nb");
assert_eq!(normalize_newlines("a\u{2029}b", LINE_TERMINATORS), "a\nb");
}
}
#[cfg(target_pointer_width = "64")]
static_assert!(std::mem::size_of::<rome_rowan::TextRange>() == 8usize);
#[cfg(target_pointer_width = "64")]
static_assert!(std::mem::size_of::<crate::format_element::tag::VerbatimKind>() == 8usize);
#[cfg(not(debug_assertions))]
#[cfg(target_pointer_width = "64")]
static_assert!(std::mem::size_of::<crate::format_element::Tag>() == 16usize);
// Increasing the size of FormatElement has serious consequences on runtime performance and memory footprint.
// Is there a more efficient way to encode the data to avoid increasing its size? Can the information
// be recomputed at a later point in time?
// You reduced the size of a format element? Excellent work!
#[cfg(not(debug_assertions))]
#[cfg(target_pointer_width = "64")]
static_assert!(std::mem::size_of::<crate::FormatElement>() == 24usize);
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/printed_tokens.rs | crates/rome_formatter/src/printed_tokens.rs | use indexmap::IndexSet;
use rome_rowan::{Direction, Language, SyntaxNode, SyntaxToken, TextSize};
/// Tracks the ranges of the formatted (including replaced or tokens formatted as verbatim) tokens.
///
/// This implementation uses the fact that no two tokens can have an overlapping range to avoid the need for an interval tree.
/// Thus, testing if a token has already been formatted only requires testing if a token starting at the same offset has been formatted.
#[derive(Debug, Clone, Default)]
pub struct PrintedTokens {
/// Key: Start of a token's range
offsets: IndexSet<TextSize>,
disabled: bool,
}
#[derive(Copy, Clone)]
pub struct PrintedTokensSnapshot {
len: usize,
disabled: bool,
}
impl PrintedTokens {
/// Tracks a formatted token
///
/// ## Panics
/// If this token has been formatted before.
pub fn track_token<L: Language>(&mut self, token: &SyntaxToken<L>) {
if self.disabled {
return;
}
let range = token.text_trimmed_range();
if !self.offsets.insert(range.start()) {
panic!("You tried to print the token '{token:?}' twice, and this is not valid.");
}
}
/// Enables or disables the assertion tracking
pub(crate) fn set_disabled(&mut self, disabled: bool) {
self.disabled = disabled;
}
pub(crate) fn is_disabled(&self) -> bool {
self.disabled
}
pub(crate) fn snapshot(&self) -> PrintedTokensSnapshot {
PrintedTokensSnapshot {
len: self.offsets.len(),
disabled: self.disabled,
}
}
pub(crate) fn restore(&mut self, snapshot: PrintedTokensSnapshot) {
let PrintedTokensSnapshot { len, disabled } = snapshot;
self.offsets.truncate(len);
self.disabled = disabled
}
/// Asserts that all tokens of the passed in node have been tracked
///
/// ## Panics
/// If any descendant token of `root` hasn't been tracked
pub fn assert_all_tracked<L: Language>(&self, root: &SyntaxNode<L>) {
let mut offsets = self.offsets.clone();
for token in root.descendants_tokens(Direction::Next) {
if !offsets.remove(&token.text_trimmed_range().start()) {
panic!("token has not been seen by the formatter: {token:#?}.\
\nUse `format_replaced` if you want to replace a token from the formatted output.\
\nUse `format_removed` if you want to remove a token from the formatted output.\n\
parent: {:#?}", token.parent())
}
}
for offset in offsets {
panic!("tracked offset {offset:?} doesn't match any token of {root:#?}. Have you passed a token from another tree?");
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/separated.rs | crates/rome_formatter/src/separated.rs | use crate::prelude::*;
use crate::{write, CstFormatContext, GroupId};
use rome_rowan::{AstNode, AstSeparatedElement, SyntaxResult, SyntaxToken};
pub trait FormatSeparatedElementRule<N>
where
N: AstNode,
{
type Context;
type FormatNode<'a>: Format<Self::Context>
where
N: 'a;
type FormatSeparator<'a>: Format<Self::Context>
where
N: 'a;
fn format_node<'a>(&self, node: &'a N) -> Self::FormatNode<'a>;
fn format_separator<'a>(
&self,
separator: &'a SyntaxToken<N::Language>,
) -> Self::FormatSeparator<'a>;
}
/// Formats a single element inside a separated list.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct FormatSeparatedElement<N, R>
where
N: AstNode,
R: FormatSeparatedElementRule<N>,
{
element: AstSeparatedElement<N::Language, N>,
rule: R,
is_last: bool,
/// The separator to write if the element has no separator yet.
separator: &'static str,
options: FormatSeparatedOptions,
}
impl<N, R> FormatSeparatedElement<N, R>
where
N: AstNode,
R: FormatSeparatedElementRule<N>,
{
/// Returns the node belonging to the element.
pub fn node(&self) -> SyntaxResult<&N> {
self.element.node()
}
}
impl<N, R, C> Format<C> for FormatSeparatedElement<N, R>
where
N: AstNode,
N::Language: 'static,
R: FormatSeparatedElementRule<N, Context = C>,
C: CstFormatContext<Language = N::Language>,
{
fn fmt(&self, f: &mut Formatter<C>) -> FormatResult<()> {
let node = self.element.node()?;
let separator = self.element.trailing_separator()?;
let format_node = self.rule.format_node(node);
if !self.options.nodes_grouped {
format_node.fmt(f)?;
} else {
group(&format_node).fmt(f)?;
}
// Reuse the existing trailing separator or create it if it wasn't in the
// input source. Only print the last trailing token if the outer group breaks
if let Some(separator) = separator {
let format_separator = self.rule.format_separator(separator);
if self.is_last {
match self.options.trailing_separator {
TrailingSeparator::Allowed => {
// Use format_replaced instead of wrapping the result of format_token
// in order to remove only the token itself when the group doesn't break
// but still print its associated trivia unconditionally
format_only_if_breaks(separator, &format_separator)
.with_group_id(self.options.group_id)
.fmt(f)?;
}
TrailingSeparator::Mandatory => {
write!(f, [format_separator])?;
}
TrailingSeparator::Disallowed => {
// A trailing separator was present where it wasn't allowed, opt out of formatting
return Err(FormatError::SyntaxError);
}
TrailingSeparator::Omit => {
write!(f, [format_removed(separator)])?;
}
}
} else {
write!(f, [format_separator])?;
}
} else if self.is_last {
match self.options.trailing_separator {
TrailingSeparator::Allowed => {
write!(
f,
[if_group_breaks(&text(self.separator))
.with_group_id(self.options.group_id)]
)?;
}
TrailingSeparator::Mandatory => {
text(self.separator).fmt(f)?;
}
TrailingSeparator::Omit | TrailingSeparator::Disallowed => { /* no op */ }
}
} else {
unreachable!(
"This is a syntax error, separator must be present between every two elements"
);
};
Ok(())
}
}
/// Iterator for formatting separated elements. Prints the separator between each element and
/// inserts a trailing separator if necessary
pub struct FormatSeparatedIter<I, Node, Rule>
where
Node: AstNode,
{
next: Option<AstSeparatedElement<Node::Language, Node>>,
rule: Rule,
inner: I,
separator: &'static str,
options: FormatSeparatedOptions,
}
impl<I, Node, Rule> FormatSeparatedIter<I, Node, Rule>
where
Node: AstNode,
{
pub fn new(inner: I, separator: &'static str, rule: Rule) -> Self {
Self {
inner,
rule,
separator,
next: None,
options: FormatSeparatedOptions::default(),
}
}
/// Wraps every node inside of a group
pub fn nodes_grouped(mut self) -> Self {
self.options.nodes_grouped = true;
self
}
pub fn with_trailing_separator(mut self, separator: TrailingSeparator) -> Self {
self.options.trailing_separator = separator;
self
}
#[allow(unused)]
pub fn with_group_id(mut self, group_id: Option<GroupId>) -> Self {
self.options.group_id = group_id;
self
}
}
impl<I, Node, Rule> Iterator for FormatSeparatedIter<I, Node, Rule>
where
Node: AstNode,
I: Iterator<Item = AstSeparatedElement<Node::Language, Node>>,
Rule: FormatSeparatedElementRule<Node> + Clone,
{
type Item = FormatSeparatedElement<Node, Rule>;
fn next(&mut self) -> Option<Self::Item> {
let element = self.next.take().or_else(|| self.inner.next())?;
self.next = self.inner.next();
let is_last = self.next.is_none();
Some(FormatSeparatedElement {
element,
rule: self.rule.clone(),
is_last,
separator: self.separator,
options: self.options,
})
}
}
impl<I, Node, Rule> std::iter::FusedIterator for FormatSeparatedIter<I, Node, Rule>
where
Node: AstNode,
I: Iterator<Item = AstSeparatedElement<Node::Language, Node>> + std::iter::FusedIterator,
Rule: FormatSeparatedElementRule<Node> + Clone,
{
}
impl<I, Node, Rule> std::iter::ExactSizeIterator for FormatSeparatedIter<I, Node, Rule>
where
Node: AstNode,
I: Iterator<Item = AstSeparatedElement<Node::Language, Node>> + ExactSizeIterator,
Rule: FormatSeparatedElementRule<Node> + Clone,
{
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
pub enum TrailingSeparator {
/// A trailing separator is allowed and preferred
#[default]
Allowed,
/// A trailing separator is not allowed
Disallowed,
/// A trailing separator is mandatory for the syntax to be correct
Mandatory,
/// A trailing separator might be present, but the consumer
/// decides to remove it
Omit,
}
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq)]
pub struct FormatSeparatedOptions {
trailing_separator: TrailingSeparator,
group_id: Option<GroupId>,
nodes_grouped: bool,
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/comments/builder.rs | crates/rome_formatter/src/comments/builder.rs | use super::{
map::CommentsMap, CommentPlacement, CommentStyle, CommentTextPosition, DecoratedComment,
SourceComment, TransformSourceMap,
};
use crate::source_map::{DeletedRangeEntry, DeletedRanges};
use crate::{TextRange, TextSize};
use rome_rowan::syntax::SyntaxElementKey;
use rome_rowan::{
Direction, Language, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, WalkEvent,
};
use rustc_hash::FxHashSet;
/// Extracts all comments from a syntax tree.
pub(super) struct CommentsBuilderVisitor<'a, Style: CommentStyle> {
builder: CommentsBuilder<Style::Language>,
style: &'a Style,
parentheses: SourceParentheses<'a>,
// State
pending_comments: Vec<DecoratedComment<Style::Language>>,
preceding_node: Option<SyntaxNode<Style::Language>>,
following_node_index: Option<usize>,
parents: Vec<SyntaxNode<Style::Language>>,
last_token: Option<SyntaxToken<Style::Language>>,
}
impl<'a, Style> CommentsBuilderVisitor<'a, Style>
where
Style: CommentStyle,
{
pub(super) fn new(style: &'a Style, source_map: Option<&'a TransformSourceMap>) -> Self {
Self {
style,
builder: Default::default(),
parentheses: SourceParentheses::from_source_map(source_map),
pending_comments: Default::default(),
preceding_node: Default::default(),
following_node_index: Default::default(),
parents: Default::default(),
last_token: Default::default(),
}
}
pub(super) fn visit(
mut self,
root: &SyntaxNode<Style::Language>,
) -> (
CommentsMap<SyntaxElementKey, SourceComment<Style::Language>>,
FxHashSet<SyntaxElementKey>,
) {
for event in root.preorder_with_tokens(Direction::Next) {
match event {
WalkEvent::Enter(SyntaxElement::Node(node)) => {
self.visit_node(WalkEvent::Enter(node))
}
WalkEvent::Leave(SyntaxElement::Node(node)) => {
self.visit_node(WalkEvent::Leave(node))
}
WalkEvent::Enter(SyntaxElement::Token(token)) => self.visit_token(token),
WalkEvent::Leave(SyntaxElement::Token(_)) => {
// Handled as part of enter
}
}
}
assert!(
self.parents.is_empty(),
"Expected all enclosing nodes to have been processed but contains {:#?}",
self.parents
);
// Process any comments attached to the last token.
// Important for range formatting where it isn't guaranteed that the
// last token is an EOF token.
if let Some(last_token) = self.last_token.take() {
self.parents.push(root.clone());
let (comments_start, lines_before, position, trailing_end) =
self.visit_trailing_comments(last_token, None);
Self::update_comments(
&mut self.pending_comments[comments_start..],
position,
lines_before,
trailing_end,
);
}
self.flush_comments(None);
self.builder.finish()
}
fn visit_node(&mut self, event: WalkEvent<SyntaxNode<Style::Language>>) {
match event {
WalkEvent::Enter(node) => {
// Lists cannot have comments attached. They either belong to the entire parent or to
// the first child. So we ignore lists all together
if node.kind().is_list() {
return;
}
let is_root = matches!(self.following_node_index, Some(0));
// Associate comments with the most outer node
// Set following here because it is the "following node" of the next token's leading trivia.
if self.following_node_index.is_none() || is_root {
// Flush in case the node doesn't have any tokens.
self.flush_comments(Some(&node));
self.following_node_index = Some(self.parents.len());
}
self.parents.push(node);
}
WalkEvent::Leave(node) => {
if node.kind().is_list() {
return;
}
self.parents.pop().unwrap();
// We're passed this node, flush any pending comments for its children
self.following_node_index = None;
self.flush_comments(None);
// We're passed this node, so it must precede the sibling that comes next.
self.preceding_node = Some(node);
}
}
}
fn visit_token(&mut self, token: SyntaxToken<Style::Language>) {
// Process the trailing trivia of the last token
let (comments_start, mut lines_before, mut position, mut trailing_end) =
if let Some(last_token) = self.last_token.take() {
self.visit_trailing_comments(last_token, Some(&token))
} else {
(
self.pending_comments.len(),
0,
CommentTextPosition::SameLine,
None,
)
};
// Process the leading trivia of the current token. the trailing trivia is handled as part of the next token
for leading in token.leading_trivia().pieces() {
if leading.is_newline() {
lines_before += 1;
// All comments following from here are own line comments
position = CommentTextPosition::OwnLine;
if trailing_end.is_none() {
trailing_end = Some(self.pending_comments.len());
}
} else if leading.is_skipped() {
self.builder.mark_has_skipped(&token);
lines_before = 0;
break;
} else if let Some(comment) = leading.as_comments() {
let kind = Style::get_comment_kind(&comment);
self.queue_comment(DecoratedComment {
enclosing: self.enclosing_node().clone(),
preceding: self.preceding_node.clone(),
following: None,
following_token: Some(token.clone()),
lines_before,
lines_after: 0,
text_position: position,
kind,
comment,
});
lines_before = 0;
}
}
self.last_token = Some(token);
Self::update_comments(
&mut self.pending_comments[comments_start..],
position,
lines_before,
trailing_end,
);
// Set following node to `None` because it now becomes the enclosing node.
if let Some(following_node) = self.following_node() {
self.flush_comments(Some(&following_node.clone()));
self.following_node_index = None;
// The following node is only set after entering a node
// That means, following node is only set for the first token of a node.
// Unset preceding node if this is the first token because the preceding node belongs to the parent.
self.preceding_node = None;
}
}
fn enclosing_node(&self) -> &SyntaxNode<Style::Language> {
let element = match self.following_node_index {
None => self.parents.last(),
Some(index) if index == 0 => Some(&self.parents[0]),
Some(index) => Some(&self.parents[index - 1]),
};
element.expect("Expected enclosing nodes to at least contain the root node.")
}
fn following_node(&self) -> Option<&SyntaxNode<Style::Language>> {
self.following_node_index.map(|index| {
self.parents
.get(index)
.expect("Expected following node index to point to a valid parent node")
})
}
fn queue_comment(&mut self, comment: DecoratedComment<Style::Language>) {
self.pending_comments.push(comment);
}
fn update_comments(
comments: &mut [DecoratedComment<Style::Language>],
position: CommentTextPosition,
lines_before: u32,
trailing_end: Option<usize>,
) {
let trailing_end = trailing_end.unwrap_or(comments.len());
let mut comments = comments.iter_mut().enumerate().peekable();
// Update the lines after of all comments as well as the positioning of end of line comments.
while let Some((index, comment)) = comments.next() {
// Update the position of all trailing comments to be end of line as we've seen a line break since.
if index < trailing_end && position.is_own_line() {
comment.text_position = CommentTextPosition::EndOfLine;
}
comment.lines_after = comments
.peek()
.map_or(lines_before, |(_, next)| next.lines_before);
}
}
fn flush_comments(&mut self, following: Option<&SyntaxNode<Style::Language>>) {
for mut comment in self.pending_comments.drain(..) {
comment.following = following.cloned();
let placement = self.style.place_comment(comment);
self.builder.add_comment(placement);
}
}
fn visit_trailing_comments(
&mut self,
token: SyntaxToken<Style::Language>,
following_token: Option<&SyntaxToken<Style::Language>>,
) -> (usize, u32, CommentTextPosition, Option<usize>) {
let mut comments_start = 0;
// The index of the last trailing comment in `pending_comments`.
let mut trailing_end: Option<usize> = None;
// Number of lines before the next comment, token, or skipped token trivia
let mut lines_before = 0;
// Trailing comments are all `SameLine` comments EXCEPT if any is followed by a line break,
// a leading comment (that always have line breaks), or there's a line break before the token.
let mut position = CommentTextPosition::SameLine;
// Process the trailing trivia of the last token
for piece in token.trailing_trivia().pieces() {
if piece.is_newline() {
lines_before += 1;
// All comments following from here are own line comments
position = CommentTextPosition::OwnLine;
if trailing_end.is_none() {
trailing_end = Some(self.pending_comments.len());
}
} else if let Some(comment) = piece.as_comments() {
self.queue_comment(DecoratedComment {
enclosing: self.enclosing_node().clone(),
preceding: self.preceding_node.clone(),
following: None,
following_token: following_token.cloned(),
lines_before,
lines_after: 0, // Will be initialized after
text_position: position,
kind: Style::get_comment_kind(&comment),
comment,
});
lines_before = 0;
}
if let Some(parens_source_range) = self
.parentheses
.r_paren_source_range(piece.text_range().end())
{
self.flush_before_r_paren_comments(
parens_source_range,
&token,
position,
lines_before,
comments_start,
trailing_end,
);
lines_before = 0;
position = CommentTextPosition::SameLine;
comments_start = 0;
trailing_end = None;
}
}
(comments_start, lines_before, position, trailing_end)
}
/// Processes comments appearing right before a `)` of a parenthesized expressions.
#[cold]
fn flush_before_r_paren_comments(
&mut self,
parens_source_range: TextRange,
last_token: &SyntaxToken<Style::Language>,
position: CommentTextPosition,
lines_before: u32,
start: usize,
trailing_end: Option<usize>,
) {
let enclosing = self.enclosing_node().clone();
let comments = &mut self.pending_comments[start..];
let trailing_end = trailing_end.unwrap_or(comments.len());
let mut comments = comments.iter_mut().enumerate().peekable();
let parenthesized_node = self
.parentheses
.outer_most_parenthesized_node(last_token, parens_source_range);
let preceding = parenthesized_node;
// Using the `enclosing` as default but it's mainly to satisfy Rust. The only case where it is used
// is if someone formats a Parenthesized expression as the root. Something we explicitly disallow
// in rome_js_formatter
let enclosing = preceding.parent().unwrap_or(enclosing);
// Update the lines after of all comments as well as the positioning of end of line comments.
while let Some((index, comment)) = comments.next() {
// Update the position of all trailing comments to be end of line as we've seen a line break since.
if index < trailing_end && position.is_own_line() {
comment.text_position = CommentTextPosition::EndOfLine;
}
comment.preceding = Some(preceding.clone());
comment.enclosing = enclosing.clone();
comment.lines_after = comments
.peek()
.map_or(lines_before, |(_, next)| next.lines_before);
}
self.flush_comments(None);
}
}
struct CommentsBuilder<L: Language> {
comments: CommentsMap<SyntaxElementKey, SourceComment<L>>,
skipped: FxHashSet<SyntaxElementKey>,
}
impl<L: Language> CommentsBuilder<L> {
fn add_comment(&mut self, placement: CommentPlacement<L>) {
match placement {
CommentPlacement::Leading { node, comment } => {
self.push_leading_comment(&node, comment);
}
CommentPlacement::Trailing { node, comment } => {
self.push_trailing_comment(&node, comment);
}
CommentPlacement::Dangling { node, comment } => {
self.push_dangling_comment(&node, comment)
}
CommentPlacement::Default(mut comment) => {
match comment.text_position {
CommentTextPosition::EndOfLine => {
match (comment.take_preceding_node(), comment.take_following_node()) {
(Some(preceding), Some(_)) => {
// Attach comments with both preceding and following node to the preceding
// because there's a line break separating it from the following node.
// ```javascript
// a; // comment
// b
// ```
self.push_trailing_comment(&preceding, comment);
}
(Some(preceding), None) => {
self.push_trailing_comment(&preceding, comment);
}
(None, Some(following)) => {
self.push_leading_comment(&following, comment);
}
(None, None) => {
self.push_dangling_comment(
&comment.enclosing_node().clone(),
comment,
);
}
}
}
CommentTextPosition::OwnLine => {
match (comment.take_preceding_node(), comment.take_following_node()) {
// Following always wins for a leading comment
// ```javascript
// a;
// // comment
// b
// ```
// attach the comment to the `b` expression statement
(_, Some(following)) => {
self.push_leading_comment(&following, comment);
}
(Some(preceding), None) => {
self.push_trailing_comment(&preceding, comment);
}
(None, None) => {
self.push_dangling_comment(
&comment.enclosing_node().clone(),
comment,
);
}
}
}
CommentTextPosition::SameLine => {
match (comment.take_preceding_node(), comment.take_following_node()) {
(Some(preceding), Some(following)) => {
// Only make it a trailing comment if it directly follows the preceding node but not if it is separated
// by one or more tokens
// ```javascript
// a /* comment */ b; // Comment is a trailing comment
// a, /* comment */ b; // Comment should be a leading comment
// ```
if preceding.text_range().end()
== comment.piece().as_piece().token().text_range().end()
{
self.push_trailing_comment(&preceding, comment);
} else {
self.push_leading_comment(&following, comment);
}
}
(Some(preceding), None) => {
self.push_trailing_comment(&preceding, comment);
}
(None, Some(following)) => {
self.push_leading_comment(&following, comment);
}
(None, None) => {
self.push_dangling_comment(
&comment.enclosing_node().clone(),
comment,
);
}
}
}
}
}
}
}
fn mark_has_skipped(&mut self, token: &SyntaxToken<L>) {
self.skipped.insert(token.key());
}
fn push_leading_comment(&mut self, node: &SyntaxNode<L>, comment: impl Into<SourceComment<L>>) {
self.comments.push_leading(node.key(), comment.into());
}
fn push_dangling_comment(
&mut self,
node: &SyntaxNode<L>,
comment: impl Into<SourceComment<L>>,
) {
self.comments.push_dangling(node.key(), comment.into());
}
fn push_trailing_comment(
&mut self,
node: &SyntaxNode<L>,
comment: impl Into<SourceComment<L>>,
) {
self.comments.push_trailing(node.key(), comment.into());
}
fn finish(
self,
) -> (
CommentsMap<SyntaxElementKey, SourceComment<L>>,
FxHashSet<SyntaxElementKey>,
) {
(self.comments, self.skipped)
}
}
impl<L: Language> Default for CommentsBuilder<L> {
fn default() -> Self {
Self {
comments: CommentsMap::new(),
skipped: FxHashSet::default(),
}
}
}
enum SourceParentheses<'a> {
Empty,
SourceMap {
map: &'a TransformSourceMap,
next: Option<DeletedRangeEntry<'a>>,
tail: DeletedRanges<'a>,
},
}
impl<'a> SourceParentheses<'a> {
fn from_source_map(source_map: Option<&'a TransformSourceMap>) -> Self {
match source_map {
None => Self::Empty,
Some(source_map) => {
let mut deleted = source_map.deleted_ranges();
SourceParentheses::SourceMap {
map: source_map,
next: deleted.next(),
tail: deleted,
}
}
}
}
/// Returns the range of `node` including its parentheses if any. Otherwise returns the range as is
fn parenthesized_range<L: Language>(&self, node: &SyntaxNode<L>) -> TextRange {
match self {
SourceParentheses::Empty => node.text_trimmed_range(),
SourceParentheses::SourceMap { map, .. } => map.trimmed_source_range(node),
}
}
/// Tests if the next offset is at a position where the original source document used to have an `)`.
///
/// Must be called with offsets in increasing order.
///
/// Returns the source range of the `)` if there's any `)` in the deleted range at this offset. Returns `None` otherwise
fn r_paren_source_range(&mut self, offset: TextSize) -> Option<TextRange> {
match self {
SourceParentheses::Empty => None,
SourceParentheses::SourceMap { next, tail, .. } => {
while let Some(range) = next {
#[allow(clippy::comparison_chain)]
if range.transformed == offset {
// A deleted range can contain multiple tokens. See if there's any `)` in the deleted
// range and compute its source range.
return range.text.find(')').map(|r_paren_position| {
let start = range.source + TextSize::from(r_paren_position as u32);
TextRange::at(start, TextSize::from(1))
});
} else if range.transformed > offset {
return None;
} else {
*next = tail.next();
}
}
None
}
}
}
/// Searches the outer most node that still is inside of the parentheses specified by the `parentheses_source_range`.
fn outer_most_parenthesized_node<L: Language>(
&self,
token: &SyntaxToken<L>,
parentheses_source_range: TextRange,
) -> SyntaxNode<L> {
match self {
SourceParentheses::Empty => token.parent().unwrap(),
SourceParentheses::SourceMap { map, .. } => {
debug_assert_eq!(map.source().text_slice(parentheses_source_range), ")");
// How this works: We search the outer most node that, in the source document ends right after the `)`.
// The issue is, it is possible that multiple nodes end right after the `)`
//
// ```javascript
// !(
// a
// /* comment */
// )
// ```
// The issue is, that in the transformed document, the `ReferenceIdentifier`, `IdentifierExpression`, `UnaryExpression`, and `ExpressionStatement`
// all end at the end position of `)`.
// However, not all the nodes start at the same position. That's why this code also tracks the start.
// We first find the closest node that directly ends at the position of the right paren. We then continue
// upwards to find the most outer node that starts at the same position as that node. (In this case,
// `ReferenceIdentifier` -> `IdentifierExpression`.
let mut start_offset = None;
let r_paren_source_end = parentheses_source_range.end();
let ancestors = token.ancestors().take_while(|node| {
let source_range = self.parenthesized_range(node);
if let Some(start) = start_offset {
TextRange::new(start, r_paren_source_end).contains_range(source_range)
}
// Greater than to guarantee that we always return at least one node AND
// handle the case where a node is wrapped in multiple parentheses.
// Take the first node that fully encloses the parentheses
else if source_range.end() >= r_paren_source_end {
start_offset = Some(source_range.start());
true
} else {
source_range.end() < r_paren_source_end
}
});
// SAFETY:
// * The builder starts with a node which guarantees that every token has a parent node.
// * The above `take_while` guarantees to return `true` for the parent of the token.
// Thus, there's always at least one node
ancestors.last().unwrap()
}
}
}
}
#[cfg(test)]
mod tests {
use super::CommentsBuilderVisitor;
use crate::comments::{
CommentKind, CommentPlacement, CommentStyle, CommentTextPosition, CommentsMap,
DecoratedComment, SourceComment,
};
use crate::{TextSize, TransformSourceMap, TransformSourceMapBuilder};
use rome_js_parser::{parse_module, JsParserOptions};
use rome_js_syntax::{
JsIdentifierExpression, JsLanguage, JsParameters, JsParenthesizedExpression,
JsPropertyObjectMember, JsReferenceIdentifier, JsShorthandPropertyObjectMember,
JsSyntaxKind, JsSyntaxNode, JsUnaryExpression,
};
use rome_rowan::syntax::SyntaxElementKey;
use rome_rowan::{
chain_trivia_pieces, AstNode, BatchMutation, SyntaxNode, SyntaxTriviaPieceComments,
TextRange,
};
use std::cell::RefCell;
#[test]
fn leading_comment() {
let (root, decorated, comments) = extract_comments(
r#"const foo = {
a: 'a',
/* comment for this line */
b
};"#,
);
assert_eq!(decorated.len(), 1);
let comment = decorated.last().unwrap();
assert_eq!(comment.text_position(), CommentTextPosition::OwnLine);
assert_eq!(comment.lines_before(), 1);
assert_eq!(comment.lines_after(), 1);
assert_eq!(
comment
.preceding_node()
.map(|node| node.text_trimmed().to_string())
.as_deref(),
Some("a: 'a'")
);
assert_eq!(
comment
.following_node()
.map(|node| node.text_trimmed().to_string())
.as_deref(),
Some("b")
);
assert_eq!(
comment.enclosing_node().kind(),
JsSyntaxKind::JS_OBJECT_EXPRESSION
);
let b = root
.descendants()
.find_map(JsShorthandPropertyObjectMember::cast)
.unwrap();
assert!(!comments.leading(&b.syntax().key()).is_empty());
}
#[test]
fn trailing_comment() {
let (root, decorated, comments) = extract_comments(
r#"const foo = {
a: 'a' /* comment for this line */,
b
};"#,
);
assert_eq!(decorated.len(), 1);
let comment = decorated.last().unwrap();
assert_eq!(comment.text_position(), CommentTextPosition::SameLine);
assert_eq!(comment.lines_after(), 0);
assert_eq!(comment.lines_before(), 0);
assert_eq!(
comment
.preceding_node()
.map(|node| node.text_trimmed().to_string())
.as_deref(),
Some("a: 'a'")
);
assert_eq!(
comment
.following_node()
.map(|node| node.text_trimmed().to_string())
.as_deref(),
Some("b")
);
assert_eq!(
comment.enclosing_node().kind(),
JsSyntaxKind::JS_OBJECT_EXPRESSION
);
let a = root
.descendants()
.find_map(JsPropertyObjectMember::cast)
.unwrap();
assert!(!comments.trailing(&a.syntax().key()).is_empty());
}
#[test]
fn end_of_line_comment() {
let (root, decorated, comments) = extract_comments(
r#"const foo = {
a: 'a', /* comment for this line */
b
};"#,
);
assert_eq!(decorated.len(), 1);
let comment = decorated.last().unwrap();
assert_eq!(comment.text_position(), CommentTextPosition::EndOfLine);
assert_eq!(comment.lines_before(), 0);
assert_eq!(comment.lines_after(), 1);
assert_eq!(
comment
.preceding_node()
.map(|node| node.text_trimmed().to_string())
.as_deref(),
Some("a: 'a'")
);
assert_eq!(
comment
.following_node()
.map(|node| node.text_trimmed().to_string())
.as_deref(),
Some("b")
);
assert_eq!(
comment.enclosing_node().kind(),
JsSyntaxKind::JS_OBJECT_EXPRESSION
);
let a = root
.descendants()
.find_map(JsPropertyObjectMember::cast)
.unwrap();
assert!(!comments.trailing(&a.syntax().key()).is_empty());
}
#[test]
fn dangling_arrow() {
let (root, decorated_comments, comments) = extract_comments("(/* comment */) => true");
assert_eq!(decorated_comments.len(), 1);
let decorated = &decorated_comments[0];
assert_eq!(decorated.text_position(), CommentTextPosition::SameLine);
assert_eq!(decorated.lines_before(), 0);
assert_eq!(decorated.lines_after(), 0);
assert_eq!(decorated.preceding_node(), None);
assert_eq!(decorated.following_node(), None);
assert_eq!(
decorated.enclosing_node().kind(),
JsSyntaxKind::JS_PARAMETERS
);
let parameters = root.descendants().find_map(JsParameters::cast).unwrap();
assert!(!comments.dangling(¶meters.syntax().key()).is_empty());
}
#[test]
fn dangling_comments() {
let (root, decorated_comments, comments) = extract_comments(
r#"
function (/* test */) {}
"#,
);
assert_eq!(decorated_comments.len(), 1);
let decorated = &decorated_comments[0];
assert_eq!(decorated.text_position(), CommentTextPosition::SameLine);
assert_eq!(decorated.lines_before(), 0);
assert_eq!(decorated.lines_after(), 0);
assert_eq!(decorated.preceding_node(), None);
assert_eq!(decorated.following_node(), None);
assert_eq!(
decorated.enclosing_node().kind(),
JsSyntaxKind::JS_PARAMETERS
);
let parameters = root.descendants().find_map(JsParameters::cast).unwrap();
assert!(!comments.dangling(¶meters.syntax().key()).is_empty());
}
#[test]
fn r_paren() {
let source = r#"!(
a
/* comment */
)
/* comment */
b;"#;
let mut source_map_builder = TransformSourceMapBuilder::with_source(source.to_string());
let l_paren_range = TextRange::new(TextSize::from(1), TextSize::from(2));
let r_paren_range = TextRange::new(TextSize::from(27), TextSize::from(28));
assert_eq!(&source[l_paren_range], "(");
assert_eq!(&source[r_paren_range], ")");
source_map_builder.add_deleted_range(l_paren_range);
source_map_builder.add_deleted_range(r_paren_range);
source_map_builder.extend_trimmed_node_range(
TextRange::new(TextSize::from(7), TextSize::from(8)),
TextRange::new(l_paren_range.start(), r_paren_range.end()),
);
let source_map = source_map_builder.finish();
let root = parse_module(source, JsParserOptions::default()).syntax();
// A lot of code that simply removes the parenthesized expression and moves the parens
// trivia to the identifiers leading / trailing trivia.
let parenthesized = root
.descendants()
.find_map(JsParenthesizedExpression::cast)
.unwrap();
let reference_identifier = root
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/comments/map.rs | crates/rome_formatter/src/comments/map.rs | use countme::Count;
use rustc_hash::FxHashMap;
use std::fmt::{Debug, Formatter};
use std::iter::FusedIterator;
use std::num::NonZeroU32;
use std::ops::Range;
/// An optimized multi-map implementation for storing leading, dangling, and trailing parts for a key.
///
/// A naive implementation using three multimaps, one to store the leading, dangling, and trailing parts,
/// requires between `keys < allocations < keys * 3` vec allocations.
///
/// This map implementation optimises for the use case where:
/// * Parts belonging to the same key are inserted together. For example, all parts for the key `a` are inserted
/// before inserting any parts for the key `b`.
/// * The parts per key are inserted in the following order: leading, dangling, and then trailing parts.
///
/// Parts inserted in the above mentioned order are stored in a `Vec` shared by all keys to reduce the number
/// of allocations and increased cache locality. The implementation falls back to
/// storing the leading, dangling, and trailing parts of a key in dedicated `Vec`s if the parts
/// aren't inserted in the above described order. However, this comes with a slight performance penalty due to:
/// * Requiring up to three [Vec] allocations, one for the leading, dangling, and trailing parts.
/// * Requires copying already inserted parts for that key (by cloning) into the newly allocated [Vec]s.
/// * Resolving the slices for every part requires an extra level of indirection.
///
/// ## Limitations
///
/// The map supports storing up to `u32::MAX - 1` parts. Inserting the `u32::MAX`nth part panics.
///
/// ## Comments
///
/// Storing the leading, dangling, and trailing comments is an exemplary use case for this map implementation because
/// it is generally desired to keep the comments in the same order as in the source document. This translates to
/// inserting the comments per node and for every node in leading, dangling, trailing order (same order as this map optimises for).
///
/// Running Rome formatter on real world use cases showed that more than 99.99% of comments get inserted in
/// the described order.
///
/// The size limitation isn't a concern for comments because Rome supports source documents with a size up to 4GB (`u32::MAX`)
/// and every comment has at least a size of 2 bytes:
/// * 1 byte for the start sequence, e.g. `#`
/// * 1 byte for the end sequence, e.g. `\n`
///
/// Meaning, the upper bound for comments parts in a document are `u32::MAX / 2`.
pub(super) struct CommentsMap<K, V> {
/// Lookup table to retrieve the entry for a key.
index: FxHashMap<K, Entry>,
/// Flat array storing all the parts that have been inserted in order.
parts: Vec<V>,
/// Vector containing the leading, dangling, and trailing vectors for out of order entries.
///
/// The length of `out_of_order` is a multiple of 3 where:
/// * `index % 3 == 0`: Leading parts
/// * `index % 3 == 1`: Dangling parts
/// * `index % 3 == 2`: Trailing parts
out_of_order: Vec<Vec<V>>,
}
impl<K: std::hash::Hash + Eq, V> CommentsMap<K, V> {
pub fn new() -> Self {
Self {
index: FxHashMap::default(),
parts: Vec::new(),
out_of_order: Vec::new(),
}
}
/// Pushes a leading part for `key`.
pub fn push_leading(&mut self, key: K, part: V)
where
V: Clone,
{
match self.index.get_mut(&key) {
None => {
let start = self.parts.len();
self.parts.push(part);
self.index.insert(
key,
Entry::InOrder(InOrderEntry::leading(start..self.parts.len())),
);
}
// Has only leading comments and no elements have been pushed since
Some(Entry::InOrder(entry))
if entry.trailing_start.is_none() && self.parts.len() == entry.range().end =>
{
self.parts.push(part);
entry.increment_leading_range();
}
Some(Entry::OutOfOrder(entry)) => {
let leading = &mut self.out_of_order[entry.leading_index()];
leading.push(part);
}
Some(entry) => {
let out_of_order =
Self::entry_to_out_of_order(entry, &self.parts, &mut self.out_of_order);
self.out_of_order[out_of_order.leading_index()].push(part);
}
}
}
/// Pushes a dangling part for `key`
pub fn push_dangling(&mut self, key: K, part: V)
where
V: Clone,
{
match self.index.get_mut(&key) {
None => {
let start = self.parts.len();
self.parts.push(part);
self.index.insert(
key,
Entry::InOrder(InOrderEntry::dangling(start..self.parts.len())),
);
}
// Has leading and dangling comments and its comments are at the end of parts
Some(Entry::InOrder(entry))
if entry.trailing_end.is_none() && self.parts.len() == entry.range().end =>
{
self.parts.push(part);
entry.increment_dangling_range();
}
Some(Entry::OutOfOrder(entry)) => {
let dangling = &mut self.out_of_order[entry.dangling_index()];
dangling.push(part);
}
Some(entry) => {
let out_of_order =
Self::entry_to_out_of_order(entry, &self.parts, &mut self.out_of_order);
self.out_of_order[out_of_order.dangling_index()].push(part);
}
}
}
/// Pushes a trailing part for `key`.
pub fn push_trailing(&mut self, key: K, part: V)
where
V: Clone,
{
match self.index.get_mut(&key) {
None => {
let start = self.parts.len();
self.parts.push(part);
self.index.insert(
key,
Entry::InOrder(InOrderEntry::trailing(start..self.parts.len())),
);
}
// Its comments are at the end
Some(Entry::InOrder(entry)) if entry.range().end == self.parts.len() => {
self.parts.push(part);
entry.increment_trailing_range();
}
Some(Entry::OutOfOrder(entry)) => {
let trailing = &mut self.out_of_order[entry.trailing_index()];
trailing.push(part);
}
Some(entry) => {
let out_of_order =
Self::entry_to_out_of_order(entry, &self.parts, &mut self.out_of_order);
self.out_of_order[out_of_order.trailing_index()].push(part);
}
}
}
#[cold]
fn entry_to_out_of_order<'a>(
entry: &'a mut Entry,
parts: &[V],
out_of_order: &mut Vec<Vec<V>>,
) -> &'a mut OutOfOrderEntry
where
V: Clone,
{
match entry {
Entry::InOrder(in_order) => {
let index = out_of_order.len();
out_of_order.push(parts[in_order.leading_range()].to_vec());
out_of_order.push(parts[in_order.dangling_range()].to_vec());
out_of_order.push(parts[in_order.trailing_range()].to_vec());
*entry = Entry::OutOfOrder(OutOfOrderEntry {
leading_index: index,
_count: Count::new(),
});
match entry {
Entry::InOrder(_) => unreachable!(),
Entry::OutOfOrder(out_of_order) => out_of_order,
}
}
Entry::OutOfOrder(entry) => entry,
}
}
/// Retrieves all leading parts of `key`
pub fn leading(&self, key: &K) -> &[V] {
match self.index.get(key) {
None => &[],
Some(Entry::InOrder(in_order)) => &self.parts[in_order.leading_range()],
Some(Entry::OutOfOrder(entry)) => &self.out_of_order[entry.leading_index()],
}
}
/// Retrieves all dangling parts of `key`.
pub fn dangling(&self, key: &K) -> &[V] {
match self.index.get(key) {
None => &[],
Some(Entry::InOrder(in_order)) => &self.parts[in_order.dangling_range()],
Some(Entry::OutOfOrder(entry)) => &self.out_of_order[entry.dangling_index()],
}
}
/// Retrieves all trailing parts of `key`.
pub fn trailing(&self, key: &K) -> &[V] {
match self.index.get(key) {
None => &[],
Some(Entry::InOrder(in_order)) => &self.parts[in_order.trailing_range()],
Some(Entry::OutOfOrder(entry)) => &self.out_of_order[entry.trailing_index()],
}
}
/// Returns `true` if `key` has any leading, dangling, or trailing part.
pub fn has(&self, key: &K) -> bool {
self.index.get(key).is_some()
}
/// Returns an iterator over all leading, dangling, and trailing parts of `key`.
pub fn parts(&self, key: &K) -> PartsIterator<V> {
match self.index.get(key) {
None => PartsIterator::Slice([].iter()),
Some(entry) => PartsIterator::from_entry(entry, self),
}
}
/// Returns an iterator over the parts of all keys.
#[allow(unused)]
pub fn all_parts(&self) -> impl Iterator<Item = &V> {
self.index
.values()
.flat_map(|entry| PartsIterator::from_entry(entry, self))
}
}
impl<K: std::hash::Hash + Eq, V> Default for CommentsMap<K, V> {
fn default() -> Self {
Self::new()
}
}
impl<K, V> std::fmt::Debug for CommentsMap<K, V>
where
K: std::fmt::Debug,
V: std::fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut builder = f.debug_map();
for (key, entry) in &self.index {
builder.entry(&key, &DebugEntry { entry, map: self });
}
builder.finish()
}
}
/// Iterator to iterate over all leading, dangling, and trailing parts of a key.
pub(super) enum PartsIterator<'a, V> {
/// The slice into the [CommentsMap::parts] [Vec] if this is an in-order entry or the trailing parts
/// of an out-of-order entry.
Slice(std::slice::Iter<'a, V>),
/// Iterator over the leading parts of an out-of-order entry. Returns the dangling parts, and then the
/// trailing parts once the leading iterator is fully consumed.
Leading {
leading: std::slice::Iter<'a, V>,
dangling: &'a [V],
trailing: &'a [V],
},
/// Iterator over the dangling parts of an out-of-order entry. Returns the trailing parts
/// once the leading iterator is fully consumed.
Dangling {
dangling: std::slice::Iter<'a, V>,
trailing: &'a [V],
},
}
impl<'a, V> PartsIterator<'a, V> {
fn from_entry<K>(entry: &Entry, map: &'a CommentsMap<K, V>) -> Self {
match entry {
Entry::OutOfOrder(entry) => PartsIterator::Leading {
leading: map.out_of_order[entry.leading_index()].iter(),
dangling: &map.out_of_order[entry.dangling_index()],
trailing: &map.out_of_order[entry.trailing_index()],
},
Entry::InOrder(entry) => PartsIterator::Slice(map.parts[entry.range()].iter()),
}
}
}
impl<'a, V> Iterator for PartsIterator<'a, V> {
type Item = &'a V;
fn next(&mut self) -> Option<Self::Item> {
match self {
PartsIterator::Slice(inner) => inner.next(),
PartsIterator::Leading {
leading,
dangling,
trailing,
} => match leading.next() {
Some(next) => Some(next),
None if !dangling.is_empty() => {
let mut dangling_iterator = dangling.iter();
let next = dangling_iterator.next().unwrap();
*self = PartsIterator::Dangling {
dangling: dangling_iterator,
trailing,
};
Some(next)
}
None => {
let mut trailing_iterator = trailing.iter();
let next = trailing_iterator.next();
*self = PartsIterator::Slice(trailing_iterator);
next
}
},
PartsIterator::Dangling { dangling, trailing } => match dangling.next() {
Some(next) => Some(next),
None => {
let mut trailing_iterator = trailing.iter();
let next = trailing_iterator.next();
*self = PartsIterator::Slice(trailing_iterator);
next
}
},
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self {
PartsIterator::Slice(slice) => slice.size_hint(),
PartsIterator::Leading {
leading,
dangling,
trailing,
} => {
let len = leading.len() + dangling.len() + trailing.len();
(len, Some(len))
}
PartsIterator::Dangling { dangling, trailing } => {
let len = dangling.len() + trailing.len();
(len, Some(len))
}
}
}
fn last(self) -> Option<Self::Item>
where
Self: Sized,
{
match self {
PartsIterator::Slice(slice) => slice.last(),
PartsIterator::Leading {
leading,
dangling,
trailing,
} => trailing
.last()
.or_else(|| dangling.last())
.or_else(|| leading.last()),
PartsIterator::Dangling { dangling, trailing } => {
trailing.last().or_else(|| dangling.last())
}
}
}
}
impl<V> ExactSizeIterator for PartsIterator<'_, V> {}
impl<V> FusedIterator for PartsIterator<'_, V> {}
#[derive(Debug)]
enum Entry {
InOrder(InOrderEntry),
OutOfOrder(OutOfOrderEntry),
}
struct DebugEntry<'a, K, V> {
entry: &'a Entry,
map: &'a CommentsMap<K, V>,
}
impl<K, V> Debug for DebugEntry<'_, K, V>
where
K: Debug,
V: Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let leading = match self.entry {
Entry::OutOfOrder(entry) => self.map.out_of_order[entry.leading_index()].as_slice(),
Entry::InOrder(entry) => &self.map.parts[entry.leading_range()],
};
let dangling = match self.entry {
Entry::OutOfOrder(entry) => self.map.out_of_order[entry.dangling_index()].as_slice(),
Entry::InOrder(entry) => &self.map.parts[entry.dangling_range()],
};
let trailing = match self.entry {
Entry::OutOfOrder(entry) => self.map.out_of_order[entry.trailing_index()].as_slice(),
Entry::InOrder(entry) => &self.map.parts[entry.trailing_range()],
};
let mut list = f.debug_list();
list.entries(leading.iter().map(DebugValue::Leading));
list.entries(dangling.iter().map(DebugValue::Dangling));
list.entries(trailing.iter().map(DebugValue::Trailing));
list.finish()
}
}
enum DebugValue<'a, V> {
Leading(&'a V),
Dangling(&'a V),
Trailing(&'a V),
}
impl<V> Debug for DebugValue<'_, V>
where
V: Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
DebugValue::Leading(leading) => f.debug_tuple("Leading").field(leading).finish(),
DebugValue::Dangling(dangling) => f.debug_tuple("Dangling").field(dangling).finish(),
DebugValue::Trailing(trailing) => f.debug_tuple("Trailing").field(trailing).finish(),
}
}
}
#[derive(Debug)]
struct InOrderEntry {
/// Index into the [CommentsMap::parts] vector where the leading parts of this entry start
leading_start: PartIndex,
/// Index into the [CommentsMap::parts] vector where the dangling parts (and, thus, the leading parts end) start.
dangling_start: PartIndex,
/// Index into the [CommentsMap::parts] vector where the trailing parts (and, thus, the dangling parts end) of this entry start
trailing_start: Option<PartIndex>,
/// Index into the [CommentsMap::parts] vector where the trailing parts of this entry end
trailing_end: Option<PartIndex>,
_count: Count<InOrderEntry>,
}
impl InOrderEntry {
fn leading(range: Range<usize>) -> Self {
InOrderEntry {
leading_start: PartIndex::from_len(range.start),
dangling_start: PartIndex::from_len(range.end),
trailing_start: None,
trailing_end: None,
_count: Count::new(),
}
}
fn dangling(range: Range<usize>) -> Self {
let start = PartIndex::from_len(range.start);
InOrderEntry {
leading_start: start,
dangling_start: start,
trailing_start: Some(PartIndex::from_len(range.end)),
trailing_end: None,
_count: Count::new(),
}
}
fn trailing(range: Range<usize>) -> Self {
let start = PartIndex::from_len(range.start);
InOrderEntry {
leading_start: start,
dangling_start: start,
trailing_start: Some(start),
trailing_end: Some(PartIndex::from_len(range.end)),
_count: Count::new(),
}
}
fn increment_leading_range(&mut self) {
assert!(
self.trailing_start.is_none(),
"Can't extend the leading range for an in order entry with dangling comments."
);
self.dangling_start.increment();
}
fn increment_dangling_range(&mut self) {
assert!(
self.trailing_end.is_none(),
"Can't extend the dangling range for an in order entry with trailing comments."
);
match &mut self.trailing_start {
Some(start) => start.increment(),
None => self.trailing_start = Some(self.dangling_start.incremented()),
}
}
fn increment_trailing_range(&mut self) {
match (self.trailing_start, &mut self.trailing_end) {
// Already has some trailing comments
(Some(_), Some(end)) => end.increment(),
// Has dangling comments only
(Some(start), None) => self.trailing_end = Some(start.incremented()),
// Has leading comments only
(None, None) => {
self.trailing_start = Some(self.dangling_start);
self.trailing_end = Some(self.dangling_start.incremented())
}
(None, Some(_)) => {
unreachable!()
}
}
}
fn leading_range(&self) -> Range<usize> {
self.leading_start.value()..self.dangling_start.value()
}
fn dangling_range(&self) -> Range<usize> {
match self.trailing_start {
None => self.dangling_start.value()..self.dangling_start.value(),
Some(trailing_start) => self.dangling_start.value()..trailing_start.value(),
}
}
fn trailing_range(&self) -> Range<usize> {
match (self.trailing_start, self.trailing_end) {
(Some(trailing_start), Some(trailing_end)) => {
trailing_start.value()..trailing_end.value()
}
// Only dangling comments
(Some(trailing_start), None) => trailing_start.value()..trailing_start.value(),
(None, Some(_)) => {
panic!("Trailing end shouldn't be set if trailing start is none");
}
(None, None) => self.dangling_start.value()..self.dangling_start.value(),
}
}
fn range(&self) -> Range<usize> {
self.leading_start.value()
..self
.trailing_end
.or(self.trailing_start)
.unwrap_or(self.dangling_start)
.value()
}
}
#[derive(Debug)]
struct OutOfOrderEntry {
/// Index into the [CommentsMap::out_of_order] vector at which offset the leaading vec is stored.
leading_index: usize,
_count: Count<OutOfOrderEntry>,
}
impl OutOfOrderEntry {
const fn leading_index(&self) -> usize {
self.leading_index
}
const fn dangling_index(&self) -> usize {
self.leading_index + 1
}
const fn trailing_index(&self) -> usize {
self.leading_index + 2
}
}
/// Index into the [CommentsMap::parts] vector.
///
/// Stores the index as a [NonZeroU32], starting at 1 instead of 0 so that
/// `size_of::<PartIndex>() == size_of::<Option<PartIndex>>()`.
///
/// This means, that only `u32 - 1` parts can be stored. This should be sufficient for storing comments
/// because: Comments have length of two or more bytes because they consist of a start and end character sequence (`#` + new line, `/*` and `*/`).
/// Thus, a document with length `u32` can have at most `u32::MAX / 2` comment-parts.
#[repr(transparent)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
struct PartIndex(NonZeroU32);
impl PartIndex {
fn from_len(value: usize) -> Self {
Self(NonZeroU32::try_from(value as u32 + 1).unwrap())
}
fn value(&self) -> usize {
(u32::from(self.0) - 1) as usize
}
fn increment(&mut self) {
*self = self.incremented();
}
fn incremented(&self) -> PartIndex {
PartIndex(NonZeroU32::new(self.0.get() + 1).unwrap())
}
}
#[cfg(test)]
mod tests {
use crate::comments::map::CommentsMap;
static EMPTY: [i32; 0] = [];
#[test]
fn leading_dangling_trailing() {
let mut map = CommentsMap::new();
map.push_leading("a", 1);
map.push_dangling("a", 2);
map.push_dangling("a", 3);
map.push_trailing("a", 4);
assert_eq!(map.parts, vec![1, 2, 3, 4]);
assert_eq!(map.leading(&"a"), &[1]);
assert_eq!(map.dangling(&"a"), &[2, 3]);
assert_eq!(map.trailing(&"a"), &[4]);
assert!(map.has(&"a"));
assert_eq!(
map.parts(&"a").copied().collect::<Vec<_>>(),
vec![1, 2, 3, 4]
);
}
#[test]
fn dangling_trailing() {
let mut map = CommentsMap::new();
map.push_dangling("a", 1);
map.push_dangling("a", 2);
map.push_trailing("a", 3);
assert_eq!(map.parts, vec![1, 2, 3]);
assert_eq!(map.leading(&"a"), &EMPTY);
assert_eq!(map.dangling(&"a"), &[1, 2]);
assert_eq!(map.trailing(&"a"), &[3]);
assert!(map.has(&"a"));
assert_eq!(map.parts(&"a").copied().collect::<Vec<_>>(), vec![1, 2, 3]);
}
#[test]
fn trailing() {
let mut map = CommentsMap::new();
map.push_trailing("a", 1);
map.push_trailing("a", 2);
assert_eq!(map.parts, vec![1, 2]);
assert_eq!(map.leading(&"a"), &EMPTY);
assert_eq!(map.dangling(&"a"), &EMPTY);
assert_eq!(map.trailing(&"a"), &[1, 2]);
assert!(map.has(&"a"));
assert_eq!(map.parts(&"a").copied().collect::<Vec<_>>(), vec![1, 2]);
}
#[test]
fn empty() {
let map = CommentsMap::<&str, i32>::default();
assert_eq!(map.parts, Vec::<i32>::new());
assert_eq!(map.leading(&"a"), &EMPTY);
assert_eq!(map.dangling(&"a"), &EMPTY);
assert_eq!(map.trailing(&"a"), &EMPTY);
assert!(!map.has(&"a"));
assert_eq!(
map.parts(&"a").copied().collect::<Vec<_>>(),
Vec::<i32>::new()
);
}
#[test]
fn multiple_keys() {
let mut map = CommentsMap::new();
map.push_leading("a", 1);
map.push_dangling("b", 2);
map.push_trailing("c", 3);
map.push_leading("d", 4);
map.push_dangling("d", 5);
map.push_trailing("d", 6);
assert_eq!(map.parts, &[1, 2, 3, 4, 5, 6]);
assert_eq!(map.leading(&"a"), &[1]);
assert_eq!(map.dangling(&"a"), &EMPTY);
assert_eq!(map.trailing(&"a"), &EMPTY);
assert_eq!(map.parts(&"a").copied().collect::<Vec<_>>(), vec![1]);
assert_eq!(map.leading(&"b"), &EMPTY);
assert_eq!(map.dangling(&"b"), &[2]);
assert_eq!(map.trailing(&"b"), &EMPTY);
assert_eq!(map.parts(&"b").copied().collect::<Vec<_>>(), vec![2]);
assert_eq!(map.leading(&"c"), &EMPTY);
assert_eq!(map.dangling(&"c"), &EMPTY);
assert_eq!(map.trailing(&"c"), &[3]);
assert_eq!(map.parts(&"c").copied().collect::<Vec<_>>(), vec![3]);
assert_eq!(map.leading(&"d"), &[4]);
assert_eq!(map.dangling(&"d"), &[5]);
assert_eq!(map.trailing(&"d"), &[6]);
assert_eq!(map.parts(&"d").copied().collect::<Vec<_>>(), vec![4, 5, 6]);
}
#[test]
fn dangling_leading() {
let mut map = CommentsMap::new();
map.push_dangling("a", 1);
map.push_leading("a", 2);
map.push_dangling("a", 3);
map.push_trailing("a", 4);
assert_eq!(map.leading(&"a"), [2]);
assert_eq!(map.dangling(&"a"), [1, 3]);
assert_eq!(map.trailing(&"a"), [4]);
assert_eq!(
map.parts(&"a").copied().collect::<Vec<_>>(),
vec![2, 1, 3, 4]
);
assert!(map.has(&"a"));
}
#[test]
fn trailing_leading() {
let mut map = CommentsMap::new();
map.push_trailing("a", 1);
map.push_leading("a", 2);
map.push_dangling("a", 3);
map.push_trailing("a", 4);
assert_eq!(map.leading(&"a"), [2]);
assert_eq!(map.dangling(&"a"), [3]);
assert_eq!(map.trailing(&"a"), [1, 4]);
assert_eq!(
map.parts(&"a").copied().collect::<Vec<_>>(),
vec![2, 3, 1, 4]
);
assert!(map.has(&"a"));
}
#[test]
fn trailing_dangling() {
let mut map = CommentsMap::new();
map.push_trailing("a", 1);
map.push_dangling("a", 2);
map.push_trailing("a", 3);
assert_eq!(map.leading(&"a"), &EMPTY);
assert_eq!(map.dangling(&"a"), &[2]);
assert_eq!(map.trailing(&"a"), &[1, 3]);
assert_eq!(map.parts(&"a").copied().collect::<Vec<_>>(), vec![2, 1, 3]);
assert!(map.has(&"a"));
}
#[test]
fn keys_out_of_order() {
let mut map = CommentsMap::new();
map.push_leading("a", 1);
map.push_dangling("b", 2);
map.push_leading("a", 3);
map.push_trailing("c", 4);
map.push_dangling("b", 5);
map.push_leading("d", 6);
map.push_trailing("c", 7);
assert_eq!(map.leading(&"a"), &[1, 3]);
assert_eq!(map.dangling(&"b"), &[2, 5]);
assert_eq!(map.trailing(&"c"), &[4, 7]);
assert!(map.has(&"a"));
assert!(map.has(&"b"));
assert!(map.has(&"c"));
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/token/number.rs | crates/rome_formatter/src/token/number.rs | use crate::token::string::ToAsciiLowercaseCow;
use rome_rowan::{Language, SyntaxToken};
use std::borrow::Cow;
use std::num::NonZeroUsize;
use crate::prelude::*;
use crate::{CstFormatContext, Format};
pub fn format_number_token<L>(token: &SyntaxToken<L>) -> CleanedNumberLiteralText<L>
where
L: Language,
{
CleanedNumberLiteralText { token }
}
pub struct CleanedNumberLiteralText<'token, L>
where
L: Language,
{
token: &'token SyntaxToken<L>,
}
impl<L, C> Format<C> for CleanedNumberLiteralText<'_, L>
where
L: Language + 'static,
C: CstFormatContext<Language = L>,
{
fn fmt(&self, f: &mut Formatter<C>) -> FormatResult<()> {
format_replaced(
self.token,
&syntax_token_cow_slice(
format_trimmed_number(self.token.text_trimmed()),
self.token,
self.token.text_trimmed_range().start(),
),
)
.fmt(f)
}
}
enum FormatNumberLiteralState {
IntegerPart,
DecimalPart(FormatNumberLiteralDecimalPart),
Exponent(FormatNumberLiteralExponent),
}
struct FormatNumberLiteralDecimalPart {
dot_index: usize,
last_non_zero_index: Option<NonZeroUsize>,
}
struct FormatNumberLiteralExponent {
e_index: usize,
is_negative: bool,
first_digit_index: Option<NonZeroUsize>,
first_non_zero_index: Option<NonZeroUsize>,
}
// Regex-free version of https://github.com/prettier/prettier/blob/ca246afacee8e6d5db508dae01730c9523bbff1d/src/common/util.js#L341-L356
fn format_trimmed_number(text: &str) -> Cow<str> {
use FormatNumberLiteralState::*;
let text = text.to_ascii_lowercase_cow();
let mut copied_or_ignored_chars = 0usize;
let mut iter = text.chars().enumerate();
let mut curr = iter.next();
let mut state = IntegerPart;
// Will be filled only if and when the first place that needs reformatting is detected.
let mut cleaned_text = String::new();
// Look at only the start of the text, ignore any sign, and make sure numbers always start with a digit. Add 0 if missing.
if let Some((_, '+' | '-')) = curr {
curr = iter.next();
}
if let Some((curr_index, '.')) = curr {
cleaned_text.push_str(&text[copied_or_ignored_chars..curr_index]);
copied_or_ignored_chars = curr_index;
cleaned_text.push('0');
}
// Loop over the rest of the text, applying the remaining rules.
loop {
// We use a None pseudo-char at the end of the string to simplify the match cases that follow
let curr_or_none_terminator_char = match curr {
Some((curr_index, curr_char)) => (curr_index, Some(curr_char)),
None => (text.len(), None),
};
// Look for termination of the decimal part or exponent and see if we need to print it differently.
match (&state, curr_or_none_terminator_char) {
(
DecimalPart(FormatNumberLiteralDecimalPart {
dot_index,
last_non_zero_index: None,
}),
(curr_index, Some('e') | None),
) => {
// The decimal part equals zero, ignore it completely.
// Caveat: Prettier still prints a single `.0` unless there was *only* a trailing dot.
if curr_index > dot_index + 1 {
cleaned_text.push_str(&text[copied_or_ignored_chars..=*dot_index]);
cleaned_text.push('0');
} else {
cleaned_text.push_str(&text[copied_or_ignored_chars..*dot_index]);
}
copied_or_ignored_chars = curr_index;
}
(
DecimalPart(FormatNumberLiteralDecimalPart {
last_non_zero_index: Some(last_non_zero_index),
..
}),
(curr_index, Some('e') | None),
) if last_non_zero_index.get() < curr_index - 1 => {
// The decimal part ends with at least one zero, ignore them but copy the part from the dot until the last non-zero.
cleaned_text.push_str(&text[copied_or_ignored_chars..=last_non_zero_index.get()]);
copied_or_ignored_chars = curr_index;
}
(
Exponent(FormatNumberLiteralExponent {
e_index,
first_non_zero_index: None,
..
}),
(curr_index, None),
) => {
// The exponent equals zero, ignore it completely.
cleaned_text.push_str(&text[copied_or_ignored_chars..*e_index]);
copied_or_ignored_chars = curr_index;
}
(
Exponent(FormatNumberLiteralExponent {
e_index,
is_negative,
first_digit_index: Some(first_digit_index),
first_non_zero_index: Some(first_non_zero_index),
}),
(curr_index, None),
) if (first_digit_index.get() > e_index + 1 && !is_negative)
|| (first_non_zero_index.get() > first_digit_index.get()) =>
{
// The exponent begins with a plus or at least one zero, ignore them but copy the part from the first non-zero until the end.
cleaned_text.push_str(&text[copied_or_ignored_chars..=*e_index]);
if *is_negative {
cleaned_text.push('-');
}
cleaned_text.push_str(&text[first_non_zero_index.get()..curr_index]);
copied_or_ignored_chars = curr_index;
}
_ => {}
}
// Update state after the current char
match (&state, curr) {
// Cases entering or remaining in decimal part
(_, Some((curr_index, '.'))) => {
state = DecimalPart(FormatNumberLiteralDecimalPart {
dot_index: curr_index,
last_non_zero_index: None,
});
}
(DecimalPart(decimal_part), Some((curr_index, '1'..='9'))) => {
state = DecimalPart(FormatNumberLiteralDecimalPart {
last_non_zero_index: Some(unsafe {
// We've already entered InDecimalPart, so curr_index must be >0
NonZeroUsize::new_unchecked(curr_index)
}),
..*decimal_part
});
}
// Cases entering or remaining in exponent
(_, Some((curr_index, 'e'))) => {
state = Exponent(FormatNumberLiteralExponent {
e_index: curr_index,
is_negative: false,
first_digit_index: None,
first_non_zero_index: None,
});
}
(Exponent(exponent), Some((_, '-'))) => {
state = Exponent(FormatNumberLiteralExponent {
is_negative: true,
..*exponent
});
}
(
Exponent(
exponent @ FormatNumberLiteralExponent {
first_digit_index: None,
..
},
),
Some((curr_index, curr_char @ '0'..='9')),
) => {
state = Exponent(FormatNumberLiteralExponent {
first_digit_index: Some(unsafe {
// We've already entered InExponent, so curr_index must be >0
NonZeroUsize::new_unchecked(curr_index)
}),
first_non_zero_index: if curr_char != '0' {
Some(unsafe {
// We've already entered InExponent, so curr_index must be >0
NonZeroUsize::new_unchecked(curr_index)
})
} else {
None
},
..*exponent
});
}
(
Exponent(
exponent @ FormatNumberLiteralExponent {
first_non_zero_index: None,
..
},
),
Some((curr_index, '1'..='9')),
) => {
state = Exponent(FormatNumberLiteralExponent {
first_non_zero_index: Some(unsafe { NonZeroUsize::new_unchecked(curr_index) }),
..*exponent
});
}
_ => {}
}
// Repeat or exit
match curr {
None | Some((_, 'x') /* hex bailout */) => break,
Some(_) => curr = iter.next(),
}
}
if cleaned_text.is_empty() {
text
} else {
// Append any unconsidered text
cleaned_text.push_str(&text[copied_or_ignored_chars..]);
Cow::Owned(cleaned_text)
}
}
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use super::format_trimmed_number;
#[test]
fn removes_unnecessary_plus_and_zeros_from_scientific_notation() {
assert_eq!("1e2", format_trimmed_number("1e02"));
assert_eq!("1e2", format_trimmed_number("1e+2"));
}
#[test]
fn removes_unnecessary_scientific_notation() {
assert_eq!("1", format_trimmed_number("1e0"));
assert_eq!("1", format_trimmed_number("1e-0"));
}
#[test]
fn does_not_get_bamboozled_by_hex() {
assert_eq!("0xe0", format_trimmed_number("0xe0"));
assert_eq!("0x10e0", format_trimmed_number("0x10e0"));
}
#[test]
fn makes_sure_numbers_always_start_with_a_digit() {
assert_eq!("0.2", format_trimmed_number(".2"));
}
#[test]
fn removes_extraneous_trailing_decimal_zeroes() {
assert_eq!("0.1", format_trimmed_number("0.10"));
}
#[test]
fn keeps_one_trailing_decimal_zero() {
assert_eq!("0.0", format_trimmed_number("0.00"));
}
#[test]
fn removes_trailing_dot() {
assert_eq!("1", format_trimmed_number("1."));
}
#[test]
fn cleans_all_at_once() {
assert_eq!("0.0", format_trimmed_number(".00e-0"));
}
#[test]
fn keeps_the_input_string_if_no_change_needed() {
assert!(matches!(
format_trimmed_number("0.1e2"),
Cow::Borrowed("0.1e2")
));
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/token/string.rs | crates/rome_formatter/src/token/string.rs | use std::borrow::Cow;
pub trait ToAsciiLowercaseCow {
/// Returns the same value as String::to_lowercase. The only difference
/// is that this functions returns ```Cow``` and does not allocate
/// if the string is already in lowercase.
fn to_ascii_lowercase_cow(&self) -> Cow<str>;
}
impl ToAsciiLowercaseCow for str {
fn to_ascii_lowercase_cow(&self) -> Cow<str> {
debug_assert!(self.is_ascii());
let bytes = self.as_bytes();
for idx in 0..bytes.len() {
let chr = bytes[idx];
if chr != chr.to_ascii_lowercase() {
let mut s = bytes.to_vec();
for b in &mut s[idx..] {
b.make_ascii_lowercase();
}
return Cow::Owned(unsafe { String::from_utf8_unchecked(s) });
}
}
Cow::Borrowed(self)
}
}
impl ToAsciiLowercaseCow for String {
#[inline(always)]
fn to_ascii_lowercase_cow(&self) -> Cow<str> {
self.as_str().to_ascii_lowercase_cow()
}
}
/// This signal is used to tell to the next character what it should do
#[derive(Eq, PartialEq)]
pub enum CharSignal {
/// There hasn't been any signal
None,
/// The function decided to keep the previous character
Keep,
/// The function has decided to print the character. Saves the character that was
/// already written
AlreadyPrinted(char),
}
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub enum Quote {
Double,
Single,
}
impl Quote {
pub fn as_char(&self) -> char {
match self {
Quote::Double => '"',
Quote::Single => '\'',
}
}
pub fn as_string(&self) -> &str {
match self {
Quote::Double => "\"",
Quote::Single => "'",
}
}
/// Returns the quote, prepended with a backslash (escaped)
pub fn as_escaped(&self) -> &str {
match self {
Quote::Double => "\\\"",
Quote::Single => "\\'",
}
}
pub fn as_bytes(&self) -> u8 {
self.as_char() as u8
}
/// Given the current quote, it returns the other one
pub fn other(&self) -> Self {
match self {
Quote::Double => Quote::Single,
Quote::Single => Quote::Double,
}
}
}
/// This function is responsible of:
///
/// - reducing the number of escapes
/// - normalising the new lines
///
/// # Escaping
///
/// The way it works is the following: we split the content by analyzing all the
/// characters that could keep the escape.
///
/// Each time we retrieve one of this character, we push inside a new string all the content
/// found **before** the current character.
///
/// After that the function checks if the current character should be also be printed or not.
/// These characters (like quotes) can have an escape that might be removed. If that happens,
/// we use [CharSignal] to tell to the next iteration what it should do with that character.
///
/// For example, let's take this example:
/// ```js
/// ("hello! \'")
/// ```
///
/// Here, we want to remove the backslash (\) from the content. So when we encounter `\`,
/// the algorithm checks if after `\` there's a `'`, and if so, then we push inside the final string
/// only `'` and we ignore the backlash. Then we signal the next iteration with [CharSignal::AlreadyPrinted],
/// so when we process the next `'`, we decide to ignore it and reset the signal.
///
/// Another example is the following:
///
/// ```js
/// (" \\' ")
/// ```
///
/// Here, we need to keep all the backslash. We check the first one and we look ahead. We find another
/// `\`, so we keep it the first and we signal the next iteration with [CharSignal::Keep].
/// Then the next iteration comes along. We have the second `\`, we look ahead we find a `'`. Although,
/// as opposed to the previous example, we have a signal that says that we should keep the current
/// character. Then we do so. The third iteration comes along and we find `'`. We still have the
/// [CharSignal::Keep]. We do so and then we set the signal to [CharSignal::None]
///
/// # Newlines
///
/// By default the formatter uses `\n` as a newline. The function replaces
/// `\r\n` with `\n`,
pub fn normalize_string(raw_content: &str, preferred_quote: Quote) -> Cow<str> {
let alternate_quote = preferred_quote.other();
// A string should be manipulated only if its raw content contains backslash or quotes
if !raw_content.contains(['\\', preferred_quote.as_char(), alternate_quote.as_char()]) {
return Cow::Borrowed(raw_content);
}
let mut reduced_string = String::new();
let mut signal = CharSignal::None;
let mut chars = raw_content.char_indices().peekable();
while let Some((_, current_char)) = chars.next() {
let next_character = chars.peek();
if let CharSignal::AlreadyPrinted(char) = signal {
if char == current_char {
continue;
}
}
match current_char {
'\\' => {
let bytes = raw_content.as_bytes();
if let Some((next_index, next_character)) = next_character {
// If we encounter an alternate quote that is escaped, we have to
// remove the escape from it.
// This is done because of how the enclosed strings can change.
// Check `computed_preferred_quote` for more details.
if *next_character as u8 == alternate_quote.as_bytes()
// This check is a safety net for cases where the backslash is at the end
// of the raw content:
// ("\\")
// The second backslash is at the end.
&& *next_index < bytes.len()
{
match signal {
CharSignal::Keep => {
reduced_string.push(current_char);
}
_ => {
reduced_string.push(alternate_quote.as_char());
signal = CharSignal::AlreadyPrinted(alternate_quote.as_char());
}
}
} else if signal == CharSignal::Keep {
reduced_string.push(current_char);
signal = CharSignal::None;
}
// The next character is another backslash, or
// a character that should be kept in the next iteration
else if "^\n\r\"'01234567\\bfnrtuvx\u{2028}\u{2029}".contains(*next_character)
{
signal = CharSignal::Keep;
// fallback, keep the backslash
reduced_string.push(current_char);
} else {
// these, usually characters that can have their
// escape removed: "\a" => "a"
// So we ignore the current slash and we continue
// to the next iteration
continue;
}
} else {
// fallback, keep the backslash
reduced_string.push(current_char);
}
}
'\n' | '\t' => {
if let CharSignal::AlreadyPrinted(the_char) = signal {
if matches!(the_char, '\n' | '\t') {
signal = CharSignal::None
}
} else {
reduced_string.push(current_char);
}
}
// If the current character is \r and the
// next is \n, skip over the entire sequence
'\r' if next_character.map_or(false, |(_, c)| *c == '\n') => {
reduced_string.push('\n');
signal = CharSignal::AlreadyPrinted('\n');
}
_ => {
// If we encounter a preferred quote and it's not escaped, we have to replace it with
// an escaped version.
// This is done because of how the enclosed strings can change.
// Check `computed_preferred_quote` for more details.
if current_char == preferred_quote.as_char() {
let last_char = &reduced_string.chars().last();
if let Some('\\') = last_char {
reduced_string.push(preferred_quote.as_char());
} else {
reduced_string.push_str(preferred_quote.as_escaped());
}
} else if current_char == alternate_quote.as_char() {
match signal {
CharSignal::None | CharSignal::Keep => {
reduced_string.push(alternate_quote.as_char());
}
CharSignal::AlreadyPrinted(_) => (),
}
} else {
reduced_string.push(current_char);
}
signal = CharSignal::None;
}
}
}
// Don't allocate a new string of this is empty
if reduced_string.is_empty() {
Cow::Borrowed(raw_content)
} else {
// don't allocate a new string if the new string is still equals to the input string
if reduced_string == raw_content {
Cow::Borrowed(raw_content)
} else {
Cow::Owned(reduced_string)
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/token/mod.rs | crates/rome_formatter/src/token/mod.rs | pub mod number;
pub mod string;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/format_element/document.rs | crates/rome_formatter/src/format_element/document.rs | use super::tag::Tag;
use crate::format_element::tag::DedentMode;
use crate::prelude::tag::GroupMode;
use crate::prelude::*;
use crate::printer::LineEnding;
use crate::{format, write};
use crate::{
BufferExtensions, Format, FormatContext, FormatElement, FormatOptions, FormatResult, Formatter,
IndentStyle, LineWidth, PrinterOptions, TransformSourceMap,
};
use rome_rowan::TextSize;
use rustc_hash::FxHashMap;
use std::collections::HashMap;
use std::ops::Deref;
/// A formatted document.
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct Document {
elements: Vec<FormatElement>,
}
impl Document {
/// Sets [`expand`](tag::Group::expand) to [`GroupMode::Propagated`] if the group contains any of:
/// * a group with [`expand`](tag::Group::expand) set to [GroupMode::Propagated] or [GroupMode::Expand].
/// * a non-soft [line break](FormatElement::Line) with mode [LineMode::Hard], [LineMode::Empty], or [LineMode::Literal].
/// * a [FormatElement::ExpandParent]
///
/// [`BestFitting`] elements act as expand boundaries, meaning that the fact that a
/// [`BestFitting`]'s content expands is not propagated past the [`BestFitting`] element.
///
/// [`BestFitting`]: FormatElement::BestFitting
pub(crate) fn propagate_expand(&mut self) {
#[derive(Debug)]
enum Enclosing<'a> {
Group(&'a tag::Group),
BestFitting,
}
fn expand_parent(enclosing: &[Enclosing]) {
if let Some(Enclosing::Group(group)) = enclosing.last() {
group.propagate_expand();
}
}
fn propagate_expands<'a>(
elements: &'a [FormatElement],
enclosing: &mut Vec<Enclosing<'a>>,
checked_interned: &mut FxHashMap<&'a Interned, bool>,
) -> bool {
let mut expands = false;
for element in elements {
let element_expands = match element {
FormatElement::Tag(Tag::StartGroup(group)) => {
enclosing.push(Enclosing::Group(group));
false
}
FormatElement::Tag(Tag::EndGroup) => match enclosing.pop() {
Some(Enclosing::Group(group)) => !group.mode().is_flat(),
_ => false,
},
FormatElement::Interned(interned) => match checked_interned.get(interned) {
Some(interned_expands) => *interned_expands,
None => {
let interned_expands =
propagate_expands(interned, enclosing, checked_interned);
checked_interned.insert(interned, interned_expands);
interned_expands
}
},
FormatElement::BestFitting(best_fitting) => {
enclosing.push(Enclosing::BestFitting);
for variant in best_fitting.variants() {
propagate_expands(variant, enclosing, checked_interned);
}
// Best fitting acts as a boundary
expands = false;
enclosing.pop();
continue;
}
FormatElement::StaticText { text } => text.contains('\n'),
FormatElement::DynamicText { text, .. } => text.contains('\n'),
FormatElement::LocatedTokenText { slice, .. } => slice.contains('\n'),
FormatElement::ExpandParent
| FormatElement::Line(LineMode::Hard | LineMode::Empty) => true,
_ => false,
};
if element_expands {
expands = true;
expand_parent(enclosing)
}
}
expands
}
let mut enclosing: Vec<Enclosing> = Vec::new();
let mut interned: FxHashMap<&Interned, bool> = FxHashMap::default();
propagate_expands(self, &mut enclosing, &mut interned);
}
}
impl From<Vec<FormatElement>> for Document {
fn from(elements: Vec<FormatElement>) -> Self {
Self { elements }
}
}
impl Deref for Document {
type Target = [FormatElement];
fn deref(&self) -> &Self::Target {
self.elements.as_slice()
}
}
impl std::fmt::Display for Document {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let formatted = format!(IrFormatContext::default(), [self.elements.as_slice()])
.expect("Formatting not to throw any FormatErrors");
f.write_str(
formatted
.print()
.expect("Expected a valid document")
.as_code(),
)
}
}
#[derive(Clone, Default, Debug)]
struct IrFormatContext {
/// The interned elements that have been printed to this point
printed_interned_elements: HashMap<Interned, usize>,
}
impl FormatContext for IrFormatContext {
type Options = IrFormatOptions;
fn options(&self) -> &Self::Options {
&IrFormatOptions
}
fn source_map(&self) -> Option<&TransformSourceMap> {
None
}
}
#[derive(Debug, Clone, Default)]
struct IrFormatOptions;
impl FormatOptions for IrFormatOptions {
fn indent_style(&self) -> IndentStyle {
IndentStyle::Space(2)
}
fn line_width(&self) -> LineWidth {
LineWidth(80)
}
fn as_print_options(&self) -> PrinterOptions {
PrinterOptions {
tab_width: 2,
print_width: self.line_width().into(),
line_ending: LineEnding::LineFeed,
indent_style: IndentStyle::Space(2),
}
}
}
impl Format<IrFormatContext> for &[FormatElement] {
fn fmt(&self, f: &mut Formatter<IrFormatContext>) -> FormatResult<()> {
use Tag::*;
write!(f, [ContentArrayStart])?;
let mut tag_stack = Vec::new();
let mut first_element = true;
let mut in_text = false;
let mut iter = self.iter().peekable();
while let Some(element) = iter.next() {
if !first_element && !in_text && !element.is_end_tag() {
// Write a separator between every two elements
write!(f, [text(","), soft_line_break_or_space()])?;
}
first_element = false;
match element {
element @ FormatElement::Space
| element @ FormatElement::StaticText { .. }
| element @ FormatElement::DynamicText { .. }
| element @ FormatElement::LocatedTokenText { .. } => {
if !in_text {
write!(f, [text("\"")])?;
}
in_text = true;
match element {
FormatElement::Space => {
write!(f, [text(" ")])?;
}
element if element.is_text() => f.write_element(element.clone())?,
_ => unreachable!(),
}
let is_next_text = iter.peek().map_or(false, |e| e.is_text() || e.is_space());
if !is_next_text {
write!(f, [text("\"")])?;
in_text = false;
}
}
FormatElement::Line(mode) => match mode {
LineMode::SoftOrSpace => {
write!(f, [text("soft_line_break_or_space")])?;
}
LineMode::Soft => {
write!(f, [text("soft_line_break")])?;
}
LineMode::Hard => {
write!(f, [text("hard_line_break")])?;
}
LineMode::Empty => {
write!(f, [text("empty_line")])?;
}
},
FormatElement::ExpandParent => {
write!(f, [text("expand_parent")])?;
}
FormatElement::LineSuffixBoundary => {
write!(f, [text("line_suffix_boundary")])?;
}
FormatElement::BestFitting(best_fitting) => {
write!(f, [text("best_fitting([")])?;
f.write_elements([
FormatElement::Tag(StartIndent),
FormatElement::Line(LineMode::Hard),
])?;
for variant in best_fitting.variants() {
write!(f, [variant.deref(), hard_line_break()])?;
}
f.write_elements([
FormatElement::Tag(EndIndent),
FormatElement::Line(LineMode::Hard),
])?;
write!(f, [text("])")])?;
}
FormatElement::Interned(interned) => {
let interned_elements = &mut f.context_mut().printed_interned_elements;
match interned_elements.get(interned).copied() {
None => {
let index = interned_elements.len();
interned_elements.insert(interned.clone(), index);
write!(
f,
[
dynamic_text(
&std::format!("<interned {index}>"),
TextSize::default()
),
space(),
&interned.deref(),
]
)?;
}
Some(reference) => {
write!(
f,
[dynamic_text(
&std::format!("<ref interned *{reference}>"),
TextSize::default()
)]
)?;
}
}
}
FormatElement::Tag(tag) => {
if tag.is_start() {
first_element = true;
tag_stack.push(tag.kind());
}
// Handle documents with mismatching start/end or superfluous end tags
else {
match tag_stack.pop() {
None => {
// Only write the end tag without any indent to ensure the output document is valid.
write!(
f,
[
text("<END_TAG_WITHOUT_START<"),
dynamic_text(
&std::format!("{:?}", tag.kind()),
TextSize::default()
),
text(">>"),
]
)?;
first_element = false;
continue;
}
Some(start_kind) if start_kind != tag.kind() => {
write!(
f,
[
ContentArrayEnd,
text(")"),
soft_line_break_or_space(),
text("ERROR<START_END_TAG_MISMATCH<start: "),
dynamic_text(
&std::format!("{start_kind:?}"),
TextSize::default()
),
text(", end: "),
dynamic_text(
&std::format!("{:?}", tag.kind()),
TextSize::default()
),
text(">>")
]
)?;
first_element = false;
continue;
}
_ => {
// all ok
}
}
}
match tag {
StartIndent => {
write!(f, [text("indent(")])?;
}
StartDedent(mode) => {
let label = match mode {
DedentMode::Level => "dedent",
DedentMode::Root => "dedentRoot",
};
write!(f, [text(label), text("(")])?;
}
StartAlign(tag::Align(count)) => {
write!(
f,
[
text("align("),
dynamic_text(&count.to_string(), TextSize::default()),
text(","),
space(),
]
)?;
}
StartLineSuffix => {
write!(f, [text("line_suffix(")])?;
}
StartVerbatim(_) => {
write!(f, [text("verbatim(")])?;
}
StartGroup(group) => {
write!(f, [text("group(")])?;
if let Some(group_id) = group.id() {
write!(
f,
[
dynamic_text(
&std::format!("\"{group_id:?}\""),
TextSize::default()
),
text(","),
space(),
]
)?;
}
match group.mode() {
GroupMode::Flat => {}
GroupMode::Expand => {
write!(f, [text("expand: true,"), space()])?;
}
GroupMode::Propagated => {
write!(f, [text("expand: propagated,"), space()])?;
}
}
}
StartIndentIfGroupBreaks(id) => {
write!(
f,
[
text("indent_if_group_breaks("),
dynamic_text(&std::format!("\"{id:?}\""), TextSize::default()),
text(","),
space(),
]
)?;
}
StartConditionalContent(condition) => {
match condition.mode {
PrintMode::Flat => {
write!(f, [text("if_group_fits_on_line(")])?;
}
PrintMode::Expanded => {
write!(f, [text("if_group_breaks(")])?;
}
}
if let Some(group_id) = condition.group_id {
write!(
f,
[
dynamic_text(
&std::format!("\"{group_id:?}\""),
TextSize::default()
),
text(","),
space(),
]
)?;
}
}
StartLabelled(label_id) => {
write!(
f,
[
text("label("),
dynamic_text(
&std::format!("\"{label_id:?}\""),
TextSize::default()
),
text(","),
space(),
]
)?;
}
StartFill => {
write!(f, [text("fill(")])?;
}
StartEntry => {
// handled after the match for all start tags
}
EndEntry => write!(f, [ContentArrayEnd])?,
EndFill
| EndLabelled
| EndConditionalContent
| EndIndentIfGroupBreaks
| EndAlign
| EndIndent
| EndGroup
| EndLineSuffix
| EndDedent
| EndVerbatim => {
write!(f, [ContentArrayEnd, text(")")])?;
}
};
if tag.is_start() {
write!(f, [ContentArrayStart])?;
}
}
}
}
while let Some(top) = tag_stack.pop() {
write!(
f,
[
ContentArrayEnd,
text(")"),
soft_line_break_or_space(),
dynamic_text(
&std::format!("<START_WITHOUT_END<{top:?}>>"),
TextSize::default()
),
]
)?;
}
write!(f, [ContentArrayEnd])
}
}
struct ContentArrayStart;
impl Format<IrFormatContext> for ContentArrayStart {
fn fmt(&self, f: &mut Formatter<IrFormatContext>) -> FormatResult<()> {
use Tag::*;
write!(f, [text("[")])?;
f.write_elements([
FormatElement::Tag(StartGroup(tag::Group::new())),
FormatElement::Tag(StartIndent),
FormatElement::Line(LineMode::Soft),
])
}
}
struct ContentArrayEnd;
impl Format<IrFormatContext> for ContentArrayEnd {
fn fmt(&self, f: &mut Formatter<IrFormatContext>) -> FormatResult<()> {
use Tag::*;
f.write_elements([
FormatElement::Tag(EndIndent),
FormatElement::Line(LineMode::Soft),
FormatElement::Tag(EndGroup),
])?;
write!(f, [text("]")])
}
}
impl FormatElements for [FormatElement] {
fn will_break(&self) -> bool {
use Tag::*;
let mut ignore_depth = 0usize;
for element in self {
match element {
// Line suffix
// Ignore if any of its content breaks
FormatElement::Tag(StartLineSuffix) => {
ignore_depth += 1;
}
FormatElement::Tag(EndLineSuffix) => {
ignore_depth -= 1;
}
FormatElement::Interned(interned) if ignore_depth == 0 => {
if interned.will_break() {
return true;
}
}
element if ignore_depth == 0 && element.will_break() => {
return true;
}
_ => continue,
}
}
debug_assert_eq!(ignore_depth, 0, "Unclosed start container");
false
}
fn has_label(&self, expected: LabelId) -> bool {
self.first()
.map_or(false, |element| element.has_label(expected))
}
fn start_tag(&self, kind: TagKind) -> Option<&Tag> {
// Assert that the document ends at a tag with the specified kind;
let _ = self.end_tag(kind)?;
fn traverse_slice<'a>(
slice: &'a [FormatElement],
kind: TagKind,
depth: &mut usize,
) -> Option<&'a Tag> {
for element in slice.iter().rev() {
match element {
FormatElement::Tag(tag) if tag.kind() == kind => {
if tag.is_start() {
if *depth == 0 {
// Invalid document
return None;
} else if *depth == 1 {
return Some(tag);
} else {
*depth -= 1;
}
} else {
*depth += 1;
}
}
FormatElement::Interned(interned) => {
match traverse_slice(interned, kind, depth) {
Some(start) => {
return Some(start);
}
// Reached end or invalid document
None if *depth == 0 => {
return None;
}
_ => {
// continue with other elements
}
}
}
_ => {}
}
}
None
}
let mut depth = 0usize;
traverse_slice(self, kind, &mut depth)
}
fn end_tag(&self, kind: TagKind) -> Option<&Tag> {
self.last().and_then(|element| element.end_tag(kind))
}
}
#[cfg(test)]
mod tests {
use crate::prelude::*;
use crate::SimpleFormatContext;
use crate::{format, format_args, write};
#[test]
fn display_elements() {
let formatted = format!(
SimpleFormatContext::default(),
[format_with(|f| {
write!(
f,
[group(&format_args![
text("("),
soft_block_indent(&format_args![
text("Some longer content"),
space(),
text("That should ultimately break"),
])
])]
)
})]
)
.unwrap();
let document = formatted.into_document();
assert_eq!(
&std::format!("{document}"),
r#"[
group([
"(",
indent([
soft_line_break,
"Some longer content That should ultimately break"
]),
soft_line_break
])
]"#
);
}
#[test]
fn display_invalid_document() {
use Tag::*;
let document = Document::from(vec![
FormatElement::StaticText { text: "[" },
FormatElement::Tag(StartGroup(tag::Group::new())),
FormatElement::Tag(StartIndent),
FormatElement::Line(LineMode::Soft),
FormatElement::StaticText { text: "a" },
// Close group instead of indent
FormatElement::Tag(EndGroup),
FormatElement::Line(LineMode::Soft),
FormatElement::Tag(EndIndent),
FormatElement::StaticText { text: "]" },
// End tag without start
FormatElement::Tag(EndIndent),
// Start tag without an end
FormatElement::Tag(StartIndent),
]);
assert_eq!(
&std::format!("{document}"),
r#"[
"[",
group([
indent([soft_line_break, "a"])
ERROR<START_END_TAG_MISMATCH<start: Indent, end: Group>>,
soft_line_break
])
ERROR<START_END_TAG_MISMATCH<start: Group, end: Indent>>,
"]"<END_TAG_WITHOUT_START<Indent>>,
indent([])
<START_WITHOUT_END<Indent>>
]"#
);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/format_element/tag.rs | crates/rome_formatter/src/format_element/tag.rs | use crate::format_element::PrintMode;
use crate::{GroupId, TextSize};
use std::cell::Cell;
use std::num::NonZeroU8;
/// A Tag marking the start and end of some content to which some special formatting should be applied.
///
/// Tags always come in pairs of a start and an end tag and the styling defined by this tag
/// will be applied to all elements in between the start/end tags.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Tag {
/// Indents the content one level deeper, see [crate::builders::indent] for documentation and examples.
StartIndent,
EndIndent,
/// Variant of [TagKind::Indent] that indents content by a number of spaces. For example, `Align(2)`
/// indents any content following a line break by an additional two spaces.
///
/// Nesting (Aligns)[TagKind::Align] has the effect that all except the most inner align are handled as (Indent)[TagKind::Indent].
StartAlign(Align),
EndAlign,
/// Reduces the indention of the specified content either by one level or to the root, depending on the mode.
/// Reverse operation of `Indent` and can be used to *undo* an `Align` for nested content.
StartDedent(DedentMode),
EndDedent,
/// Creates a logical group where its content is either consistently printed:
/// * on a single line: Omitting `LineMode::Soft` line breaks and printing spaces for `LineMode::SoftOrSpace`
/// * on multiple lines: Printing all line breaks
///
/// See [crate::builders::group] for documentation and examples.
StartGroup(Group),
EndGroup,
/// Allows to specify content that gets printed depending on whatever the enclosing group
/// is printed on a single line or multiple lines. See [crate::builders::if_group_breaks] for examples.
StartConditionalContent(Condition),
EndConditionalContent,
/// Optimized version of [Tag::StartConditionalContent] for the case where some content
/// should be indented if the specified group breaks.
StartIndentIfGroupBreaks(GroupId),
EndIndentIfGroupBreaks,
/// Concatenates multiple elements together with a given separator printed in either
/// flat or expanded mode to fill the print width. Expect that the content is a list of alternating
/// [element, separator] See [crate::Formatter::fill].
StartFill,
EndFill,
/// Entry inside of a [Tag::StartFill]
StartEntry,
EndEntry,
/// Delay the printing of its content until the next line break
StartLineSuffix,
EndLineSuffix,
/// A token that tracks tokens/nodes that are printed as verbatim.
StartVerbatim(VerbatimKind),
EndVerbatim,
/// Special semantic element marking the content with a label.
/// This does not directly influence how the content will be printed.
///
/// See [crate::builders::labelled] for documentation.
StartLabelled(LabelId),
EndLabelled,
}
impl Tag {
/// Returns `true` if `self` is any start tag.
pub const fn is_start(&self) -> bool {
matches!(
self,
Tag::StartIndent
| Tag::StartAlign(_)
| Tag::StartDedent(_)
| Tag::StartGroup { .. }
| Tag::StartConditionalContent(_)
| Tag::StartIndentIfGroupBreaks(_)
| Tag::StartFill
| Tag::StartEntry
| Tag::StartLineSuffix
| Tag::StartVerbatim(_)
| Tag::StartLabelled(_)
)
}
/// Returns `true` if `self` is any end tag.
pub const fn is_end(&self) -> bool {
!self.is_start()
}
pub const fn kind(&self) -> TagKind {
use Tag::*;
match self {
StartIndent | EndIndent => TagKind::Indent,
StartAlign(_) | EndAlign => TagKind::Align,
StartDedent(_) | EndDedent => TagKind::Dedent,
StartGroup(_) | EndGroup => TagKind::Group,
StartConditionalContent(_) | EndConditionalContent => TagKind::ConditionalContent,
StartIndentIfGroupBreaks(_) | EndIndentIfGroupBreaks => TagKind::IndentIfGroupBreaks,
StartFill | EndFill => TagKind::Fill,
StartEntry | EndEntry => TagKind::Entry,
StartLineSuffix | EndLineSuffix => TagKind::LineSuffix,
StartVerbatim(_) | EndVerbatim => TagKind::Verbatim,
StartLabelled(_) | EndLabelled => TagKind::Labelled,
}
}
}
/// The kind of a [Tag].
///
/// Each start end tag pair has its own [tag kind](TagKind).
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TagKind {
Indent,
Align,
Dedent,
Group,
ConditionalContent,
IndentIfGroupBreaks,
Fill,
Entry,
LineSuffix,
Verbatim,
Labelled,
}
#[derive(Debug, Copy, Default, Clone, Eq, PartialEq)]
pub enum GroupMode {
/// Print group in flat mode.
#[default]
Flat,
/// The group should be printed in expanded mode
Expand,
/// Expand mode has been propagated from an enclosing group to this group.
Propagated,
}
impl GroupMode {
pub const fn is_flat(&self) -> bool {
matches!(self, GroupMode::Flat)
}
}
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct Group {
id: Option<GroupId>,
mode: Cell<GroupMode>,
}
impl Group {
pub fn new() -> Self {
Self {
id: None,
mode: Cell::new(GroupMode::Flat),
}
}
pub fn with_id(mut self, id: Option<GroupId>) -> Self {
self.id = id;
self
}
pub fn with_mode(mut self, mode: GroupMode) -> Self {
self.mode = Cell::new(mode);
self
}
pub fn mode(&self) -> GroupMode {
self.mode.get()
}
pub fn propagate_expand(&self) {
if self.mode.get() == GroupMode::Flat {
self.mode.set(GroupMode::Propagated)
}
}
pub fn id(&self) -> Option<GroupId> {
self.id
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum DedentMode {
/// Reduces the indent by a level (if the current indent is > 0)
Level,
/// Reduces the indent to the root
Root,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Condition {
/// * Flat -> Omitted if the enclosing group is a multiline group, printed for groups fitting on a single line
/// * Multiline -> Omitted if the enclosing group fits on a single line, printed if the group breaks over multiple lines.
pub(crate) mode: PrintMode,
/// The id of the group for which it should check if it breaks or not. The group must appear in the document
/// before the conditional group (but doesn't have to be in the ancestor chain).
pub(crate) group_id: Option<GroupId>,
}
impl Condition {
pub fn new(mode: PrintMode) -> Self {
Self {
mode,
group_id: None,
}
}
pub fn with_group_id(mut self, id: Option<GroupId>) -> Self {
self.group_id = id;
self
}
pub fn mode(&self) -> PrintMode {
self.mode
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Align(pub(crate) NonZeroU8);
impl Align {
pub fn count(&self) -> NonZeroU8 {
self.0
}
}
#[derive(Debug, Eq, Copy, Clone)]
pub struct LabelId {
value: u64,
#[cfg(debug_assertions)]
name: &'static str,
}
impl PartialEq for LabelId {
fn eq(&self, other: &Self) -> bool {
let is_equal = self.value == other.value;
#[cfg(debug_assertions)]
{
if is_equal {
assert_eq!(self.name, other.name, "Two `LabelId`s with different names have the same `value`. Are you mixing labels of two different `LabelDefinition` or are the values returned by the `LabelDefinition` not unique?");
}
}
is_equal
}
}
impl LabelId {
pub fn of<T: Label>(label: T) -> Self {
Self {
value: label.id(),
#[cfg(debug_assertions)]
name: label.debug_name(),
}
}
}
/// Defines the valid labels of a language. You want to have at most one implementation per formatter
/// project.
pub trait Label {
/// Returns the `u64` uniquely identifying this specific label.
fn id(&self) -> u64;
/// Returns the name of the label that is shown in debug builds.
fn debug_name(&self) -> &'static str;
}
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub enum VerbatimKind {
Bogus,
Suppressed,
Verbatim {
/// the length of the formatted node
length: TextSize,
},
}
impl VerbatimKind {
pub const fn is_bogus(&self) -> bool {
matches!(self, VerbatimKind::Bogus)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/printer/line_suffixes.rs | crates/rome_formatter/src/printer/line_suffixes.rs | use crate::printer::call_stack::PrintElementArgs;
use crate::FormatElement;
/// Stores the queued line suffixes.
#[derive(Debug, Default)]
pub(super) struct LineSuffixes<'a> {
suffixes: Vec<LineSuffixEntry<'a>>,
}
impl<'a> LineSuffixes<'a> {
/// Extends the line suffixes with `elements`, storing their call stack arguments with them.
pub(super) fn extend<I>(&mut self, args: PrintElementArgs, elements: I)
where
I: IntoIterator<Item = &'a FormatElement>,
{
self.suffixes
.extend(elements.into_iter().map(LineSuffixEntry::Suffix));
self.suffixes.push(LineSuffixEntry::Args(args));
}
/// Takes all the pending line suffixes.
pub(super) fn take_pending<'l>(
&'l mut self,
) -> impl Iterator<Item = LineSuffixEntry<'a>> + DoubleEndedIterator + 'l + ExactSizeIterator
{
self.suffixes.drain(..)
}
/// Returns `true` if there are any line suffixes and `false` otherwise.
pub(super) fn has_pending(&self) -> bool {
!self.suffixes.is_empty()
}
}
#[derive(Debug, Copy, Clone)]
pub(super) enum LineSuffixEntry<'a> {
/// A line suffix to print
Suffix(&'a FormatElement),
/// Potentially changed call arguments that should be used to format any following items.
Args(PrintElementArgs),
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/printer/call_stack.rs | crates/rome_formatter/src/printer/call_stack.rs | use crate::format_element::tag::TagKind;
use crate::format_element::PrintMode;
use crate::printer::stack::{Stack, StackedStack};
use crate::printer::Indention;
use crate::{IndentStyle, InvalidDocumentError, PrintError, PrintResult};
use std::fmt::Debug;
use std::num::NonZeroU8;
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub(super) enum StackFrameKind {
Root,
Tag(TagKind),
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub(super) struct StackFrame {
kind: StackFrameKind,
args: PrintElementArgs,
}
/// Stores arguments passed to `print_element` call, holding the state specific to printing an element.
/// E.g. the `indent` depends on the token the Printer's currently processing. That's why
/// it must be stored outside of the [PrinterState] that stores the state common to all elements.
///
/// The state is passed by value, which is why it's important that it isn't storing any heavy
/// data structures. Such structures should be stored on the [PrinterState] instead.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub(super) struct PrintElementArgs {
indent: Indention,
mode: PrintMode,
}
impl PrintElementArgs {
pub fn new(indent: Indention) -> Self {
Self {
indent,
..Self::default()
}
}
pub(super) fn mode(&self) -> PrintMode {
self.mode
}
pub(super) fn indention(&self) -> Indention {
self.indent
}
pub fn increment_indent_level(mut self, indent_style: IndentStyle) -> Self {
self.indent = self.indent.increment_level(indent_style);
self
}
pub fn decrement_indent(mut self) -> Self {
self.indent = self.indent.decrement();
self
}
pub fn reset_indent(mut self) -> Self {
self.indent = Indention::default();
self
}
pub fn set_indent_align(mut self, count: NonZeroU8) -> Self {
self.indent = self.indent.set_align(count);
self
}
pub fn with_print_mode(mut self, mode: PrintMode) -> Self {
self.mode = mode;
self
}
}
impl Default for PrintElementArgs {
fn default() -> Self {
Self {
indent: Indention::Level(0),
mode: PrintMode::Expanded,
}
}
}
/// Call stack that stores the [PrintElementCallArgs].
///
/// New [PrintElementCallArgs] are pushed onto the stack for every [`start`](Tag::is_start) [`Tag`](FormatElement::Tag)
/// and popped when reaching the corresponding [`end`](Tag::is_end) [`Tag`](FormatElement::Tag).
pub(super) trait CallStack {
type Stack: Stack<StackFrame> + Debug;
fn stack(&self) -> &Self::Stack;
fn stack_mut(&mut self) -> &mut Self::Stack;
/// Pops the call arguments at the top and asserts that they correspond to a start tag of `kind`.
///
/// Returns `Ok` with the arguments if the kind of the top stack frame matches `kind`, otherwise
/// returns `Err`.
fn pop(&mut self, kind: TagKind) -> PrintResult<PrintElementArgs> {
let last = self.stack_mut().pop();
match last {
Some(StackFrame {
kind: StackFrameKind::Tag(actual_kind),
args,
}) if actual_kind == kind => Ok(args),
// Start / End kind don't match
Some(StackFrame {
kind: StackFrameKind::Tag(expected_kind),
..
}) => Err(PrintError::InvalidDocument(Self::invalid_document_error(
kind,
Some(expected_kind),
))),
// Tried to pop the outer most stack frame, which is not valid
Some(
frame @ StackFrame {
kind: StackFrameKind::Root,
..
},
) => {
// Put it back in to guarantee that the stack is never empty
self.stack_mut().push(frame);
Err(PrintError::InvalidDocument(Self::invalid_document_error(
kind, None,
)))
}
// This should be unreachable but having it for completeness. Happens if the stack is empty.
None => Err(PrintError::InvalidDocument(Self::invalid_document_error(
kind, None,
))),
}
}
#[cold]
fn invalid_document_error(
end_kind: TagKind,
start_kind: Option<TagKind>,
) -> InvalidDocumentError {
match start_kind {
None => InvalidDocumentError::StartTagMissing { kind: end_kind },
Some(start_kind) => InvalidDocumentError::StartEndTagMismatch {
start_kind,
end_kind,
},
}
}
/// Returns the [PrintElementArgs] for the current stack frame.
fn top(&self) -> PrintElementArgs {
self.stack()
.top()
.expect("Expected `stack` to never be empty.")
.args
}
/// Returns the [TagKind] of the current stack frame or [None] if this is the root stack frame.
fn top_kind(&self) -> Option<TagKind> {
match self
.stack()
.top()
.expect("Expected `stack` to never be empty.")
.kind
{
StackFrameKind::Root => None,
StackFrameKind::Tag(kind) => Some(kind),
}
}
/// Creates a new stack frame for a [FormatElement::Tag] of `kind` with `args` as the call arguments.
fn push(&mut self, kind: TagKind, args: PrintElementArgs) {
self.stack_mut().push(StackFrame {
kind: StackFrameKind::Tag(kind),
args,
})
}
}
/// Call stack used for printing the [FormatElement]s
#[derive(Debug, Clone)]
pub(super) struct PrintCallStack(Vec<StackFrame>);
impl PrintCallStack {
pub(super) fn new(args: PrintElementArgs) -> Self {
Self(vec![StackFrame {
kind: StackFrameKind::Root,
args,
}])
}
}
impl CallStack for PrintCallStack {
type Stack = Vec<StackFrame>;
fn stack(&self) -> &Self::Stack {
&self.0
}
fn stack_mut(&mut self) -> &mut Self::Stack {
&mut self.0
}
}
/// Call stack used for measuring if some content fits on the line.
///
/// The stack is a view on top of the [PrintCallStack] because the stack frames are still necessary for printing.
#[must_use]
pub(super) struct FitsCallStack<'print> {
stack: StackedStack<'print, StackFrame>,
}
impl<'print> FitsCallStack<'print> {
pub(super) fn new(print: &'print PrintCallStack, saved: Vec<StackFrame>) -> Self {
let stack = StackedStack::with_vec(&print.0, saved);
Self { stack }
}
pub(super) fn finish(self) -> Vec<StackFrame> {
self.stack.into_vec()
}
}
impl<'a> CallStack for FitsCallStack<'a> {
type Stack = StackedStack<'a, StackFrame>;
fn stack(&self) -> &Self::Stack {
&self.stack
}
fn stack_mut(&mut self) -> &mut Self::Stack {
&mut self.stack
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/printer/mod.rs | crates/rome_formatter/src/printer/mod.rs | mod call_stack;
mod line_suffixes;
mod printer_options;
mod queue;
mod stack;
pub use printer_options::*;
use crate::format_element::{BestFittingElement, LineMode, PrintMode};
use crate::{
ActualStart, FormatElement, GroupId, IndentStyle, InvalidDocumentError, PrintError,
PrintResult, Printed, SourceMarker, TextRange,
};
use crate::format_element::document::Document;
use crate::format_element::tag::Condition;
use crate::prelude::tag::{DedentMode, Tag, TagKind, VerbatimKind};
use crate::prelude::Tag::EndFill;
use crate::printer::call_stack::{
CallStack, FitsCallStack, PrintCallStack, PrintElementArgs, StackFrame,
};
use crate::printer::line_suffixes::{LineSuffixEntry, LineSuffixes};
use crate::printer::queue::{
AllPredicate, FitsEndPredicate, FitsQueue, PrintQueue, Queue, SingleEntryPredicate,
};
use drop_bomb::DebugDropBomb;
use rome_rowan::{TextLen, TextSize};
use std::num::NonZeroU8;
use unicode_width::UnicodeWidthChar;
/// Prints the format elements into a string
#[derive(Debug, Default)]
pub struct Printer<'a> {
options: PrinterOptions,
state: PrinterState<'a>,
}
impl<'a> Printer<'a> {
pub fn new(options: PrinterOptions) -> Self {
Self {
options,
state: PrinterState::default(),
}
}
/// Prints the passed in element as well as all its content
pub fn print(self, document: &'a Document) -> PrintResult<Printed> {
self.print_with_indent(document, 0)
}
/// Prints the passed in element as well as all its content,
/// starting at the specified indentation level
pub fn print_with_indent(
mut self,
document: &'a Document,
indent: u16,
) -> PrintResult<Printed> {
tracing::debug_span!("Printer::print").in_scope(move || {
let mut stack = PrintCallStack::new(PrintElementArgs::new(Indention::Level(indent)));
let mut queue: PrintQueue<'a> = PrintQueue::new(document.as_ref());
while let Some(element) = queue.pop() {
self.print_element(&mut stack, &mut queue, element)?;
if queue.is_empty() {
self.flush_line_suffixes(&mut queue, &mut stack, None);
}
}
Ok(Printed::new(
self.state.buffer,
None,
self.state.source_markers,
self.state.verbatim_markers,
))
})
}
/// Prints a single element and push the following elements to queue
fn print_element(
&mut self,
stack: &mut PrintCallStack,
queue: &mut PrintQueue<'a>,
element: &'a FormatElement,
) -> PrintResult<()> {
use Tag::*;
let args = stack.top();
match element {
FormatElement::Space => {
if self.state.line_width > 0 {
self.state.pending_space = true;
}
}
FormatElement::StaticText { text } => self.print_text(text, None),
FormatElement::DynamicText {
text,
source_position,
} => self.print_text(text, Some(*source_position)),
FormatElement::LocatedTokenText {
slice,
source_position,
} => self.print_text(slice, Some(*source_position)),
FormatElement::Line(line_mode) => {
if args.mode().is_flat()
&& matches!(line_mode, LineMode::Soft | LineMode::SoftOrSpace)
{
if line_mode == &LineMode::SoftOrSpace && self.state.line_width > 0 {
self.state.pending_space = true;
}
} else if self.state.line_suffixes.has_pending() {
self.flush_line_suffixes(queue, stack, Some(element));
} else {
// Only print a newline if the current line isn't already empty
if self.state.line_width > 0 {
self.print_str("\n");
}
// Print a second line break if this is an empty line
if line_mode == &LineMode::Empty && !self.state.has_empty_line {
self.print_str("\n");
self.state.has_empty_line = true;
}
self.state.pending_space = false;
self.state.pending_indent = args.indention();
}
}
FormatElement::ExpandParent => {
// Handled in `Document::propagate_expands()
}
FormatElement::LineSuffixBoundary => {
const HARD_BREAK: &FormatElement = &FormatElement::Line(LineMode::Hard);
self.flush_line_suffixes(queue, stack, Some(HARD_BREAK));
}
FormatElement::BestFitting(best_fitting) => {
self.print_best_fitting(best_fitting, queue, stack)?;
}
FormatElement::Interned(content) => {
queue.extend_back(content);
}
FormatElement::Tag(StartGroup(group)) => {
let group_mode = if !group.mode().is_flat() {
PrintMode::Expanded
} else {
match args.mode() {
PrintMode::Flat if self.state.measured_group_fits => {
// A parent group has already verified that this group fits on a single line
// Thus, just continue in flat mode
PrintMode::Flat
}
// The printer is either in expanded mode or it's necessary to re-measure if the group fits
// because the printer printed a line break
_ => {
self.state.measured_group_fits = true;
// Measure to see if the group fits up on a single line. If that's the case,
// print the group in "flat" mode, otherwise continue in expanded mode
stack.push(TagKind::Group, args.with_print_mode(PrintMode::Flat));
let fits = self.fits(queue, stack)?;
stack.pop(TagKind::Group)?;
if fits {
PrintMode::Flat
} else {
PrintMode::Expanded
}
}
}
};
stack.push(TagKind::Group, args.with_print_mode(group_mode));
if let Some(id) = group.id() {
self.state.group_modes.insert_print_mode(id, group_mode);
}
}
FormatElement::Tag(StartFill) => {
self.print_fill_entries(queue, stack)?;
}
FormatElement::Tag(StartIndent) => {
stack.push(
TagKind::Indent,
args.increment_indent_level(self.options.indent_style()),
);
}
FormatElement::Tag(StartDedent(mode)) => {
let args = match mode {
DedentMode::Level => args.decrement_indent(),
DedentMode::Root => args.reset_indent(),
};
stack.push(TagKind::Dedent, args);
}
FormatElement::Tag(StartAlign(align)) => {
stack.push(TagKind::Align, args.set_indent_align(align.count()));
}
FormatElement::Tag(StartConditionalContent(Condition { mode, group_id })) => {
let group_mode = match group_id {
None => args.mode(),
Some(id) => self.state.group_modes.unwrap_print_mode(*id, element),
};
if group_mode != *mode {
queue.skip_content(TagKind::ConditionalContent);
} else {
stack.push(TagKind::ConditionalContent, args);
}
}
FormatElement::Tag(StartIndentIfGroupBreaks(group_id)) => {
let group_mode = self.state.group_modes.unwrap_print_mode(*group_id, element);
let args = match group_mode {
PrintMode::Flat => args,
PrintMode::Expanded => args.increment_indent_level(self.options.indent_style),
};
stack.push(TagKind::IndentIfGroupBreaks, args);
}
FormatElement::Tag(StartLineSuffix) => {
self.state
.line_suffixes
.extend(args, queue.iter_content(TagKind::LineSuffix));
}
FormatElement::Tag(StartVerbatim(kind)) => {
if let VerbatimKind::Verbatim { length } = kind {
self.state.verbatim_markers.push(TextRange::at(
TextSize::from(self.state.buffer.len() as u32),
*length,
));
}
stack.push(TagKind::Verbatim, args);
}
FormatElement::Tag(tag @ (StartLabelled(_) | StartEntry)) => {
stack.push(tag.kind(), args);
}
FormatElement::Tag(
tag @ (EndLabelled
| EndEntry
| EndGroup
| EndIndent
| EndDedent
| EndAlign
| EndConditionalContent
| EndIndentIfGroupBreaks
| EndVerbatim
| EndLineSuffix
| EndFill),
) => {
stack.pop(tag.kind())?;
}
};
Ok(())
}
fn fits(&mut self, queue: &PrintQueue<'a>, stack: &PrintCallStack) -> PrintResult<bool> {
let mut measure = FitsMeasurer::new(queue, stack, self);
let result = measure.fits(&mut AllPredicate);
measure.finish();
result
}
fn print_text(&mut self, text: &str, source_position: Option<TextSize>) {
if !self.state.pending_indent.is_empty() {
let (indent_char, repeat_count) = match self.options.indent_style() {
IndentStyle::Tab => ('\t', 1),
IndentStyle::Space(count) => (' ', count),
};
let indent = std::mem::take(&mut self.state.pending_indent);
let total_indent_char_count = indent.level() as usize * repeat_count as usize;
self.state
.buffer
.reserve(total_indent_char_count + indent.align() as usize);
for _ in 0..total_indent_char_count {
self.print_char(indent_char);
}
for _ in 0..indent.align() {
self.print_char(' ');
}
}
// Print pending spaces
if self.state.pending_space {
self.print_str(" ");
self.state.pending_space = false;
}
// Insert source map markers before and after the token
//
// If the token has source position information the start marker
// will use the start position of the original token, and the end
// marker will use that position + the text length of the token
//
// If the token has no source position (was created by the formatter)
// both the start and end marker will use the last known position
// in the input source (from state.source_position)
if let Some(source) = source_position {
self.state.source_position = source;
}
self.push_marker(SourceMarker {
source: self.state.source_position,
dest: self.state.buffer.text_len(),
});
self.print_str(text);
if source_position.is_some() {
self.state.source_position += text.text_len();
}
self.push_marker(SourceMarker {
source: self.state.source_position,
dest: self.state.buffer.text_len(),
});
}
fn push_marker(&mut self, marker: SourceMarker) {
if let Some(last) = self.state.source_markers.last() {
if last != &marker {
self.state.source_markers.push(marker)
}
} else {
self.state.source_markers.push(marker);
}
}
fn flush_line_suffixes(
&mut self,
queue: &mut PrintQueue<'a>,
stack: &mut PrintCallStack,
line_break: Option<&'a FormatElement>,
) {
let suffixes = self.state.line_suffixes.take_pending();
if suffixes.len() > 0 {
// Print this line break element again once all the line suffixes have been flushed
if let Some(line_break) = line_break {
queue.push(line_break);
}
for entry in suffixes.rev() {
match entry {
LineSuffixEntry::Suffix(suffix) => {
queue.push(suffix);
}
LineSuffixEntry::Args(args) => {
stack.push(TagKind::LineSuffix, args);
const LINE_SUFFIX_END: &FormatElement =
&FormatElement::Tag(Tag::EndLineSuffix);
queue.push(LINE_SUFFIX_END);
}
}
}
}
}
fn print_best_fitting(
&mut self,
best_fitting: &'a BestFittingElement,
queue: &mut PrintQueue<'a>,
stack: &mut PrintCallStack,
) -> PrintResult<()> {
let args = stack.top();
if args.mode().is_flat() && self.state.measured_group_fits {
queue.extend_back(best_fitting.most_flat());
self.print_entry(queue, stack, args)
} else {
self.state.measured_group_fits = true;
let normal_variants = &best_fitting.variants()[..best_fitting.variants().len() - 1];
for variant in normal_variants.iter() {
// Test if this variant fits and if so, use it. Otherwise try the next
// variant.
// Try to fit only the first variant on a single line
if !matches!(variant.first(), Some(&FormatElement::Tag(Tag::StartEntry))) {
return invalid_start_tag(TagKind::Entry, variant.first());
}
let entry_args = args.with_print_mode(PrintMode::Flat);
// Skip the first element because we want to override the args for the entry and the
// args must be popped from the stack as soon as it sees the matching end entry.
let content = &variant[1..];
queue.extend_back(content);
stack.push(TagKind::Entry, entry_args);
let variant_fits = self.fits(queue, stack)?;
stack.pop(TagKind::Entry)?;
// Remove the content slice because printing needs the variant WITH the start entry
let popped_slice = queue.pop_slice();
debug_assert_eq!(popped_slice, Some(content));
if variant_fits {
queue.extend_back(variant);
return self.print_entry(queue, stack, entry_args);
}
}
// No variant fits, take the last (most expanded) as fallback
let most_expanded = best_fitting.most_expanded();
queue.extend_back(most_expanded);
self.print_entry(queue, stack, args.with_print_mode(PrintMode::Expanded))
}
}
/// Tries to fit as much content as possible on a single line.
///
/// `Fill` is a sequence of *item*, *separator*, *item*, *separator*, *item*, ... entries.
/// The goal is to fit as many items (with their separators) on a single line as possible and
/// first expand the *separator* if the content exceeds the print width and only fallback to expanding
/// the *item*s if the *item* or the *item* and the expanded *separator* don't fit on the line.
///
/// The implementation handles the following 5 cases:
///
/// * The *item*, *separator*, and the *next item* fit on the same line.
/// Print the *item* and *separator* in flat mode.
/// * The *item* and *separator* fit on the line but there's not enough space for the *next item*.
/// Print the *item* in flat mode and the *separator* in expanded mode.
/// * The *item* fits on the line but the *separator* does not in flat mode.
/// Print the *item* in flat mode and the *separator* in expanded mode.
/// * The *item* fits on the line but the *separator* does not in flat **NOR** expanded mode.
/// Print the *item* and *separator* in expanded mode.
/// * The *item* does not fit on the line.
/// Print the *item* and *separator* in expanded mode.
fn print_fill_entries(
&mut self,
queue: &mut PrintQueue<'a>,
stack: &mut PrintCallStack,
) -> PrintResult<()> {
let args = stack.top();
// It's already known that the content fit, print all items in flat mode.
if self.state.measured_group_fits && args.mode().is_flat() {
stack.push(TagKind::Fill, args.with_print_mode(PrintMode::Flat));
return Ok(());
}
stack.push(TagKind::Fill, args);
while matches!(queue.top(), Some(FormatElement::Tag(Tag::StartEntry))) {
let mut measurer = FitsMeasurer::new_flat(queue, stack, self);
// The number of item/separator pairs that fit on the same line.
let mut flat_pairs = 0usize;
let mut item_fits = measurer.fill_item_fits()?;
let last_pair_layout = if item_fits {
// Measure the remaining pairs until the first item or separator that does not fit (or the end of the fill element).
// Optimisation to avoid re-measuring the next-item twice:
// * Once when measuring if the *item*, *separator*, *next-item* fit
// * A second time when measuring if *next-item*, *separator*, *next-next-item* fit.
loop {
// Item that fits without a following separator.
if !matches!(
measurer.queue.top(),
Some(FormatElement::Tag(Tag::StartEntry))
) {
break FillPairLayout::Flat;
}
let separator_fits = measurer.fill_separator_fits(PrintMode::Flat)?;
// Item fits but the flat separator does not.
if !separator_fits {
break FillPairLayout::ItemMaybeFlat;
}
// Last item/separator pair that both fit
if !matches!(
measurer.queue.top(),
Some(FormatElement::Tag(Tag::StartEntry))
) {
break FillPairLayout::Flat;
}
item_fits = measurer.fill_item_fits()?;
if item_fits {
flat_pairs += 1;
} else {
// Item and separator both fit, but the next element doesn't.
// Print the separator in expanded mode and then re-measure if the item now
// fits in the next iteration of the outer loop.
break FillPairLayout::ItemFlatSeparatorExpanded;
}
}
} else {
// Neither item nor separator fit, print both in expanded mode.
FillPairLayout::Expanded
};
measurer.finish();
self.state.measured_group_fits = true;
// Print all pairs that fit in flat mode.
for _ in 0..flat_pairs {
self.print_fill_item(queue, stack, args.with_print_mode(PrintMode::Flat))?;
self.print_fill_separator(queue, stack, args.with_print_mode(PrintMode::Flat))?;
}
let item_mode = match last_pair_layout {
FillPairLayout::Flat | FillPairLayout::ItemFlatSeparatorExpanded => PrintMode::Flat,
FillPairLayout::Expanded => PrintMode::Expanded,
FillPairLayout::ItemMaybeFlat => {
let mut measurer = FitsMeasurer::new_flat(queue, stack, self);
// SAFETY: That the item fits is guaranteed by `ItemMaybeFlat`.
// Re-measuring is required to get the measurer in the correct state for measuring the separator.
assert!(measurer.fill_item_fits()?);
let separator_fits = measurer.fill_separator_fits(PrintMode::Expanded)?;
measurer.finish();
if separator_fits {
PrintMode::Flat
} else {
PrintMode::Expanded
}
}
};
self.print_fill_item(queue, stack, args.with_print_mode(item_mode))?;
if matches!(queue.top(), Some(FormatElement::Tag(Tag::StartEntry))) {
let separator_mode = match last_pair_layout {
FillPairLayout::Flat => PrintMode::Flat,
FillPairLayout::ItemFlatSeparatorExpanded
| FillPairLayout::Expanded
| FillPairLayout::ItemMaybeFlat => PrintMode::Expanded,
};
// Push a new stack frame with print mode `Flat` for the case where the separator gets printed in expanded mode
// but does contain a group to ensure that the group will measure "fits" with the "flat" versions of the next item/separator.
stack.push(TagKind::Fill, args.with_print_mode(PrintMode::Flat));
self.print_fill_separator(queue, stack, args.with_print_mode(separator_mode))?;
stack.pop(TagKind::Fill)?;
}
}
if queue.top() == Some(&FormatElement::Tag(EndFill)) {
Ok(())
} else {
invalid_end_tag(TagKind::Fill, stack.top_kind())
}
}
/// Semantic alias for [Self::print_entry] for fill items.
fn print_fill_item(
&mut self,
queue: &mut PrintQueue<'a>,
stack: &mut PrintCallStack,
args: PrintElementArgs,
) -> PrintResult<()> {
self.print_entry(queue, stack, args)
}
/// Semantic alias for [Self::print_entry] for fill separators.
fn print_fill_separator(
&mut self,
queue: &mut PrintQueue<'a>,
stack: &mut PrintCallStack,
args: PrintElementArgs,
) -> PrintResult<()> {
self.print_entry(queue, stack, args)
}
/// Fully print an element (print the element itself and all its descendants)
///
/// Unlike [print_element], this function ensures the entire element has
/// been printed when it returns and the queue is back to its original state
fn print_entry(
&mut self,
queue: &mut PrintQueue<'a>,
stack: &mut PrintCallStack,
args: PrintElementArgs,
) -> PrintResult<()> {
let start_entry = queue.top();
if !matches!(start_entry, Some(&FormatElement::Tag(Tag::StartEntry))) {
return invalid_start_tag(TagKind::Entry, start_entry);
}
let mut depth = 0;
while let Some(element) = queue.pop() {
match element {
FormatElement::Tag(Tag::StartEntry) => {
// Handle the start of the first element by pushing the args on the stack.
if depth == 0 {
depth = 1;
stack.push(TagKind::Entry, args);
continue;
}
depth += 1;
}
FormatElement::Tag(Tag::EndEntry) => {
depth -= 1;
// Reached the end entry, pop the entry from the stack and return.
if depth == 0 {
stack.pop(TagKind::Entry)?;
return Ok(());
}
}
_ => {
// Fall through
}
}
self.print_element(stack, queue, element)?;
}
invalid_end_tag(TagKind::Entry, stack.top_kind())
}
fn print_str(&mut self, content: &str) {
for char in content.chars() {
self.print_char(char);
self.state.has_empty_line = false;
}
}
fn print_char(&mut self, char: char) {
if char == '\n' {
self.state
.buffer
.push_str(self.options.line_ending.as_str());
self.state.generated_line += 1;
self.state.generated_column = 0;
self.state.line_width = 0;
// Fit's only tests if groups up to the first line break fit.
// The next group must re-measure if it still fits.
self.state.measured_group_fits = false;
} else {
self.state.buffer.push(char);
self.state.generated_column += 1;
let char_width = if char == '\t' {
self.options.tab_width as usize
} else {
char.width().unwrap_or(0)
};
self.state.line_width += char_width;
}
}
}
#[derive(Copy, Clone, Debug)]
enum FillPairLayout {
/// The item, separator, and next item fit. Print the first item and the separator in flat mode.
Flat,
/// The item and separator fit but the next element does not. Print the item in flat mode and
/// the separator in expanded mode.
ItemFlatSeparatorExpanded,
/// The item does not fit. Print the item and any potential separator in expanded mode.
Expanded,
/// The item fits but the separator does not in flat mode. If the separator fits in expanded mode then
/// print the item in flat and the separator in expanded mode, otherwise print both in expanded mode.
ItemMaybeFlat,
}
/// Printer state that is global to all elements.
/// Stores the result of the print operation (buffer and mappings) and at what
/// position the printer currently is.
#[derive(Default, Debug)]
struct PrinterState<'a> {
buffer: String,
source_markers: Vec<SourceMarker>,
source_position: TextSize,
pending_indent: Indention,
pending_space: bool,
measured_group_fits: bool,
generated_line: usize,
generated_column: usize,
line_width: usize,
has_empty_line: bool,
line_suffixes: LineSuffixes<'a>,
verbatim_markers: Vec<TextRange>,
group_modes: GroupModes,
// Re-used queue to measure if a group fits. Optimisation to avoid re-allocating a new
// vec everytime a group gets measured
fits_stack: Vec<StackFrame>,
fits_queue: Vec<&'a [FormatElement]>,
}
/// Tracks the mode in which groups with ids are printed. Stores the groups at `group.id()` index.
/// This is based on the assumption that the group ids for a single document are dense.
#[derive(Debug, Default)]
struct GroupModes(Vec<Option<PrintMode>>);
impl GroupModes {
fn insert_print_mode(&mut self, group_id: GroupId, mode: PrintMode) {
let index = u32::from(group_id) as usize;
if self.0.len() <= index {
self.0.resize(index + 1, None);
}
self.0[index] = Some(mode);
}
fn get_print_mode(&self, group_id: GroupId) -> Option<PrintMode> {
let index = u32::from(group_id) as usize;
self.0
.get(index)
.and_then(|option| option.as_ref().copied())
}
fn unwrap_print_mode(&self, group_id: GroupId, next_element: &FormatElement) -> PrintMode {
self.get_print_mode(group_id).unwrap_or_else(|| {
panic!("Expected group with id {group_id:?} to exist but it wasn't present in the document. Ensure that a group with such a document appears in the document before the element {next_element:?}.")
})
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum Indention {
/// Indent the content by `count` levels by using the indention sequence specified by the printer options.
Level(u16),
/// Indent the content by n-`level`s using the indention sequence specified by the printer options and `align` spaces.
Align { level: u16, align: NonZeroU8 },
}
impl Indention {
const fn is_empty(&self) -> bool {
matches!(self, Indention::Level(0))
}
/// Creates a new indention level with a zero-indent.
const fn new() -> Self {
Indention::Level(0)
}
/// Returns the indention level
fn level(&self) -> u16 {
match self {
Indention::Level(count) => *count,
Indention::Align { level: indent, .. } => *indent,
}
}
/// Returns the number of trailing align spaces or 0 if none
fn align(&self) -> u8 {
match self {
Indention::Level(_) => 0,
Indention::Align { align, .. } => (*align).into(),
}
}
/// Increments the level by one.
///
/// The behaviour depends on the [`indent_style`][IndentStyle] if this is an [Indent::Align]:
/// * **Tabs**: `align` is converted into an indent. This results in `level` increasing by two: once for the align, once for the level increment
/// * **Spaces**: Increments the `level` by one and keeps the `align` unchanged.
/// Keeps any the current value is [Indent::Align] and increments the level by one.
fn increment_level(self, indent_style: IndentStyle) -> Self {
match self {
Indention::Level(count) => Indention::Level(count + 1),
// Increase the indent AND convert the align to an indent
Indention::Align { level, .. } if indent_style.is_tab() => Indention::Level(level + 2),
Indention::Align {
level: indent,
align,
} => Indention::Align {
level: indent + 1,
align,
},
}
}
/// Decrements the indent by one by:
/// * Reducing the level by one if this is [Indent::Level]
/// * Removing the `align` if this is [Indent::Align]
///
/// No-op if the level is already zero.
fn decrement(self) -> Self {
match self {
Indention::Level(level) => Indention::Level(level.saturating_sub(1)),
Indention::Align { level, .. } => Indention::Level(level),
}
}
/// Adds an `align` of `count` spaces to the current indention.
///
/// It increments the `level` value if the current value is [Indent::IndentAlign].
fn set_align(self, count: NonZeroU8) -> Self {
match self {
Indention::Level(indent_count) => Indention::Align {
level: indent_count,
align: count,
},
// Convert the existing align to an indent
Indention::Align { level: indent, .. } => Indention::Align {
level: indent + 1,
align: count,
},
}
}
}
impl Default for Indention {
fn default() -> Self {
Indention::new()
}
}
#[must_use = "FitsMeasurer must be finished."]
struct FitsMeasurer<'a, 'print> {
state: FitsState,
queue: FitsQueue<'a, 'print>,
stack: FitsCallStack<'print>,
printer: &'print mut Printer<'a>,
must_be_flat: bool,
/// Bomb that enforces that finish is explicitly called to restore the `fits_stack` and `fits_queue` vectors.
bomb: DebugDropBomb,
}
impl<'a, 'print> FitsMeasurer<'a, 'print> {}
impl<'a, 'print> FitsMeasurer<'a, 'print> {
fn new_flat(
print_queue: &'print PrintQueue<'a>,
print_stack: &'print PrintCallStack,
printer: &'print mut Printer<'a>,
) -> Self {
let mut measurer = Self::new(print_queue, print_stack, printer);
measurer.must_be_flat = true;
measurer
}
fn new(
print_queue: &'print PrintQueue<'a>,
print_stack: &'print PrintCallStack,
printer: &'print mut Printer<'a>,
) -> Self {
let saved_stack = std::mem::take(&mut printer.state.fits_stack);
let saved_queue = std::mem::take(&mut printer.state.fits_queue);
debug_assert!(saved_stack.is_empty());
debug_assert!(saved_queue.is_empty());
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/printer/stack.rs | crates/rome_formatter/src/printer/stack.rs | /// A school book stack. Allows adding, removing, and inspecting elements at the back.
pub(super) trait Stack<T> {
/// Removes the last element if any and returns it
fn pop(&mut self) -> Option<T>;
/// Pushes a new element at the back
fn push(&mut self, value: T);
/// Returns the last element if any
fn top(&self) -> Option<&T>;
/// Returns `true` if the stack is empty
fn is_empty(&self) -> bool;
}
impl<T> Stack<T> for Vec<T> {
fn pop(&mut self) -> Option<T> {
self.pop()
}
fn push(&mut self, value: T) {
self.push(value)
}
fn top(&self) -> Option<&T> {
self.last()
}
fn is_empty(&self) -> bool {
self.is_empty()
}
}
/// A Stack that is stacked on top of another stack. Guarantees that the underlying stack remains unchanged.
#[derive(Debug, Clone)]
pub(super) struct StackedStack<'a, T> {
/// The content of the original stack.
original: &'a [T],
/// Items that have been pushed since the creation of this stack and aren't part of the `original` stack.
stack: Vec<T>,
}
impl<'a, T> StackedStack<'a, T> {
#[cfg(test)]
pub(super) fn new(original: &'a [T]) -> Self {
Self::with_vec(original, Vec::new())
}
/// Creates a new stack that uses `stack` for storing its elements.
pub(super) fn with_vec(original: &'a [T], stack: Vec<T>) -> Self {
Self { original, stack }
}
/// Returns the underlying `stack` vector.
pub(super) fn into_vec(self) -> Vec<T> {
self.stack
}
}
impl<T> Stack<T> for StackedStack<'_, T>
where
T: Copy,
{
fn pop(&mut self) -> Option<T> {
self.stack.pop().or_else(|| match self.original {
[rest @ .., last] => {
self.original = rest;
Some(*last)
}
_ => None,
})
}
fn push(&mut self, value: T) {
self.stack.push(value);
}
fn top(&self) -> Option<&T> {
self.stack.last().or_else(|| self.original.last())
}
fn is_empty(&self) -> bool {
self.original.is_empty() && self.stack.is_empty()
}
}
#[cfg(test)]
mod tests {
use crate::printer::stack::{Stack, StackedStack};
#[test]
fn restore_consumed_stack() {
let original = vec![1, 2, 3];
let mut restorable = StackedStack::new(&original);
restorable.push(4);
assert_eq!(restorable.pop(), Some(4));
assert_eq!(restorable.pop(), Some(3));
assert_eq!(restorable.pop(), Some(2));
assert_eq!(restorable.pop(), Some(1));
assert_eq!(restorable.pop(), None);
assert_eq!(original, vec![1, 2, 3]);
}
#[test]
fn restore_partially_consumed_stack() {
let original = vec![1, 2, 3];
let mut restorable = StackedStack::new(&original);
restorable.push(4);
assert_eq!(restorable.pop(), Some(4));
assert_eq!(restorable.pop(), Some(3));
assert_eq!(restorable.pop(), Some(2));
restorable.push(5);
restorable.push(6);
restorable.push(7);
assert_eq!(original, vec![1, 2, 3]);
}
#[test]
fn restore_stack() {
let original = vec![1, 2, 3];
let mut restorable = StackedStack::new(&original);
restorable.push(4);
restorable.push(5);
restorable.push(6);
restorable.push(7);
assert_eq!(restorable.pop(), Some(7));
assert_eq!(restorable.pop(), Some(6));
assert_eq!(restorable.pop(), Some(5));
assert_eq!(original, vec![1, 2, 3]);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/printer/queue.rs | crates/rome_formatter/src/printer/queue.rs | use crate::format_element::tag::TagKind;
use crate::prelude::Tag;
use crate::printer::stack::{Stack, StackedStack};
use crate::printer::{invalid_end_tag, invalid_start_tag};
use crate::{FormatElement, PrintResult};
use std::fmt::Debug;
use std::iter::FusedIterator;
use std::marker::PhantomData;
/// Queue of [FormatElement]s.
pub(super) trait Queue<'a> {
type Stack: Stack<&'a [FormatElement]>;
fn stack(&self) -> &Self::Stack;
fn stack_mut(&mut self) -> &mut Self::Stack;
fn next_index(&self) -> usize;
fn set_next_index(&mut self, index: usize);
/// Pops the element at the end of the queue.
fn pop(&mut self) -> Option<&'a FormatElement> {
match self.stack().top() {
Some(top_slice) => {
// SAFETY: Safe because queue ensures that slices inside `slices` are never empty.
let next_index = self.next_index();
let element = &top_slice[next_index];
if next_index + 1 == top_slice.len() {
self.stack_mut().pop().unwrap();
self.set_next_index(0);
} else {
self.set_next_index(next_index + 1);
}
Some(element)
}
None => None,
}
}
/// Returns the next element, not traversing into [FormatElement::Interned].
fn top_with_interned(&self) -> Option<&'a FormatElement> {
self.stack()
.top()
.map(|top_slice| &top_slice[self.next_index()])
}
/// Returns the next element, recursively resolving the first element of [FormatElement::Interned].
fn top(&self) -> Option<&'a FormatElement> {
let mut top = self.top_with_interned();
while let Some(FormatElement::Interned(interned)) = top {
top = interned.first()
}
top
}
/// Queues a single element to process before the other elements in this queue.
fn push(&mut self, element: &'a FormatElement) {
self.extend_back(std::slice::from_ref(element))
}
/// Queues a slice of elements to process before the other elements in this queue.
fn extend_back(&mut self, elements: &'a [FormatElement]) {
match elements {
[] => {
// Don't push empty slices
}
slice => {
let next_index = self.next_index();
let stack = self.stack_mut();
if let Some(top) = stack.pop() {
stack.push(&top[next_index..])
}
stack.push(slice);
self.set_next_index(0);
}
}
}
/// Removes top slice.
fn pop_slice(&mut self) -> Option<&'a [FormatElement]> {
self.set_next_index(0);
self.stack_mut().pop()
}
/// Skips all content until it finds the corresponding end tag with the given kind.
fn skip_content(&mut self, kind: TagKind)
where
Self: Sized,
{
let iter = self.iter_content(kind);
for _ in iter {
// consume whole iterator until end
}
}
/// Iterates over all elements until it finds the matching end tag of the specified kind.
fn iter_content<'q>(&'q mut self, kind: TagKind) -> QueueContentIterator<'a, 'q, Self>
where
Self: Sized,
{
QueueContentIterator::new(self, kind)
}
}
/// Queue with the elements to print.
#[derive(Debug, Default, Clone)]
pub(super) struct PrintQueue<'a> {
slices: Vec<&'a [FormatElement]>,
next_index: usize,
}
impl<'a> PrintQueue<'a> {
pub(super) fn new(slice: &'a [FormatElement]) -> Self {
let slices = match slice {
[] => Vec::default(),
slice => vec![slice],
};
Self {
slices,
next_index: 0,
}
}
pub(super) fn is_empty(&self) -> bool {
self.slices.is_empty()
}
}
impl<'a> Queue<'a> for PrintQueue<'a> {
type Stack = Vec<&'a [FormatElement]>;
fn stack(&self) -> &Self::Stack {
&self.slices
}
fn stack_mut(&mut self) -> &mut Self::Stack {
&mut self.slices
}
fn next_index(&self) -> usize {
self.next_index
}
fn set_next_index(&mut self, index: usize) {
self.next_index = index
}
}
/// Queue for measuring if an element fits on the line.
///
/// The queue is a view on top of the [PrintQueue] because no elements should be removed
/// from the [PrintQueue] while measuring.
#[must_use]
#[derive(Debug)]
pub(super) struct FitsQueue<'a, 'print> {
stack: StackedStack<'print, &'a [FormatElement]>,
next_index: usize,
}
impl<'a, 'print> FitsQueue<'a, 'print> {
pub(super) fn new(
print_queue: &'print PrintQueue<'a>,
saved: Vec<&'a [FormatElement]>,
) -> Self {
let stack = StackedStack::with_vec(&print_queue.slices, saved);
Self {
stack,
next_index: print_queue.next_index,
}
}
pub(super) fn finish(self) -> Vec<&'a [FormatElement]> {
self.stack.into_vec()
}
}
impl<'a, 'print> Queue<'a> for FitsQueue<'a, 'print> {
type Stack = StackedStack<'print, &'a [FormatElement]>;
fn stack(&self) -> &Self::Stack {
&self.stack
}
fn stack_mut(&mut self) -> &mut Self::Stack {
&mut self.stack
}
fn next_index(&self) -> usize {
self.next_index
}
fn set_next_index(&mut self, index: usize) {
self.next_index = index;
}
}
/// Iterator that calls [Queue::pop] until it reaches the end of the document.
///
/// The iterator traverses into the content of any [FormatElement::Interned].
pub(super) struct QueueIterator<'a, 'q, Q: Queue<'a>> {
queue: &'q mut Q,
lifetime: PhantomData<&'a ()>,
}
impl<'a, Q> Iterator for QueueIterator<'a, '_, Q>
where
Q: Queue<'a>,
{
type Item = &'a FormatElement;
fn next(&mut self) -> Option<Self::Item> {
self.queue.pop()
}
}
impl<'a, Q> FusedIterator for QueueIterator<'a, '_, Q> where Q: Queue<'a> {}
pub(super) struct QueueContentIterator<'a, 'q, Q: Queue<'a>> {
queue: &'q mut Q,
kind: TagKind,
depth: usize,
lifetime: PhantomData<&'a ()>,
}
impl<'a, 'q, Q> QueueContentIterator<'a, 'q, Q>
where
Q: Queue<'a>,
{
fn new(queue: &'q mut Q, kind: TagKind) -> Self {
Self {
queue,
kind,
depth: 1,
lifetime: PhantomData,
}
}
}
impl<'a, Q> Iterator for QueueContentIterator<'a, '_, Q>
where
Q: Queue<'a>,
{
type Item = &'a FormatElement;
fn next(&mut self) -> Option<Self::Item> {
match self.depth {
0 => None,
_ => {
let mut top = self.queue.pop();
while let Some(FormatElement::Interned(interned)) = top {
self.queue.extend_back(interned);
top = self.queue.pop();
}
match top.expect("Missing end signal.") {
element @ FormatElement::Tag(tag) if tag.kind() == self.kind => {
if tag.is_start() {
self.depth += 1;
} else {
self.depth -= 1;
if self.depth == 0 {
return None;
}
}
Some(element)
}
element => Some(element),
}
}
}
}
}
impl<'a, Q> FusedIterator for QueueContentIterator<'a, '_, Q> where Q: Queue<'a> {}
/// A predicate determining when to end measuring if some content fits on the line.
///
/// Called for every [`element`](FormatElement) in the [FitsQueue] when measuring if a content
/// fits on the line. The measuring of the content ends after the first element [`element`](FormatElement) for which this
/// predicate returns `true` (similar to a take while iterator except that it takes while the predicate returns `false`).
pub(super) trait FitsEndPredicate {
fn is_end(&mut self, element: &FormatElement) -> PrintResult<bool>;
}
/// Filter that includes all elements until it reaches the end of the document.
pub(super) struct AllPredicate;
impl FitsEndPredicate for AllPredicate {
fn is_end(&mut self, _element: &FormatElement) -> PrintResult<bool> {
Ok(false)
}
}
/// Filter that takes all elements between two matching [Tag::StartEntry] and [Tag::EndEntry] tags.
#[derive(Debug)]
pub(super) enum SingleEntryPredicate {
Entry { depth: usize },
Done,
}
impl SingleEntryPredicate {
pub(super) const fn is_done(&self) -> bool {
matches!(self, SingleEntryPredicate::Done)
}
}
impl Default for SingleEntryPredicate {
fn default() -> Self {
SingleEntryPredicate::Entry { depth: 0 }
}
}
impl FitsEndPredicate for SingleEntryPredicate {
fn is_end(&mut self, element: &FormatElement) -> PrintResult<bool> {
let result = match self {
SingleEntryPredicate::Done => true,
SingleEntryPredicate::Entry { depth } => match element {
FormatElement::Tag(Tag::StartEntry) => {
*depth += 1;
false
}
FormatElement::Tag(Tag::EndEntry) => {
if *depth == 0 {
return invalid_end_tag(TagKind::Entry, None);
}
*depth -= 1;
let is_end = *depth == 0;
if is_end {
*self = SingleEntryPredicate::Done;
}
is_end
}
FormatElement::Interned(_) => false,
element if *depth == 0 => {
return invalid_start_tag(TagKind::Entry, Some(element));
}
_ => false,
},
};
Ok(result)
}
}
#[cfg(test)]
mod tests {
use crate::format_element::LineMode;
use crate::prelude::Tag;
use crate::printer::queue::{PrintQueue, Queue};
use crate::FormatElement;
#[test]
fn extend_back_pop_last() {
let mut queue =
PrintQueue::new(&[FormatElement::Tag(Tag::StartEntry), FormatElement::Space]);
assert_eq!(queue.pop(), Some(&FormatElement::Tag(Tag::StartEntry)));
queue.extend_back(&[FormatElement::Line(LineMode::SoftOrSpace)]);
assert_eq!(
queue.pop(),
Some(&FormatElement::Line(LineMode::SoftOrSpace))
);
assert_eq!(queue.pop(), Some(&FormatElement::Space));
assert_eq!(queue.pop(), None);
}
#[test]
fn extend_back_empty_queue() {
let mut queue =
PrintQueue::new(&[FormatElement::Tag(Tag::StartEntry), FormatElement::Space]);
assert_eq!(queue.pop(), Some(&FormatElement::Tag(Tag::StartEntry)));
assert_eq!(queue.pop(), Some(&FormatElement::Space));
queue.extend_back(&[FormatElement::Line(LineMode::SoftOrSpace)]);
assert_eq!(
queue.pop(),
Some(&FormatElement::Line(LineMode::SoftOrSpace))
);
assert_eq!(queue.pop(), None);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_formatter/src/printer/printer_options/mod.rs | crates/rome_formatter/src/printer/printer_options/mod.rs | use crate::{FormatOptions, IndentStyle, LineWidth};
/// Options that affect how the [crate::Printer] prints the format tokens
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PrinterOptions {
/// Width of a single tab character (does it equal 2, 4, ... spaces?)
pub tab_width: u8,
/// What's the max width of a line. Defaults to 80
pub print_width: PrintWidth,
/// The type of line ending to apply to the printed input
pub line_ending: LineEnding,
/// Whether the printer should use tabs or spaces to indent code and if spaces, by how many.
pub indent_style: IndentStyle,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct PrintWidth(u32);
impl PrintWidth {
pub fn new(width: u32) -> Self {
Self(width)
}
}
impl Default for PrintWidth {
fn default() -> Self {
LineWidth::default().into()
}
}
impl From<LineWidth> for PrintWidth {
fn from(width: LineWidth) -> Self {
Self(u16::from(width) as u32)
}
}
impl From<PrintWidth> for usize {
fn from(width: PrintWidth) -> Self {
width.0 as usize
}
}
impl<'a, O> From<&'a O> for PrinterOptions
where
O: FormatOptions,
{
fn from(options: &'a O) -> Self {
PrinterOptions::default()
.with_indent(options.indent_style())
.with_print_width(options.line_width().into())
}
}
impl PrinterOptions {
pub fn with_print_width(mut self, width: PrintWidth) -> Self {
self.print_width = width;
self
}
pub fn with_indent(mut self, style: IndentStyle) -> Self {
self.indent_style = style;
self
}
pub(crate) fn indent_style(&self) -> IndentStyle {
self.indent_style
}
/// Width of an indent in characters.
pub(super) const fn indent_width(&self) -> u8 {
match self.indent_style {
IndentStyle::Tab => self.tab_width,
IndentStyle::Space(count) => count,
}
}
}
#[allow(dead_code)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum LineEnding {
/// Line Feed only (\n), common on Linux and macOS as well as inside git repos
LineFeed,
/// Carriage Return + Line Feed characters (\r\n), common on Windows
CarriageReturnLineFeed,
/// Carriage Return character only (\r), used very rarely
CarriageReturn,
}
impl LineEnding {
#[inline]
pub const fn as_str(&self) -> &'static str {
match self {
LineEnding::LineFeed => "\n",
LineEnding::CarriageReturnLineFeed => "\r\n",
LineEnding::CarriageReturn => "\r",
}
}
}
impl Default for PrinterOptions {
fn default() -> Self {
PrinterOptions {
tab_width: 2,
print_width: PrintWidth::default(),
indent_style: Default::default(),
line_ending: LineEnding::LineFeed,
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_transform/src/lib.rs | crates/rome_js_transform/src/lib.rs | mod declare_transformation;
mod registry;
mod transformers;
use crate::registry::visit_transformation_registry;
use rome_analyze::{
AnalysisFilter, Analyzer, AnalyzerContext, AnalyzerOptions, AnalyzerSignal, ControlFlow,
InspectMatcher, LanguageRoot, MatchQueryParams, MetadataRegistry, RuleRegistry,
};
use rome_diagnostics::Error;
use rome_js_syntax::{JsFileSource, JsLanguage};
use rome_rowan::BatchMutation;
use std::convert::Infallible;
/// 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_transformation_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<JsLanguage>,
filter: AnalysisFilter,
inspect_matcher: V,
options: &'a AnalyzerOptions,
source_type: JsFileSource,
mut emit_signal: F,
) -> (Option<B>, Vec<Error>)
where
V: FnMut(&MatchQueryParams<JsLanguage>) + 'a,
F: FnMut(&dyn AnalyzerSignal<JsLanguage>) -> ControlFlow<B> + 'a,
B: 'a,
{
let mut registry = RuleRegistry::builder(&filter, root);
visit_transformation_registry(&mut registry);
let (registry, mut 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(registry, inspect_matcher),
|_| -> Vec<Result<_, Infallible>> { unreachable!() },
|_| {},
&mut emit_signal,
);
for ((phase, _), visitor) in visitors {
analyzer.add_visitor(phase, visitor);
}
services.insert_service(source_type);
(
analyzer.run(AnalyzerContext {
root: root.clone(),
range: filter.range,
services,
options,
}),
diagnostics,
)
}
/// 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
pub fn transform<'a, F, B>(
root: &LanguageRoot<JsLanguage>,
filter: AnalysisFilter,
options: &'a AnalyzerOptions,
source_type: JsFileSource,
emit_signal: F,
) -> (Option<B>, Vec<Error>)
where
F: FnMut(&dyn AnalyzerSignal<JsLanguage>) -> ControlFlow<B> + 'a,
B: 'a,
{
analyze_with_inspect_matcher(root, filter, |_| {}, options, source_type, emit_signal)
}
pub(crate) type JsBatchMutation = BatchMutation<JsLanguage>;
#[cfg(test)]
mod tests {
use rome_analyze::{AnalyzerOptions, Never, RuleCategories, RuleFilter};
use rome_js_parser::{parse, JsParserOptions};
use rome_js_syntax::JsFileSource;
use std::slice;
use crate::{transform, AnalysisFilter, ControlFlow};
#[ignore]
#[test]
fn quick_test() {
const SOURCE: &str = r#"enum Foo { Lorem, Ipsum }"#;
let parsed = parse(SOURCE, JsFileSource::tsx(), JsParserOptions::default());
let options = AnalyzerOptions::default();
let rule_filter = RuleFilter::Rule("transformations", "transformEnum");
transform(
&parsed.tree(),
AnalysisFilter {
categories: RuleCategories::TRANSFORMATION,
enabled_rules: Some(slice::from_ref(&rule_filter)),
..AnalysisFilter::default()
},
&options,
JsFileSource::tsx(),
|signal| {
for transformation in signal.transformations() {
let new_code = transformation.mutation.commit();
eprintln!("{new_code}");
}
ControlFlow::<Never>::Continue(())
},
);
// assert_eq!(error_ranges.as_slice(), &[]);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_transform/src/declare_transformation.rs | crates/rome_js_transform/src/declare_transformation.rs | #[macro_export]
macro_rules! declare_transformation {
( $( #[doc = $doc:literal] )+ $vis:vis $id:ident {
version: $version:literal,
name: $name:tt,
$( $key:ident: $value:expr, )*
} ) => {
$( #[doc = $doc] )*
$vis enum $id {}
impl ::rome_analyze::RuleMeta for $id {
type Group = $crate::registry::TransformationGroup;
const METADATA: ::rome_analyze::RuleMetadata =
::rome_analyze::RuleMetadata::new($version, $name, concat!( $( $doc, "\n", )* ));
}
};
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_transform/src/registry.rs | crates/rome_js_transform/src/registry.rs | use crate::transformers::ts_enum::TsEnum;
use rome_analyze::{GroupCategory, RegistryVisitor, RuleCategory, RuleGroup};
use rome_js_syntax::JsLanguage;
pub(crate) struct TransformationGroup;
pub(crate) struct TransformationCategory;
impl GroupCategory for TransformationCategory {
type Language = JsLanguage;
const CATEGORY: RuleCategory = RuleCategory::Transformation;
fn record_groups<V: RegistryVisitor<Self::Language> + ?Sized>(registry: &mut V) {
registry.record_group::<TransformationGroup>()
}
}
impl RuleGroup for TransformationGroup {
type Language = JsLanguage;
type Category = TransformationCategory;
const NAME: &'static str = "transformations";
fn record_rules<V: RegistryVisitor<Self::Language> + ?Sized>(registry: &mut V) {
registry.record_rule::<TsEnum>();
}
}
pub fn visit_transformation_registry<V: RegistryVisitor<JsLanguage>>(registry: &mut V) {
registry.record_category::<TransformationCategory>();
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_transform/src/transformers/mod.rs | crates/rome_js_transform/src/transformers/mod.rs | pub(crate) mod ts_enum;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_transform/src/transformers/ts_enum.rs | crates/rome_js_transform/src/transformers/ts_enum.rs | use crate::{declare_transformation, JsBatchMutation};
use rome_analyze::context::RuleContext;
use rome_analyze::{Ast, Rule};
use rome_js_factory::make::{
ident, js_assignment_expression, js_call_argument_list, js_call_arguments, js_call_expression,
js_computed_member_assignment, js_decorator_list, js_directive_list, js_expression_statement,
js_formal_parameter, js_function_body, js_function_expression, js_identifier_assignment,
js_identifier_binding, js_identifier_expression, js_logical_expression, js_module_item_list,
js_number_literal_expression, js_object_expression, js_object_member_list, js_parameter_list,
js_parameters, js_parenthesized_expression, js_reference_identifier, js_statement_list,
js_string_literal, js_string_literal_expression, js_variable_declaration,
js_variable_declarator, js_variable_declarator_list, js_variable_statement, token,
};
use rome_js_syntax::{
AnyJsAssignment, AnyJsAssignmentPattern, AnyJsBinding, AnyJsBindingPattern, AnyJsCallArgument,
AnyJsExpression, AnyJsFormalParameter, AnyJsLiteralExpression, AnyJsModuleItem, AnyJsParameter,
AnyJsStatement, JsAssignmentExpression, JsComputedMemberAssignment, JsExpressionStatement,
JsFunctionExpression, JsInitializerClause, JsLogicalExpression, JsModuleItemList,
JsStatementList, JsVariableStatement, TsEnumDeclaration, T,
};
use rome_rowan::{AstNode, BatchMutationExt, TriviaPieceKind};
declare_transformation! {
/// Transform a TypeScript [TsEnumDeclaration]
pub(crate) TsEnum {
version: "next",
name: "transformEnum",
}
}
#[derive(Debug)]
pub struct TsEnumMembers {
name: String,
member_names: Vec<(String, Option<JsInitializerClause>)>,
}
impl Rule for TsEnum {
type Query = Ast<TsEnumDeclaration>;
type State = TsEnumMembers;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let mut member_names = vec![];
let id = node.id().ok()?;
let name = id.text();
for member in node.members() {
let member = member.ok()?;
let key = member.name().ok()?.text();
let value = member.initializer().clone();
member_names.push((key, value));
}
Some(TsEnumMembers { name, member_names })
}
fn transform(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsBatchMutation> {
let node = ctx.query();
let mut mutation = node.clone().begin();
let parent = node.syntax().parent();
if let Some(parent) = parent {
if let Some(module_list) = JsModuleItemList::cast(parent) {
let variable = make_variable(state);
let function = make_function_caller(state);
let statements = vec![
AnyJsModuleItem::AnyJsStatement(AnyJsStatement::JsVariableStatement(variable)),
AnyJsModuleItem::AnyJsStatement(AnyJsStatement::JsExpressionStatement(
function,
)),
];
let new_modules_list = js_module_item_list(statements.into_iter());
mutation.replace_node(module_list, new_modules_list);
}
}
Some(mutation)
}
}
/// Out of an enum, this functions emits the generation of the:
///
/// ```ts
/// enum Foo {}
/// var Foo;
/// ```
fn make_variable(node: &TsEnumMembers) -> JsVariableStatement {
let binding = js_variable_declarator(AnyJsBindingPattern::AnyJsBinding(
AnyJsBinding::JsIdentifierBinding(js_identifier_binding(ident(node.name.as_str()))),
))
.build();
let list = js_variable_declarator_list([binding], []);
js_variable_statement(
js_variable_declaration(
token(T![var]).with_trailing_trivia([(TriviaPieceKind::Whitespace, " ")]),
list,
)
.build(),
)
.with_semicolon_token(token(T![;]))
.build()
}
fn make_function_caller(node: &TsEnumMembers) -> JsExpressionStatement {
let callee = js_parenthesized_expression(
token(T!['(']),
AnyJsExpression::JsFunctionExpression(make_function(node)),
token(T![')']),
);
let argument = AnyJsCallArgument::AnyJsExpression(AnyJsExpression::JsLogicalExpression(
make_logical_expression(node),
));
let arguments = js_call_arguments(
token(T!['(']),
js_call_argument_list([argument], []),
token(T![')']),
);
let expression = js_call_expression(
AnyJsExpression::JsParenthesizedExpression(callee),
arguments,
)
.build();
js_expression_statement(AnyJsExpression::JsCallExpression(expression))
.with_semicolon_token(token(T![;]))
.build()
}
fn make_function(node: &TsEnumMembers) -> JsFunctionExpression {
let parameters_list = js_parameter_list(
[AnyJsParameter::AnyJsFormalParameter(
AnyJsFormalParameter::JsFormalParameter(
js_formal_parameter(
js_decorator_list(vec![]),
AnyJsBindingPattern::AnyJsBinding(AnyJsBinding::JsIdentifierBinding(
js_identifier_binding(ident(node.name.as_str())),
)),
)
.build(),
),
)],
[],
);
let parameters = js_parameters(token(T!['(']), parameters_list, token(T![')']));
let body = js_function_body(
token(T!['{']),
js_directive_list([]),
make_members(node),
token(T!['}']),
);
js_function_expression(token(T![function]), parameters, body).build()
}
fn make_members(ts_enum: &TsEnumMembers) -> JsStatementList {
let mut list = vec![];
for (index, (name, value)) in ts_enum.member_names.iter().enumerate() {
let value = value
.as_ref()
.and_then(|initializer| initializer.expression().ok())
.unwrap_or_else(|| {
AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsNumberLiteralExpression(
js_number_literal_expression(ident(&index.to_string())),
),
)
});
list.push(AnyJsStatement::JsExpressionStatement(
make_high_order_assignment(ts_enum.name.as_str(), name.as_str(), value),
));
}
js_statement_list(list.into_iter())
}
fn make_logical_expression(node: &TsEnumMembers) -> JsLogicalExpression {
let left = js_identifier_expression(js_reference_identifier(ident(node.name.as_str())));
let expression = js_assignment_expression(
AnyJsAssignmentPattern::AnyJsAssignment(AnyJsAssignment::JsIdentifierAssignment(
js_identifier_assignment(ident(node.name.as_str())),
)),
token(T![=]),
AnyJsExpression::JsObjectExpression(js_object_expression(
token(T!['{']),
js_object_member_list([], []),
token(T!['}']),
)),
);
let right = js_parenthesized_expression(
token(T!['(']),
AnyJsExpression::JsAssignmentExpression(expression),
token(T![')']),
);
js_logical_expression(
AnyJsExpression::JsIdentifierExpression(left),
token(T![||]),
AnyJsExpression::JsParenthesizedExpression(right),
)
}
fn make_high_order_assignment(
enum_name: &str,
member_name: &str,
member_value: AnyJsExpression,
) -> JsExpressionStatement {
let left = js_computed_member_assignment(
AnyJsExpression::JsIdentifierExpression(js_identifier_expression(js_reference_identifier(
ident(enum_name),
))),
token(T!['[']),
AnyJsExpression::JsAssignmentExpression(make_assignment_expression_from_member(
enum_name,
member_name,
member_value,
)),
token(T![']']),
);
let right = js_string_literal_expression(js_string_literal(member_name));
let expression = js_assignment_expression(
AnyJsAssignmentPattern::AnyJsAssignment(AnyJsAssignment::JsComputedMemberAssignment(left)),
token(T![=]),
AnyJsExpression::AnyJsLiteralExpression(AnyJsLiteralExpression::JsStringLiteralExpression(
right,
)),
);
js_expression_statement(AnyJsExpression::JsAssignmentExpression(expression))
.with_semicolon_token(token(T![;]))
.build()
}
/// Makes
/// ```js
/// Foo["Lorem"] = 0
/// ```
fn make_assignment_expression_from_member(
enum_name: &str,
member_name: &str,
member_value: AnyJsExpression,
) -> JsAssignmentExpression {
let left = make_computed_member_assignment(enum_name, member_name);
js_assignment_expression(
AnyJsAssignmentPattern::AnyJsAssignment(AnyJsAssignment::JsComputedMemberAssignment(left)),
token(T![=]),
member_value,
)
}
/// Creates
/// ```js
/// Foo["Lorem"]
/// ```
fn make_computed_member_assignment(
enum_name: &str,
member_name: &str,
) -> JsComputedMemberAssignment {
let object = js_identifier_expression(js_reference_identifier(ident(enum_name)));
let member = js_string_literal_expression(js_string_literal(member_name));
js_computed_member_assignment(
AnyJsExpression::JsIdentifierExpression(object),
token(T!['[']),
AnyJsExpression::AnyJsLiteralExpression(AnyJsLiteralExpression::JsStringLiteralExpression(
member,
)),
token(T![']']),
)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_transform/tests/spec_tests.rs | crates/rome_js_transform/tests/spec_tests.rs | use rome_analyze::{AnalysisFilter, AnalyzerTransformation, ControlFlow, Never, RuleFilter};
use rome_js_formatter::context::JsFormatOptions;
use rome_js_formatter::format_node;
use rome_js_parser::{parse, JsParserOptions};
use rome_js_syntax::{JsFileSource, JsLanguage};
use rome_rowan::AstNode;
use rome_test_utils::{
assert_errors_are_absent, create_analyzer_options, diagnostic_to_string,
has_bogus_nodes_or_empty_slots, register_leak_checker, scripts_from_json,
write_transformation_snapshot,
};
use std::{ffi::OsStr, fs::read_to_string, path::Path, slice};
tests_macros::gen_tests! {"tests/specs/**/*.{cjs,js,jsx,tsx,ts,json,jsonc}", crate::run_test, "module"}
fn run_test(input: &'static str, _: &str, _: &str, _: &str) {
register_leak_checker();
let input_file = Path::new(input);
let file_name = input_file.file_name().and_then(OsStr::to_str).unwrap();
let rule_folder = input_file.parent().unwrap();
let rule = rule_folder.file_name().unwrap().to_str().unwrap();
if rule == "specs" {
panic!("the test file must be placed in the {rule}/<group-name>/<rule-name>/ directory");
}
if rome_js_transform::metadata()
.find_rule("transformations", rule)
.is_none()
{
panic!("could not find rule transformations/{rule}");
}
let rule_filter = RuleFilter::Rule("transformations", rule);
let filter = AnalysisFilter {
enabled_rules: Some(slice::from_ref(&rule_filter)),
..AnalysisFilter::default()
};
let mut snapshot = String::new();
let extension = input_file.extension().unwrap_or_default();
let input_code = read_to_string(input_file)
.unwrap_or_else(|err| panic!("failed to read {:?}: {:?}", input_file, err));
let quantity_diagnostics = if let Some(scripts) = scripts_from_json(extension, &input_code) {
for script in scripts {
analyze_and_snap(
&mut snapshot,
&script,
JsFileSource::js_script(),
filter,
file_name,
input_file,
JsParserOptions::default(),
);
}
0
} else {
let Ok(source_type) = input_file.try_into() else {
return;
};
analyze_and_snap(
&mut snapshot,
&input_code,
source_type,
filter,
file_name,
input_file,
JsParserOptions::default(),
)
};
insta::with_settings!({
prepend_module_to_snapshot => false,
snapshot_path => input_file.parent().unwrap(),
}, {
insta::assert_snapshot!(file_name, snapshot, file_name);
});
if input_code.contains("/* should not generate diagnostics */") && quantity_diagnostics > 0 {
panic!("This test should not generate diagnostics");
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn analyze_and_snap(
snapshot: &mut String,
input_code: &str,
source_type: JsFileSource,
filter: AnalysisFilter,
file_name: &str,
input_file: &Path,
parser_options: JsParserOptions,
) -> usize {
let parsed = parse(input_code, source_type, parser_options.clone());
let root = parsed.tree();
let mut diagnostics = Vec::new();
let options = create_analyzer_options(input_file, &mut diagnostics);
let mut transformations = vec![];
let (_, errors) = rome_js_transform::transform(&root, filter, &options, source_type, |event| {
for transformation in event.transformations() {
check_transformation(
input_file,
input_code,
source_type,
&transformation,
parser_options.clone(),
);
let node = transformation.mutation.commit();
let formatted = format_node(JsFormatOptions::new(source_type), &node).unwrap();
transformations.push(formatted.print().unwrap().as_code().to_string());
}
ControlFlow::<Never>::Continue(())
});
for error in errors {
diagnostics.push(diagnostic_to_string(file_name, input_code, error));
}
write_transformation_snapshot(
snapshot,
input_code,
transformations.as_slice(),
source_type.file_extension(),
);
diagnostics.len()
}
fn check_transformation(
path: &Path,
source: &str,
source_type: JsFileSource,
transformation: &AnalyzerTransformation<JsLanguage>,
options: JsParserOptions,
) {
let (_, text_edit) = transformation.mutation.as_text_edits().unwrap_or_default();
let output = text_edit.new_string(source);
let new_tree = transformation.mutation.clone().commit();
// Checks that applying the text edits returned by the BatchMutation
// returns the same code as printing the modified syntax tree
assert_eq!(new_tree.to_string(), output);
if has_bogus_nodes_or_empty_slots(&new_tree) {
panic!(
"modified tree has bogus nodes or empty slots:\n{new_tree:#?} \n\n {}",
new_tree
)
}
// Checks the returned tree contains no missing children node
if format!("{new_tree:?}").contains("missing (required)") {
panic!("modified tree has missing children:\n{new_tree:#?}")
}
// Re-parse the modified code and panic if the resulting tree has syntax errors
let re_parse = parse(&output, source_type, options);
assert_errors_are_absent(re_parse.tree().syntax(), re_parse.diagnostics(), path);
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_parser/src/tree_sink.rs | crates/rome_parser/src/tree_sink.rs | use crate::prelude::*;
use crate::token_source::Trivia;
use rome_rowan::{
Language, NodeCache, SyntaxFactory, SyntaxKind, SyntaxNode, TextRange, TextSize, TreeBuilder,
TriviaPiece,
};
/// An abstraction for syntax tree implementations
pub trait TreeSink {
type Kind: SyntaxKind;
/// Adds new token to the current branch.
fn token(&mut self, kind: Self::Kind, end: TextSize);
/// Start new branch and make it current.
fn start_node(&mut self, kind: Self::Kind);
/// Finish current branch and restore previous
/// branch as current.
fn finish_node(&mut self);
/// Emit errors
fn errors(&mut self, errors: Vec<ParseDiagnostic>);
}
/// Structure for converting events to a syntax tree representation, while preserving whitespace.
///
/// `LosslessTreeSink` also handles attachment of trivia (whitespace) to nodes.
#[derive(Debug)]
pub struct LosslessTreeSink<'a, L, Factory>
where
L: Language,
Factory: SyntaxFactory<Kind = L::Kind>,
{
text: &'a str,
trivia_list: &'a [Trivia],
text_pos: TextSize,
trivia_pos: usize,
parents_count: usize,
errors: Vec<ParseDiagnostic>,
inner: TreeBuilder<'a, L, Factory>,
/// Signal that the sink must generate an EOF token when its finishing. See [LosslessTreeSink::finish] for more details.
needs_eof: bool,
trivia_pieces: Vec<TriviaPiece>,
}
impl<'a, L, Factory> TreeSink for LosslessTreeSink<'a, L, Factory>
where
L: Language,
Factory: SyntaxFactory<Kind = L::Kind>,
{
type Kind = L::Kind;
fn token(&mut self, kind: L::Kind, end: TextSize) {
self.do_token(kind, end);
}
fn start_node(&mut self, kind: L::Kind) {
self.inner.start_node(kind);
self.parents_count += 1;
}
fn finish_node(&mut self) {
self.parents_count -= 1;
if self.parents_count == 0 && self.needs_eof {
self.do_token(L::Kind::EOF, TextSize::from(self.text.len() as u32));
}
self.inner.finish_node();
}
fn errors(&mut self, errors: Vec<ParseDiagnostic>) {
self.errors = errors;
}
}
impl<'a, L, Factory> LosslessTreeSink<'a, L, Factory>
where
L: Language,
Factory: SyntaxFactory<Kind = L::Kind>,
{
pub fn new(text: &'a str, trivia: &'a [Trivia]) -> Self {
Self {
text,
trivia_list: trivia,
text_pos: 0.into(),
trivia_pos: 0,
parents_count: 0,
inner: TreeBuilder::default(),
errors: vec![],
needs_eof: true,
trivia_pieces: Vec::with_capacity(128),
}
}
/// Reusing `NodeCache` between different [LosslessTreeSink]s saves memory.
/// It allows to structurally share underlying trees.
pub fn with_cache(text: &'a str, trivia: &'a [Trivia], cache: &'a mut NodeCache) -> Self {
Self {
text,
trivia_list: trivia,
text_pos: 0.into(),
trivia_pos: 0,
parents_count: 0,
inner: TreeBuilder::with_cache(cache),
errors: vec![],
needs_eof: true,
trivia_pieces: Vec::with_capacity(128),
}
}
/// Finishes the tree and return the root node with possible parser errors.
///
/// If tree is finished without a [rome_rowan::SyntaxKind::EOF], one will be generated and all pending trivia
/// will be appended to its leading trivia.
pub fn finish(self) -> (SyntaxNode<L>, Vec<ParseDiagnostic>) {
(self.inner.finish(), self.errors)
}
#[inline]
fn do_token(&mut self, kind: L::Kind, token_end: TextSize) {
if kind == L::Kind::EOF {
self.needs_eof = false;
}
let token_start = self.text_pos;
// Every trivia up to the token (including line breaks) will be the leading trivia
self.eat_trivia(false);
let trailing_start = self.trivia_pieces.len();
self.text_pos = token_end;
// Everything until the next linebreak (but not including it)
// will be the trailing trivia...
self.eat_trivia(true);
let token_range = TextRange::new(token_start, self.text_pos);
let text = &self.text[token_range];
let leading = &self.trivia_pieces[0..trailing_start];
let trailing = &self.trivia_pieces[trailing_start..];
self.inner.token_with_trivia(kind, text, leading, trailing);
self.trivia_pieces.clear();
}
fn eat_trivia(&mut self, trailing: bool) {
for trivia in &self.trivia_list[self.trivia_pos..] {
if trailing != trivia.trailing() || self.text_pos != trivia.offset() {
break;
}
let trivia_piece = TriviaPiece::new(trivia.kind(), trivia.len());
self.trivia_pieces.push(trivia_piece);
self.text_pos += trivia.len();
self.trivia_pos += 1;
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_parser/src/event.rs | crates/rome_parser/src/event.rs | //! Events emitted by the Parser which are then constructed into a syntax tree
use std::mem;
use std::num::NonZeroU32;
use crate::diagnostic::ParseDiagnostic;
use crate::tree_sink::TreeSink;
use rome_rowan::{SyntaxKind, TextSize};
/// Events emitted by the Parser, these events are later
/// made into a syntax tree with `process` into TreeSink.
#[derive(Debug, Clone)]
pub enum Event<K: SyntaxKind> {
/// This event signifies the start of the node.
/// It should be either abandoned (in which case the
/// `kind` is `TOMBSTONE`, and the event is ignored),
/// or completed via a `Finish` event.
///
/// All tokens between a `Start` and a `Finish` would
/// become the children of the respective node.
Start {
kind: K,
forward_parent: Option<NonZeroU32>,
},
/// Complete the previous `Start` event
Finish,
/// Produce a single leaf-element.
Token {
kind: K,
/// The end offset of this token.
end: TextSize,
},
}
impl<K: SyntaxKind> Event<K> {
pub fn tombstone() -> Self {
Event::Start {
kind: K::TOMBSTONE,
forward_parent: None,
}
}
}
/// Generate the syntax tree with the control of events.
#[inline]
pub fn process<K: SyntaxKind + PartialEq>(
sink: &mut impl TreeSink<Kind = K>,
mut events: Vec<Event<K>>,
errors: Vec<ParseDiagnostic>,
) {
sink.errors(errors);
let mut forward_parents = Vec::new();
for i in 0..events.len() {
match &mut events[i] {
Event::Start {
kind,
forward_parent,
..
} => {
if *kind == K::TOMBSTONE {
continue;
}
// For events[A, B, C], B is A's forward_parent, C is B's forward_parent,
// in the normal control flow, the parent-child relation: `A -> B -> C`,
// while with the magic forward_parent, it writes: `C <- B <- A`.
// append `A` into parents.
forward_parents.push(*kind);
let mut idx = i;
let mut fp = *forward_parent;
while let Some(fwd) = fp {
idx += u32::from(fwd) as usize;
// append `A`'s forward_parent `B`
fp = match mem::replace(&mut events[idx], Event::tombstone()) {
Event::Start {
kind,
forward_parent,
..
} => {
if kind != K::TOMBSTONE {
forward_parents.push(kind);
}
forward_parent
}
_ => unreachable!(),
};
// append `B`'s forward_parent `C` in the next stage.
}
for kind in forward_parents.drain(..).rev() {
sink.start_node(kind);
}
}
Event::Finish { .. } => sink.finish_node(),
Event::Token { kind, end } => {
sink.token(*kind, *end);
}
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_parser/src/prelude.rs | crates/rome_parser/src/prelude.rs | pub use crate::diagnostic::{ParseDiagnostic, ToDiagnostic};
pub use crate::marker::{CompletedMarker, Marker};
pub use crate::parsed_syntax::ParsedSyntax;
pub use crate::token_source::{BumpWithContext, NthToken, TokenSource};
pub use crate::{token_set, TokenSet};
pub use crate::{Parser, SyntaxFeature};
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_parser/src/lib.rs | crates/rome_parser/src/lib.rs | //! # Authoring Parse Rules
//!
//! This is a short, or not so short, guide to implement parse rules using the Rome parser infrastructure.
//!
//! ## Naming
//! The convention is to prefix your parse rule with `parse_` and then use the name defined in the grammar file.
//!
//! For example, `parse_for_statement` or `parse_expression`.
//!
//! ## Signature
//! Most parse rules take a `&mut` reference to the parser as their only parameter and return a `ParsedSyntax`.
//!
//! ```rust,ignore
//! fn parse_rule_name(&mut: Parser) -> ParsedSyntax {}
//! ```
//!
//! You're free to add additional parameters to your function if needed. There are rare cases where you want to consider returning `ConditionalParsedSyntax` as explained in [conditional syntax](#conditional-syntax)
//!
//!
//! ## Parsing a single node
//!
//! Let's assume you want to parse the JS `if` statement:
//!
//! ```js
//! JsIfStatement =
//! if
//! (
//! test: JsAnyExpression
//! )
//! consequent: JsBlockStatement
//! else_clause: JsElseClause?
//! ```
//!
//! ### Presence Test
//!
//! Now, the parsing function must first test if the parser is positioned at an `if` statement and return `Absent` if that's not the case.
//!
//! ```rust, ignore
//! if !p.at(T![if]) {
//! return ParsedSyntax::Absent;
//! }
//! ```
//!
//! Why return `ParsedSyntax::Absent`? The function must return `ParsedSyntax::Absent` if the rule can't predict by the next token(s) if they form the expected node or not. Doing so allows the calling rule to decide if this is an error and perform an error recovery if necessary. The second reason is to ensure that the rule doesn't return a node where all children are missing.
//!
//! Your rule implementation may want to consider more than just the first child to determine if it can parse at least some of the expected children.
//! For example, the if statement rule could test if the parser is located at an `else` clause and then create an `if` statement where all children are missing except the `else` clause:
//!
//! ```rust, ignore
//! if !p.at(T![if]) && !p.at(T![else]){
//! return Absent
//! }
//! ```
//!
//! Your implementation can also call into another parsing rule if the first child is a node and not a token.
//!
//! ```rust, ignore
//! let assignment_target = parse_assignment_target(p);
//!
//! if assignment_target.is_absent() {
//! return Absent;
//! }
//!
//! let my_node = assignment_target.precede_or_missing();
//! ```
//!
//! But be careful with calling other rules. Your rule mustn't progress the parser - meaning that it can't
//! advance in the parsing process and consume tokens - if it returns `Absent`.
//!
//!
//! ### Parse children
//! The parse rules will guide you in how to write your implementation and the parser infrastructure provides the following convenience APIs:
//!
//! * Optional token `'ident'?`: Use `p.eat(token)`. It eats the next token if it matches the passed-in token.
//! * Required token `'ident'`: Use`p.expect(token)`. It eats the next token if it matches the passed-in token.
//! It adds an `Expected 'x' but found 'y' instead` error and a missing marker if the token isn't present in the source code.
//! * Optional node `body: JsBlockStatement?`: Use`parse_block_statement(p).or_missing(p)`. It parses the block if it is present in the source code and adds a missing marker if it isn't.
//! * Required node `body: JsBlockStatement`: Use `parse_block_statement(p).or_missing_with_error(p, error_builder)`:
//! it parses the block statement if it is present in the source code and adds a missing marker and an error if not.
//!
//! Using the above-described rules result in the following implementation for the `if` statement rule.
//!
//! ```rust, ignore
//! fn parse_if_statement(p: &mut Parser) -> ParsedSyntax {
//! if !p.at(T![if]) {
//! return Absent;
//! }
//!
//! let m = p.start();
//!
//! p.expect(T![if]);
//! p.expect(T!['(']);
//! parse_any_expression(p).or_add_diagnostic(p, js_parse_errors::expeced_if_statement);
//! p.expect(T![')']);
//! parse_block_statement(p).or_add_diagnostic(p, js_parse_errors::expected_block_statement);
//! // the else block is optional, handle the marker by using `ok`
//! parse_else_clause(p).ok();
//!
//! Present(m.complete(p, JS_IF_STATEMENT));
//! }
//! ```
//!
//! Hold on, what are these *missing* markers? Rome's AST facade uses fixed offsets to retrieve a particular child from a node.
//! For example, the 3rd child of the if statement is the condition. However, the condition would become the second element
//! if the opening parentheses `(` isn't present in the source text. That's where missing elements come into play.
//!
//! ## Parsing Lists & Error Recovery
//!
//! Parsing lists is different from parsing single elements with a fixed set of children because it requires looping until
//! the parser reaches a terminal token (or the end of the file).
//!
//! You may remember that `parse_*` methods shouldn't progress parsing if they return `Absent`.
//! Not progressing the parser is problematic inside `while` loops because it inevitably results in an infinite loop.
//!
//! That's why you must do error recovery when parsing lists. Luckily, the parser comes with the infrastructure to make error recovery a piece of cake.
//! The general structure for parsing a list is (yes, that's something the parser infrastructure should provide for you):
//!
//!
//! Let's try to parse an array:
//!
//! ```js
//! [ 1, 3, 6 ]
//! ```
//!
//! We will use `ParseSeparatedList` in order to achieve that
//!
//! ```rust, ignore
//! struct ArrayElementsList;
//!
//! impl ParseSeparatedList for ArrayElementsList {
//! type ParsedElement = CompletedMarker;
//!
//! fn parse_element(&mut self, p: &mut Parser) -> ParsedSyntax<Self::ParsedElement> {
//! parse_array_element(p)
//! }
//!
//! fn is_at_list_end(&self, p: &mut Parser) -> bool {
//! p.at_ts(token_set![T![default], T![case], T!['}']])
//! }
//!
//! fn recover(
//! &mut self,
//! p: &mut Parser,
//! parsed_element: ParsedSyntax<Self::ParsedElement>,
//! ) -> parser::RecoveryResult {
//! parsed_element.or_recover(
//! p,
//! &ParseRecovery::new(JS_BOGUS_STATEMENT, STMT_RECOVERY_SET),
//! js_parse_error::expected_case,
//! )
//! }
//! };
//! ```
//!
//! Let's run through this step by step:
//!
//! ```rust, ignore
//! parsed_element.or_recover(
//! p,
//! &ParseRecovery::new(JS_BOGUS_STATEMENT, STMT_RECOVERY_SET),
//! js_parse_error::expected_case,
//! )
//! ```
//!
//! The `or_recover` performs an error recovery if the `parse_array_element` method returns `Absent`;
//! there's no array element in the source text.
//!
//! The recovery eats all tokens until it finds one of the tokens specified in the `token_set`,
//! a line break (if you called `enable_recovery_on_line_break`) or the end of the file.
//!
//! The recovery doesn't throw the tokens away but instead wraps them inside a `JS_BOGUS_EXPRESSION` node (first parameter).
//! There exist multiple `BOGUS_*` nodes. You must consult the grammar to understand which `BOGUS*` node is supported in your case.
//!
//! > You usually want to include the terminal token ending your list, the element separator token, and the token terminating a statement in your recovery set.
//!
//!
//! Now, the problem with recovery is that it can fail, and there are two reasons:
//!
//! - the parser reached the end of the file;
//! - the next token is one of the tokens specified in the recovery set, meaning there is nothing to recover from;
//!
//! In these cases the `ParseSeparatedList` and `ParseNodeList` will recover the parser for you.
//!
//! ## Conditional Syntax
//!
//! The conditional syntax allows you to express that some syntax may not be valid in all source files. Some use cases are:
//!
//! * syntax that is only supported in strict or sloppy mode: for example, `with` statements is not valid when a JavaScript file uses `"use strict"` or is a module;
//! * syntax that is only supported in certain file types: Typescript, JSX, modules;
//! * syntax that is only available in specific language versions: experimental features, different versions of the language e.g. (ECMA versions for JavaScript);
//!
//! The idea is that the parser always parses the syntax regardless of whatever it is supported in this specific file or context.
//! The main motivation behind doing so is that this gives us perfect error recovery and allows us to use the same code regardless of whether the syntax is supported.
//!
//! However, conditional syntax must be handled because we want to add a diagnostic if the syntax isn't supported for the current file, and the parsed tokens must be attached somewhere.
//!
//! Let's have a look at the `with` statement that is only allowed in loose mode/sloppy mode:
//!
//! ```rust, ignore
//! fn parse_with_statement(p: &mut Parser) -> ParsedSyntax {
//! if !p.at(T![with]) {
//! return Absent;
//! }
//!
//! let m = p.start();
//! p.bump(T![with]); // with
//! parenthesized_expression(p).or_add_diagnostic(p, js_errors::expected_parenthesized_expression);
//! parse_statement(p).or_add_diagnostic(p, js_error::expected_statement);
//! let with_stmt = m.complete(p, JS_WITH_STATEMENT);
//!
//! let conditional = StrictMode.excluding_syntax(p, with_stmt, |p, marker| {
//! p.err_builder("`with` statements are not allowed in strict mode", marker.range(p))
//! });
//!
//!
//! }
//! ```
//!
//! The start of the rule is the same as for any other rule. The exciting bits start with
//!
//! ```rust, ignore
//! let conditional = StrictMode.excluding_syntax(p, with_stmt, |p, marker| {
//! p.err_builder("`with` statements are not allowed in strict mode", marker.range(p))
//! });
//! ```
//!
//! The `StrictMode.excluding_syntax` converts the parsed syntax to a bogus node and uses the diagnostic builder to create a diagnostic if the feature is not supported.
//!
//! You can convert the `ConditionalParsedSyntax` to a regular `ParsedSyntax` by calling `or_invalid_to_bogus`, which wraps the whole parsed `with` statement in an `BOGUS` node if the parser is in strict mode and otherwise returns the unchanged `with` statement.
//!
//! What if there's no `BOGUS` node matching the node of your parse rule? You must then return the `ConditionalParsedSyntax` without making the `or_invalid_to_bogus` recovery. It's then up to the caller to recover the potentially invalid syntax.
//!
//!
//! ## Summary
//!
//! * Parse rules are named `parse_rule_name`
//! * The parse rules should return a `ParsedSyntax`
//! * The rule must return `Present` if it consumes any token and, therefore, can parse the node with at least some of its children.
//! * It returns `Absent` otherwise and must not progress parsing nor add any errors.
//! * Lists must perform error recovery to avoid infinite loops.
//! * Consult the grammar to identify the `BOGUS` node that is valid in the context of your rule.
//!
use crate::diagnostic::{expected_token, ParseDiagnostic, ToDiagnostic};
use crate::event::Event;
use crate::event::Event::Token;
use crate::token_source::{BumpWithContext, NthToken, TokenSource};
use rome_console::fmt::Display;
use rome_diagnostics::location::AsSpan;
use rome_rowan::{
AnyFileSource, AstNode, FileSource, FileSourceError, Language, SendNode, SyntaxKind,
SyntaxNode, TextRange, TextSize,
};
use std::any::type_name;
use std::path::Path;
pub mod diagnostic;
pub mod event;
mod marker;
pub mod parse_lists;
pub mod parse_recovery;
pub mod parsed_syntax;
pub mod prelude;
pub mod token_set;
pub mod token_source;
pub mod tree_sink;
use crate::parsed_syntax::ParsedSyntax;
use crate::parsed_syntax::ParsedSyntax::{Absent, Present};
pub use marker::{CompletedMarker, Marker};
use rome_diagnostics::serde::Diagnostic;
pub use token_set::TokenSet;
pub struct ParserContext<K: SyntaxKind> {
events: Vec<Event<K>>,
skipping: bool,
diagnostics: Vec<ParseDiagnostic>,
}
impl<K: SyntaxKind> Default for ParserContext<K> {
fn default() -> Self {
Self::new()
}
}
impl<K: SyntaxKind> ParserContext<K> {
pub fn new() -> Self {
Self {
skipping: false,
events: Vec::new(),
diagnostics: Vec::new(),
}
}
/// Returns the slice with the parse events
pub fn events(&self) -> &[Event<K>] {
&self.events
}
/// Returns a slice with the parse diagnostics
pub fn diagnostics(&self) -> &[ParseDiagnostic] {
&self.diagnostics
}
/// Drops all diagnostics after `at`.
pub fn truncate_diagnostics(&mut self, at: usize) {
self.diagnostics.truncate(at);
}
/// Pushes a new token event
pub fn push_token(&mut self, kind: K, end: TextSize) {
self.push_event(Token { kind, end });
}
/// Pushes a parse event
pub fn push_event(&mut self, event: Event<K>) {
self.events.push(event)
}
/// Returns `true` if the parser is skipping a token as skipped token trivia.
pub fn is_skipping(&self) -> bool {
self.skipping
}
/// Splits the events into two at the given `position`. Returns a newly allocated vector containing the
/// elements from `[position;len]`.
///
/// ## Safety
/// The method is marked as `unsafe` to discourage its usage. Removing events can lead to
/// corrupted events if not done carefully.
pub unsafe fn split_off_events(&mut self, position: usize) -> Vec<Event<K>> {
self.events.split_off(position)
}
/// Get the current index of the last event
fn cur_event_pos(&self) -> usize {
self.events.len().saturating_sub(1)
}
/// Remove `amount` events from the parser
fn drain_events(&mut self, amount: usize) {
self.events.truncate(self.events.len() - amount);
}
/// Rewind the parser back to a previous position in time
pub fn rewind(&mut self, checkpoint: ParserContextCheckpoint) {
let ParserContextCheckpoint {
event_pos,
errors_pos,
} = checkpoint;
self.drain_events(self.cur_event_pos() - event_pos);
self.diagnostics.truncate(errors_pos as usize);
}
/// Get a checkpoint representing the progress of the parser at this point of time
#[must_use]
pub fn checkpoint(&self) -> ParserContextCheckpoint {
ParserContextCheckpoint {
event_pos: self.cur_event_pos(),
errors_pos: self.diagnostics.len() as u32,
}
}
pub fn finish(self) -> (Vec<Event<K>>, Vec<ParseDiagnostic>) {
(self.events, self.diagnostics)
}
}
/// A structure signifying the Parser progress at one point in time
#[derive(Debug)]
pub struct ParserContextCheckpoint {
event_pos: usize,
/// The length of the errors list at the time the checkpoint was created.
/// Safety: The parser only supports files <= 4Gb. Storing a `u32` is sufficient to store one error
/// for each single character in the file, which should be sufficient for any realistic file.
errors_pos: u32,
}
impl ParserContextCheckpoint {
pub fn event_position(&self) -> usize {
self.event_pos
}
}
pub trait Parser: Sized {
type Kind: SyntaxKind;
type Source: TokenSource<Kind = Self::Kind>;
/// Returns a reference to the [`ParserContext`](ParserContext)
fn context(&self) -> &ParserContext<Self::Kind>;
/// Returns a mutable reference to the [`ParserContext`](ParserContext).
fn context_mut(&mut self) -> &mut ParserContext<Self::Kind>;
/// Returns a reference to the [`TokenSource``](TokenSource]
fn source(&self) -> &Self::Source;
/// Returns a mutable reference to the [`TokenSource`](TokenSource)
fn source_mut(&mut self) -> &mut Self::Source;
/// Returns `true` if the parser is trying to parse some syntax but only if it has no errors.
///
/// Returning `true` disables more involved error recovery.
fn is_speculative_parsing(&self) -> bool {
false
}
/// Gets the source text of a range
///
/// # Panics
///
/// If the range is out of bounds
fn text(&self, span: TextRange) -> &str {
&self.source().text()[span]
}
/// Gets the current token kind of the parser
fn cur(&self) -> Self::Kind {
self.source().current()
}
/// Gets the range of the current token
fn cur_range(&self) -> TextRange {
self.source().current_range()
}
/// Tests if there's a line break before the current token (between the last and current)
fn has_preceding_line_break(&self) -> bool {
self.source().has_preceding_line_break()
}
/// Get the source code of the parser's current token.
fn cur_text(&self) -> &str {
&self.source().text()[self.cur_range()]
}
/// Checks if the parser is currently at a specific token
fn at(&self, kind: Self::Kind) -> bool {
self.cur() == kind
}
/// Check if the parser's current token is contained in a token set
fn at_ts(&self, kinds: TokenSet<Self::Kind>) -> bool {
kinds.contains(self.cur())
}
/// Look ahead at a token and get its kind.
fn nth(&mut self, n: usize) -> Self::Kind
where
Self::Source: NthToken,
{
self.source_mut().nth(n)
}
/// Checks if a token lookahead is something
fn nth_at(&mut self, n: usize, kind: Self::Kind) -> bool
where
Self::Source: NthToken,
{
self.nth(n) == kind
}
/// Tests if there's a line break before the nth token.
#[inline]
fn has_nth_preceding_line_break(&mut self, n: usize) -> bool
where
Self::Source: NthToken,
{
self.source_mut().has_nth_preceding_line_break(n)
}
/// Consume the current token if `kind` matches.
fn bump(&mut self, kind: Self::Kind) {
assert_eq!(
kind,
self.cur(),
"expected {:?} but at {:?}",
kind,
self.cur()
);
self.do_bump(kind)
}
/// Consume any token but cast it as a different kind
fn bump_remap(&mut self, kind: Self::Kind) {
self.do_bump(kind);
}
/// Bumps the current token regardless of its kind and advances to the next token.
fn bump_any(&mut self) {
let kind = self.cur();
assert_ne!(kind, Self::Kind::EOF);
self.do_bump(kind);
}
/// Consumes the current token if `kind` matches and lexes the next token using the
/// specified `context.
fn bump_with_context(
&mut self,
kind: Self::Kind,
context: <Self::Source as BumpWithContext>::Context,
) where
Self::Source: BumpWithContext,
{
assert_eq!(
kind,
self.cur(),
"expected {:?} but at {:?}",
kind,
self.cur()
);
self.do_bump_with_context(kind, context);
}
#[doc(hidden)]
fn do_bump_with_context(
&mut self,
kind: Self::Kind,
context: <Self::Source as BumpWithContext>::Context,
) where
Self::Source: BumpWithContext,
{
let end = self.cur_range().end();
self.context_mut().push_token(kind, end);
if self.context().skipping {
self.source_mut().skip_as_trivia_with_context(context);
} else {
self.source_mut().bump_with_context(context);
}
}
#[doc(hidden)]
fn do_bump(&mut self, kind: Self::Kind) {
let end = self.cur_range().end();
self.context_mut().push_token(kind, end);
if self.context().skipping {
self.source_mut().skip_as_trivia();
} else {
self.source_mut().bump();
}
}
/// Consume the next token if `kind` matches.
fn eat(&mut self, kind: Self::Kind) -> bool {
if !self.at(kind) {
return false;
}
self.do_bump(kind);
true
}
/// Try to eat a specific token kind, if the kind is not there then adds an error to the events stack.
fn expect(&mut self, kind: Self::Kind) -> bool {
if self.eat(kind) {
true
} else {
self.error(expected_token(kind));
false
}
}
/// Allows parsing an unsupported syntax as skipped trivia tokens.
fn parse_as_skipped_trivia_tokens<P>(&mut self, parse: P)
where
P: FnOnce(&mut Self),
{
let events_pos = self.context().events.len();
self.context_mut().skipping = true;
parse(self);
self.context_mut().skipping = false;
// Truncate any start/finish events
self.context_mut().events.truncate(events_pos);
}
/// Add a diagnostic
fn error(&mut self, err: impl ToDiagnostic<Self>) {
let err = err.into_diagnostic(self);
// Don't report another diagnostic if the last diagnostic is at the same position of the current one
if let Some(previous) = self.context().diagnostics.last() {
match (&err.diagnostic_range(), &previous.diagnostic_range()) {
(Some(err_range), Some(previous_range))
if err_range.start() == previous_range.start() =>
{
return;
}
_ => {}
}
}
self.context_mut().diagnostics.push(err)
}
/// Creates a new diagnostic. Pass the message and the range where the error occurred
#[must_use]
fn err_builder(&self, message: impl Display, span: impl AsSpan) -> ParseDiagnostic {
ParseDiagnostic::new(message, span)
}
/// Bump and add an error event
fn err_and_bump(&mut self, err: impl ToDiagnostic<Self>, unknown_syntax_kind: Self::Kind) {
let m = self.start();
self.bump_any();
m.complete(self, unknown_syntax_kind);
self.error(err);
}
/// Returns the kind of the last bumped token.
fn last(&self) -> Option<Self::Kind> {
self.context()
.events
.iter()
.rev()
.find_map(|event| match event {
Token { kind, .. } => Some(*kind),
_ => None,
})
}
/// Returns the end offset of the last bumped token.
fn last_end(&self) -> Option<TextSize> {
self.context()
.events
.iter()
.rev()
.find_map(|event| match event {
Token { end, .. } => Some(*end),
_ => None,
})
}
/// Starts a new node in the syntax tree. All nodes and tokens
/// consumed between the `start` and the corresponding `Marker::complete`
/// belong to the same node.
fn start(&mut self) -> Marker {
let pos = self.context().events.len() as u32;
let start = self.source().position();
self.context_mut().push_event(Event::tombstone());
Marker::new(pos, start)
}
}
/// Captures the progress of the parser and allows to test if the parsing is still making progress
#[derive(Debug, Eq, Ord, PartialOrd, PartialEq, Hash, Default)]
pub struct ParserProgress(Option<TextSize>);
impl ParserProgress {
/// Returns true if the current parser position is passed this position
#[inline]
pub fn has_progressed<P>(&self, p: &P) -> bool
where
P: Parser,
{
match self.0 {
None => true,
Some(pos) => pos < p.source().position(),
}
}
/// Asserts that the parsing is still making progress.
///
/// # Panics
///
/// Panics if the parser is still at this position
#[inline]
pub fn assert_progressing<P>(&mut self, p: &P)
where
P: Parser,
{
assert!(
self.has_progressed(p),
"The parser is no longer progressing. Stuck at '{}' {:?}:{:?}",
p.cur_text(),
p.cur(),
p.cur_range(),
);
self.0 = Some(p.source().position());
}
}
/// A syntax feature that may or may not be supported depending on the file type and parser configuration
pub trait SyntaxFeature: Sized {
type Parser<'source>: Parser;
/// Returns `true` if the current parsing context supports this syntax feature.
fn is_supported(&self, p: &Self::Parser<'_>) -> bool;
/// Returns `true` if the current parsing context doesn't support this syntax feature.
fn is_unsupported(&self, p: &Self::Parser<'_>) -> bool {
!self.is_supported(p)
}
/// Adds a diagnostic and changes the kind of the node to [SyntaxKind::to_bogus] if this feature isn't
/// supported.
///
/// Returns the parsed syntax.
fn exclusive_syntax<'source, S, E, D>(
&self,
p: &mut Self::Parser<'source>,
syntax: S,
error_builder: E,
) -> ParsedSyntax
where
S: Into<ParsedSyntax>,
E: FnOnce(&Self::Parser<'source>, &CompletedMarker) -> D,
D: ToDiagnostic<Self::Parser<'source>>,
{
syntax.into().map(|mut syntax| {
if self.is_unsupported(p) {
let error = error_builder(p, &syntax);
p.error(error);
syntax.change_to_bogus(p);
syntax
} else {
syntax
}
})
}
/// Parses a syntax and adds a diagnostic and changes the kind of the node to [SyntaxKind::to_bogus] if this feature isn't
/// supported.
///
/// Returns the parsed syntax.
fn parse_exclusive_syntax<'source, P, E>(
&self,
p: &mut Self::Parser<'source>,
parse: P,
error_builder: E,
) -> ParsedSyntax
where
P: FnOnce(&mut Self::Parser<'source>) -> ParsedSyntax,
E: FnOnce(&Self::Parser<'source>, &CompletedMarker) -> ParseDiagnostic,
{
if self.is_supported(p) {
parse(p)
} else {
let diagnostics_checkpoint = p.context().diagnostics().len();
let syntax = parse(p);
p.context_mut().truncate_diagnostics(diagnostics_checkpoint);
match syntax {
Present(mut syntax) => {
let diagnostic = error_builder(p, &syntax);
p.error(diagnostic);
syntax.change_to_bogus(p);
Present(syntax)
}
_ => Absent,
}
}
}
/// Adds a diagnostic and changes the kind of the node to [SyntaxKind::to_bogus] if this feature is
/// supported.
///
/// Returns the parsed syntax.
fn excluding_syntax<'source, S, E>(
&self,
p: &mut Self::Parser<'source>,
syntax: S,
error_builder: E,
) -> ParsedSyntax
where
S: Into<ParsedSyntax>,
E: FnOnce(&Self::Parser<'source>, &CompletedMarker) -> ParseDiagnostic,
{
syntax.into().map(|mut syntax| {
if self.is_unsupported(p) {
syntax
} else {
let error = error_builder(p, &syntax);
p.error(error);
syntax.change_to_bogus(p);
syntax
}
})
}
}
/// Language-independent cache entry for a parsed file
///
/// This struct holds a handle to the root node of the parsed syntax tree,
/// along with the list of diagnostics emitted by the parser while generating
/// this entry.
///
/// It can be dynamically downcast into a concrete [SyntaxNode] or [AstNode] of
/// the corresponding language, generally through a language-specific capability
#[derive(Clone)]
pub struct AnyParse {
pub(crate) root: SendNode,
pub(crate) diagnostics: Vec<ParseDiagnostic>,
pub(crate) file_source: AnyFileSource,
}
impl AnyParse {
pub fn new(
root: SendNode,
diagnostics: Vec<ParseDiagnostic>,
file_source: AnyFileSource,
) -> AnyParse {
AnyParse {
root,
diagnostics,
file_source,
}
}
pub fn syntax<L>(&self) -> SyntaxNode<L>
where
L: Language + 'static,
{
self.root.clone().into_node().unwrap_or_else(|| {
panic!(
"could not downcast root node to language {}",
type_name::<L>()
)
})
}
pub fn file_source<'a, F, L>(&self, path: &'a Path) -> Result<F, FileSourceError>
where
F: FileSource<'a, L> + 'static,
L: Language + 'static,
{
self.file_source.unwrap_cast_from_path(path)
}
pub fn tree<N>(&self) -> N
where
N: AstNode,
N::Language: 'static,
{
N::unwrap_cast(self.syntax::<N::Language>())
}
/// This function transforms diagnostics coming from the parser into serializable diagnostics
pub fn into_diagnostics(self) -> Vec<Diagnostic> {
self.diagnostics.into_iter().map(Diagnostic::new).collect()
}
/// Get the diagnostics which occurred when parsing
pub fn diagnostics(&self) -> &[ParseDiagnostic] {
&self.diagnostics
}
pub fn has_errors(&self) -> bool {
self.diagnostics.iter().any(|diag| diag.is_error())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_parser/src/token_set.rs | crates/rome_parser/src/token_set.rs | use rome_rowan::SyntaxKind;
use std::marker::PhantomData;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TokenSet<K: SyntaxKind>([u128; 2], PhantomData<K>);
impl<K: SyntaxKind> TokenSet<K> {
pub const EMPTY: TokenSet<K> = TokenSet([0; 2], PhantomData);
pub fn singleton(kind: K) -> Self {
unsafe { TokenSet::from_raw(kind.to_raw().0) }
}
pub const fn union(self, other: TokenSet<K>) -> Self {
TokenSet(
[self.0[0] | other.0[0], self.0[1] | other.0[1]],
PhantomData,
)
}
pub fn contains(&self, kind: K) -> bool {
let kind = kind.to_raw().0;
let num = kind as usize;
match num {
0..=127 => self.0[0] & mask(kind)[0] != 0,
_ => self.0[1] & mask(kind)[1] != 0,
}
}
/// Constructs a token set for a single kind from a kind's raw `u16` representation.
///
/// # Safety
///
/// This method is marked unsafe to discourage its usage over using `TokenSet::singleton`.
/// It exists to support the `token_set` macro in a `const` context.
#[doc(hidden)]
pub const unsafe fn from_raw(kind: u16) -> Self {
TokenSet(mask(kind), PhantomData)
}
}
const fn mask(kind: u16) -> [u128; 2] {
let num = kind as usize;
match num {
0..=127 => [1u128 << num, 0],
_ => [0, 1u128 << (num - 127)],
}
}
/// Utility macro for making a new token set
#[macro_export]
macro_rules! token_set {
($($t:expr),*) => {{
use $crate::TokenSet;
TokenSet::EMPTY$(.union(unsafe { TokenSet::from_raw($t as u16) }))*
}};
($($t:expr),* ,) => { token_set!($($t),*) };
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_parser/src/token_source.rs | crates/rome_parser/src/token_source.rs | use crate::diagnostic::ParseDiagnostic;
use rome_rowan::{SyntaxKind, TextRange, TextSize, TriviaPieceKind};
/// A comment or a whitespace trivia in the source code.
#[derive(Debug, Copy, Clone)]
pub struct Trivia {
/// The kind of the trivia token.
kind: TriviaPieceKind,
/// The range of the trivia in the source text
range: TextRange,
/// Whatever this is the trailing or leading trivia of a non-trivia token.
trailing: bool,
}
impl Trivia {
pub fn new(kind: TriviaPieceKind, range: TextRange, trailing: bool) -> Self {
Self {
kind,
range,
trailing,
}
}
/// Returns the kind of the token
pub fn kind(&self) -> TriviaPieceKind {
self.kind
}
/// Returns the token's length in bytes
pub fn len(&self) -> TextSize {
self.range.len()
}
/// Returns the byte offset of the trivia in the source text
pub fn offset(&self) -> TextSize {
self.range.start()
}
/// Returns `true` if this is the trailing trivia of a non-trivia token or false otherwise.
pub fn trailing(&self) -> bool {
self.trailing
}
/// Returns the text range of this trivia
pub fn text_range(&self) -> TextRange {
self.range
}
}
pub trait TokenSource {
type Kind: SyntaxKind;
/// Returns the kind of the current non-trivia token
fn current(&self) -> Self::Kind;
/// Returns the range of the current non-trivia token
fn current_range(&self) -> TextRange;
/// Returns the source text
fn text(&self) -> &str;
/// Returns the byte offset of the current token from the start of the source document
fn position(&self) -> TextSize {
self.current_range().start()
}
/// Returns true if the current token is preceded by a line break
fn has_preceding_line_break(&self) -> bool;
fn bump(&mut self);
fn skip_as_trivia(&mut self);
/// Ends this token source and returns the source text's trivia
fn finish(self) -> (Vec<Trivia>, Vec<ParseDiagnostic>);
}
pub trait BumpWithContext: TokenSource {
type Context;
fn bump_with_context(&mut self, context: Self::Context);
/// Skips the current token as skipped token trivia
fn skip_as_trivia_with_context(&mut self, context: Self::Context);
}
/// Token source that supports inspecting the 'nth' token (lookahead)
pub trait NthToken: TokenSource {
/// Gets the kind of the nth non-trivia token
fn nth(&mut self, n: usize) -> Self::Kind;
/// Returns true if the nth non-trivia token is preceded by a line break
fn has_nth_preceding_line_break(&mut self, n: usize) -> bool;
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_parser/src/parse_lists.rs | crates/rome_parser/src/parse_lists.rs | //! A set of traits useful to parse various types of lists
use crate::parse_recovery::RecoveryResult;
use crate::prelude::*;
use crate::ParserProgress;
use rome_rowan::SyntaxKind;
/// Use this trait to parse simple lists that don't have particular requirements.
///
/// ```rust,ignore
/// use rome_js_parser::{ParseSeparatedList};
///
/// struct MyList;
///
///
/// impl ParseNormalList for MyList {
/// // impl missing members
/// }
/// ```
pub trait ParseNodeList {
type Kind: SyntaxKind;
type Parser<'source>: Parser<Kind = Self::Kind>;
/// The kind of the list node
const LIST_KIND: Self::Kind;
/// Parses a single element of the list
fn parse_element(&mut self, p: &mut Self::Parser<'_>) -> ParsedSyntax;
/// It creates a marker just before starting a list
fn start_list(&mut self, p: &mut Self::Parser<'_>) -> Marker {
p.start()
}
/// This method is used to check the current token inside the loop. When this method return [false],
/// the trait will exit from the loop.
///
/// Usually here you want to check the current token.
fn is_at_list_end(&self, p: &mut Self::Parser<'_>) -> bool;
/// This method is used to recover the parser in case [Self::parse_element] returns [ParsedSyntax::Absent]
fn recover(&mut self, p: &mut Self::Parser<'_>, parsed_element: ParsedSyntax)
-> RecoveryResult;
/// It creates a [ParsedSyntax] that will contain the list
fn finish_list(&mut self, p: &mut Self::Parser<'_>, m: Marker) {
m.complete(p, Self::LIST_KIND);
}
/// Parses a simple list
///
/// # Panics
///
/// It panics if the parser doesn't advance at each cycle of the loop
fn parse_list(&mut self, p: &mut Self::Parser<'_>) {
let elements = self.start_list(p);
let mut progress = ParserProgress::default();
while !p.at(<<Self::Parser<'_> as Parser>::Kind as SyntaxKind>::EOF)
&& !self.is_at_list_end(p)
{
progress.assert_progressing(p);
let parsed_element = self.parse_element(p);
if self.recover(p, parsed_element).is_err() {
break;
}
}
self.finish_list(p, elements);
}
}
/// A trait to parse lists that will be separated by a recurring element
///
/// ```rust,ignore
/// use rome_js_parser::{ParseSeparatedList};
///
/// struct MyList;
///
/// impl ParseSeparatedList for MyList {
/// // impl missing members
/// }
/// ```
pub trait ParseSeparatedList {
type Kind: SyntaxKind;
type Parser<'source>: Parser<Kind = Self::Kind>;
/// The kind of the list node
const LIST_KIND: Self::Kind;
/// Parses a single element of the list
fn parse_element(&mut self, p: &mut Self::Parser<'_>) -> ParsedSyntax;
/// It creates a marker just before starting a list
fn start_list(&mut self, p: &mut Self::Parser<'_>) -> Marker {
p.start()
}
/// This method is used to check the current token inside the loop. When this method return [false],
/// the trait will exit from the loop.
///
/// Usually here you want to check the current token.
fn is_at_list_end(&self, p: &mut Self::Parser<'_>) -> bool;
/// This method is used to recover the parser in case [Self::parse_element] returns [ParsedSyntax::Absent]
fn recover(&mut self, p: &mut Self::Parser<'_>, parsed_element: ParsedSyntax)
-> RecoveryResult;
/// It creates a [ParsedSyntax] that will contain the list
/// Only called if the list isn't empty
fn finish_list(&mut self, p: &mut Self::Parser<'_>, m: Marker) -> CompletedMarker {
m.complete(p, Self::LIST_KIND)
}
/// The [SyntaxKind] of the element that separates the elements of the list
fn separating_element_kind(&mut self) -> Self::Kind;
/// `true` if the list allows for an optional trailing element
fn allow_trailing_separating_element(&self) -> bool {
false
}
/// Method called at each iteration of the the loop and checks if the expected
/// separator is present.
///
/// If present, it [parses](Self::separating_element_kind) it and continues with loop.
/// If not present, it adds a missing marker.
fn expect_separator(&mut self, p: &mut Self::Parser<'_>) -> bool {
p.expect(self.separating_element_kind())
}
/// Parses a list of elements separated by a recurring element
///
/// # Panics
///
/// It panics if the parser doesn't advance at each cycle of the loop
fn parse_list(&mut self, p: &mut Self::Parser<'_>) -> CompletedMarker {
let elements = self.start_list(p);
let mut progress = ParserProgress::default();
let mut first = true;
while !p.at(<Self::Parser<'_> as Parser>::Kind::EOF) && !self.is_at_list_end(p) {
if first {
first = false;
} else {
self.expect_separator(p);
if self.allow_trailing_separating_element() && self.is_at_list_end(p) {
break;
}
}
progress.assert_progressing(p);
let parsed_element = self.parse_element(p);
if parsed_element.is_absent() && p.at(self.separating_element_kind()) {
// a missing element
continue;
} else if self.recover(p, parsed_element).is_err() {
break;
}
}
self.finish_list(p, elements)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_parser/src/parse_recovery.rs | crates/rome_parser/src/parse_recovery.rs | use crate::prelude::*;
use rome_rowan::SyntaxKind;
use std::error::Error;
use std::fmt::{Display, Formatter};
#[derive(Debug, Eq, PartialEq)]
pub enum RecoveryError {
/// Recovery failed because the parser reached the end of file
Eof,
/// Recovery failed because it didn't eat any tokens. Meaning, the parser is already in a recovered state.
/// This is an error because:
/// a) It shouldn't create a completed marker wrapping no tokens
/// b) This results in an infinite-loop if the recovery is used inside a while loop. For example,
/// it's common that list parsing also recovers at the end of a statement or block. However, list elements
/// don't start with a `;` or `}` which is why parsing, for example, an array element fails again and
/// the array expression triggers another recovery. Handling this as an error ensures that list parsing
/// rules break out of the loop the same way as they would at the EOF.
AlreadyRecovered,
/// Returned if there's an unexpected token and the parser is speculatively parsing a syntax.
/// Error-recovery is disabled when doing speculative parsing because it can then make the impression
/// that the parser was able to correctly parse a syntax when, in fact, it only skipped over the tokens.
///
/// For example the syntax `(a, b, c) ...` in JavaScript can either be a parenthesized expression
/// or an arrow function, depending on what kind of token `...` is. Thus, the parer's only option is
/// to make the following assumption:
/// "Let's assume `(a, b, c) ...`" is an arrow function expression"
///
/// The parser then tries to parse `(a, b, c)` as an arrow function parameters and validates that `...`
/// indeed is the `=>`. The parser rewinds and re-parses the syntax as a parenthesized expression
/// if it turns out that `...` isn't the `=>` token or if any element in `(a, b, c)` isn't a valid parameter (for example `5 + 3` isn't valid).
RecoveryDisabled,
}
impl Error for RecoveryError {}
impl Display for RecoveryError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
RecoveryError::Eof => write!(f, "EOF"),
RecoveryError::AlreadyRecovered => write!(f, "already recovered"),
RecoveryError::RecoveryDisabled => write!(f, "recovery disabled"),
}
}
}
pub type RecoveryResult = Result<CompletedMarker, RecoveryError>;
/// Recovers the parser by finding a token/point (depending on the configuration) from where
/// the caller knows how to proceed parsing. The recovery wraps all the skipped tokens inside a `Bogus` node.
/// A safe recovery point for an array element could by finding the next `,` or `]`.
pub struct ParseRecovery<K: SyntaxKind> {
node_kind: K,
recovery_set: TokenSet<K>,
line_break: bool,
}
impl<K: SyntaxKind> ParseRecovery<K> {
/// Creates a new parse recovery that eats all tokens until it finds any token in the passed recovery set.
pub fn new(node_kind: K, recovery_set: TokenSet<K>) -> Self {
Self {
node_kind,
recovery_set,
line_break: false,
}
}
/// Enable recovery on line breaks
pub fn enable_recovery_on_line_break(mut self) -> Self {
self.line_break = true;
self
}
// TODO: Add a `recover_until` which recovers until the parser reached a token inside of the recovery set
// or the passed in `parse_*` rule was able to successfully parse an element.
/// Tries to recover by parsing all tokens into an `Bogus*` node until the parser finds any token
/// specified in the recovery set, the EOF, or a line break (depending on configuration).
/// Returns `Ok(bogus_node)` if recovery was successful, and `Err(RecoveryError::Eof)` if the parser
/// is at the end of the file (before starting recovery).
pub fn recover<P>(&self, p: &mut P) -> RecoveryResult
where
P: Parser<Kind = K>,
{
if p.at(P::Kind::EOF) {
return Err(RecoveryError::Eof);
}
if self.recovered(p) {
return Err(RecoveryError::AlreadyRecovered);
}
if p.is_speculative_parsing() {
return Err(RecoveryError::RecoveryDisabled);
}
let m = p.start();
while !self.recovered(p) {
p.bump_any();
}
Ok(m.complete(p, self.node_kind))
}
#[inline]
fn recovered<P>(&self, p: &P) -> bool
where
P: Parser<Kind = K>,
{
p.at_ts(self.recovery_set)
|| p.at(P::Kind::EOF)
|| (self.line_break && p.has_preceding_line_break())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_parser/src/parsed_syntax.rs | crates/rome_parser/src/parsed_syntax.rs | use crate::parse_recovery::{ParseRecovery, RecoveryResult};
use crate::parsed_syntax::ParsedSyntax::{Absent, Present};
use crate::prelude::*;
use rome_rowan::TextRange;
/// Syntax that is either present in the source tree or absent.
///
/// This type is commonly used as the return type of parse functions with the following types
///
///
/// ## Parse Rule conventions
///
/// * A parse rule must return [ParsedSyntax::Present] if it is able to parse a node or at least parts of it. For example,
/// the `parse_for_statement` should return [ParsedSyntax::Present] for `for (` even tough many of the required children are missing
/// because it is still able to parse parts of the for statement.
/// * A parse rule must return [ParsedSyntax::Absent] if the expected node isn't present in the source code.
/// In most cases, this means if the first expected token isn't present, for example,
/// if the `for` keyword isn't present when parsing a for statement.
/// However, it can be possible for rules to recover even if the first token doesn't match. One example
/// is when parsing an assignment target that has an optional default. The rule can recover even
/// if the assignment target is missing as long as the cursor is then positioned at an `=` token.
/// The rule must then return [ParsedSyntax::Present] with the partial parsed node.
/// * A parse rule must not eat any tokens when it returns [ParsedSyntax::Absent]
/// * A parse rule must not add any errors when it returns [ParsedSyntax::Absent]
///
/// This is a custom enum over using `Option` because [ParsedSyntax::Absent] values must be handled by the caller.
#[derive(Debug, PartialEq, Eq)]
#[must_use = "this `ParsedSyntax` may be an `Absent` variant, which should be handled"]
pub enum ParsedSyntax {
/// A syntax that isn't present in the source code. Used when a parse rule can't match the current
/// token of the parser.
Absent,
/// A completed syntax node with all or some of its children.
Present(CompletedMarker),
}
impl ParsedSyntax {
/// Converts from `ParsedSyntax` to `Option<CompletedMarker>`.
///
/// Converts `self` into an `Option<CompletedMarker>`, consuming `self`
#[inline]
pub fn ok(self) -> Option<CompletedMarker> {
match self {
Absent => None,
Present(marker) => Some(marker),
}
}
/// Calls `op` if the syntax is present and otherwise returns [ParsedSyntax::Absent]
#[inline]
pub fn and_then<F>(self, op: F) -> ParsedSyntax
where
F: FnOnce(CompletedMarker) -> ParsedSyntax,
{
match self {
Absent => Absent,
Present(marker) => op(marker),
}
}
/// Calls `op` if the syntax is absent ond otherwise returns [ParsedSyntax::Present]
#[inline]
pub fn or_else<F>(self, op: F) -> ParsedSyntax
where
F: FnOnce() -> ParsedSyntax,
{
match self {
Absent => op(),
t => t,
}
}
/// Returns `true` if the parsed syntax is [ParsedSyntax::Present]
#[inline]
#[must_use]
pub fn is_present(&self) -> bool {
matches!(self, Present(_))
}
/// Returns `true` if the parsed syntax is [ParsedSyntax::Absent]
#[inline]
#[must_use]
pub fn is_absent(&self) -> bool {
matches!(self, Absent)
}
/// It returns the contained [ParsedSyntax::Present] value, consuming the `self` value
///
/// # Panics
///
/// Panics if the current syntax is [ParsedSyntax::Absent]
#[inline]
#[track_caller]
pub fn unwrap(self) -> CompletedMarker {
match self {
Absent => {
panic!("Called `unwrap` on an `Absent` syntax");
}
Present(marker) => marker,
}
}
/// Returns the contained [ParsedSyntax::Present] value or passed default
#[allow(unused)]
#[inline]
pub fn unwrap_or(self, default: CompletedMarker) -> CompletedMarker {
match self {
Absent => default,
Present(marker) => marker,
}
}
/// Returns the contained [ParsedSyntax::Present] value or computes it from a clojure.
#[inline]
#[allow(unused)]
pub fn unwrap_or_else<F>(self, default: F) -> CompletedMarker
where
F: FnOnce() -> CompletedMarker,
{
match self {
Absent => default(),
Present(marker) => marker,
}
}
/// Returns the contained [ParsedSyntax::Present] value, consuming the self value.
///
/// # Panics
///
/// Panics if the value is an [ParsedSyntax::Absent] with a custom panic message provided by msg.
#[inline]
#[track_caller]
pub fn expect(self, msg: &str) -> CompletedMarker {
match self {
Present(marker) => marker,
Absent => panic!("{}", msg),
}
}
/// Maps a [ParsedSyntax::Present] `ParsedSyntax` by applying a function to a contained [ParsedSyntax::Present] value,
/// leaving an [ParsedSyntax::Absent] value untouched.
///
/// This function can be used to compose the results of two functions.
pub fn map<F>(self, mapper: F) -> ParsedSyntax
where
F: FnOnce(CompletedMarker) -> CompletedMarker,
{
match self {
Absent => Absent,
Present(element) => Present(mapper(element)),
}
}
/// Returns the kind of the syntax if it is present or [None] otherwise
#[inline]
pub fn kind<P>(&self, p: &P) -> Option<P::Kind>
where
P: Parser,
{
match self {
Absent => None,
Present(marker) => Some(marker.kind(p)),
}
}
/// Adds a diagnostic at the current parser position if the syntax is present and return its marker.
#[inline]
pub fn add_diagnostic_if_present<P, E, D>(
self,
p: &mut P,
error_builder: E,
) -> Option<CompletedMarker>
where
P: Parser,
E: FnOnce(&P, TextRange) -> D,
D: ToDiagnostic<P>,
{
match self {
Present(syntax) => {
let range = syntax.range(p);
let range = TextRange::new(range.start(), range.end());
let diagnostic = error_builder(p, range);
p.error(diagnostic);
Some(syntax)
}
Absent => None,
}
}
/// It returns the syntax if present or adds a diagnostic at the current parser position.
#[inline]
pub fn or_add_diagnostic<P, E, D>(self, p: &mut P, error_builder: E) -> Option<CompletedMarker>
where
P: Parser,
E: FnOnce(&P, TextRange) -> D,
D: ToDiagnostic<P>,
{
match self {
Present(syntax) => Some(syntax),
Absent => {
let diagnostic = error_builder(p, p.cur_range());
p.error(diagnostic);
None
}
}
}
/// It creates and returns a marker preceding this parsed syntax if it is present or starts
/// a new marker and adds an error to the current parser position.
/// See [CompletedMarker.precede]
#[inline]
pub fn precede_or_add_diagnostic<P, E, D>(self, p: &mut P, error_builder: E) -> Marker
where
P: Parser,
E: FnOnce(&P, TextRange) -> D,
D: ToDiagnostic<P>,
{
match self {
Present(completed) => completed.precede(p),
Absent => {
let diagnostic = error_builder(p, p.cur_range());
p.error(diagnostic);
p.start()
}
}
}
/// Creates a new marker that precedes this syntax or starts a new marker
#[inline]
pub fn precede<P>(self, p: &mut P) -> Marker
where
P: Parser,
{
match self {
Present(marker) => marker.precede(p),
Absent => p.start(),
}
}
/// Returns this Syntax if it is present in the source text or tries to recover the
/// parser if the syntax is absent. The recovery...
///
/// * eats all unexpected tokens into a `Bogus*` node until the parser reaches one
/// of the "safe tokens" configured in the [ParseRecovery].
/// * creates an error using the passed in error builder and adds it to the parsing diagnostics.
///
/// The error recovery can fail if the parser is located at the EOF token or if the parser
/// is already at a valid position according to the [ParseRecovery].
pub fn or_recover<P, E>(
self,
p: &mut P,
recovery: &ParseRecovery<P::Kind>,
error_builder: E,
) -> RecoveryResult
where
P: Parser,
E: FnOnce(&P, TextRange) -> ParseDiagnostic,
{
match self {
Present(syntax) => Ok(syntax),
Absent => match recovery.recover(p) {
Ok(recovered) => {
let diagnostic = error_builder(p, recovered.range(p));
p.error(diagnostic);
Ok(recovered)
}
Err(recovery_error) => {
let diagnostic = error_builder(p, p.cur_range());
p.error(diagnostic);
Err(recovery_error)
}
},
}
}
}
impl From<CompletedMarker> for ParsedSyntax {
fn from(marker: CompletedMarker) -> Self {
Present(marker)
}
}
impl From<Option<CompletedMarker>> for ParsedSyntax {
fn from(option: Option<CompletedMarker>) -> Self {
match option {
Some(completed) => Present(completed),
None => Absent,
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_parser/src/diagnostic.rs | crates/rome_parser/src/diagnostic.rs | use crate::token_source::TokenSource;
use crate::Parser;
use rome_diagnostics::console::fmt::Display;
use rome_diagnostics::console::{markup, MarkupBuf};
use rome_diagnostics::location::AsSpan;
use rome_diagnostics::{Advices, Diagnostic, Location, LogCategory, MessageAndDescription, Visit};
use rome_rowan::{SyntaxKind, TextLen, TextRange};
use std::cmp::Ordering;
/// A specialized diagnostic for the parser
///
/// Parser diagnostics are always **errors**.
///
/// A parser diagnostics structured in this way:
/// 1. a mandatory message and a mandatory [TextRange]
/// 2. a list of details, useful to give more information and context around the error
/// 3. a hint, which should tell the user how they could fix their issue
///
/// These information **are printed in this exact order**.
///
#[derive(Debug, Diagnostic, Clone)]
#[diagnostic(category = "parse", severity = Error)]
pub struct ParseDiagnostic {
/// The location where the error is occurred
#[location(span)]
span: Option<TextRange>,
#[message]
#[description]
message: MessageAndDescription,
#[advice]
advice: ParserAdvice,
}
/// Possible details related to the diagnostic
#[derive(Debug, Default, Clone)]
struct ParserAdvice {
/// A list a possible details that can be attached to the diagnostic.
/// Useful to explain the nature errors.
detail_list: Vec<ParserAdviceDetail>,
/// A message for the user that should tell the user how to fix the issue
hint: Option<MarkupBuf>,
}
/// The structure of the advice. A message that gives details, a possible range so
/// the diagnostic is able to highlight the part of the code we want to explain.
#[derive(Debug, Clone)]
struct ParserAdviceDetail {
/// A message that should explain this detail
message: MarkupBuf,
/// An optional range that should highlight the details of the code
span: Option<TextRange>,
}
impl ParserAdvice {
fn add_detail(&mut self, message: impl Display, range: Option<TextRange>) {
self.detail_list.push(ParserAdviceDetail {
message: markup! { {message} }.to_owned(),
span: range,
});
}
fn add_hint(&mut self, message: impl Display) {
self.hint = Some(markup! { { message } }.to_owned());
}
}
impl Advices for ParserAdvice {
fn record(&self, visitor: &mut dyn Visit) -> std::io::Result<()> {
for detail in &self.detail_list {
let ParserAdviceDetail { span, message } = detail;
visitor.record_log(LogCategory::Info, &markup! { {message} }.to_owned())?;
let location = Location::builder().span(span).build();
visitor.record_frame(location)?;
}
if let Some(hint) = &self.hint {
visitor.record_log(LogCategory::Info, &markup! { {hint} }.to_owned())?;
}
Ok(())
}
}
impl ParseDiagnostic {
pub fn new(message: impl Display, span: impl AsSpan) -> Self {
Self {
span: span.as_span(),
message: MessageAndDescription::from(markup! { {message} }.to_owned()),
advice: ParserAdvice::default(),
}
}
pub const fn is_error(&self) -> bool {
true
}
/// Use this API if you want to highlight more code frame, to help to explain where's the error.
///
/// A detail is printed **after the actual error** and before the hint.
///
/// ## Examples
///
/// ```
/// # use rome_console::fmt::{Termcolor};
/// # use rome_console::markup;
/// # use rome_diagnostics::{DiagnosticExt, PrintDiagnostic, console::fmt::Formatter};
/// # use rome_parser::diagnostic::ParseDiagnostic;
/// # use rome_rowan::{TextSize, TextRange};
/// # use std::fmt::Write;
///
/// let source = "const a";
/// let range = TextRange::new(TextSize::from(0), TextSize::from(5));
/// let mut diagnostic = ParseDiagnostic::new("this is wrong!", range)
/// .detail(TextRange::new(TextSize::from(6), TextSize::from(7)), "This is reason why it's broken");
///
/// let mut write = rome_diagnostics::termcolor::Buffer::no_color();
/// let error = diagnostic
/// .clone()
/// .with_file_path("example.js")
/// .with_file_source_code(source.to_string());
/// Formatter::new(&mut Termcolor(&mut write))
/// .write_markup(markup! {
/// {PrintDiagnostic::verbose(&error)}
/// })
/// .expect("failed to emit diagnostic");
///
/// let mut result = String::new();
/// write!(
/// result,
/// "{}",
/// std::str::from_utf8(write.as_slice()).expect("non utf8 in error buffer")
/// ).expect("");
///
pub fn detail(mut self, range: impl AsSpan, message: impl Display) -> Self {
self.advice.add_detail(message, range.as_span());
self
}
/// Small message that should suggest the user how they could fix the error
///
/// Hints are rendered a **last part** of the diagnostics
///
/// ## Examples
///
/// ```
/// # use rome_console::fmt::{Termcolor};
/// # use rome_console::markup;
/// # use rome_diagnostics::{DiagnosticExt, PrintDiagnostic, console::fmt::Formatter};
/// # use rome_parser::diagnostic::ParseDiagnostic;
/// # use rome_rowan::{TextSize, TextRange};
/// # use std::fmt::Write;
///
/// let source = "const a";
/// let range = TextRange::new(TextSize::from(0), TextSize::from(5));
/// let mut diagnostic = ParseDiagnostic::new("this is wrong!", range)
/// .hint("You should delete the code");
///
/// let mut write = rome_diagnostics::termcolor::Buffer::no_color();
/// let error = diagnostic
/// .clone()
/// .with_file_path("example.js")
/// .with_file_source_code(source.to_string());
/// Formatter::new(&mut Termcolor(&mut write))
/// .write_markup(markup! {
/// {PrintDiagnostic::verbose(&error)}
/// })
/// .expect("failed to emit diagnostic");
///
/// let mut result = String::new();
/// write!(
/// result,
/// "{}",
/// std::str::from_utf8(write.as_slice()).expect("non utf8 in error buffer")
/// ).expect("");
///
/// assert!(result.contains("× this is wrong!"));
/// assert!(result.contains("i You should delete the code"));
/// assert!(result.contains("> 1 │ const a"));
/// ```
///
pub fn hint(mut self, message: impl Display) -> Self {
self.advice.add_hint(message);
self
}
/// Retrieves the range that belongs to the diagnostic
pub(crate) fn diagnostic_range(&self) -> Option<&TextRange> {
self.span.as_ref()
}
}
pub trait ToDiagnostic<P>
where
P: Parser,
{
fn into_diagnostic(self, p: &P) -> ParseDiagnostic;
}
impl<P: Parser> ToDiagnostic<P> for ParseDiagnostic {
fn into_diagnostic(self, _: &P) -> ParseDiagnostic {
self
}
}
#[must_use]
pub fn expected_token<K>(token: K) -> ExpectedToken
where
K: SyntaxKind,
{
ExpectedToken(
token
.to_string()
.expect("Expected token to be a punctuation or keyword."),
)
}
#[must_use]
pub fn expected_token_any<K: SyntaxKind>(tokens: &[K]) -> ExpectedTokens {
use std::fmt::Write;
let mut expected = String::new();
for (index, token) in tokens.iter().enumerate() {
if index > 0 {
expected.push_str(", ");
}
if index == tokens.len() - 1 {
expected.push_str("or ");
}
let _ = write!(
&mut expected,
"'{}'",
token
.to_string()
.expect("Expected token to be a punctuation or keyword.")
);
}
ExpectedTokens(expected)
}
pub struct ExpectedToken(&'static str);
impl<P> ToDiagnostic<P> for ExpectedToken
where
P: Parser,
{
fn into_diagnostic(self, p: &P) -> ParseDiagnostic {
if p.cur() == P::Kind::EOF {
p.err_builder(
format!("expected `{}` but instead the file ends", self.0),
p.cur_range(),
)
.detail(p.cur_range(), "the file ends here")
} else {
p.err_builder(
format!("expected `{}` but instead found `{}`", self.0, p.cur_text()),
p.cur_range(),
)
.hint(format!("Remove {}", p.cur_text()))
}
}
}
pub struct ExpectedTokens(String);
impl<P> ToDiagnostic<P> for ExpectedTokens
where
P: Parser,
{
fn into_diagnostic(self, p: &P) -> ParseDiagnostic {
if p.cur() == P::Kind::EOF {
p.err_builder(
format!("expected {} but instead the file ends", self.0),
p.cur_range(),
)
.detail(p.cur_range(), "the file ends here")
} else {
p.err_builder(
format!("expected {} but instead found `{}`", self.0, p.cur_text()),
p.cur_range(),
)
.hint(format!("Remove {}", p.cur_text()))
}
}
}
/// Creates a diagnostic saying that the node `name` was expected at range
pub fn expected_node(name: &str, range: TextRange) -> ExpectedNodeDiagnosticBuilder {
ExpectedNodeDiagnosticBuilder::with_single_node(name, range)
}
/// Creates a diagnostic saying that any of the nodes in `names` was expected at range
pub fn expected_any(names: &[&str], range: TextRange) -> ExpectedNodeDiagnosticBuilder {
ExpectedNodeDiagnosticBuilder::with_any(names, range)
}
pub struct ExpectedNodeDiagnosticBuilder {
names: String,
range: TextRange,
}
impl ExpectedNodeDiagnosticBuilder {
fn with_single_node(name: &str, range: TextRange) -> Self {
ExpectedNodeDiagnosticBuilder {
names: format!("{} {}", article_for(name), name),
range,
}
}
fn with_any(names: &[&str], range: TextRange) -> Self {
debug_assert!(names.len() > 1, "Requires at least 2 names");
if names.len() < 2 {
return Self::with_single_node(names.first().unwrap_or(&"<missing>"), range);
}
let mut joined_names = String::new();
for (index, name) in names.iter().enumerate() {
if index > 0 {
joined_names.push_str(", ");
}
if index == names.len() - 1 {
joined_names.push_str("or ");
}
joined_names.push_str(article_for(name));
joined_names.push(' ');
joined_names.push_str(name);
}
Self {
names: joined_names,
range,
}
}
}
impl<P: Parser> ToDiagnostic<P> for ExpectedNodeDiagnosticBuilder {
fn into_diagnostic(self, p: &P) -> ParseDiagnostic {
let range = &self.range;
let msg = if p.source().text().text_len() <= range.start() {
format!(
"expected {} but instead found the end of the file",
self.names
)
} else {
format!(
"expected {} but instead found '{}'",
self.names,
p.text(*range)
)
};
let diag = p.err_builder(msg, self.range);
diag.detail(self.range, format!("Expected {} here", self.names))
}
}
fn article_for(name: &str) -> &'static str {
match name.chars().next() {
Some('a' | 'e' | 'i' | 'o' | 'u') => "an",
_ => "a",
}
}
/// Merges two lists of parser diagnostics. Only keeps the error from the first collection if two start at the same range.
///
/// The two lists must be so sorted by their source range in increasing order.
pub fn merge_diagnostics(
first: Vec<ParseDiagnostic>,
second: Vec<ParseDiagnostic>,
) -> Vec<ParseDiagnostic> {
if first.is_empty() {
return second;
}
if second.is_empty() {
return first;
}
let mut merged = Vec::new();
let mut first_iter = first.into_iter();
let mut second_iter = second.into_iter();
let mut current_first: Option<ParseDiagnostic> = first_iter.next();
let mut current_second: Option<ParseDiagnostic> = second_iter.next();
loop {
match (current_first, current_second) {
(Some(first_item), Some(second_item)) => {
let (first, second) = match (
first_item.diagnostic_range(),
second_item.diagnostic_range(),
) {
(Some(first_range), Some(second_range)) => {
match first_range.start().cmp(&second_range.start()) {
Ordering::Less => {
merged.push(first_item);
(first_iter.next(), Some(second_item))
}
Ordering::Equal => {
// Only keep one error, skip the one from the second list.
(Some(first_item), second_iter.next())
}
Ordering::Greater => {
merged.push(second_item);
(Some(first_item), second_iter.next())
}
}
}
(Some(_), None) => {
merged.push(second_item);
(Some(first_item), second_iter.next())
}
(None, Some(_)) => {
merged.push(first_item);
(first_iter.next(), Some(second_item))
}
(None, None) => {
merged.push(first_item);
merged.push(second_item);
(first_iter.next(), second_iter.next())
}
};
current_first = first;
current_second = second;
}
(None, None) => return merged,
(Some(first_item), None) => {
merged.push(first_item);
merged.extend(first_iter);
return merged;
}
(None, Some(second_item)) => {
merged.push(second_item);
merged.extend(second_iter);
return merged;
}
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_parser/src/marker.rs | crates/rome_parser/src/marker.rs | use crate::event::Event;
use crate::event::Event::Token;
use crate::token_source::TokenSource;
use crate::Parser;
use drop_bomb::DebugDropBomb;
use rome_rowan::{SyntaxKind, TextRange, TextSize};
use std::num::NonZeroU32;
/// A structure signifying the start of parsing of a syntax tree node
#[derive(Debug)]
#[must_use = "Marker must either be `completed` or `abandoned`"]
pub struct Marker {
/// The index in the events list
pos: u32,
/// The byte index where the node starts
start: TextSize,
pub(crate) old_start: u32,
child_idx: Option<usize>,
bomb: DebugDropBomb,
}
impl Marker {
pub fn new(pos: u32, start: TextSize) -> Marker {
Marker {
pos,
start,
old_start: pos,
child_idx: None,
bomb: DebugDropBomb::new("Marker must either be `completed` or `abandoned` to avoid that children are implicitly attached to a marker's parent."),
}
}
fn old_start(mut self, old: u32) -> Self {
if self.old_start >= old {
self.old_start = old;
};
self
}
/// Finishes the syntax tree node and assigns `kind` to it,
/// and mark the create a `CompletedMarker` for possible future
/// operation like `.precede()` to deal with forward_parent.
pub fn complete<P>(mut self, p: &mut P, kind: P::Kind) -> CompletedMarker
where
P: Parser,
{
self.bomb.defuse();
let context = p.context_mut();
let idx = self.pos as usize;
match context.events[idx] {
Event::Start {
kind: ref mut slot, ..
} => {
*slot = kind;
}
_ => unreachable!(),
}
let finish_pos = context.events.len() as u32;
context.push_event(Event::Finish);
let new = CompletedMarker::new(self.pos, finish_pos, self.start);
new.old_start(self.old_start)
}
/// Abandons the syntax tree node. All its children
/// are attached to its parent instead.
pub fn abandon<P>(mut self, p: &mut P)
where
P: Parser,
{
self.bomb.defuse();
let idx = self.pos as usize;
if idx == p.context().events.len() - 1 {
if let Some(Event::Start {
forward_parent: None,
kind,
}) = p.context_mut().events.pop()
{
assert_eq!(kind, P::Kind::TOMBSTONE);
}
}
if let Some(idx) = self.child_idx {
match p.context_mut().events[idx] {
Event::Start {
ref mut forward_parent,
..
} => {
*forward_parent = None;
}
_ => unreachable!(),
}
}
}
pub fn start(&self) -> TextSize {
self.start
}
}
/// A structure signifying a completed node
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CompletedMarker {
start_pos: u32,
offset: TextSize,
// Hack for parsing completed markers which have been preceded
// This should be redone completely in the future
old_start: u32,
finish_pos: u32,
}
impl CompletedMarker {
pub fn new(start_pos: u32, finish_pos: u32, offset: TextSize) -> Self {
CompletedMarker {
start_pos,
offset,
old_start: start_pos,
finish_pos,
}
}
pub(crate) fn old_start(mut self, old: u32) -> Self {
// For multiple precedes we should not update the old start
if self.old_start >= old {
self.old_start = old;
};
self
}
/// Change the kind of node this marker represents
pub fn change_kind<P>(&mut self, p: &mut P, new_kind: P::Kind)
where
P: Parser,
{
match p
.context_mut()
.events
.get_mut(self.start_pos as usize)
.expect("Finish position of marker is OOB")
{
Event::Start { kind, .. } => {
*kind = new_kind;
}
_ => unreachable!(),
}
}
pub fn change_to_bogus<P>(&mut self, p: &mut P)
where
P: Parser,
{
self.change_kind(p, self.kind(p).to_bogus());
}
/// Get the range of the marker
pub fn range<P>(&self, p: &P) -> TextRange
where
P: Parser,
{
let end = p.context().events[self.old_start as usize..self.finish_pos as usize]
.iter()
.rev()
.find_map(|event| match event {
Token { end, .. } => Some(*end),
_ => None,
})
.unwrap_or(self.offset);
TextRange::new(self.offset, end)
}
/// Get the underlying text of a marker
pub fn text<'a, P>(&self, p: &'a P) -> &'a str
where
P: Parser,
{
&p.source().text()[self.range(p)]
}
/// This method allows to create a new node which starts
/// *before* the current one. That is, parser could start
/// node `A`, then complete it, and then after parsing the
/// whole `A`, decide that it should have started some node
/// `B` before starting `A`. `precede` allows to do exactly
/// that. See also docs about `forward_parent` in `Event::Start`.
///
/// Given completed events `[START, FINISH]` and its corresponding
/// `CompletedMarker(pos: 0, _)`.
/// Append a new `START` events as `[START, FINISH, NEWSTART]`,
/// then mark `NEWSTART` as `START`'s parent with saving its relative
/// distance to `NEWSTART` into forward_parent(=2 in this case);
pub fn precede<P>(self, p: &mut P) -> Marker
where
P: Parser,
{
let mut new_pos = p.start();
let idx = self.start_pos as usize;
match p.context_mut().events[idx] {
Event::Start {
ref mut forward_parent,
..
} => {
// Safety: The new marker is always inserted after the start marker of this node, thus
// subtracting the two positions can never be 0.
*forward_parent = Some(NonZeroU32::try_from(new_pos.pos - self.start_pos).unwrap());
}
_ => unreachable!(),
}
new_pos.child_idx = Some(self.start_pos as usize);
new_pos.start = self.offset;
new_pos.old_start(self.old_start)
}
/// Undo this completion and turns into a `Marker`
pub fn undo_completion<P>(self, p: &mut P) -> Marker
where
P: Parser,
{
let start_idx = self.start_pos as usize;
let finish_idx = self.finish_pos as usize;
let events = &mut p.context_mut().events;
match events[start_idx] {
Event::Start {
ref mut kind,
forward_parent: None,
} => *kind = P::Kind::TOMBSTONE,
_ => unreachable!(),
}
match events[finish_idx] {
ref mut slot @ Event::Finish { .. } => *slot = Event::tombstone(),
_ => unreachable!(),
}
Marker::new(self.start_pos, self.offset)
}
pub fn kind<P>(&self, p: &P) -> P::Kind
where
P: Parser,
{
match p.context().events[self.start_pos as usize] {
Event::Start { kind, .. } => kind,
_ => unreachable!(),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/src/adapters.rs | crates/rome_diagnostics/src/adapters.rs | //! This modules exposes a number of "adapter diagnostics" that wrap error types
//! such as [std::error::Error] or [std::io::Error] in newtypes implementing the
//! [Diagnostic] trait
use std::io;
use rome_console::{fmt, markup};
use crate::{category, Category, Diagnostic, DiagnosticTags};
/// Implements [Diagnostic] over types implementing [std::error::Error].
#[derive(Debug)]
pub struct StdError {
error: Box<dyn std::error::Error + Send + Sync>,
}
impl<E: std::error::Error + Send + Sync + 'static> From<E> for StdError {
fn from(error: E) -> Self {
Self {
error: Box::new(error),
}
}
}
impl Diagnostic for StdError {
fn description(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(fmt, "{}", self.error)
}
fn message(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
fmt.write_markup(markup!({ AsConsoleDisplay(&self.error) }))
}
}
struct AsConsoleDisplay<'a, T>(&'a T);
impl<T: std::fmt::Display> fmt::Display for AsConsoleDisplay<'_, T> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
fmt.write_fmt(format_args!("{}", self.0))
}
}
/// Implements [Diagnostic] over for [io::Error].
#[derive(Debug)]
pub struct IoError {
error: io::Error,
}
impl From<io::Error> for IoError {
fn from(error: io::Error) -> Self {
Self { error }
}
}
impl Diagnostic for IoError {
fn category(&self) -> Option<&'static Category> {
Some(category!("internalError/io"))
}
fn description(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(fmt, "{}", self.error)
}
fn tags(&self) -> DiagnosticTags {
DiagnosticTags::INTERNAL
}
fn message(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
let error = self.error.to_string();
fmt.write_str(&error)
}
}
/// Implements [Diagnostic] over for [bpaf::ParseFailure].
#[derive(Debug)]
pub struct BpafError {
error: bpaf::ParseFailure,
}
impl From<bpaf::ParseFailure> for BpafError {
fn from(error: bpaf::ParseFailure) -> Self {
Self { error }
}
}
impl Diagnostic for BpafError {
fn category(&self) -> Option<&'static Category> {
Some(category!("flags/invalid"))
}
fn tags(&self) -> DiagnosticTags {
DiagnosticTags::FIXABLE
}
fn description(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let bpaf::ParseFailure::Stderr(reason) = &self.error {
write!(fmt, "{}", reason)?;
}
Ok(())
}
fn message(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
if let bpaf::ParseFailure::Stderr(reason) = &self.error {
let error = reason.to_string();
fmt.write_str(&error)?;
}
Ok(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/src/serde.rs | crates/rome_diagnostics/src/serde.rs | use std::io;
use rome_console::{fmt, markup, MarkupBuf};
use rome_text_edit::TextEdit;
use rome_text_size::TextRange;
use serde::{
de::{self, SeqAccess},
Deserialize, Deserializer, Serialize, Serializer,
};
use crate::{
diagnostic::internal::AsDiagnostic, diagnostic::DiagnosticTag, Advices as _, Backtrace,
Category, DiagnosticTags, LogCategory, Resource, Severity, SourceCode, Visit,
};
/// Serializable representation for a [Diagnostic](super::Diagnostic).
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub struct Diagnostic {
category: Option<&'static Category>,
severity: Severity,
description: String,
message: MarkupBuf,
advices: Advices,
verbose_advices: Advices,
location: Location,
tags: DiagnosticTags,
source: Option<Box<Self>>,
}
impl Diagnostic {
pub fn new<D: AsDiagnostic>(diag: D) -> Self {
Self::new_impl(diag.as_diagnostic())
}
fn new_impl<D: super::Diagnostic + ?Sized>(diag: &D) -> Self {
let category = diag.category();
let severity = diag.severity();
let description = PrintDescription(diag).to_string();
let mut message = MarkupBuf::default();
let mut fmt = fmt::Formatter::new(&mut message);
// SAFETY: Writing to a MarkupBuf should never fail
diag.message(&mut fmt).unwrap();
let mut advices = Advices::new();
// SAFETY: The Advices visitor never returns an error
diag.advices(&mut advices).unwrap();
let mut verbose_advices = Advices::new();
// SAFETY: The Advices visitor never returns an error
diag.verbose_advices(&mut verbose_advices).unwrap();
let location = diag.location().into();
let tags = diag.tags();
let source = diag.source().map(Self::new_impl).map(Box::new);
Self {
category,
severity,
description,
message,
advices,
verbose_advices,
location,
tags,
source,
}
}
}
impl super::Diagnostic for Diagnostic {
fn category(&self) -> Option<&'static Category> {
self.category
}
fn severity(&self) -> Severity {
self.severity
}
fn description(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt.write_str(&self.description)
}
fn message(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
fmt.write_markup(markup! { {self.message} })
}
fn advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.advices.record(visitor)
}
fn verbose_advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.verbose_advices.record(visitor)
}
fn location(&self) -> super::Location<'_> {
super::Location::builder()
.resource(&self.location.path)
.span(&self.location.span)
.source_code(&self.location.source_code)
.build()
}
fn tags(&self) -> DiagnosticTags {
self.tags
}
fn source(&self) -> Option<&dyn super::Diagnostic> {
self.source
.as_deref()
.map(|source| source as &dyn super::Diagnostic)
}
}
/// Wrapper type implementing [std::fmt::Display] for types implementing [Diagnostic](super::Diagnostic),
/// prints the description of the diagnostic as a string.
struct PrintDescription<'fmt, D: ?Sized>(pub &'fmt D);
impl<'fmt, D: super::Diagnostic + ?Sized> std::fmt::Display for PrintDescription<'fmt, D> {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.description(fmt).map_err(|_| std::fmt::Error)
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(test, derive(Eq, PartialEq))]
struct Location {
path: Option<Resource<String>>,
span: Option<TextRange>,
source_code: Option<String>,
}
impl From<super::Location<'_>> for Location {
fn from(loc: super::Location<'_>) -> Self {
Self {
path: loc.resource.map(super::Resource::to_owned),
span: loc.span,
source_code: loc
.source_code
.map(|source_code| source_code.text.to_string()),
}
}
}
/// Implementation of [Visitor] collecting serializable [Advice] into a vector.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(test, derive(Eq, PartialEq))]
struct Advices {
advices: Vec<Advice>,
}
impl Advices {
fn new() -> Self {
Self {
advices: Vec::new(),
}
}
}
impl Visit for Advices {
fn record_log(&mut self, category: LogCategory, text: &dyn fmt::Display) -> io::Result<()> {
self.advices
.push(Advice::Log(category, markup!({ text }).to_owned()));
Ok(())
}
fn record_list(&mut self, list: &[&dyn fmt::Display]) -> io::Result<()> {
self.advices.push(Advice::List(
list.iter()
.map(|item| markup!({ item }).to_owned())
.collect(),
));
Ok(())
}
fn record_frame(&mut self, location: super::Location<'_>) -> io::Result<()> {
self.advices.push(Advice::Frame(location.into()));
Ok(())
}
fn record_diff(&mut self, diff: &TextEdit) -> io::Result<()> {
self.advices.push(Advice::Diff(diff.clone()));
Ok(())
}
fn record_backtrace(
&mut self,
title: &dyn fmt::Display,
backtrace: &Backtrace,
) -> io::Result<()> {
self.advices.push(Advice::Backtrace(
markup!({ title }).to_owned(),
backtrace.clone(),
));
Ok(())
}
fn record_command(&mut self, command: &str) -> io::Result<()> {
self.advices.push(Advice::Command(command.into()));
Ok(())
}
fn record_group(
&mut self,
title: &dyn fmt::Display,
advice: &dyn super::Advices,
) -> io::Result<()> {
let mut advices = Advices::new();
advice.record(&mut advices)?;
self.advices
.push(Advice::Group(markup!({ title }).to_owned(), advices));
Ok(())
}
}
impl super::Advices for Advices {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
for advice in &self.advices {
advice.record(visitor)?;
}
Ok(())
}
}
/// Serializable representation of a [Diagnostic](super::Diagnostic) advice
///
/// See the [Visitor] trait for additional documentation on all the supported
/// advice types.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(test, derive(Eq, PartialEq))]
enum Advice {
Log(LogCategory, MarkupBuf),
List(Vec<MarkupBuf>),
Frame(Location),
Diff(TextEdit),
Backtrace(MarkupBuf, Backtrace),
Command(String),
Group(MarkupBuf, Advices),
}
impl super::Advices for Advice {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
match self {
Advice::Log(category, text) => visitor.record_log(*category, text),
Advice::List(list) => {
let as_display: Vec<&dyn fmt::Display> =
list.iter().map(|item| item as &dyn fmt::Display).collect();
visitor.record_list(&as_display)
}
Advice::Frame(location) => visitor.record_frame(super::Location {
resource: location.path.as_ref().map(super::Resource::as_deref),
span: location.span,
source_code: location.source_code.as_deref().map(|text| SourceCode {
text,
line_starts: None,
}),
}),
Advice::Diff(diff) => visitor.record_diff(diff),
Advice::Backtrace(title, backtrace) => visitor.record_backtrace(title, backtrace),
Advice::Command(command) => visitor.record_command(command),
Advice::Group(title, advice) => visitor.record_group(title, advice),
}
}
}
impl From<DiagnosticTag> for DiagnosticTags {
fn from(tag: DiagnosticTag) -> Self {
match tag {
DiagnosticTag::Fixable => DiagnosticTags::FIXABLE,
DiagnosticTag::Internal => DiagnosticTags::INTERNAL,
DiagnosticTag::UnnecessaryCode => DiagnosticTags::UNNECESSARY_CODE,
DiagnosticTag::DeprecatedCode => DiagnosticTags::DEPRECATED_CODE,
}
}
}
// Custom `serde` implementation for `DiagnosticTags` as a list of `DiagnosticTag` enum
impl Serialize for DiagnosticTags {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut flags = Vec::new();
if self.contains(Self::FIXABLE) {
flags.push(DiagnosticTag::Fixable);
}
if self.contains(Self::INTERNAL) {
flags.push(DiagnosticTag::Internal);
}
if self.contains(Self::UNNECESSARY_CODE) {
flags.push(DiagnosticTag::UnnecessaryCode);
}
if self.contains(Self::DEPRECATED_CODE) {
flags.push(DiagnosticTag::DeprecatedCode);
}
serializer.collect_seq(flags)
}
}
impl<'de> Deserialize<'de> for DiagnosticTags {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct Visitor;
impl<'de> de::Visitor<'de> for Visitor {
type Value = DiagnosticTags;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "DiagnosticTags")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut result = DiagnosticTags::empty();
while let Some(item) = seq.next_element::<DiagnosticTag>()? {
result |= DiagnosticTags::from(item);
}
Ok(result)
}
}
deserializer.deserialize_seq(Visitor)
}
}
#[cfg(feature = "schema")]
impl schemars::JsonSchema for DiagnosticTags {
fn schema_name() -> String {
String::from("DiagnosticTags")
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
<Vec<DiagnosticTag>>::json_schema(gen)
}
}
#[cfg(test)]
mod tests {
use std::io;
use rome_text_size::{TextRange, TextSize};
use serde_json::{from_value, json, to_value, Value};
use crate::{
self as rome_diagnostics, {Advices, LogCategory, Visit},
};
use rome_diagnostics_macros::Diagnostic;
#[derive(Debug, Diagnostic)]
#[diagnostic(
severity = Warning,
category = "internalError/io",
message(
description = "text description",
message(<Emphasis>"markup message"</Emphasis>),
),
tags(INTERNAL)
)]
struct TestDiagnostic {
#[location(resource)]
path: String,
#[location(span)]
span: TextRange,
#[location(source_code)]
source_code: String,
#[advice]
advices: TestAdvices,
#[verbose_advice]
verbose_advices: TestAdvices,
}
impl Default for TestDiagnostic {
fn default() -> Self {
TestDiagnostic {
path: String::from("path"),
span: TextRange::new(TextSize::from(0), TextSize::from(6)),
source_code: String::from("source_code"),
advices: TestAdvices,
verbose_advices: TestAdvices,
}
}
}
#[derive(Debug)]
struct TestAdvices;
impl Advices for TestAdvices {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
visitor.record_log(LogCategory::Warn, &"log")?;
Ok(())
}
}
fn serialized() -> Value {
let advices = json!([
{
"Log": [
"Warn",
[
{
"content": "log",
"elements": []
}
]
]
}
]);
json!({
"category": "internalError/io",
"severity": "warning",
"description": "text description",
"message": [
{
"content": "markup message",
"elements": [
"Emphasis"
]
}
],
"advices": {
"advices": advices
},
"verbose_advices": {
"advices": advices
},
"location": {
"path": {
"file": "path"
},
"source_code": "source_code",
"span": [
0,
6
]
},
"tags": [
"internal"
],
"source": null
})
}
#[test]
fn test_serialize() {
let diag = TestDiagnostic::default();
let diag = super::Diagnostic::new(diag);
let json = to_value(&diag).unwrap();
let expected = serialized();
assert_eq!(json, expected, "actual:\n{json:#}\nexpected:\n{expected:#}");
}
#[test]
fn test_deserialize() {
let json = serialized();
let diag: super::Diagnostic = from_value(json).unwrap();
let expected = TestDiagnostic::default();
let expected = super::Diagnostic::new(expected);
assert_eq!(
diag, expected,
"actual:\n{diag:#?}\nexpected:\n{expected:#?}"
);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/src/lib.rs | crates/rome_diagnostics/src/lib.rs | #![deny(rust_2018_idioms)]
use ::serde::{Deserialize, Serialize};
pub mod adapters;
pub mod advice;
pub mod context;
pub mod diagnostic;
pub mod display;
pub mod error;
pub mod location;
pub mod panic;
pub mod serde;
mod suggestion;
pub use self::suggestion::{Applicability, CodeSuggestion};
pub use termcolor;
#[doc(hidden)]
// Convenience re-export for procedural macro
pub use rome_console as console;
// Re-export macros from utility crates
pub use rome_diagnostics_categories::{category, category_concat, Category};
pub use rome_diagnostics_macros::Diagnostic;
pub use crate::advice::{
Advices, CodeFrameAdvice, CommandAdvice, DiffAdvice, LogAdvice, LogCategory, Visit,
};
pub use crate::context::{Context, DiagnosticExt};
pub use crate::diagnostic::{Diagnostic, DiagnosticTags, Severity};
pub use crate::display::{
set_bottom_frame, Backtrace, MessageAndDescription, PrintDescription, PrintDiagnostic,
};
pub use crate::error::{Error, Result};
pub use crate::location::{LineIndex, LineIndexBuf, Location, Resource, SourceCode};
use rome_console::fmt::{Formatter, Termcolor};
use rome_console::markup;
use std::fmt::Write;
pub mod prelude {
//! Anonymously re-exports all the traits declared by this module, this is
//! intended to be imported as `use rome_diagnostics::prelude::*;` to
//! automatically bring all these traits into the ambient context
pub use crate::advice::{Advices as _, Visit as _};
pub use crate::context::{Context as _, DiagnosticExt as _};
pub use crate::diagnostic::Diagnostic as _;
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum DiagnosticTag {
Unnecessary,
Deprecated,
Both,
}
impl DiagnosticTag {
pub fn is_unnecessary(&self) -> bool {
matches!(self, DiagnosticTag::Unnecessary | DiagnosticTag::Both)
}
pub fn is_deprecated(&self) -> bool {
matches!(self, DiagnosticTag::Deprecated | DiagnosticTag::Both)
}
}
pub const MAXIMUM_DISPLAYABLE_DIAGNOSTICS: u16 = 200;
/// Utility function for testing purpose. The function will print an [Error]
/// to a string, which is then returned by the function.
pub fn print_diagnostic_to_string(diagnostic: &Error) -> String {
let mut buffer = termcolor::Buffer::no_color();
Formatter::new(&mut Termcolor(&mut buffer))
.write_markup(markup! {
{PrintDiagnostic::verbose(diagnostic)}
})
.expect("failed to emit diagnostic");
let mut content = String::new();
writeln!(
content,
"{}",
std::str::from_utf8(buffer.as_slice()).expect("non utf8 in error buffer")
)
.unwrap();
content
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/src/panic.rs | crates/rome_diagnostics/src/panic.rs | use std::panic::UnwindSafe;
#[derive(Default, Debug)]
pub struct PanicError {
pub info: String,
pub backtrace: Option<std::backtrace::Backtrace>,
}
thread_local! {
static LAST_PANIC: std::cell::Cell<Option<PanicError>> = std::cell::Cell::new(None);
}
impl std::fmt::Display for PanicError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let r = f.write_fmt(format_args!("{}\n", self.info));
if let Some(backtrace) = &self.backtrace {
f.write_fmt(format_args!("Backtrace: {}", backtrace))
} else {
r
}
}
}
/// Take and set a specific panic hook before calling `f` inside a `catch_unwind`, then
/// return the old set_hook.
///
/// If `f` panicks am `Error` with the panic message plus backtrace will be returned.
pub fn catch_unwind<F, R>(f: F) -> Result<R, PanicError>
where
F: FnOnce() -> R + UnwindSafe,
{
let prev = std::panic::take_hook();
std::panic::set_hook(Box::new(|info| {
let info = info.to_string();
let backtrace = std::backtrace::Backtrace::capture();
LAST_PANIC.with(|cell| {
cell.set(Some(PanicError {
info,
backtrace: Some(backtrace),
}))
})
}));
let result = std::panic::catch_unwind(f)
.map_err(|_| LAST_PANIC.with(|cell| cell.take()).unwrap_or_default());
std::panic::set_hook(prev);
result
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/src/error.rs | crates/rome_diagnostics/src/error.rs | //! The `error` module contains the implementation of [Error], a dynamic
//! container struct for any type implementing [Diagnostic].
//!
//! We reduce the size of `Error` by using `Box<Box<dyn Diagnostic>>` (a thin
//! pointer to a fat pointer) rather than `Box<dyn Diagnostic>` (a fat
//! pointer), in order to make returning a `Result<T, Error>` more efficient.
//!
//! When [`ThinBox`](https://doc.rust-lang.org/std/boxed/struct.ThinBox.html)
//! becomes available in stable Rust, we can switch to that.
use std::ops::Deref;
use std::{
fmt::{Debug, Formatter},
io,
};
use rome_console::fmt;
use crate::{
diagnostic::internal::AsDiagnostic, Category, Diagnostic, DiagnosticTags, Location, Severity,
Visit,
};
/// The `Error` struct wraps any type implementing [Diagnostic] into a single
/// dynamic type.
pub struct Error {
inner: Box<Box<dyn Diagnostic + Send + Sync + 'static>>,
}
/// Implement the [Diagnostic] trait as inherent methods on the [Error] type.
impl Error {
/// Calls [Diagnostic::category] on the [Diagnostic] wrapped by this [Error].
pub fn category(&self) -> Option<&'static Category> {
self.as_diagnostic().category()
}
/// Calls [Diagnostic::severity] on the [Diagnostic] wrapped by this [Error].
pub fn severity(&self) -> Severity {
self.as_diagnostic().severity()
}
/// Calls [Diagnostic::description] on the [Diagnostic] wrapped by this [Error].
pub fn description(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.as_diagnostic().description(fmt)
}
/// Calls [Diagnostic::message] on the [Diagnostic] wrapped by this [Error].
pub fn message(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
self.as_diagnostic().message(fmt)
}
/// Calls [Diagnostic::advices] on the [Diagnostic] wrapped by this [Error].
pub fn advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.as_diagnostic().advices(visitor)
}
/// Calls [Diagnostic::verbose_advices] on the [Diagnostic] wrapped by this [Error].
pub fn verbose_advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.as_diagnostic().verbose_advices(visitor)
}
/// Calls [Diagnostic::location] on the [Diagnostic] wrapped by this [Error].
pub fn location(&self) -> Location<'_> {
self.as_diagnostic().location()
}
/// Calls [Diagnostic::tags] on the [Diagnostic] wrapped by this [Error].
pub fn tags(&self) -> DiagnosticTags {
self.as_diagnostic().tags()
}
/// Calls [Diagnostic::source] on the [Diagnostic] wrapped by this [Error].
pub fn source(&self) -> Option<&dyn Diagnostic> {
self.as_diagnostic().source()
}
}
/// Implement [From] for all types implementing [Diagnostic], [Send], [Sync]
/// and outlives the `'static` lifetime.
impl<T> From<T> for Error
where
T: Diagnostic + Send + Sync + 'static,
{
fn from(diag: T) -> Self {
Self {
inner: Box::new(Box::new(diag)),
}
}
}
impl AsDiagnostic for Error {
type Diagnostic = dyn Diagnostic;
fn as_diagnostic(&self) -> &Self::Diagnostic {
&**self.inner
}
fn as_dyn(&self) -> &dyn Diagnostic {
self.as_diagnostic()
}
}
impl AsRef<dyn Diagnostic + 'static> for Error {
fn as_ref(&self) -> &(dyn Diagnostic + 'static) {
self.as_diagnostic()
}
}
impl Deref for Error {
type Target = dyn Diagnostic + 'static;
fn deref(&self) -> &Self::Target {
self.as_diagnostic()
}
}
// Defer the implementation of `Debug` and `Drop` to the wrapped type
impl Debug for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Debug::fmt(self.as_diagnostic(), f)
}
}
/// Alias of [std::result::Result] with the `Err` type defaulting to [Error].
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[cfg(test)]
mod tests {
use std::{
mem::size_of,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
use crate::{Diagnostic, Error, Result};
#[derive(Debug)]
struct TestDiagnostic(Arc<AtomicBool>);
impl Diagnostic for TestDiagnostic {}
impl Drop for TestDiagnostic {
fn drop(&mut self) {
let was_dropped = self.0.swap(true, Ordering::Relaxed);
assert!(!was_dropped);
}
}
#[test]
fn test_drop() {
let drop_flag = AtomicBool::new(false);
let drop_flag = Arc::new(drop_flag);
let diag = TestDiagnostic(drop_flag.clone());
let error = Error::from(diag);
drop(error);
assert!(drop_flag.load(Ordering::Relaxed));
}
#[test]
fn test_error_size() {
assert_eq!(size_of::<Error>(), size_of::<usize>());
}
#[test]
fn test_result_size() {
assert_eq!(size_of::<Result<()>>(), size_of::<usize>());
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/src/display.rs | crates/rome_diagnostics/src/display.rs | use std::{io, iter};
use rome_console::{fmt, markup, HorizontalLine, Markup, MarkupBuf, MarkupElement, MarkupNode};
use rome_text_edit::TextEdit;
use unicode_width::UnicodeWidthStr;
mod backtrace;
mod diff;
mod frame;
mod message;
use crate::display::frame::SourceFile;
use crate::{
diagnostic::internal::AsDiagnostic, Advices, Diagnostic, DiagnosticTags, Location, LogCategory,
Resource, Severity, Visit,
};
pub use self::backtrace::{set_bottom_frame, Backtrace};
pub use self::message::MessageAndDescription;
/// Helper struct from printing the description of a diagnostic into any
/// formatter implementing [std::fmt::Write].
pub struct PrintDescription<'fmt, D: ?Sized>(pub &'fmt D);
impl<'fmt, D: AsDiagnostic + ?Sized> std::fmt::Display for PrintDescription<'fmt, D> {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0
.as_diagnostic()
.description(fmt)
.map_err(|_| std::fmt::Error)
}
}
/// Helper struct for printing a diagnostic as markup into any formatter
/// implementing [rome_console::fmt::Write].
pub struct PrintDiagnostic<'fmt, D: ?Sized> {
diag: &'fmt D,
verbose: bool,
}
impl<'fmt, D: AsDiagnostic + ?Sized> PrintDiagnostic<'fmt, D> {
pub fn simple(diag: &'fmt D) -> Self {
Self {
diag,
verbose: false,
}
}
pub fn verbose(diag: &'fmt D) -> Self {
Self {
diag,
verbose: true,
}
}
}
impl<'fmt, D: AsDiagnostic + ?Sized> fmt::Display for PrintDiagnostic<'fmt, D> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
let diagnostic = self.diag.as_diagnostic();
// Print the header for the diagnostic
fmt.write_markup(markup! {
{PrintHeader(diagnostic)}"\n\n"
})?;
// Wrap the formatter with an indentation level and print the advices
let mut slot = None;
let mut fmt = IndentWriter::wrap(fmt, &mut slot, true, " ");
let mut visitor = PrintAdvices(&mut fmt);
print_advices(&mut visitor, diagnostic, self.verbose)
}
}
/// Display struct implementing the formatting of a diagnostic header.
struct PrintHeader<'fmt, D: ?Sized>(&'fmt D);
impl<'fmt, D: Diagnostic + ?Sized> fmt::Display for PrintHeader<'fmt, D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> io::Result<()> {
let Self(diagnostic) = *self;
// Wrap the formatter with a counter to measure the width of the printed text
let mut slot = None;
let mut fmt = CountWidth::wrap(f, &mut slot);
// Print the diagnostic location if it has a file path
let location = diagnostic.location();
let file_name = match &location.resource {
Some(Resource::File(file)) => Some(file),
_ => None,
};
if let Some(name) = file_name {
fmt.write_str(name)?;
// Print the line and column position if the location has a span and source code
// (the source code is necessary to convert a byte offset into a line + column)
if let (Some(span), Some(source_code)) = (location.span, location.source_code) {
let file = SourceFile::new(source_code);
if let Ok(location) = file.location(span.start()) {
fmt.write_markup(markup! {
":"{location.line_number.get()}":"{location.column_number.get()}
})?;
}
}
fmt.write_str(" ")?;
}
// Print the category of the diagnostic, with a hyperlink if
// the category has an associated link
if let Some(category) = diagnostic.category() {
if let Some(link) = category.link() {
fmt.write_markup(markup! {
<Hyperlink href={link}>{category.name()}</Hyperlink>" "
})?;
} else {
fmt.write_markup(markup! {
{category.name()}" "
})?;
}
}
// Print the internal, fixable and fatal tags
let tags = diagnostic.tags();
if tags.contains(DiagnosticTags::INTERNAL) {
fmt.write_markup(markup! {
<Inverse><Error>" INTERNAL "</Error></Inverse>" "
})?;
}
if tags.contains(DiagnosticTags::FIXABLE) {
fmt.write_markup(markup! {
<Inverse>" FIXABLE "</Inverse>" "
})?;
}
if diagnostic.severity() == Severity::Fatal {
fmt.write_markup(markup! {
<Inverse><Error>" FATAL "</Error></Inverse>" "
})?;
}
// Load the printed width for the header, and fill the rest of the line
// with the '━' line character up to 100 columns with at least 10 characters
const HEADER_WIDTH: usize = 100;
const MIN_WIDTH: usize = 10;
let text_width = slot.map_or(0, |writer| writer.width);
let line_width = HEADER_WIDTH.saturating_sub(text_width).max(MIN_WIDTH);
HorizontalLine::new(line_width).fmt(f)
}
}
/// Wrapper for a type implementing [fmt::Write] that counts the total width of
/// all printed characters.
struct CountWidth<'a, W: ?Sized> {
writer: &'a mut W,
width: usize,
}
impl<'write> CountWidth<'write, dyn fmt::Write + 'write> {
/// Wrap the writer in an existing [fmt::Formatter] with an instance of [CountWidth].
fn wrap<'slot, 'fmt: 'write + 'slot>(
fmt: &'fmt mut fmt::Formatter<'_>,
slot: &'slot mut Option<Self>,
) -> fmt::Formatter<'slot> {
fmt.wrap_writer(|writer| slot.get_or_insert(Self { writer, width: 0 }))
}
}
impl<W: fmt::Write + ?Sized> fmt::Write for CountWidth<'_, W> {
fn write_str(&mut self, elements: &fmt::MarkupElements<'_>, content: &str) -> io::Result<()> {
self.writer.write_str(elements, content)?;
self.width += UnicodeWidthStr::width(content);
Ok(())
}
fn write_fmt(
&mut self,
elements: &fmt::MarkupElements<'_>,
content: std::fmt::Arguments<'_>,
) -> io::Result<()> {
if let Some(content) = content.as_str() {
self.write_str(elements, content)
} else {
let content = content.to_string();
self.write_str(elements, &content)
}
}
}
/// Write the advices for `diagnostic` into `visitor`.
fn print_advices<V, D>(visitor: &mut V, diagnostic: &D, verbose: bool) -> io::Result<()>
where
V: Visit,
D: Diagnostic + ?Sized,
{
// Visit the advices of the diagnostic with a lightweight visitor that
// detects if the diagnostic has any frame or backtrace advice
let mut frame_visitor = FrameVisitor {
location: diagnostic.location(),
skip_frame: false,
};
diagnostic.advices(&mut frame_visitor)?;
let skip_frame = frame_visitor.skip_frame;
// Print the message for the diagnostic as a log advice
print_message_advice(visitor, diagnostic, skip_frame)?;
// Print the other advices for the diagnostic
diagnostic.advices(visitor)?;
// Print the tags of the diagnostic as advices
print_tags_advices(visitor, diagnostic)?;
// If verbose printing is enabled, print the verbose advices in a nested group
if verbose {
// Count the number of verbose advices in the diagnostic
let mut counter = CountAdvices(0);
diagnostic.verbose_advices(&mut counter)?;
// If the diagnostic has any verbose advice, print the group
if !counter.is_empty() {
let verbose_advices = PrintVerboseAdvices(diagnostic);
visitor.record_group(&"Verbose advice", &verbose_advices)?;
}
}
Ok(())
}
/// Advice visitor used to detect if the diagnostic contains any frame or backtrace diagnostic.
#[derive(Debug)]
struct FrameVisitor<'diag> {
location: Location<'diag>,
skip_frame: bool,
}
impl Visit for FrameVisitor<'_> {
fn record_frame(&mut self, location: Location<'_>) -> io::Result<()> {
if location == self.location {
self.skip_frame = true;
}
Ok(())
}
fn record_backtrace(&mut self, _: &dyn fmt::Display, _: &Backtrace) -> io::Result<()> {
self.skip_frame = true;
Ok(())
}
}
/// Print the message and code frame for the diagnostic as advices.
fn print_message_advice<V, D>(visitor: &mut V, diagnostic: &D, skip_frame: bool) -> io::Result<()>
where
V: Visit,
D: Diagnostic + ?Sized,
{
// Print the entire message / cause chain for the diagnostic to a MarkupBuf
let message = {
let mut message = MarkupBuf::default();
let mut fmt = fmt::Formatter::new(&mut message);
fmt.write_markup(markup!({ PrintCauseChain(diagnostic) }))?;
message
};
// Print a log advice for the message, with a special fallback if the buffer is empty
if message.is_empty() {
visitor.record_log(
LogCategory::None,
&markup! {
<Dim>"no diagnostic message provided"</Dim>
},
)?;
} else {
let category = match diagnostic.severity() {
Severity::Fatal | Severity::Error => LogCategory::Error,
Severity::Warning => LogCategory::Warn,
Severity::Information | Severity::Hint => LogCategory::Info,
};
visitor.record_log(category, &message)?;
}
// If the diagnostic has no explicit code frame or backtrace advice, print
// a code frame advice with the location of the diagnostic
if !skip_frame {
let location = diagnostic.location();
if location.span.is_some() {
visitor.record_frame(location)?;
}
}
Ok(())
}
/// Display wrapper for printing the "cause chain" of a diagnostic, with the
/// message of this diagnostic and all of its sources.
struct PrintCauseChain<'fmt, D: ?Sized>(&'fmt D);
impl<'fmt, D: Diagnostic + ?Sized> fmt::Display for PrintCauseChain<'fmt, D> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
let Self(diagnostic) = *self;
diagnostic.message(fmt)?;
let chain = iter::successors(diagnostic.source(), |prev| prev.source());
for diagnostic in chain {
fmt.write_str("\n\nCaused by:\n")?;
let mut slot = None;
let mut fmt = IndentWriter::wrap(fmt, &mut slot, true, " ");
diagnostic.message(&mut fmt)?;
}
Ok(())
}
}
/// Implementation of [Visitor] that prints the advices for a diagnostic.
struct PrintAdvices<'a, 'b>(&'a mut fmt::Formatter<'b>);
impl PrintAdvices<'_, '_> {
fn print_log(
&mut self,
kind: MarkupElement<'_>,
prefix: char,
text: &dyn fmt::Display,
) -> io::Result<()> {
self.0.write_markup(Markup(&[MarkupNode {
elements: &[MarkupElement::Emphasis, kind.clone()],
content: &prefix as &dyn fmt::Display,
}]))?;
self.0.write_str(" ")?;
let mut slot = None;
let mut fmt = IndentWriter::wrap(self.0, &mut slot, false, " ");
fmt.write_markup(Markup(&[MarkupNode {
elements: &[kind],
content: text,
}]))?;
self.0.write_str("\n\n")
}
}
impl Visit for PrintAdvices<'_, '_> {
fn record_log(&mut self, category: LogCategory, text: &dyn fmt::Display) -> io::Result<()> {
match category {
LogCategory::None => self.0.write_markup(markup! { {text}"\n\n" }),
LogCategory::Info => self.print_log(MarkupElement::Info, '\u{2139}', text),
LogCategory::Warn => self.print_log(MarkupElement::Warn, '\u{26a0}', text),
LogCategory::Error => self.print_log(MarkupElement::Error, '\u{2716}', text),
}
}
fn record_list(&mut self, list: &[&dyn fmt::Display]) -> io::Result<()> {
for item in list {
let mut slot = None;
let mut fmt = IndentWriter::wrap(self.0, &mut slot, false, " ");
fmt.write_markup(markup! {
"- "{*item}"\n"
})?;
}
if list.is_empty() {
Ok(())
} else {
self.0.write_str("\n")
}
}
fn record_frame(&mut self, location: Location<'_>) -> io::Result<()> {
frame::print_frame(self.0, location)
}
fn record_diff(&mut self, diff: &TextEdit) -> io::Result<()> {
diff::print_diff(self.0, diff)
}
fn record_backtrace(
&mut self,
title: &dyn fmt::Display,
backtrace: &Backtrace,
) -> io::Result<()> {
let mut backtrace = backtrace.clone();
backtrace.resolve();
if backtrace.is_empty() {
return Ok(());
}
self.record_log(LogCategory::Info, title)?;
backtrace::print_backtrace(self.0, &backtrace)
}
fn record_command(&mut self, command: &str) -> io::Result<()> {
self.0.write_markup(markup! {
<Emphasis>"$"</Emphasis>" "{command}"\n\n"
})
}
fn record_group(&mut self, title: &dyn fmt::Display, advice: &dyn Advices) -> io::Result<()> {
self.0.write_markup(markup! {
<Emphasis>{title}</Emphasis>"\n\n"
})?;
let mut slot = None;
let mut fmt = IndentWriter::wrap(self.0, &mut slot, true, " ");
let mut visitor = PrintAdvices(&mut fmt);
advice.record(&mut visitor)
}
}
/// Print the fatal and internal tags for the diagnostic as log advices.
fn print_tags_advices<V, D>(visitor: &mut V, diagnostic: &D) -> io::Result<()>
where
V: Visit,
D: Diagnostic + ?Sized,
{
if diagnostic.severity() == Severity::Fatal {
visitor.record_log(LogCategory::Warn, &"Rome exited as this error could not be handled and resulted in a fatal error. Please report it if necessary.")?;
}
if diagnostic.tags().contains(DiagnosticTags::INTERNAL) {
visitor.record_log(LogCategory::Warn, &"This diagnostic was derived from an internal Rome error. Potential bug, please report it if necessary.")?;
}
Ok(())
}
/// Advice visitor that counts how many advices are visited.
struct CountAdvices(usize);
impl CountAdvices {
fn is_empty(&self) -> bool {
self.0 == 0
}
}
impl Visit for CountAdvices {
fn record_log(&mut self, _: LogCategory, _: &dyn fmt::Display) -> io::Result<()> {
self.0 += 1;
Ok(())
}
fn record_list(&mut self, _: &[&dyn fmt::Display]) -> io::Result<()> {
self.0 += 1;
Ok(())
}
fn record_frame(&mut self, _: Location<'_>) -> io::Result<()> {
self.0 += 1;
Ok(())
}
fn record_diff(&mut self, _: &TextEdit) -> io::Result<()> {
self.0 += 1;
Ok(())
}
fn record_backtrace(&mut self, _: &dyn fmt::Display, _: &Backtrace) -> io::Result<()> {
self.0 += 1;
Ok(())
}
fn record_command(&mut self, _: &str) -> io::Result<()> {
self.0 += 1;
Ok(())
}
fn record_group(&mut self, _: &dyn fmt::Display, _: &dyn Advices) -> io::Result<()> {
self.0 += 1;
Ok(())
}
}
/// Implements [Advices] for verbose advices of a diagnostic.
struct PrintVerboseAdvices<'a, D: ?Sized>(&'a D);
impl<D: Diagnostic + ?Sized> Advices for PrintVerboseAdvices<'_, D> {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.0.verbose_advices(visitor)
}
}
/// Wrapper type over [fmt::Write] that injects `ident_text` at the start of
/// every line.
struct IndentWriter<'a, W: ?Sized> {
writer: &'a mut W,
pending_indent: bool,
ident_text: &'static str,
}
impl<'write> IndentWriter<'write, dyn fmt::Write + 'write> {
fn wrap<'slot, 'fmt: 'write + 'slot>(
fmt: &'fmt mut fmt::Formatter<'_>,
slot: &'slot mut Option<Self>,
pending_indent: bool,
ident_text: &'static str,
) -> fmt::Formatter<'slot> {
fmt.wrap_writer(|writer| {
slot.get_or_insert(Self {
writer,
pending_indent,
ident_text,
})
})
}
}
impl<W: fmt::Write + ?Sized> fmt::Write for IndentWriter<'_, W> {
fn write_str(
&mut self,
elements: &fmt::MarkupElements<'_>,
mut content: &str,
) -> io::Result<()> {
while !content.is_empty() {
if self.pending_indent {
self.writer.write_str(elements, self.ident_text)?;
self.pending_indent = false;
}
if let Some(index) = content.find('\n') {
let (start, end) = content.split_at(index + 1);
self.writer.write_str(elements, start)?;
self.pending_indent = true;
content = end;
} else {
return self.writer.write_str(elements, content);
}
}
Ok(())
}
fn write_fmt(
&mut self,
elements: &fmt::MarkupElements<'_>,
content: std::fmt::Arguments<'_>,
) -> io::Result<()> {
if let Some(content) = content.as_str() {
self.write_str(elements, content)
} else {
let content = content.to_string();
self.write_str(elements, &content)
}
}
}
#[cfg(test)]
mod tests {
use std::io;
use rome_console::{fmt, markup};
use rome_diagnostics::{DiagnosticTags, Severity};
use rome_diagnostics_categories::{category, Category};
use rome_text_edit::TextEdit;
use rome_text_size::{TextRange, TextSize};
use serde_json::{from_value, json};
use crate::{self as rome_diagnostics};
use crate::{
Advices, Diagnostic, Location, LogCategory, PrintDiagnostic, Resource, SourceCode, Visit,
};
#[derive(Debug)]
struct TestDiagnostic<A> {
path: Option<String>,
span: Option<TextRange>,
source_code: Option<String>,
advice: Option<A>,
verbose_advice: Option<A>,
source: Option<Box<dyn Diagnostic>>,
}
impl<A> TestDiagnostic<A> {
fn empty() -> Self {
Self {
path: None,
span: None,
source_code: None,
advice: None,
verbose_advice: None,
source: None,
}
}
fn with_location() -> Self {
Self {
path: Some(String::from("path")),
span: Some(TextRange::at(TextSize::from(0), TextSize::from(6))),
source_code: Some(String::from("source code")),
advice: None,
verbose_advice: None,
source: None,
}
}
}
impl<A: Advices + std::fmt::Debug> Diagnostic for TestDiagnostic<A> {
fn category(&self) -> Option<&'static Category> {
Some(category!("internalError/io"))
}
fn severity(&self) -> Severity {
Severity::Error
}
fn description(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(fmt, "diagnostic message")
}
fn message(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
write!(fmt, "diagnostic message")
}
fn advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
if let Some(advice) = &self.advice {
advice.record(visitor)?;
}
Ok(())
}
fn verbose_advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
if let Some(advice) = &self.verbose_advice {
advice.record(visitor)?;
}
Ok(())
}
fn location(&self) -> Location<'_> {
Location::builder()
.resource(&self.path)
.span(&self.span)
.source_code(&self.source_code)
.build()
}
fn tags(&self) -> DiagnosticTags {
DiagnosticTags::FIXABLE
}
fn source(&self) -> Option<&dyn Diagnostic> {
self.source.as_deref()
}
}
#[derive(Debug)]
struct LogAdvices;
impl Advices for LogAdvices {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
visitor.record_log(LogCategory::Error, &"error")?;
visitor.record_log(LogCategory::Warn, &"warn")?;
visitor.record_log(LogCategory::Info, &"info")?;
visitor.record_log(LogCategory::None, &"none")
}
}
#[derive(Debug)]
struct ListAdvice;
impl Advices for ListAdvice {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
visitor.record_list(&[&"item 1", &"item 2"])
}
}
#[derive(Debug)]
struct FrameAdvice;
impl Advices for FrameAdvice {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
visitor.record_frame(Location {
resource: Some(Resource::File("other_path")),
span: Some(TextRange::new(TextSize::from(8), TextSize::from(16))),
source_code: Some(SourceCode {
text: "context location context",
line_starts: None,
}),
})
}
}
#[derive(Debug)]
struct DiffAdvice;
impl Advices for DiffAdvice {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
let diff =
TextEdit::from_unicode_words("context before context", "context after context");
visitor.record_diff(&diff)
}
}
#[derive(Debug)]
struct BacktraceAdvice;
impl Advices for BacktraceAdvice {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
let backtrace = from_value(json!([
{
"ip": 0x0f0f0f0f,
"symbols": [
{
"name": "crate::module::function",
"filename": "crate/src/module.rs",
"lineno": 8,
"colno": 16
}
]
}
]));
visitor.record_backtrace(&"Backtrace Title", &backtrace.unwrap())
}
}
#[derive(Debug)]
struct CommandAdvice;
impl Advices for CommandAdvice {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
visitor.record_command("rome command --argument")
}
}
#[derive(Debug)]
struct GroupAdvice;
impl Advices for GroupAdvice {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
visitor.record_group(&"Group Title", &LogAdvices)
}
}
#[test]
fn test_header() {
let diag = TestDiagnostic::<LogAdvices>::with_location();
let diag = markup!({ PrintDiagnostic::verbose(&diag) }).to_owned();
let expected = markup!{
"path:1:1 internalError/io "<Inverse>" FIXABLE "</Inverse>" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
"\n"
<Emphasis><Error>" ✖"</Error></Emphasis>" "<Error>"diagnostic message"</Error>"\n"
" \n"
<Emphasis><Error>" >"</Error></Emphasis>" "<Emphasis>"1 │ "</Emphasis>"source code\n"
" "<Emphasis>" │ "</Emphasis><Emphasis><Error>"^^^^^^"</Error></Emphasis>"\n"
" \n"
}.to_owned();
assert_eq!(
diag, expected,
"\nactual:\n{diag:#?}\nexpected:\n{expected:#?}"
);
}
#[test]
fn test_log_advices() {
let diag = TestDiagnostic {
advice: Some(LogAdvices),
..TestDiagnostic::empty()
};
let diag = markup!({ PrintDiagnostic::verbose(&diag) }).to_owned();
let expected = markup!{
"internalError/io "<Inverse>" FIXABLE "</Inverse>" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
"\n"
<Emphasis><Error>" ✖"</Error></Emphasis>" "<Error>"diagnostic message"</Error>"\n"
" \n"
<Emphasis><Error>" ✖"</Error></Emphasis>" "<Error>"error"</Error>"\n"
" \n"
<Emphasis><Warn>" ⚠"</Warn></Emphasis>" "<Warn>"warn"</Warn>"\n"
" \n"
<Emphasis><Info>" ℹ"</Info></Emphasis>" "<Info>"info"</Info>"\n"
" \n"
" none\n"
" \n"
}.to_owned();
assert_eq!(
diag, expected,
"\nactual:\n{diag:#?}\nexpected:\n{expected:#?}"
);
}
#[test]
fn test_list_advice() {
let diag = TestDiagnostic {
advice: Some(ListAdvice),
..TestDiagnostic::empty()
};
let diag = markup!({ PrintDiagnostic::verbose(&diag) }).to_owned();
let expected = markup!{
"internalError/io "<Inverse>" FIXABLE "</Inverse>" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
"\n"
<Emphasis><Error>" ✖"</Error></Emphasis>" "<Error>"diagnostic message"</Error>"\n"
" \n"
" - item 1\n"
" - item 2\n"
" \n"
}.to_owned();
assert_eq!(
diag, expected,
"\nactual:\n{diag:#?}\nexpected:\n{expected:#?}"
);
}
#[test]
fn test_frame_advice() {
let diag = TestDiagnostic {
advice: Some(FrameAdvice),
..TestDiagnostic::empty()
};
let diag = markup!({ PrintDiagnostic::verbose(&diag) }).to_owned();
let expected = markup!{
"internalError/io "<Inverse>" FIXABLE "</Inverse>" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
"\n"
<Emphasis><Error>" ✖"</Error></Emphasis>" "<Error>"diagnostic message"</Error>"\n"
" \n"
<Emphasis><Error>" >"</Error></Emphasis>" "<Emphasis>"1 │ "</Emphasis>"context location context\n"
" "<Emphasis>" │ "</Emphasis>" "<Emphasis><Error>"^^^^^^^^"</Error></Emphasis>"\n"
" \n"
}.to_owned();
assert_eq!(
diag, expected,
"\nactual:\n{diag:#?}\nexpected:\n{expected:#?}"
);
}
#[test]
fn test_diff_advice() {
let diag = TestDiagnostic {
advice: Some(DiffAdvice),
..TestDiagnostic::empty()
};
let diag = markup!({ PrintDiagnostic::verbose(&diag) }).to_owned();
let expected = markup!{
"internalError/io "<Inverse>" FIXABLE "</Inverse>" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
"\n"
<Emphasis><Error>" ✖"</Error></Emphasis>" "<Error>"diagnostic message"</Error>"\n"
" \n"
<Error>" -"</Error>" "<Error>"context"</Error><Error><Dim>"·"</Dim></Error><Error><Emphasis>"before"</Emphasis></Error><Error><Dim>"·"</Dim></Error><Error>"context"</Error>"\n"
<Success>" +"</Success>" "<Success>"context"</Success><Success><Dim>"·"</Dim></Success><Success><Emphasis>"after"</Emphasis></Success><Success><Dim>"·"</Dim></Success><Success>"context"</Success>"\n"
" \n"
}.to_owned();
assert_eq!(
diag, expected,
"\nactual:\n{diag:#?}\nexpected:\n{expected:#?}"
);
}
#[test]
fn test_backtrace_advice() {
let diag = TestDiagnostic {
advice: Some(BacktraceAdvice),
..TestDiagnostic::empty()
};
let diag = markup!({ PrintDiagnostic::verbose(&diag) }).to_owned();
let expected = markup!{
"internalError/io "<Inverse>" FIXABLE "</Inverse>" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
"\n"
<Emphasis><Error>" ✖"</Error></Emphasis>" "<Error>"diagnostic message"</Error>"\n"
" \n"
<Emphasis><Info>" ℹ"</Info></Emphasis>" "<Info>"Backtrace Title"</Info>"\n"
" \n"
" 0: crate::module::function\n"
" at crate/src/module.rs:8:16\n"
}.to_owned();
assert_eq!(
diag, expected,
"\nactual:\n{diag:#?}\nexpected:\n{expected:#?}"
);
}
#[test]
fn test_command_advice() {
let diag = TestDiagnostic {
advice: Some(CommandAdvice),
..TestDiagnostic::empty()
};
let diag = markup!({ PrintDiagnostic::verbose(&diag) }).to_owned();
let expected = markup!{
"internalError/io "<Inverse>" FIXABLE "</Inverse>" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
"\n"
<Emphasis><Error>" ✖"</Error></Emphasis>" "<Error>"diagnostic message"</Error>"\n"
" \n"
<Emphasis>" $"</Emphasis>" rome command --argument\n"
" \n"
}.to_owned();
assert_eq!(
diag, expected,
"\nactual:\n{diag:#?}\nexpected:\n{expected:#?}"
);
}
#[test]
fn test_group_advice() {
let diag = TestDiagnostic {
advice: Some(GroupAdvice),
..TestDiagnostic::empty()
};
let diag = markup!({ PrintDiagnostic::verbose(&diag) }).to_owned();
let expected = markup!{
"internalError/io "<Inverse>" FIXABLE "</Inverse>" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
"\n"
<Emphasis><Error>" ✖"</Error></Emphasis>" "<Error>"diagnostic message"</Error>"\n"
" \n"
<Emphasis>" Group Title"</Emphasis>"\n"
" \n"
<Emphasis><Error>" ✖"</Error></Emphasis>" "<Error>"error"</Error>"\n"
" \n"
<Emphasis><Warn>" ⚠"</Warn></Emphasis>" "<Warn>"warn"</Warn>"\n"
" \n"
<Emphasis><Info>" ℹ"</Info></Emphasis>" "<Info>"info"</Info>"\n"
" \n"
" none\n"
" \n"
}.to_owned();
assert_eq!(
diag, expected,
"\nactual:\n{diag:#?}\nexpected:\n{expected:#?}"
);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/src/advice.rs | crates/rome_diagnostics/src/advice.rs | use crate::Applicability;
use crate::{
display::Backtrace,
location::{AsResource, AsSourceCode, AsSpan},
Location,
};
use rome_console::fmt::{self, Display};
use rome_console::markup;
use rome_text_edit::TextEdit;
use serde::{Deserialize, Serialize};
use std::io;
/// Trait implemented by types that support emitting advices into a diagnostic
pub trait Advices {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()>;
}
/// The `Visit` trait is used to collect advices from a diagnostic: a visitor
/// instance is provided to the [Diagnostic::advices](super::Diagnostic::advices)
/// and [Diagnostic::verbose_advices](super::Diagnostic::verbose_advices) methods,
/// and the diagnostic implementation is expected to call into the various `record_*`
/// methods to communicate advices to the user.
pub trait Visit {
/// Prints a single log entry with the provided category and markup.
fn record_log(&mut self, category: LogCategory, text: &dyn fmt::Display) -> io::Result<()> {
let _ = (category, text);
Ok(())
}
/// Prints an unordered list of items.
fn record_list(&mut self, list: &[&dyn fmt::Display]) -> io::Result<()> {
let _ = list;
Ok(())
}
/// Prints a code frame outlining the provided source location.
fn record_frame(&mut self, location: Location<'_>) -> io::Result<()> {
let _ = location;
Ok(())
}
/// Prints the diff between the `prev` and `next` strings.
fn record_diff(&mut self, diff: &TextEdit) -> io::Result<()> {
let _ = diff;
Ok(())
}
/// Prints a Rust backtrace.
fn record_backtrace(
&mut self,
title: &dyn fmt::Display,
backtrace: &Backtrace,
) -> io::Result<()> {
let _ = (title, backtrace);
Ok(())
}
/// Prints a command to the user.
fn record_command(&mut self, command: &str) -> io::Result<()> {
let _ = command;
Ok(())
}
/// Prints a group of advices under a common title.
fn record_group(&mut self, title: &dyn fmt::Display, advice: &dyn Advices) -> io::Result<()> {
let _ = (title, advice);
Ok(())
}
}
/// The category for a log advice, defines how the message should be presented
/// to the user.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum LogCategory {
/// The advice doesn't have any specific category, the message will be
/// printed as plain markup.
None,
/// Print the advices with the information style.
Info,
/// Print the advices with the warning style.
Warn,
/// Print the advices with the error style.
Error,
}
/// Utility type implementing [Advices] that emits a single log advice with
/// the provided category and text.
#[derive(Debug)]
pub struct LogAdvice<T> {
pub category: LogCategory,
pub text: T,
}
impl<T: Display> Advices for LogAdvice<T> {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
visitor.record_log(self.category, &self.text)
}
}
/// Utility type implementing [Advices] that emits a single code frame
/// advice with the provided path, span and source code.
#[derive(Debug)]
pub struct CodeFrameAdvice<Path, Span, SourceCode> {
pub path: Path,
pub span: Span,
pub source_code: SourceCode,
}
impl<Path, Span, SourceCode> Advices for CodeFrameAdvice<Path, Span, SourceCode>
where
Path: AsResource,
Span: AsSpan,
SourceCode: AsSourceCode,
{
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
let location = Location::builder()
.resource(&self.path)
.span(&self.span)
.source_code(&self.source_code)
.build();
visitor.record_frame(location)?;
Ok(())
}
}
/// Utility type implementing [Advices] that emits a diff advice with the
/// provided prev and next text.
#[derive(Debug)]
pub struct DiffAdvice<D> {
pub diff: D,
}
impl<D> Advices for DiffAdvice<D>
where
D: AsRef<TextEdit>,
{
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
visitor.record_diff(self.diff.as_ref())
}
}
/// Utility type implementing [Advices] that emits a command advice with
/// the provided text.
#[derive(Debug)]
pub struct CommandAdvice<T> {
pub command: T,
}
impl<T> Advices for CommandAdvice<T>
where
T: AsRef<str>,
{
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
visitor.record_command(self.command.as_ref())
}
}
#[derive(Debug)]
/// Utility type implementing [Advices] that emits a
/// code suggestion with the provided text
pub struct CodeSuggestionAdvice<M> {
pub applicability: Applicability,
pub msg: M,
pub suggestion: TextEdit,
}
impl<M> Advices for CodeSuggestionAdvice<M>
where
M: Display,
{
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
let applicability = match self.applicability {
Applicability::Always => "Safe fix",
Applicability::MaybeIncorrect => "Suggested fix",
};
visitor.record_log(
LogCategory::Info,
&markup! {
{applicability}": "{self.msg}
},
)?;
visitor.record_diff(&self.suggestion)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/src/location.rs | crates/rome_diagnostics/src/location.rs | use rome_text_size::{TextRange, TextSize};
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::ops::Range;
use std::{borrow::Borrow, ops::Deref};
/// Represents the location of a diagnostic in a resource.
#[derive(Debug, Clone, Copy)]
pub struct Location<'a> {
/// The resource this diagnostic is associated with.
pub resource: Option<Resource<&'a str>>,
/// An optional range of text within the resource associated with the
/// diagnostic.
pub span: Option<TextRange>,
/// The optional source code of the resource.
pub source_code: Option<BorrowedSourceCode<'a>>,
}
impl<'a> Location<'a> {
/// Creates a new instance of [LocationBuilder].
pub fn builder() -> LocationBuilder<'a> {
LocationBuilder {
resource: None,
span: None,
source_code: None,
}
}
}
/// The implementation of [PartialEq] for [Location] only compares the `path`
/// and `span` fields
impl PartialEq for Location<'_> {
fn eq(&self, other: &Self) -> bool {
self.resource == other.resource && self.span == other.span
}
}
impl Eq for Location<'_> {}
/// Represents the resource a diagnostic is associated with.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum Resource<P> {
/// The diagnostic is related to the content of the command line arguments.
Argv,
/// The diagnostic is related to the content of a memory buffer.
Memory,
/// The diagnostic is related to a file on the filesystem.
File(P),
}
impl<P> Resource<P> {
/// Returns a `FilePath<&P::Target>` if `self` points to a `Path`, or
/// `None` otherwise.
pub fn as_file(&self) -> Option<&<P as Deref>::Target>
where
P: Deref,
{
if let Resource::File(file) = self {
Some(file)
} else {
None
}
}
/// Converts a `Path<P>` to `Path<&P::Target>`.
pub fn as_deref(&self) -> Resource<&<P as Deref>::Target>
where
P: Deref,
{
match self {
Resource::Argv => Resource::Argv,
Resource::Memory => Resource::Memory,
Resource::File(file) => Resource::File(file),
}
}
}
impl Resource<&'_ str> {
/// Converts a `Path<&str>` to `Path<String>`.
pub fn to_owned(self) -> Resource<String> {
match self {
Resource::Argv => Resource::Argv,
Resource::Memory => Resource::Memory,
Resource::File(file) => Resource::File(file.to_owned()),
}
}
}
type OwnedSourceCode = SourceCode<String, LineIndexBuf>;
pub(crate) type BorrowedSourceCode<'a> = SourceCode<&'a str, &'a LineIndex>;
/// Represents the source code of a file.
#[derive(Debug, Clone, Copy)]
pub struct SourceCode<T, L> {
/// The text content of the file.
pub text: T,
/// An optional "line index" for the file, a list of byte offsets for the
/// start of each line in the file.
pub line_starts: Option<L>,
}
impl<T, L> SourceCode<T, L> {
/// Converts a `SourceCode<T, L>` to `SourceCode<&T::Target, &L::Target>`.
pub(crate) fn as_deref(&self) -> SourceCode<&<T as Deref>::Target, &<L as Deref>::Target>
where
T: Deref,
L: Deref,
{
SourceCode {
text: &self.text,
line_starts: self.line_starts.as_deref(),
}
}
}
impl BorrowedSourceCode<'_> {
/// Converts a `SourceCode<&str, &LineIndex>` to `SourceCode<String, LineIndexBuf>`.
pub(crate) fn to_owned(self) -> OwnedSourceCode {
SourceCode {
text: self.text.to_owned(),
line_starts: self.line_starts.map(ToOwned::to_owned),
}
}
}
#[derive(Debug)]
pub struct LineIndex([TextSize]);
impl LineIndex {
pub fn new(slice: &'_ [TextSize]) -> &'_ Self {
// SAFETY: Transmuting `&[TextSize]` to `&LineIndex` is safe since
// `LineIndex` is a `repr(transparent)` struct containing a `[TextSize]`
// and thus has the same memory layout
unsafe { std::mem::transmute(slice) }
}
}
impl Deref for LineIndex {
type Target = [TextSize];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ToOwned for LineIndex {
type Owned = LineIndexBuf;
fn to_owned(&self) -> Self::Owned {
LineIndexBuf(self.0.to_owned())
}
}
#[derive(Debug, Clone)]
pub struct LineIndexBuf(Vec<TextSize>);
impl LineIndexBuf {
pub fn from_source_text(source: &str) -> Self {
Self(
std::iter::once(0)
.chain(source.match_indices(&['\n', '\r']).filter_map(|(i, _)| {
let bytes = source.as_bytes();
match bytes[i] {
// Filter out the `\r` in `\r\n` to avoid counting the line break twice
b'\r' if i + 1 < bytes.len() && bytes[i + 1] == b'\n' => None,
_ => Some(i + 1),
}
}))
.map(|i| TextSize::try_from(i).expect("integer overflow"))
.collect(),
)
}
}
impl Deref for LineIndexBuf {
type Target = LineIndex;
fn deref(&self) -> &Self::Target {
LineIndex::new(self.0.as_slice())
}
}
impl Borrow<LineIndex> for LineIndexBuf {
fn borrow(&self) -> &LineIndex {
self
}
}
/// Builder type for the [Location] struct
pub struct LocationBuilder<'a> {
resource: Option<Resource<&'a str>>,
span: Option<TextRange>,
source_code: Option<BorrowedSourceCode<'a>>,
}
impl<'a> LocationBuilder<'a> {
pub fn resource<P: AsResource>(mut self, resource: &'a P) -> Self {
self.resource = resource.as_resource();
self
}
pub fn span<S: AsSpan>(mut self, span: &'a S) -> Self {
self.span = span.as_span();
self
}
pub fn source_code<S: AsSourceCode>(mut self, source_code: &'a S) -> Self {
self.source_code = source_code.as_source_code();
self
}
pub fn build(self) -> Location<'a> {
Location {
resource: self.resource,
span: self.span,
source_code: self.source_code,
}
}
}
/// Utility trait for types that can be converted to a [Resource]
pub trait AsResource {
fn as_resource(&self) -> Option<Resource<&'_ str>>;
}
impl<T: AsResource> AsResource for Option<T> {
fn as_resource(&self) -> Option<Resource<&'_ str>> {
self.as_ref().and_then(T::as_resource)
}
}
impl<T: AsResource + ?Sized> AsResource for &'_ T {
fn as_resource(&self) -> Option<Resource<&'_ str>> {
T::as_resource(*self)
}
}
impl<T: Deref<Target = str>> AsResource for Resource<T> {
fn as_resource(&self) -> Option<Resource<&'_ str>> {
Some(self.as_deref())
}
}
impl AsResource for String {
fn as_resource(&self) -> Option<Resource<&'_ str>> {
Some(Resource::File(self))
}
}
impl AsResource for str {
fn as_resource(&self) -> Option<Resource<&'_ str>> {
Some(Resource::File(self))
}
}
/// Utility trait for types that can be converted into `Option<TextRange>`
pub trait AsSpan {
fn as_span(&self) -> Option<TextRange>;
}
impl<T: AsSpan> AsSpan for Option<T> {
fn as_span(&self) -> Option<TextRange> {
self.as_ref().and_then(T::as_span)
}
}
impl<T: AsSpan + ?Sized> AsSpan for &'_ T {
fn as_span(&self) -> Option<TextRange> {
T::as_span(*self)
}
}
impl AsSpan for TextRange {
fn as_span(&self) -> Option<TextRange> {
Some(*self)
}
}
impl<T: Copy> AsSpan for Range<T>
where
TextSize: TryFrom<T>,
<TextSize as TryFrom<T>>::Error: Debug,
{
fn as_span(&self) -> Option<TextRange> {
Some(TextRange::new(
TextSize::try_from(self.start).expect("integer overflow"),
TextSize::try_from(self.end).expect("integer overflow"),
))
}
}
/// Utility trait for types that can be converted into [SourceCode]
pub trait AsSourceCode {
fn as_source_code(&self) -> Option<BorrowedSourceCode<'_>>;
}
impl<T: AsSourceCode> AsSourceCode for Option<T> {
fn as_source_code(&self) -> Option<BorrowedSourceCode<'_>> {
self.as_ref().and_then(T::as_source_code)
}
}
impl<T: AsSourceCode + ?Sized> AsSourceCode for &'_ T {
fn as_source_code(&self) -> Option<BorrowedSourceCode<'_>> {
T::as_source_code(*self)
}
}
impl AsSourceCode for BorrowedSourceCode<'_> {
fn as_source_code(&self) -> Option<BorrowedSourceCode<'_>> {
Some(*self)
}
}
impl AsSourceCode for OwnedSourceCode {
fn as_source_code(&self) -> Option<BorrowedSourceCode<'_>> {
Some(SourceCode {
text: self.text.as_str(),
line_starts: self.line_starts.as_deref(),
})
}
}
impl AsSourceCode for str {
fn as_source_code(&self) -> Option<BorrowedSourceCode<'_>> {
Some(SourceCode {
text: self,
line_starts: None,
})
}
}
impl AsSourceCode for String {
fn as_source_code(&self) -> Option<BorrowedSourceCode<'_>> {
Some(SourceCode {
text: self,
line_starts: None,
})
}
}
#[cfg(test)]
mod tests {
use rome_text_size::TextSize;
use super::LineIndexBuf;
#[test]
fn line_starts_with_carriage_return_line_feed() {
let input = "a\r\nb\r\nc";
let LineIndexBuf(starts) = LineIndexBuf::from_source_text(input);
assert_eq!(
vec![
TextSize::from(0u32),
TextSize::from(3u32),
TextSize::from(6u32)
],
starts
);
}
#[test]
fn line_starts_with_carriage_return() {
let input = "a\rb\rc";
let LineIndexBuf(starts) = LineIndexBuf::from_source_text(input);
assert_eq!(
vec![
TextSize::from(0u32),
TextSize::from(2u32),
TextSize::from(4u32)
],
starts
);
}
#[test]
fn line_starts_with_line_feed() {
let input = "a\nb\nc";
let LineIndexBuf(starts) = LineIndexBuf::from_source_text(input);
assert_eq!(
vec![
TextSize::from(0u32),
TextSize::from(2u32),
TextSize::from(4u32)
],
starts
);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/src/context.rs | crates/rome_diagnostics/src/context.rs | use rome_console::fmt;
use crate::context::internal::{SeverityDiagnostic, TagsDiagnostic};
use crate::{
diagnostic::internal::AsDiagnostic,
location::{AsResource, AsSourceCode, AsSpan},
Category, DiagnosticTags, Error, Resource, Severity, SourceCode,
};
/// This trait is implemented for all types implementing [Diagnostic](super::Diagnostic)
/// and the [Error] struct, and exposes various combinator methods to enrich
/// existing diagnostics with additional information.
pub trait DiagnosticExt: internal::Sealed + Sized {
/// Returns a new diagnostic with the provided `message` as a message and
/// description, and `self` as a source diagnostic. This is useful to
/// create chains of diagnostics, where high level errors wrap lower level
/// causes.
fn context<M>(self, message: M) -> Error
where
Self: 'static,
M: fmt::Display + 'static,
Error: From<internal::ContextDiagnostic<M, Self>>;
/// Returns a new diagnostic using the provided `category` if `self`
/// doesn't already have one.
fn with_category(self, category: &'static Category) -> Error
where
Error: From<internal::CategoryDiagnostic<Self>>;
/// Returns a new diagnostic using the provided `path` if `self`
/// doesn't already have one.
fn with_file_path(self, path: impl AsResource) -> Error
where
Error: From<internal::FilePathDiagnostic<Self>>;
/// Returns a new diagnostic using the provided `span` instead of the one in `self`.
fn with_file_span(self, span: impl AsSpan) -> Error
where
Error: From<internal::FileSpanDiagnostic<Self>>;
/// Returns a new diagnostic using the provided `source_code` if `self`
/// doesn't already have one.
fn with_file_source_code(self, source_code: impl AsSourceCode) -> Error
where
Error: From<internal::FileSourceCodeDiagnostic<Self>>;
/// Returns a new diagnostic with additional `tags`
fn with_tags(self, tags: DiagnosticTags) -> Error
where
Error: From<internal::TagsDiagnostic<Self>>;
/// Returns a new diagnostic with additional `severity`
fn with_severity(self, severity: Severity) -> Error
where
Error: From<internal::SeverityDiagnostic<Self>>;
}
impl<E: AsDiagnostic> internal::Sealed for E {}
impl<E: AsDiagnostic> DiagnosticExt for E {
fn context<M>(self, message: M) -> Error
where
E: 'static,
M: fmt::Display + 'static,
Error: From<internal::ContextDiagnostic<M, E>>,
{
Error::from(internal::ContextDiagnostic {
message,
source: self,
})
}
fn with_category(self, category: &'static Category) -> Error
where
Error: From<internal::CategoryDiagnostic<Self>>,
{
Error::from(internal::CategoryDiagnostic {
category,
source: self,
})
}
fn with_file_path(self, path: impl AsResource) -> Error
where
Error: From<internal::FilePathDiagnostic<E>>,
{
Error::from(internal::FilePathDiagnostic {
path: path.as_resource().map(Resource::to_owned),
source: self,
})
}
fn with_file_span(self, span: impl AsSpan) -> Error
where
Error: From<internal::FileSpanDiagnostic<E>>,
{
Error::from(internal::FileSpanDiagnostic {
span: span.as_span(),
source: self,
})
}
fn with_file_source_code(self, source_code: impl AsSourceCode) -> Error
where
Error: From<internal::FileSourceCodeDiagnostic<Self>>,
{
Error::from(internal::FileSourceCodeDiagnostic {
source_code: source_code.as_source_code().map(SourceCode::to_owned),
source: self,
})
}
fn with_tags(self, tags: DiagnosticTags) -> Error
where
Error: From<internal::TagsDiagnostic<Self>>,
{
Error::from(internal::TagsDiagnostic { tags, source: self })
}
fn with_severity(self, severity: Severity) -> Error
where
Error: From<internal::SeverityDiagnostic<Self>>,
{
Error::from(internal::SeverityDiagnostic {
severity,
source: self,
})
}
}
pub trait Context<T, E>: internal::Sealed {
/// If `self` is an error, returns a new diagnostic with the provided
/// `message` as a message and description, and `self` as a source
/// diagnostic. This is useful to create chains of diagnostics, where high
/// level errors wrap lower level causes.
fn context<M>(self, message: M) -> Result<T, Error>
where
E: 'static,
M: fmt::Display + 'static,
Error: From<internal::ContextDiagnostic<M, E>>;
/// If `self` is an error, returns a new diagnostic using the provided
/// `category` if `self` doesn't already have one.
fn with_category(self, category: &'static Category) -> Result<T, Error>
where
Error: From<internal::CategoryDiagnostic<E>>;
/// If `self` is an error, returns a new diagnostic using the provided
/// `path` if `self` doesn't already have one.
fn with_file_path(self, path: impl AsResource) -> Result<T, Error>
where
Error: From<internal::FilePathDiagnostic<E>>;
/// If `self` is an error, returns a new diagnostic using the provided
/// `severity` if `self` doesn't already have one.
fn with_severity(self, severity: Severity) -> Result<T, Error>
where
Error: From<internal::SeverityDiagnostic<E>>;
/// If `self` is an error, returns a new diagnostic using the provided
/// `tags` if `self` doesn't already have one.
fn with_tags(self, tags: DiagnosticTags) -> Result<T, Error>
where
Error: From<internal::TagsDiagnostic<E>>;
/// If `self` is an error, returns a new diagnostic using the provided
/// `span` instead of the one returned by `self`.
///
/// This is useful in multi-language documents, where a given diagnostic
/// may be originally emitted with a span relative to a specific substring
/// of a larger document, and later needs to have its position remapped to
/// be relative to the entire file instead.
fn with_file_span(self, span: impl AsSpan) -> Result<T, Error>
where
Error: From<internal::FileSpanDiagnostic<E>>;
}
impl<T, E: AsDiagnostic> internal::Sealed for Result<T, E> {}
impl<T, E: AsDiagnostic> Context<T, E> for Result<T, E> {
fn context<M>(self, message: M) -> Result<T, Error>
where
E: 'static,
M: fmt::Display + 'static,
Error: From<internal::ContextDiagnostic<M, E>>,
{
match self {
Ok(value) => Ok(value),
Err(source) => Err(source.context(message)),
}
}
fn with_category(self, category: &'static Category) -> Result<T, Error>
where
Error: From<internal::CategoryDiagnostic<E>>,
{
match self {
Ok(value) => Ok(value),
Err(source) => Err(source.with_category(category)),
}
}
fn with_file_path(self, path: impl AsResource) -> Result<T, Error>
where
Error: From<internal::FilePathDiagnostic<E>>,
{
match self {
Ok(value) => Ok(value),
Err(source) => Err(source.with_file_path(path)),
}
}
fn with_severity(self, severity: Severity) -> Result<T, Error>
where
Error: From<SeverityDiagnostic<E>>,
{
match self {
Ok(value) => Ok(value),
Err(source) => Err(source.with_severity(severity)),
}
}
fn with_tags(self, tags: DiagnosticTags) -> Result<T, Error>
where
Error: From<TagsDiagnostic<E>>,
{
match self {
Ok(value) => Ok(value),
Err(source) => Err(source.with_tags(tags)),
}
}
fn with_file_span(self, span: impl AsSpan) -> Result<T, Error>
where
Error: From<internal::FileSpanDiagnostic<E>>,
{
match self {
Ok(value) => Ok(value),
Err(source) => Err(source.with_file_span(span)),
}
}
}
mod internal {
//! These types need to be declared as public as they're referred to in the
//! `where` clause of other public items, but as they're not part of the
//! public API they are declared in a private module so they're not
//! accessible outside of the crate
use std::{fmt::Debug, io};
use rome_console::{fmt, markup};
use rome_rowan::TextRange;
use rome_text_edit::TextEdit;
use crate::{
diagnostic::internal::AsDiagnostic, Advices, Backtrace, Category, Diagnostic,
DiagnosticTags, LineIndex, LineIndexBuf, Location, LogCategory, Resource, Severity,
SourceCode, Visit,
};
/// This trait is inherited by `DiagnosticExt` and `Context`, since it's
/// not visible outside of `rome_diagnostics` this prevents these extension
/// traits from being implemented on other types outside of this module
///
/// Making these traits "sealed" is mainly intended as a stability
/// guarantee, if these traits were simply public any change to their
/// signature or generic implementations would be a breaking change for
/// downstream implementations, so preventing these traits from ever being
/// implemented in downstream crates ensures this doesn't happen.
pub trait Sealed {}
/// Diagnostic type returned by [super::DiagnosticExt::context], uses
/// `message` as its message and description, and `source` as its source
/// diagnostic.
pub struct ContextDiagnostic<M, E> {
pub(super) message: M,
pub(super) source: E,
}
impl<M: fmt::Display + 'static, E: AsDiagnostic> Diagnostic for ContextDiagnostic<M, E> {
fn category(&self) -> Option<&'static Category> {
self.source.as_diagnostic().category()
}
fn severity(&self) -> Severity {
self.source.as_diagnostic().severity()
}
fn description(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut writer = DisplayMarkup(fmt);
let mut fmt = fmt::Formatter::new(&mut writer);
fmt.write_markup(markup!({ self.message }))
.map_err(|_| std::fmt::Error)
}
fn message(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
fmt::Display::fmt(&self.message, fmt)
}
fn advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.source.as_diagnostic().advices(visitor)
}
fn verbose_advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.source.as_diagnostic().verbose_advices(visitor)
}
fn location(&self) -> Location<'_> {
self.source.as_diagnostic().location()
}
fn tags(&self) -> DiagnosticTags {
self.source.as_diagnostic().tags()
}
fn source(&self) -> Option<&dyn Diagnostic> {
Some(self.source.as_dyn())
}
}
impl<M: fmt::Display, E: Debug> Debug for ContextDiagnostic<M, E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Diagnostic")
.field("message", &DebugMarkup(&self.message))
.field("source", &self.source)
.finish()
}
}
/// Helper wrapper implementing [Debug] for types implementing [fmt::Display],
/// prints a debug representation of the markup generated by printing `T`.
struct DebugMarkup<T>(T);
impl<T: fmt::Display> Debug for DebugMarkup<T> {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let buffer = markup!({ self.0 }).to_owned();
Debug::fmt(&buffer, fmt)
}
}
/// Helper wrapper implementing [fmt::Write] for [std::fmt::Formatter].
struct DisplayMarkup<'a, 'b>(&'a mut std::fmt::Formatter<'b>);
impl fmt::Write for DisplayMarkup<'_, '_> {
fn write_str(&mut self, _: &fmt::MarkupElements<'_>, content: &str) -> io::Result<()> {
self.0
.write_str(content)
.map_err(|error| io::Error::new(io::ErrorKind::Other, error))
}
fn write_fmt(
&mut self,
_: &fmt::MarkupElements<'_>,
content: std::fmt::Arguments<'_>,
) -> io::Result<()> {
self.0
.write_fmt(content)
.map_err(|error| io::Error::new(io::ErrorKind::Other, error))
}
}
/// Diagnostic type returned by [super::DiagnosticExt::with_category],
/// uses `category` as its category if `source` doesn't return one.
pub struct CategoryDiagnostic<E> {
pub(super) category: &'static Category,
pub(super) source: E,
}
impl<E: Debug> Debug for CategoryDiagnostic<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Diagnostic")
.field("category", &self.category)
.field("source", &self.source)
.finish()
}
}
impl<E: AsDiagnostic> Diagnostic for CategoryDiagnostic<E> {
fn category(&self) -> Option<&'static Category> {
Some(
self.source
.as_diagnostic()
.category()
.unwrap_or(self.category),
)
}
fn severity(&self) -> Severity {
self.source.as_diagnostic().severity()
}
fn description(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.source.as_diagnostic().description(fmt)
}
fn message(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
self.source.as_diagnostic().message(fmt)
}
fn advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.source.as_diagnostic().advices(visitor)
}
fn verbose_advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.source.as_diagnostic().verbose_advices(visitor)
}
fn location(&self) -> Location<'_> {
self.source.as_diagnostic().location()
}
fn tags(&self) -> DiagnosticTags {
self.source.as_diagnostic().tags()
}
}
/// Diagnostic type returned by [super::DiagnosticExt::with_file_path],
/// uses `path` as its location path if `source` doesn't return one.
pub struct FilePathDiagnostic<E> {
pub(super) path: Option<Resource<String>>,
pub(super) source: E,
}
impl<E: Debug> Debug for FilePathDiagnostic<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Diagnostic")
.field("path", &self.path)
.field("source", &self.source)
.finish()
}
}
impl<E: AsDiagnostic> Diagnostic for FilePathDiagnostic<E> {
fn category(&self) -> Option<&'static Category> {
self.source.as_diagnostic().category()
}
fn severity(&self) -> Severity {
self.source.as_diagnostic().severity()
}
fn description(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.source.as_diagnostic().description(fmt)
}
fn message(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
self.source.as_diagnostic().message(fmt)
}
fn advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.source.as_diagnostic().advices(visitor)
}
fn verbose_advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.source.as_diagnostic().verbose_advices(visitor)
}
fn location(&self) -> Location<'_> {
let loc = self.source.as_diagnostic().location();
Location {
resource: match loc.resource {
Some(Resource::Argv) => Some(Resource::Argv),
Some(Resource::Memory) => Some(Resource::Memory),
Some(Resource::File(file)) => {
if let Some(Resource::File(path)) = &self.path {
Some(Resource::File(path.as_ref()))
} else {
Some(Resource::File(file))
}
}
None => self.path.as_ref().map(Resource::as_deref),
},
span: loc.span,
source_code: loc.source_code,
}
}
fn tags(&self) -> DiagnosticTags {
self.source.as_diagnostic().tags()
}
}
/// Diagnostic type returned by [super::DiagnosticExt::with_file_span],
/// uses `span` as its location span instead of the one returned by `source`.
pub struct FileSpanDiagnostic<E> {
pub(super) span: Option<TextRange>,
pub(super) source: E,
}
impl<E: Debug> Debug for FileSpanDiagnostic<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Diagnostic")
.field("span", &self.span)
.field("source", &self.source)
.finish()
}
}
impl<E: AsDiagnostic> Diagnostic for FileSpanDiagnostic<E> {
fn category(&self) -> Option<&'static Category> {
self.source.as_diagnostic().category()
}
fn severity(&self) -> Severity {
self.source.as_diagnostic().severity()
}
fn description(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.source.as_diagnostic().description(fmt)
}
fn message(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
self.source.as_diagnostic().message(fmt)
}
fn advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.source.as_diagnostic().advices(visitor)
}
fn verbose_advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.source.as_diagnostic().verbose_advices(visitor)
}
fn location(&self) -> Location<'_> {
let loc = self.source.as_diagnostic().location();
Location {
resource: loc.resource,
span: self.span.or(loc.span),
source_code: loc.source_code,
}
}
fn tags(&self) -> DiagnosticTags {
self.source.as_diagnostic().tags()
}
}
/// Diagnostic type returned by [super::DiagnosticExt::with_file_source_code],
/// uses `source_code` as its location source code if `source` doesn't
/// return one.
pub struct FileSourceCodeDiagnostic<E> {
pub(super) source_code: Option<SourceCode<String, LineIndexBuf>>,
pub(super) source: E,
}
impl<E: Debug> Debug for FileSourceCodeDiagnostic<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Diagnostic")
.field("source_code", &self.source_code)
.field("source", &self.source)
.finish()
}
}
impl<E: AsDiagnostic> Diagnostic for FileSourceCodeDiagnostic<E> {
fn category(&self) -> Option<&'static Category> {
self.source.as_diagnostic().category()
}
fn severity(&self) -> Severity {
self.source.as_diagnostic().severity()
}
fn description(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.source.as_diagnostic().description(fmt)
}
fn message(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
self.source.as_diagnostic().message(fmt)
}
fn advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
if let Some(source_code) = &self.source_code {
let mut visitor = FileSourceCodeVisitor {
visitor,
source_code: source_code.as_deref(),
};
self.source.as_diagnostic().advices(&mut visitor)
} else {
self.source.as_diagnostic().advices(visitor)
}
}
fn verbose_advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
if let Some(source_code) = &self.source_code {
let mut visitor = FileSourceCodeVisitor {
visitor,
source_code: source_code.as_deref(),
};
self.source.as_diagnostic().verbose_advices(&mut visitor)
} else {
self.source.as_diagnostic().verbose_advices(visitor)
}
}
fn location(&self) -> Location<'_> {
let location = self.source.as_diagnostic().location();
Location {
source_code: location
.source_code
.or_else(|| Some(self.source_code.as_ref()?.as_deref())),
..location
}
}
fn tags(&self) -> DiagnosticTags {
self.source.as_diagnostic().tags()
}
}
/// Helper wrapper for a [Visitor], automatically inject `source_code` into
/// the location of code frame advices if they don't have one already.
struct FileSourceCodeVisitor<'a> {
visitor: &'a mut dyn Visit,
source_code: SourceCode<&'a str, &'a LineIndex>,
}
impl Visit for FileSourceCodeVisitor<'_> {
fn record_log(&mut self, category: LogCategory, text: &dyn fmt::Display) -> io::Result<()> {
self.visitor.record_log(category, text)
}
fn record_list(&mut self, list: &[&dyn fmt::Display]) -> io::Result<()> {
self.visitor.record_list(list)
}
fn record_frame(&mut self, location: Location<'_>) -> io::Result<()> {
self.visitor.record_frame(Location {
source_code: Some(location.source_code.unwrap_or(self.source_code)),
..location
})
}
fn record_diff(&mut self, diff: &TextEdit) -> io::Result<()> {
self.visitor.record_diff(diff)
}
fn record_backtrace(
&mut self,
title: &dyn fmt::Display,
backtrace: &Backtrace,
) -> io::Result<()> {
self.visitor.record_backtrace(title, backtrace)
}
fn record_command(&mut self, command: &str) -> io::Result<()> {
self.visitor.record_command(command)
}
fn record_group(
&mut self,
title: &dyn fmt::Display,
advice: &dyn Advices,
) -> io::Result<()> {
self.visitor.record_group(title, advice)
}
}
/// Diagnostic type returned by [super::DiagnosticExt::with_tags],
/// merges `tags` with the tags of its source
pub struct TagsDiagnostic<E> {
pub(super) tags: DiagnosticTags,
pub(super) source: E,
}
impl<E: Debug> Debug for TagsDiagnostic<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Diagnostic")
.field("tags", &self.tags)
.field("source", &self.source)
.finish()
}
}
impl<E: AsDiagnostic> Diagnostic for TagsDiagnostic<E> {
fn category(&self) -> Option<&'static Category> {
self.source.as_diagnostic().category()
}
fn severity(&self) -> Severity {
self.source.as_diagnostic().severity()
}
fn description(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.source.as_diagnostic().description(fmt)
}
fn message(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
self.source.as_diagnostic().message(fmt)
}
fn advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.source.as_diagnostic().advices(visitor)
}
fn verbose_advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.source.as_diagnostic().verbose_advices(visitor)
}
fn location(&self) -> Location<'_> {
self.source.as_diagnostic().location()
}
fn tags(&self) -> DiagnosticTags {
self.source.as_diagnostic().tags() | self.tags
}
}
/// Diagnostic type returned by [super::DiagnosticExt::with_severity],
/// replaces `severity` with the severity of its source
pub struct SeverityDiagnostic<E> {
pub(super) severity: Severity,
pub(super) source: E,
}
impl<E: Debug> Debug for SeverityDiagnostic<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Diagnostic")
.field("severity", &self.severity)
.field("source", &self.source)
.finish()
}
}
impl<E: AsDiagnostic> Diagnostic for SeverityDiagnostic<E> {
fn category(&self) -> Option<&'static Category> {
self.source.as_diagnostic().category()
}
fn severity(&self) -> Severity {
self.severity
}
fn description(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.source.as_diagnostic().description(fmt)
}
fn message(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
self.source.as_diagnostic().message(fmt)
}
fn advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.source.as_diagnostic().advices(visitor)
}
fn verbose_advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
self.source.as_diagnostic().verbose_advices(visitor)
}
fn location(&self) -> Location<'_> {
self.source.as_diagnostic().location()
}
fn tags(&self) -> DiagnosticTags {
self.source.as_diagnostic().tags()
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/src/suggestion.rs | crates/rome_diagnostics/src/suggestion.rs | use ::serde::{Deserialize, Serialize};
use rome_console::MarkupBuf;
use rome_rowan::TextRange;
use rome_text_edit::TextEdit;
/// Indicates how a tool should manage this suggestion.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum Applicability {
/// The suggestion is definitely what the user intended.
/// This suggestion should be automatically applied.
Always,
/// The suggestion may be what the user intended, but it is uncertain.
/// The suggestion should result in valid JavaScript/TypeScript code if it is applied.
MaybeIncorrect,
}
/// A Suggestion that is provided by Rome's linter, and
/// can be reported to the user, and can be automatically
/// applied if it has the right [`Applicability`].
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CodeSuggestion {
pub span: TextRange,
pub applicability: Applicability,
pub msg: MarkupBuf,
pub suggestion: TextEdit,
pub labels: Vec<TextRange>,
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/src/diagnostic.rs | crates/rome_diagnostics/src/diagnostic.rs | use std::{convert::Infallible, fmt::Debug, io};
use bitflags::bitflags;
use serde::{Deserialize, Serialize};
use rome_console::fmt;
use crate::{Category, Location, Visit};
/// The `Diagnostic` trait defines the metadata that can be exposed by error
/// types in order to print details diagnostics in the console of the editor
///
/// ## Implementation
///
/// Most types should not have to implement this trait manually, and should
/// instead rely on the `Diagnostic` derive macro also provided by this crate:
///
/// ```
/// # use rome_diagnostics::Diagnostic;
/// #[derive(Debug, Diagnostic)]
/// #[diagnostic(category = "lint/style/noShoutyConstants", tags(FIXABLE))]
/// struct ExampleDiagnostic {
/// #[message]
/// #[description]
/// message: String,
/// }
/// ```
pub trait Diagnostic: Debug {
/// The category of a diagnostic uniquely identifying this
/// diagnostic type, such as `lint/correctness/noArguments`, `args/invalid`
/// or `format/disabled`.
fn category(&self) -> Option<&'static Category> {
None
}
/// The severity defines whether this diagnostic reports an error, a
/// warning, an information or a hint to the user.
fn severity(&self) -> Severity {
Severity::Error
}
/// The description is a text-only explanation of the issue this diagnostic
/// is reporting, intended for display contexts that do not support rich
/// markup such as in-editor popovers
///
/// The description should generally be as exhaustive as possible, since
/// the clients that do not support rendering markup will not render the
/// advices for the diagnostic either.
fn description(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let _ = fmt;
Ok(())
}
/// An explanation of the issue this diagnostic is reporting
///
/// In general it's better to keep this message as short as possible, and
/// instead rely on advices to better convey contextual explanations to the
/// user.
fn message(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
let _ = fmt;
Ok(())
}
/// Advices are the main building blocks used compose rich errors. They are
/// implemented using a visitor pattern, where consumers of a diagnostic
/// can visit the object and collect the advices that make it up for the
/// purpose of display or introspection.
fn advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
let _ = visitor;
Ok(())
}
/// Diagnostics can defines additional advices to be printed if the user
/// requires more detail about the diagnostic.
fn verbose_advices(&self, visitor: &mut dyn Visit) -> io::Result<()> {
let _ = visitor;
Ok(())
}
/// A diagnostic can be tied to a specific "location": this can be a file,
/// memory buffer, command line argument, etc. It may also be tied to a
/// specific text range within the content of that location. Finally, it
/// may also provide the source string for that location (this is required
/// in order to display a code frame advice for the diagnostic).
fn location(&self) -> Location<'_> {
Location::builder().build()
}
/// Tags convey additional boolean metadata about the nature of a diagnostic:
/// - If the diagnostic can be automatically fixed
/// - If the diagnostic resulted from and internal error
/// - If the diagnostic is being emitted as part of a crash / fatal error
/// - If the diagnostic is a warning about a piece of unused or unnecessary code
/// - If the diagnostic is a warning about a piece of deprecated or obsolete code.
fn tags(&self) -> DiagnosticTags {
DiagnosticTags::empty()
}
/// Similarly to the `source` method of the [std::error::Error] trait, this
/// returns another diagnostic that's the logical "cause" for this issue.
/// For instance, a "request failed" diagnostic may have been cause by a
/// "deserialization error". This allows low-level error to be wrapped in
/// higher level concepts, while retaining enough information to display
/// and fix the underlying issue.
fn source(&self) -> Option<&dyn Diagnostic> {
None
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
/// The severity to associate to a diagnostic.
pub enum Severity {
/// Reports a hint.
Hint,
/// Reports an information.
Information,
/// Reports a warning.
Warning,
/// Reports an error.
Error,
/// Reports a crash.
Fatal,
}
/// Internal enum used to automatically generate bit offsets for [DiagnosticTags]
/// and help with the implementation of `serde` and `schemars` for tags.
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub(super) enum DiagnosticTag {
Fixable,
Internal,
UnnecessaryCode,
DeprecatedCode,
}
bitflags! {
#[derive(Default, Debug, Copy, Clone, Eq, PartialEq)]
pub struct DiagnosticTags: u8 {
/// This diagnostic has a fix suggestion.
const FIXABLE = 1 << DiagnosticTag::Fixable as u8;
/// This diagnostic results from an internal error.
const INTERNAL = 1 << DiagnosticTag::Internal as u8;
/// This diagnostic tags unused or unnecessary code, this may change
/// how the diagnostic is render in editors.
const UNNECESSARY_CODE = 1 << DiagnosticTag::UnnecessaryCode as u8;
/// This diagnostic tags deprecated or obsolete code, this may change
/// how the diagnostic is render in editors.
const DEPRECATED_CODE = 1 << DiagnosticTag::DeprecatedCode as u8;
}
}
// Implement the `Diagnostic` on the `Infallible` error type from the standard
// library as a utility for implementing signatures that require a diagnostic
// type when the operation can never fail
impl Diagnostic for Infallible {}
pub(crate) mod internal {
//! The `AsDiagnostic` trait needs to be declared as public as its referred
//! to in the `where` clause of other public items, but as it's not part of
//! the public API it's declared in a private module so it's not accessible
//! outside of the crate
use std::fmt::Debug;
use crate::Diagnostic;
/// Since [Error](crate::Error) must implement `From<T: Diagnostic>` to
/// be used with the `?` operator, it cannot implement the [Diagnostic]
/// trait (as that would conflict with the implementation of `From<T> for T`
/// in the standard library). The [AsDiagnostic] exists as an internal
/// implementation detail to bridge this gap and allow various types and
/// functions in `rome_diagnostics` to be generic over all diagnostics +
/// `Error`.
pub trait AsDiagnostic: Debug {
type Diagnostic: Diagnostic + ?Sized;
fn as_diagnostic(&self) -> &Self::Diagnostic;
fn as_dyn(&self) -> &dyn Diagnostic;
}
impl<D: Diagnostic> AsDiagnostic for D {
type Diagnostic = D;
fn as_diagnostic(&self) -> &Self::Diagnostic {
self
}
fn as_dyn(&self) -> &dyn Diagnostic {
self
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/src/display/diff.rs | crates/rome_diagnostics/src/display/diff.rs | use std::{
collections::{BTreeMap, BTreeSet},
io, slice,
};
use rome_console::{fmt, markup, MarkupElement};
use rome_text_edit::{ChangeTag, CompressedOp, TextEdit};
use super::frame::{
calculate_print_width, print_invisibles, text_width, IntoIter, OneIndexed,
PrintInvisiblesOptions, CODE_FRAME_CONTEXT_LINES,
};
const MAX_PATCH_LINES: usize = 150;
pub(super) fn print_diff(fmt: &mut fmt::Formatter<'_>, diff: &TextEdit) -> io::Result<()> {
// Before printing, we need to preprocess the list of DiffOps it's made of to classify them by line
let mut modified_lines = BTreeSet::new();
let mut inserted_lines = BTreeMap::new();
let mut before_line_to_after = BTreeMap::new();
let mut before_line = OneIndexed::MIN;
let mut after_line = OneIndexed::MIN;
process_diff_ops(
diff,
PushToLineState {
modified_lines: &mut modified_lines,
inserted_lines: &mut inserted_lines,
before_line_to_after: &mut before_line_to_after,
},
&mut after_line,
&mut before_line,
);
let before_line_count = before_line;
let after_line_count = after_line;
// If only a single line was modified, print a "short diff"
let modified_line = if before_line_count == after_line_count {
let mut iter = modified_lines.iter().filter_map(|key| {
let line = inserted_lines.get(key)?;
// A line has been modified if its diff list is empty (the line was
// either fully inserted or fully removed) or if its diff list has
// any delete or insert operation
let has_edits = line.diffs.is_empty()
|| line.diffs.iter().any(|(tag, text)| {
matches!(tag, ChangeTag::Delete | ChangeTag::Insert) && !text.is_empty()
});
if has_edits {
Some((key, line))
} else {
None
}
});
iter.next().and_then(|(key, line)| {
if iter.next().is_some() {
return None;
}
// Disallow fully empty lines from being displayed in short mode
if !line.diffs.is_empty() {
Some((key, line))
} else {
None
}
})
} else {
None
};
if let Some((key, entry)) = modified_line {
return print_short_diff(fmt, key, entry);
}
// Otherwise if multiple lines were modified we need to perform more preprocessing,
// to merge identical line numbers and calculate how many context lines need to be rendered
let mut diffs_by_line = Vec::new();
let mut shown_line_indexes = BTreeSet::new();
process_diff_lines(
&mut inserted_lines,
&mut before_line_to_after,
&mut diffs_by_line,
&mut shown_line_indexes,
before_line_count,
after_line_count,
);
// Finally when have a flat list of lines we can now print
print_full_diff(
fmt,
&diffs_by_line,
&shown_line_indexes,
before_line_count,
after_line_count,
)
}
/// This function scans the list of DiffOps that make up the `diff` and derives
/// the following data structures:
/// - `modified_lines` is the set of [LineKey] that contain at least one insert
/// or delete operation
/// - `inserted_lines` maps a [LineKey] to the list of diff operations that
/// happen on the corresponding line
/// - `before_line_to_after` maps line numbers in the old revision of the text
/// to line numbers in the new revision
/// - `after_line` counts the number of lines in the new revision of the document
/// - `before_line` counts the number of lines in the old revision of the document
fn process_diff_ops<'diff>(
diff: &'diff TextEdit,
mut state: PushToLineState<'_, 'diff>,
after_line: &mut OneIndexed,
before_line: &mut OneIndexed,
) {
for (op_index, op) in diff.iter().enumerate() {
let op = match op {
CompressedOp::DiffOp(op) => op,
CompressedOp::EqualLines { line_count } => {
let is_first_op = op_index == 0;
for line_index in 0..=line_count.get() {
// Don't increment the first line if we are the first tuple marking the beginning of the file
if !(is_first_op && line_index == 0) {
*after_line = after_line.saturating_add(1);
*before_line = before_line.saturating_add(1);
}
state.before_line_to_after.insert(*before_line, *after_line);
push_to_line(&mut state, *before_line, *after_line, ChangeTag::Equal, "");
}
continue;
}
};
let tag = op.tag();
let text = op.text(diff);
// Get all the lines
let mut parts = text.split('\n');
// Deconstruct each text chunk
let current_line = parts.next();
// The first chunk belongs to the current line
if let Some(current_line) = current_line {
push_to_line(&mut state, *before_line, *after_line, tag, current_line);
}
// Create unique lines for each other chunk
for new_line in parts {
match tag {
ChangeTag::Equal => {
*after_line = after_line.saturating_add(1);
*before_line = before_line.saturating_add(1);
}
ChangeTag::Delete => {
*before_line = before_line.saturating_add(1);
}
ChangeTag::Insert => {
*after_line = after_line.saturating_add(1);
}
}
state.before_line_to_after.insert(*before_line, *after_line);
push_to_line(&mut state, *before_line, *after_line, tag, new_line);
}
}
}
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
struct LineKey {
before_line: Option<OneIndexed>,
after_line: Option<OneIndexed>,
}
impl LineKey {
const fn before(before_line: OneIndexed) -> Self {
Self {
before_line: Some(before_line),
after_line: None,
}
}
const fn after(after_line: OneIndexed) -> Self {
Self {
before_line: None,
after_line: Some(after_line),
}
}
}
#[derive(Debug, Clone)]
struct GroupDiffsLine<'a> {
before_line: Option<OneIndexed>,
after_line: Option<OneIndexed>,
diffs: Vec<(ChangeTag, &'a str)>,
}
impl<'a> GroupDiffsLine<'a> {
fn insert(
inserted_lines: &mut BTreeMap<LineKey, Self>,
key: LineKey,
tag: ChangeTag,
text: &'a str,
) {
inserted_lines
.entry(key)
.and_modify(|line| {
if !text.is_empty() {
line.diffs.push((tag, text));
}
})
.or_insert_with_key(|key| GroupDiffsLine {
before_line: key.before_line,
after_line: key.after_line,
diffs: if text.is_empty() {
Vec::new()
} else {
vec![(tag, text)]
},
});
}
}
struct PushToLineState<'a, 'b> {
modified_lines: &'a mut BTreeSet<LineKey>,
inserted_lines: &'a mut BTreeMap<LineKey, GroupDiffsLine<'b>>,
before_line_to_after: &'a mut BTreeMap<OneIndexed, OneIndexed>,
}
fn push_to_line<'b>(
state: &mut PushToLineState<'_, 'b>,
before_line: OneIndexed,
after_line: OneIndexed,
tag: ChangeTag,
text: &'b str,
) {
let PushToLineState {
modified_lines,
inserted_lines,
before_line_to_after,
} = state;
match tag {
ChangeTag::Insert => {
GroupDiffsLine::insert(inserted_lines, LineKey::after(after_line), tag, text);
modified_lines.insert(LineKey::after(after_line));
}
ChangeTag::Delete => {
GroupDiffsLine::insert(inserted_lines, LineKey::before(before_line), tag, text);
modified_lines.insert(LineKey::before(before_line));
}
ChangeTag::Equal => {
if before_line == OneIndexed::MIN && after_line == OneIndexed::MIN {
before_line_to_after.insert(before_line, after_line);
}
GroupDiffsLine::insert(inserted_lines, LineKey::after(after_line), tag, text);
GroupDiffsLine::insert(inserted_lines, LineKey::before(before_line), tag, text);
}
}
}
fn process_diff_lines<'lines, 'diff>(
inserted_lines: &'lines mut BTreeMap<LineKey, GroupDiffsLine<'diff>>,
before_line_to_after: &mut BTreeMap<OneIndexed, OneIndexed>,
diffs_by_line: &mut Vec<&'lines GroupDiffsLine<'diff>>,
shown_line_indexes: &mut BTreeSet<usize>,
before_line_count: OneIndexed,
after_line_count: OneIndexed,
) {
// Merge identical lines
for before_line in IntoIter::new(OneIndexed::MIN..=before_line_count) {
let after_line = match before_line_to_after.get(&before_line) {
Some(after_line) => *after_line,
None => continue,
};
let inserted_before_line = inserted_lines.get(&LineKey::before(before_line));
let inserted_after_line = inserted_lines.get(&LineKey::after(after_line));
if let (Some(inserted_before_line), Some(inserted_after_line)) =
(inserted_before_line, inserted_after_line)
{
if inserted_before_line.diffs == inserted_after_line.diffs {
let line = inserted_lines
.remove(&LineKey::before(before_line))
.unwrap();
inserted_lines.remove(&LineKey::after(after_line)).unwrap();
inserted_lines.insert(
LineKey {
before_line: Some(before_line),
after_line: Some(after_line),
},
GroupDiffsLine {
before_line: Some(before_line),
after_line: Some(after_line),
diffs: line.diffs,
},
);
}
}
}
let mut diffs_by_line_with_before_and_shared = Vec::new();
// Print before lines, including those that are shared
for before_line in IntoIter::new(OneIndexed::MIN..=before_line_count) {
let line = inserted_lines.get(&LineKey::before(before_line));
if let Some(line) = line {
diffs_by_line_with_before_and_shared.push(line);
}
// If we have a shared line then add it
if let Some(after_line) = before_line_to_after.get(&before_line) {
let line = inserted_lines.get(&LineKey {
before_line: Some(before_line),
after_line: Some(*after_line),
});
if let Some(line) = line {
diffs_by_line_with_before_and_shared.push(line);
}
}
}
// Calculate the parts of the diff we should show
let mut last_printed_after = 0;
for line in diffs_by_line_with_before_and_shared {
if let Some(after_line) = line.after_line {
catch_up_after(
inserted_lines,
diffs_by_line,
shown_line_indexes,
last_printed_after,
after_line,
);
last_printed_after = after_line.get();
}
push_displayed_line(diffs_by_line, shown_line_indexes, line);
}
catch_up_after(
inserted_lines,
diffs_by_line,
shown_line_indexes,
last_printed_after,
after_line_count,
);
}
fn push_displayed_line<'input, 'group>(
diffs_by_line: &mut Vec<&'group GroupDiffsLine<'input>>,
shown_line_indexes: &mut BTreeSet<usize>,
line: &'group GroupDiffsLine<'input>,
) {
let i = diffs_by_line.len();
diffs_by_line.push(line);
if line.before_line.is_none() || line.after_line.is_none() {
let first = i.saturating_sub(CODE_FRAME_CONTEXT_LINES.get());
let last = i + CODE_FRAME_CONTEXT_LINES.get();
shown_line_indexes.extend(first..=last);
}
}
fn catch_up_after<'input, 'lines>(
inserted_lines: &'lines BTreeMap<LineKey, GroupDiffsLine<'input>>,
diffs_by_line: &mut Vec<&'lines GroupDiffsLine<'input>>,
shown_line_indexes: &mut BTreeSet<usize>,
last_printed_after: usize,
after_line: OneIndexed,
) {
let iter = IntoIter::new(OneIndexed::from_zero_indexed(last_printed_after)..=after_line);
for i in iter {
let key = LineKey::after(i);
if let Some(line) = inserted_lines.get(&key) {
push_displayed_line(diffs_by_line, shown_line_indexes, line);
}
}
}
fn print_short_diff(
fmt: &mut fmt::Formatter<'_>,
key: &LineKey,
entry: &GroupDiffsLine<'_>,
) -> io::Result<()> {
let index = match (key.before_line, key.after_line) {
(None, Some(index)) | (Some(index), None) => index,
(None, None) | (Some(_), Some(_)) => unreachable!(
"the key of a modified line should have exactly one index in one of the two revisions"
),
};
fmt.write_markup(markup! {
<Emphasis>
{format_args!(" {} \u{2502} ", index.get())}
</Emphasis>
})?;
let mut at_line_start = true;
let last_index = entry.diffs.len().saturating_sub(1);
for (i, (tag, text)) in entry.diffs.iter().enumerate() {
let is_changed = *tag != ChangeTag::Equal;
let options = PrintInvisiblesOptions {
ignore_leading_tabs: false,
ignore_lone_spaces: false,
ignore_trailing_carriage_return: is_changed,
at_line_start,
at_line_end: i == last_index,
};
let element = match tag {
ChangeTag::Equal => None,
ChangeTag::Delete => Some(MarkupElement::Error),
ChangeTag::Insert => Some(MarkupElement::Success),
};
let has_non_whitespace = if let Some(element) = element {
let mut slot = None;
let mut fmt = ElementWrapper::wrap(fmt, &mut slot, element);
print_invisibles(&mut fmt, text, options)?
} else {
print_invisibles(fmt, text, options)?
};
if has_non_whitespace {
at_line_start = false;
}
}
fmt.write_str("\n")?;
let no_length = calculate_print_width(index);
fmt.write_markup(markup! {
<Emphasis>
{format_args!(" {: >1$} \u{2502} ", "", no_length.get())}
</Emphasis>
})?;
for (tag, text) in &entry.diffs {
let marker = match tag {
ChangeTag::Equal => markup! { " " },
ChangeTag::Delete => markup! { <Error>"-"</Error> },
ChangeTag::Insert => markup! { <Success>"+"</Success> },
};
for _ in 0..text_width(text) {
fmt.write_markup(marker)?;
}
}
fmt.write_str("\n")
}
fn print_full_diff(
fmt: &mut fmt::Formatter<'_>,
diffs_by_line: &[&'_ GroupDiffsLine<'_>],
shown_line_indexes: &BTreeSet<usize>,
before_line_count: OneIndexed,
after_line_count: OneIndexed,
) -> io::Result<()> {
// Calculate width of line no column
let before_no_length = calculate_print_width(before_line_count);
let after_no_length = calculate_print_width(after_line_count);
let line_no_length = before_no_length.get() + 1 + after_no_length.get();
// Skip displaying the gutter if the file only has a single line
let single_line = before_line_count == OneIndexed::MIN && after_line_count == OneIndexed::MIN;
let mut displayed_lines = 0;
let mut truncated = false;
let mut last_displayed_line = None;
// Print the actual frame
for (i, line) in diffs_by_line.iter().enumerate() {
if !shown_line_indexes.contains(&i) {
continue;
}
displayed_lines += 1;
if displayed_lines > MAX_PATCH_LINES {
truncated = true;
continue;
}
let mut line_type = ChangeTag::Equal;
let mut marker = markup! { " " };
if line.before_line.is_none() {
marker = markup! { <Success>"+"</Success> };
line_type = ChangeTag::Insert;
}
if line.after_line.is_none() {
marker = markup! { <Error>"-"</Error> };
line_type = ChangeTag::Delete;
}
if let Some(last_displayed_line) = last_displayed_line {
if last_displayed_line + 1 != i {
fmt.write_markup(markup! {
<Emphasis>" "{"\u{b7}".repeat(line_no_length)}" \u{2502} \n"</Emphasis>
})?;
}
}
last_displayed_line = Some(i);
if single_line {
let line = FormatDiffLine {
is_equal: line_type == ChangeTag::Equal,
ops: &line.diffs,
};
match line_type {
ChangeTag::Equal => fmt.write_markup(markup! {
" "{line}"\n"
})?,
ChangeTag::Delete => fmt.write_markup(markup! {
{marker}" "<Error>{line}</Error>"\n"
})?,
ChangeTag::Insert => fmt.write_markup(markup! {
{marker}" "<Success>{line}</Success>"\n"
})?,
}
} else {
fmt.write_str(" ")?;
if let Some(before_line) = line.before_line {
fmt.write_markup(markup! {
<Emphasis>
{format_args!("{: >1$}", before_line.get(), before_no_length.get())}
</Emphasis>
})?;
} else {
for _ in 0..before_no_length.get() {
fmt.write_str(" ")?;
}
}
fmt.write_str(" ")?;
if let Some(after_line) = line.after_line {
fmt.write_markup(markup! {
<Emphasis>
{format_args!("{: >1$}", after_line.get(), after_no_length.get())}
</Emphasis>
})?;
} else {
for _ in 0..after_no_length.get() {
fmt.write_str(" ")?;
}
}
fmt.write_markup(markup! {
<Emphasis>" \u{2502} "</Emphasis>{marker}' '
})?;
let line = FormatDiffLine {
is_equal: line_type == ChangeTag::Equal,
ops: &line.diffs,
};
match line_type {
ChangeTag::Equal => fmt.write_markup(markup! {
{line}"\n"
})?,
ChangeTag::Delete => fmt.write_markup(markup! {
<Error>{line}</Error>"\n"
})?,
ChangeTag::Insert => fmt.write_markup(markup! {
<Success>{line}</Success>"\n"
})?,
}
}
}
if truncated {
fmt.write_markup(markup! {
<Dim>{displayed_lines.saturating_sub(MAX_PATCH_LINES)}" more lines truncated\n"</Dim>
})?;
}
fmt.write_str("\n")
}
struct FormatDiffLine<'a> {
is_equal: bool,
ops: &'a [(ChangeTag, &'a str)],
}
impl fmt::Display for FormatDiffLine<'_> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> io::Result<()> {
let mut at_line_start = true;
let last_index = self.ops.len().saturating_sub(1);
for (i, (tag, text)) in self.ops.iter().enumerate() {
let is_changed = *tag != ChangeTag::Equal;
let options = PrintInvisiblesOptions {
ignore_leading_tabs: self.is_equal,
ignore_lone_spaces: self.is_equal,
ignore_trailing_carriage_return: is_changed,
at_line_start,
at_line_end: i == last_index,
};
let has_non_whitespace = if is_changed {
let mut slot = None;
let mut fmt = ElementWrapper::wrap(fmt, &mut slot, MarkupElement::Emphasis);
print_invisibles(&mut fmt, text, options)?
} else {
print_invisibles(fmt, text, options)?
};
if has_non_whitespace {
at_line_start = false;
}
}
Ok(())
}
}
struct ElementWrapper<'a, W: ?Sized>(&'a mut W, MarkupElement<'static>);
impl<'write> ElementWrapper<'write, dyn fmt::Write + 'write> {
fn wrap<'slot, 'fmt: 'write + 'slot>(
fmt: &'fmt mut fmt::Formatter<'_>,
slot: &'slot mut Option<Self>,
element: MarkupElement<'static>,
) -> fmt::Formatter<'slot> {
fmt.wrap_writer(|writer| slot.get_or_insert(Self(writer, element)))
}
}
impl<W: fmt::Write + ?Sized> fmt::Write for ElementWrapper<'_, W> {
fn write_str(&mut self, elements: &fmt::MarkupElements<'_>, content: &str) -> io::Result<()> {
let elements = fmt::MarkupElements::Node(elements, slice::from_ref(&self.1));
self.0.write_str(&elements, content)
}
fn write_fmt(
&mut self,
elements: &fmt::MarkupElements<'_>,
content: std::fmt::Arguments<'_>,
) -> io::Result<()> {
let elements = fmt::MarkupElements::Node(elements, slice::from_ref(&self.1));
self.0.write_fmt(&elements, content)
}
}
#[cfg(test)]
mod tests {
use super::print_diff;
use rome_console::{fmt, markup, MarkupBuf};
use rome_text_edit::TextEdit;
use termcolor::Buffer;
fn assert_eq_markup(actual: &MarkupBuf, expected: &MarkupBuf) {
if actual != expected {
let mut buffer = Buffer::ansi();
let mut writer = fmt::Termcolor(&mut buffer);
let mut output = fmt::Formatter::new(&mut writer);
output
.write_markup(markup! {
"assertion failed: (actual == expected)\n"
"actual:\n"
{actual}"\n"
{format_args!("{actual:#?}")}"\n"
"expected:\n"
{expected}"\n"
{format_args!("{expected:#?}")}"\n"
})
.unwrap();
let buffer = buffer.into_inner();
let buffer = String::from_utf8(buffer).unwrap();
panic!("{buffer}");
}
}
#[test]
fn test_inline() {
let diff = TextEdit::from_unicode_words("before", "after");
let mut output = MarkupBuf::default();
print_diff(&mut fmt::Formatter::new(&mut output), &diff).unwrap();
let expected = markup! {
<Error>"-"</Error>" "<Error><Emphasis>"before"</Emphasis></Error>"\n"
<Success>"+"</Success>" "<Success><Emphasis>"after"</Emphasis></Success>"\n"
"\n"
}
.to_owned();
assert_eq_markup(&output, &expected);
}
#[test]
fn test_single_line() {
let diff = TextEdit::from_unicode_words("start before end\n", "start after end \n");
let mut output = MarkupBuf::default();
print_diff(&mut fmt::Formatter::new(&mut output), &diff).unwrap();
let expected = markup! {
" "<Emphasis>"1"</Emphasis>" "<Emphasis>" │ "</Emphasis><Error>"-"</Error>" "<Error>"start"</Error><Error><Dim>"·"</Dim></Error><Error><Emphasis>"before"</Emphasis></Error><Error><Dim>"·"</Dim></Error><Error>"end"</Error>"\n"
" "<Emphasis>"1 │ "</Emphasis><Success>"+"</Success>" "<Success>"start"</Success><Success><Dim>"·"</Dim></Success><Success><Emphasis>"after"</Emphasis></Success><Success><Dim>"·"</Dim></Success><Success>"end"</Success><Success><Dim><Emphasis>"·"</Emphasis></Dim></Success>"\n"
" "<Emphasis>"2"</Emphasis>" "<Emphasis>"2 │ "</Emphasis>" \n"
"\n"
}
.to_owned();
assert_eq_markup(&output, &expected);
}
#[test]
fn test_ellipsis() {
const SOURCE_LEFT: &str = "Lorem
ipsum
dolor
sit
amet,
function
name(
args
) {}
consectetur
adipiscing
elit,
sed
do
eiusmod
incididunt
function
name(
args
) {}";
const SOURCE_RIGHT: &str = "Lorem
ipsum
dolor
sit
amet,
function name(args) {
}
consectetur
adipiscing
elit,
sed
do
eiusmod
incididunt
function name(args) {
}";
let diff = TextEdit::from_unicode_words(SOURCE_LEFT, SOURCE_RIGHT);
let mut output = MarkupBuf::default();
print_diff(&mut fmt::Formatter::new(&mut output), &diff).unwrap();
let expected = markup! {
" "<Emphasis>" 4"</Emphasis>" "<Emphasis>" 4 │ "</Emphasis>" sit\n"
" "<Emphasis>" 5"</Emphasis>" "<Emphasis>" 5 │ "</Emphasis>" amet,\n"
" "<Emphasis>" 6"</Emphasis>" "<Emphasis>" │ "</Emphasis><Error>"-"</Error>" "<Error>"function"</Error>"\n"
" "<Emphasis>" 7"</Emphasis>" "<Emphasis>" │ "</Emphasis><Error>"-"</Error>" "<Error>"name("</Error>"\n"
" "<Emphasis>" 8"</Emphasis>" "<Emphasis>" │ "</Emphasis><Error>"-"</Error>" "<Error><Dim><Emphasis>"····"</Emphasis></Dim></Error><Error>"args"</Error>"\n"
" "<Emphasis>" 9"</Emphasis>" "<Emphasis>" │ "</Emphasis><Error>"-"</Error>" "<Error>")"</Error><Error><Dim>"·"</Dim></Error><Error>"{}"</Error>"\n"
" "<Emphasis>" 6 │ "</Emphasis><Success>"+"</Success>" "<Success>"function"</Success><Success><Dim><Emphasis>"·"</Emphasis></Dim></Success><Success>"name(args)"</Success><Success><Dim>"·"</Dim></Success><Success>"{"</Success>"\n"
" "<Emphasis>" 7 │ "</Emphasis><Success>"+"</Success>" "<Success>"}"</Success>"\n"
" "<Emphasis>"10"</Emphasis>" "<Emphasis>" 8 │ "</Emphasis>" consectetur\n"
" "<Emphasis>"11"</Emphasis>" "<Emphasis>" 9 │ "</Emphasis>" adipiscing\n"
<Emphasis>" ····· │ \n"
</Emphasis>" "<Emphasis>"16"</Emphasis>" "<Emphasis>"14 │ "</Emphasis>" \n"
" "<Emphasis>"17"</Emphasis>" "<Emphasis>"15 │ "</Emphasis>" incididunt\n"
" "<Emphasis>"18"</Emphasis>" "<Emphasis>" │ "</Emphasis><Error>"-"</Error>" "<Error>"function"</Error>"\n"
" "<Emphasis>"19"</Emphasis>" "<Emphasis>" │ "</Emphasis><Error>"-"</Error>" "<Error>"name("</Error>"\n"
" "<Emphasis>"20"</Emphasis>" "<Emphasis>" │ "</Emphasis><Error>"-"</Error>" "<Error><Dim><Emphasis>"····"</Emphasis></Dim></Error><Error>"args"</Error>"\n"
" "<Emphasis>"21"</Emphasis>" "<Emphasis>" │ "</Emphasis><Error>"-"</Error>" "<Error>")"</Error><Error><Dim>"·"</Dim></Error><Error>"{}"</Error>"\n"
" "<Emphasis>"16 │ "</Emphasis><Success>"+"</Success>" "<Success>"function"</Success><Success><Dim><Emphasis>"·"</Emphasis></Dim></Success><Success>"name(args)"</Success><Success><Dim>"·"</Dim></Success><Success>"{"</Success>"\n"
" "<Emphasis>"17 │ "</Emphasis><Success>"+"</Success>" "<Success>"}"</Success>"\n"
"\n"
}.to_owned();
assert_eq_markup(&output, &expected);
}
#[test]
fn remove_single_line() {
const SOURCE_LEFT: &str = "declare module \"test\" {
interface A {
prop: string;
}
}
";
const SOURCE_RIGHT: &str = "declare module \"test\" {
interface A {
prop: string;
}
}
";
let diff = TextEdit::from_unicode_words(SOURCE_LEFT, SOURCE_RIGHT);
let mut output = MarkupBuf::default();
print_diff(&mut fmt::Formatter::new(&mut output), &diff).unwrap();
let expected = markup! {
" "<Emphasis>"1"</Emphasis>" "<Emphasis>"1 │ "</Emphasis>" declare module \"test\" {\n"
" "<Emphasis>"2"</Emphasis>" "<Emphasis>"2 │ "</Emphasis>" \tinterface A {\n"
" "<Emphasis>"3"</Emphasis>" "<Emphasis>" │ "</Emphasis><Error>"-"</Error>" \n"
" "<Emphasis>"4"</Emphasis>" "<Emphasis>"3 │ "</Emphasis>" \t\tprop: string;\n"
" "<Emphasis>"5"</Emphasis>" "<Emphasis>"4 │ "</Emphasis>" \t}\n"
"\n"
}
.to_owned();
assert_eq_markup(&output, &expected);
}
#[test]
fn remove_many_lines() {
const SOURCE_LEFT: &str = "declare module \"test\" {
interface A {
prop: string;
}
}
";
const SOURCE_RIGHT: &str = "declare module \"test\" {
interface A {
prop: string;
}
}
";
let diff = TextEdit::from_unicode_words(SOURCE_LEFT, SOURCE_RIGHT);
let mut output = MarkupBuf::default();
print_diff(&mut fmt::Formatter::new(&mut output), &diff).unwrap();
let expected = markup! {
" "<Emphasis>"1"</Emphasis>" "<Emphasis>"1 │ "</Emphasis>" declare module \"test\" {\n"
" "<Emphasis>"2"</Emphasis>" "<Emphasis>"2 │ "</Emphasis>" \tinterface A {\n"
" "<Emphasis>"3"</Emphasis>" "<Emphasis>" │ "</Emphasis><Error>"-"</Error>" \n"
" "<Emphasis>"4"</Emphasis>" "<Emphasis>" │ "</Emphasis><Error>"-"</Error>" \n"
" "<Emphasis>"5"</Emphasis>" "<Emphasis>" │ "</Emphasis><Error>"-"</Error>" \n"
" "<Emphasis>"6"</Emphasis>" "<Emphasis>"3 │ "</Emphasis>" \t\tprop: string;\n"
" "<Emphasis>"7"</Emphasis>" "<Emphasis>"4 │ "</Emphasis>" \t}\n"
"\n"
}
.to_owned();
assert_eq_markup(&output, &expected);
}
#[test]
fn insert_single_line() {
const SOURCE_LEFT: &str = "declare module \"test\" {
interface A {
prop: string;
}
}
";
const SOURCE_RIGHT: &str = "declare module \"test\" {
interface A {
prop: string;
}
}
";
let diff = TextEdit::from_unicode_words(SOURCE_LEFT, SOURCE_RIGHT);
let mut output = MarkupBuf::default();
print_diff(&mut fmt::Formatter::new(&mut output), &diff).unwrap();
let expected = markup! {
" "<Emphasis>"1"</Emphasis>" "<Emphasis>"1 │ "</Emphasis>" declare module \"test\" {\n"
" "<Emphasis>"2"</Emphasis>" "<Emphasis>"2 │ "</Emphasis>" \tinterface A {\n"
" "<Emphasis>"3 │ "</Emphasis><Success>"+"</Success>" \n"
" "<Emphasis>"3"</Emphasis>" "<Emphasis>"4 │ "</Emphasis>" \t\tprop: string;\n"
" "<Emphasis>"4"</Emphasis>" "<Emphasis>"5 │ "</Emphasis>" \t}\n"
"\n"
}
.to_owned();
assert_eq_markup(&output, &expected);
}
#[test]
fn insert_many_lines() {
const SOURCE_LEFT: &str = "declare module \"test\" {
interface A {
prop: string;
}
}
";
const SOURCE_RIGHT: &str = "declare module \"test\" {
interface A {
prop: string;
}
}
";
let diff = TextEdit::from_unicode_words(SOURCE_LEFT, SOURCE_RIGHT);
let mut output = MarkupBuf::default();
print_diff(&mut fmt::Formatter::new(&mut output), &diff).unwrap();
let expected = markup! {
" "<Emphasis>"1"</Emphasis>" "<Emphasis>"1 │ "</Emphasis>" declare module \"test\" {\n"
" "<Emphasis>"2"</Emphasis>" "<Emphasis>"2 │ "</Emphasis>" \tinterface A {\n"
" "<Emphasis>"3 │ "</Emphasis><Success>"+"</Success>" \n"
" "<Emphasis>"4 │ "</Emphasis><Success>"+"</Success>" \n"
" "<Emphasis>"5 │ "</Emphasis><Success>"+"</Success>" \n"
" "<Emphasis>"3"</Emphasis>" "<Emphasis>"6 │ "</Emphasis>" \t\tprop: string;\n"
" "<Emphasis>"4"</Emphasis>" "<Emphasis>"7 │ "</Emphasis>" \t}\n"
"\n"
}
.to_owned();
assert_eq_markup(&output, &expected);
}
#[test]
fn remove_empty_line() {
const SOURCE_LEFT: &str = "for (; ;) {
}
console.log(\"test\");
";
const SOURCE_RIGHT: &str = "for (;;) {}
console.log(\"test\");
";
let diff = TextEdit::from_unicode_words(SOURCE_LEFT, SOURCE_RIGHT);
let mut output = MarkupBuf::default();
print_diff(&mut fmt::Formatter::new(&mut output), &diff).unwrap();
let expected = markup! {
" "<Emphasis>"1"</Emphasis>" "<Emphasis>" │ "</Emphasis><Error>"-"</Error>" "<Error>"for"</Error><Error><Dim>"·"</Dim></Error><Error>"(;"</Error><Error><Dim><Emphasis>"·"</Emphasis></Dim></Error><Error>";)"</Error><Error><Dim>"·"</Dim></Error><Error>"{"</Error>"\n"
" "<Emphasis>"2"</Emphasis>" "<Emphasis>" │ "</Emphasis><Error>"-"</Error>" "<Error>"}"</Error>"\n"
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/src/display/frame.rs | crates/rome_diagnostics/src/display/frame.rs | use std::{
borrow::Cow,
io,
iter::FusedIterator,
num::NonZeroUsize,
ops::{Bound, RangeBounds},
};
use rome_console::{fmt, markup};
use rome_text_size::{TextLen, TextRange, TextSize};
use unicode_width::UnicodeWidthChar;
use crate::{
location::{BorrowedSourceCode, LineIndex},
LineIndexBuf, Location,
};
/// A const Option::unwrap without nightly features:
/// https://github.com/rust-lang/rust/issues/67441
const fn unwrap<T: Copy>(option: Option<T>) -> T {
match option {
Some(value) => value,
None => panic!("unwrapping None"),
}
}
const ONE: NonZeroUsize = unwrap(NonZeroUsize::new(1));
pub(super) const CODE_FRAME_CONTEXT_LINES: NonZeroUsize = unwrap(NonZeroUsize::new(2));
const MAX_CODE_FRAME_LINES: usize = 8;
const HALF_MAX_CODE_FRAME_LINES: usize = MAX_CODE_FRAME_LINES / 2;
/// Prints a code frame advice
pub(super) fn print_frame(fmt: &mut fmt::Formatter<'_>, location: Location<'_>) -> io::Result<()> {
let source_span = location
.source_code
.and_then(|source_code| Some((source_code, location.span?)));
let (source_code, span) = match source_span {
Some(source_span) => source_span,
None => return Ok(()),
};
let source_file = SourceFile::new(source_code);
let start_index = span.start();
let start_location = match source_file.location(start_index) {
Ok(location) => location,
Err(_) => return Ok(()),
};
let end_index = span.end();
let end_location = match source_file.location(end_index) {
Ok(location) => location,
Err(_) => return Ok(()),
};
// Increase the amount of lines we should show for "context"
let context_start = start_location
.line_number
.saturating_sub(CODE_FRAME_CONTEXT_LINES.get());
let mut context_end = end_location
.line_number
.saturating_add(CODE_FRAME_CONTEXT_LINES.get())
.min(OneIndexed::new(source_file.line_starts.len()).unwrap_or(OneIndexed::MIN));
// Remove trailing blank lines
for line_index in IntoIter::new(context_start..=context_end).rev() {
if line_index == end_location.line_number {
break;
}
let line_start = match source_file.line_start(line_index.to_zero_indexed()) {
Ok(index) => index,
Err(_) => continue,
};
let line_end = match source_file.line_start(line_index.to_zero_indexed() + 1) {
Ok(index) => index,
Err(_) => continue,
};
let line_range = TextRange::new(line_start, line_end);
let line_text = source_file.source[line_range].trim();
if !line_text.is_empty() {
break;
}
context_end = line_index;
}
// If we have too many lines in our selection, then collapse them to an ellipsis
let range_len = (context_end.get() + 1).saturating_sub(context_start.get());
let ellipsis_range = if range_len > MAX_CODE_FRAME_LINES + 2 {
let ellipsis_start = context_start.saturating_add(HALF_MAX_CODE_FRAME_LINES);
let ellipsis_end = context_end.saturating_sub(HALF_MAX_CODE_FRAME_LINES);
Some(ellipsis_start..=ellipsis_end)
} else {
None
};
// Calculate the maximum width of the line number
let max_gutter_len = calculate_print_width(context_end);
let mut printed_lines = false;
for line_index in IntoIter::new(context_start..=context_end) {
if let Some(ellipsis_range) = &ellipsis_range {
if ellipsis_range.contains(&line_index) {
if *ellipsis_range.start() == line_index {
for _ in 0..max_gutter_len.get() {
fmt.write_str(" ")?;
}
fmt.write_markup(markup! { <Emphasis>" ...\n"</Emphasis> })?;
printed_lines = true;
}
continue;
}
}
let line_start = match source_file.line_start(line_index.to_zero_indexed()) {
Ok(index) => index,
Err(_) => continue,
};
let line_end = match source_file.line_start(line_index.to_zero_indexed() + 1) {
Ok(index) => index,
Err(_) => continue,
};
let line_range = TextRange::new(line_start, line_end);
let line_text = source_file.source[line_range].trim_end_matches(['\r', '\n']);
// Ensure that the frame doesn't start with whitespace
if !printed_lines && line_index != start_location.line_number && line_text.trim().is_empty()
{
continue;
}
printed_lines = true;
// If this is within the highlighted line range
let should_highlight =
line_index >= start_location.line_number && line_index <= end_location.line_number;
let padding_width = max_gutter_len
.get()
.saturating_sub(calculate_print_width(line_index).get());
for _ in 0..padding_width {
fmt.write_str(" ")?;
}
if should_highlight {
fmt.write_markup(markup! {
<Emphasis><Error>'>'</Error></Emphasis>' '
})?;
} else {
fmt.write_str(" ")?;
}
fmt.write_markup(markup! {
<Emphasis>{format_args!("{line_index} \u{2502} ")}</Emphasis>
})?;
// Show invisible characters
print_invisibles(
fmt,
line_text,
PrintInvisiblesOptions {
ignore_trailing_carriage_return: true,
ignore_leading_tabs: true,
ignore_lone_spaces: true,
at_line_start: true,
at_line_end: true,
},
)?;
fmt.write_str("\n")?;
if should_highlight {
let is_first_line = line_index == start_location.line_number;
let is_last_line = line_index == end_location.line_number;
let start_index_relative_to_line =
start_index.max(line_range.start()) - line_range.start();
let end_index_relative_to_line = end_index.min(line_range.end()) - line_range.start();
let marker = if is_first_line && is_last_line {
// Only line in the selection
Some(TextRange::new(
start_index_relative_to_line,
end_index_relative_to_line,
))
} else if is_first_line {
// First line in selection
Some(TextRange::new(
start_index_relative_to_line,
line_text.text_len(),
))
} else if is_last_line {
// Last line in selection
let start_index = line_text
.text_len()
.checked_sub(line_text.trim_start().text_len())
// SAFETY: The length of `line_text.trim_start()` should
// never be larger than `line_text` itself
.expect("integer overflow");
Some(TextRange::new(start_index, end_index_relative_to_line))
} else {
None
};
if let Some(marker) = marker {
for _ in 0..max_gutter_len.get() {
fmt.write_str(" ")?;
}
fmt.write_markup(markup! {
<Emphasis>" \u{2502} "</Emphasis>
})?;
// Align the start of the marker with the line above by a
// number of space characters equal to the unicode print width
// of the leading part of the line (before the start of the
// marker), with a special exception for tab characters that
// still get printed as tabs to respect the user-defined tab
// display width
let leading_range = TextRange::new(TextSize::from(0), marker.start());
for c in line_text[leading_range].chars() {
match c {
'\t' => fmt.write_str("\t")?,
_ => {
if let Some(width) = c.width() {
for _ in 0..width {
fmt.write_str(" ")?;
}
}
}
}
}
let marker_width = text_width(&line_text[marker]);
for _ in 0..marker_width {
fmt.write_markup(markup! {
<Emphasis><Error>'^'</Error></Emphasis>
})?;
}
fmt.write_str("\n")?;
}
}
}
fmt.write_str("\n")
}
/// Calculate the length of the string representation of `value`
pub(super) fn calculate_print_width(mut value: OneIndexed) -> NonZeroUsize {
// SAFETY: Constant is being initialized with a non-zero value
const TEN: OneIndexed = unwrap(OneIndexed::new(10));
let mut width = ONE;
while value >= TEN {
value = OneIndexed::new(value.get() / 10).unwrap_or(OneIndexed::MIN);
width = width.checked_add(1).unwrap();
}
width
}
/// We need to set a value here since we have no way of knowing what the user's
/// preferred tab display width is, so this is set to `2` to match how tab
/// characters are printed by [print_invisibles]
const TAB_WIDTH: usize = 2;
/// Compute the unicode display width of a string, with the width of tab
/// characters set to [TAB_WIDTH] and the width of control characters set to 0
pub(super) fn text_width(text: &str) -> usize {
text.chars()
.map(|char| match char {
'\t' => TAB_WIDTH,
_ => char.width().unwrap_or(0),
})
.sum()
}
pub(super) struct PrintInvisiblesOptions {
/// Do not print tab characters at the start of the string
pub(super) ignore_leading_tabs: bool,
/// If this is set to true, space characters will only be substituted when
/// at least two of them are found in a row
pub(super) ignore_lone_spaces: bool,
/// Do not print `'\r'` characters if they're followed by `'\n'`
pub(super) ignore_trailing_carriage_return: bool,
// Set to `true` to show invisible characters at the start of the string
pub(super) at_line_start: bool,
// Set to `true` to show invisible characters at the end of the string
pub(super) at_line_end: bool,
}
/// Print `input` to `fmt` with invisible characters replaced with an
/// appropriate visual representation. Return `true` if any non-whitespace
/// character was printed
pub(super) fn print_invisibles(
fmt: &mut fmt::Formatter<'_>,
input: &str,
options: PrintInvisiblesOptions,
) -> io::Result<bool> {
let mut had_non_whitespace = false;
// Get the first trailing whitespace character in the string
let trailing_whitespace_index = input
.char_indices()
.rev()
.find_map(|(index, char)| {
if !char.is_ascii_whitespace() {
Some(index)
} else {
None
}
})
.unwrap_or(input.len());
let mut iter = input.char_indices().peekable();
let mut prev_char_was_whitespace = false;
while let Some((i, char)) = iter.next() {
let mut show_invisible = true;
// Only highlight spaces when surrounded by other spaces
if char == ' ' && options.ignore_lone_spaces {
show_invisible = false;
let next_char_is_whitespace = iter
.peek()
.map_or(false, |(_, char)| char.is_ascii_whitespace());
if prev_char_was_whitespace || next_char_is_whitespace {
show_invisible = false;
}
}
prev_char_was_whitespace = char.is_ascii_whitespace();
// Don't show leading tabs
if options.at_line_start
&& !had_non_whitespace
&& char == '\t'
&& options.ignore_leading_tabs
{
show_invisible = false;
}
// Always show if at the end of line
if options.at_line_end && i >= trailing_whitespace_index {
show_invisible = true;
}
// If we are a carriage return next to a \n then don't show the character as visible
if options.ignore_trailing_carriage_return && char == '\r' {
let next_char_is_line_feed = iter.peek().map_or(false, |(_, char)| *char == '\n');
if next_char_is_line_feed {
continue;
}
}
if !show_invisible {
if !char.is_ascii_whitespace() {
had_non_whitespace = true;
}
write!(fmt, "{char}")?;
continue;
}
if let Some(visible) = show_invisible_char(char) {
fmt.write_markup(markup! { <Dim>{visible}</Dim> })?;
continue;
}
if (char.is_whitespace() && !char.is_ascii_whitespace()) || char.is_control() {
let code = u32::from(char);
fmt.write_markup(markup! { <Inverse>"U+"{format_args!("{code:x}")}</Inverse> })?;
continue;
}
write!(fmt, "{char}")?;
}
Ok(had_non_whitespace)
}
fn show_invisible_char(char: char) -> Option<&'static str> {
match char {
' ' => Some("\u{b7}"), // Middle Dot
'\r' => Some("\u{240d}"), // Carriage Return Symbol
'\n' => Some("\u{23ce}"), // Return Symbol
'\t' => Some("\u{2192} "), // Rightwards Arrow
'\0' => Some("\u{2400}"), // Null Symbol
'\x0b' => Some("\u{240b}"), // Vertical Tabulation Symbol
'\x08' => Some("\u{232b}"), // Backspace Symbol
'\x0c' => Some("\u{21a1}"), // Downards Two Headed Arrow
_ => None,
}
}
/// A user-facing location in a source file.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(super) struct SourceLocation {
/// The user-facing line number.
pub(super) line_number: OneIndexed,
/// The user-facing column number.
pub(super) column_number: OneIndexed,
}
/// Representation of a single source file holding additional information for
/// efficiently rendering code frames
#[derive(Clone)]
pub(super) struct SourceFile<'diagnostic> {
/// The source code of the file.
source: &'diagnostic str,
/// The starting byte indices in the source code.
line_starts: Cow<'diagnostic, LineIndex>,
}
impl<'diagnostic> SourceFile<'diagnostic> {
/// Create a new [SourceFile] from a slice of text
pub(super) fn new(source_code: BorrowedSourceCode<'diagnostic>) -> Self {
// Either re-use the existing line index provided by the diagnostic or create one
Self {
source: source_code.text,
line_starts: source_code.line_starts.map_or_else(
|| Cow::Owned(LineIndexBuf::from_source_text(source_code.text)),
Cow::Borrowed,
),
}
}
/// Return the starting byte index of the line with the specified line index.
/// Convenience method that already generates errors if necessary.
fn line_start(&self, line_index: usize) -> io::Result<TextSize> {
use std::cmp::Ordering;
match line_index.cmp(&self.line_starts.len()) {
Ordering::Less => Ok(self
.line_starts
.get(line_index)
.cloned()
.expect("failed despite previous check")),
Ordering::Equal => Ok(self.source.text_len()),
Ordering::Greater => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"overflow error",
)),
}
}
fn line_index(&self, byte_index: TextSize) -> usize {
self.line_starts
.binary_search(&byte_index)
.unwrap_or_else(|next_line| next_line - 1)
}
fn line_range(&self, line_index: usize) -> io::Result<TextRange> {
let line_start = self.line_start(line_index)?;
let next_line_start = self.line_start(line_index + 1)?;
Ok(TextRange::new(line_start, next_line_start))
}
fn line_number(&self, line_index: usize) -> OneIndexed {
// SAFETY: Adding `1` to the value of `line_index` ensures it's non-zero
OneIndexed::from_zero_indexed(line_index)
}
fn column_number(&self, line_index: usize, byte_index: TextSize) -> io::Result<OneIndexed> {
let source = self.source;
let line_range = self.line_range(line_index)?;
let column_index = column_index(source, line_range, byte_index);
// SAFETY: Adding `1` to the value of `column_index` ensures it's non-zero
Ok(OneIndexed::from_zero_indexed(column_index))
}
/// Get a source location from a byte index into the text of this file
pub(super) fn location(&self, byte_index: TextSize) -> io::Result<SourceLocation> {
let line_index = self.line_index(byte_index);
Ok(SourceLocation {
line_number: self.line_number(line_index),
column_number: self.column_number(line_index, byte_index)?,
})
}
}
/// The column index at the given byte index in the source file.
/// This is the number of characters to the given byte index.
///
/// If the byte index is smaller than the start of the line, then `0` is returned.
/// If the byte index is past the end of the line, the column index of the last
/// character `+ 1` is returned.
fn column_index(source: &str, line_range: TextRange, byte_index: TextSize) -> usize {
let end_index = std::cmp::min(
byte_index,
std::cmp::min(line_range.end(), source.text_len()),
);
(usize::from(line_range.start())..usize::from(end_index))
.filter(|byte_index| source.is_char_boundary(byte_index + 1))
.count()
}
/// Type-safe wrapper for a value whose logical range starts at `1`, for
/// instance the line or column numbers in a file
///
/// Internally this is represented as a [NonZeroUsize], this enables some
/// memory optimizations
#[repr(transparent)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OneIndexed(NonZeroUsize);
impl OneIndexed {
// SAFETY: These constants are being initialized with non-zero values
/// The smallest value that can be represented by this integer type.
pub const MIN: Self = unwrap(Self::new(1));
/// The largest value that can be represented by this integer type
pub const MAX: Self = unwrap(Self::new(usize::MAX));
/// Creates a non-zero if the given value is not zero.
pub const fn new(value: usize) -> Option<Self> {
match NonZeroUsize::new(value) {
Some(value) => Some(Self(value)),
None => None,
}
}
/// Construct a new [OneIndexed] from a zero-indexed value
pub const fn from_zero_indexed(value: usize) -> Self {
Self(ONE.saturating_add(value))
}
/// Returns the value as a primitive type.
pub const fn get(self) -> usize {
self.0.get()
}
/// Return the zero-indexed primitive value for this [OneIndexed]
pub const fn to_zero_indexed(self) -> usize {
self.0.get() - 1
}
/// Saturating integer addition. Computes `self + rhs`, saturating at
/// the numeric bounds instead of overflowing.
pub const fn saturating_add(self, rhs: usize) -> Self {
match NonZeroUsize::new(self.0.get().saturating_add(rhs)) {
Some(value) => Self(value),
None => Self::MAX,
}
}
/// Saturating integer subtraction. Computes `self - rhs`, saturating
/// at the numeric bounds instead of overflowing.
pub const fn saturating_sub(self, rhs: usize) -> Self {
match NonZeroUsize::new(self.0.get().saturating_sub(rhs)) {
Some(value) => Self(value),
None => Self::MIN,
}
}
}
impl fmt::Display for OneIndexed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> io::Result<()> {
self.0.get().fmt(f)
}
}
impl std::fmt::Display for OneIndexed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.get().fmt(f)
}
}
/// Adapter type implementing [Iterator] for ranges of [OneIndexed],
/// since [std::iter::Step] is unstable
pub struct IntoIter(std::ops::Range<usize>);
impl IntoIter {
/// Construct a new iterator over a range of [OneIndexed] of any kind
/// (`..`, `a..`, `..b`, `..=c`, `d..e`, or `f..=g`)
pub fn new<R: RangeBounds<OneIndexed>>(range: R) -> Self {
let start = match range.start_bound() {
Bound::Included(value) => value.get(),
Bound::Excluded(value) => value.get() + 1,
Bound::Unbounded => 1,
};
let end = match range.end_bound() {
Bound::Included(value) => value.get() + 1,
Bound::Excluded(value) => value.get(),
Bound::Unbounded => usize::MAX,
};
Self(start..end)
}
}
impl Iterator for IntoIter {
type Item = OneIndexed;
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|index| OneIndexed::new(index).unwrap())
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl DoubleEndedIterator for IntoIter {
fn next_back(&mut self) -> Option<Self::Item> {
self.0
.next_back()
.map(|index| OneIndexed::new(index).unwrap())
}
}
impl FusedIterator for IntoIter {}
#[cfg(test)]
mod tests {
use std::num::NonZeroUsize;
use super::{calculate_print_width, OneIndexed};
#[test]
fn print_width() {
let one = NonZeroUsize::new(1).unwrap();
let two = NonZeroUsize::new(2).unwrap();
let three = NonZeroUsize::new(3).unwrap();
let four = NonZeroUsize::new(4).unwrap();
assert_eq!(calculate_print_width(OneIndexed::new(1).unwrap()), one);
assert_eq!(calculate_print_width(OneIndexed::new(9).unwrap()), one);
assert_eq!(calculate_print_width(OneIndexed::new(10).unwrap()), two);
assert_eq!(calculate_print_width(OneIndexed::new(11).unwrap()), two);
assert_eq!(calculate_print_width(OneIndexed::new(19).unwrap()), two);
assert_eq!(calculate_print_width(OneIndexed::new(20).unwrap()), two);
assert_eq!(calculate_print_width(OneIndexed::new(21).unwrap()), two);
assert_eq!(calculate_print_width(OneIndexed::new(99).unwrap()), two);
assert_eq!(calculate_print_width(OneIndexed::new(100).unwrap()), three);
assert_eq!(calculate_print_width(OneIndexed::new(101).unwrap()), three);
assert_eq!(calculate_print_width(OneIndexed::new(110).unwrap()), three);
assert_eq!(calculate_print_width(OneIndexed::new(199).unwrap()), three);
assert_eq!(calculate_print_width(OneIndexed::new(999).unwrap()), three);
assert_eq!(calculate_print_width(OneIndexed::new(1000).unwrap()), four);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/src/display/backtrace.rs | crates/rome_diagnostics/src/display/backtrace.rs | use std::{borrow::Cow, path::PathBuf};
use std::{cell::Cell, fmt::Write as _, io, os::raw::c_void, path::Path, slice};
use rome_console::{fmt, markup};
use serde::{Deserialize, Serialize};
use super::IndentWriter;
/// The [Backtrace] type can be used to capture a native Rust stack trace, to
/// be displayed a diagnostic advice for native errors.
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub struct Backtrace {
inner: BacktraceKind,
}
impl Default for Backtrace {
// Do not inline this function to ensure it creates a stack frame, so that
// internal functions above it in the backtrace can be hidden when the
// backtrace is printed
#[inline(never)]
fn default() -> Self {
Self::capture(Backtrace::default as usize)
}
}
impl Backtrace {
/// Take a snapshot of the current state of the stack and return it as a [Backtrace].
pub fn capture(top_frame: usize) -> Self {
Self {
inner: BacktraceKind::Native(NativeBacktrace::new(top_frame)),
}
}
/// Since the `capture` function only takes a lightweight snapshot of the
/// stack, it's necessary to perform an additional resolution step to map
/// the list of instruction pointers on the stack to actual symbol
/// information (like function name and file location) before printing the
/// backtrace.
pub(super) fn resolve(&mut self) {
if let BacktraceKind::Native(inner) = &mut self.inner {
inner.resolve();
}
}
fn frames(&self) -> BacktraceFrames<'_> {
match &self.inner {
BacktraceKind::Native(inner) => BacktraceFrames::Native(inner.frames()),
BacktraceKind::Serialized(inner) => BacktraceFrames::Serialized(inner),
}
}
pub(crate) fn is_empty(&self) -> bool {
self.frames().is_empty()
}
}
impl serde::Serialize for Backtrace {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
let frames = match &self.inner {
BacktraceKind::Native(backtrace) => {
let mut backtrace = backtrace.clone();
backtrace.resolve();
let frames: Vec<_> = backtrace
.frames()
.iter()
.map(SerializedFrame::from)
.collect();
Cow::Owned(frames)
}
BacktraceKind::Serialized(frames) => Cow::Borrowed(frames),
};
frames.serialize(serializer)
}
}
impl<'de> serde::Deserialize<'de> for Backtrace {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
Ok(Self {
inner: BacktraceKind::Serialized(<Vec<SerializedFrame>>::deserialize(deserializer)?),
})
}
}
#[cfg(feature = "schema")]
impl schemars::JsonSchema for Backtrace {
fn schema_name() -> String {
String::from("Backtrace")
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
<Vec<SerializedFrame>>::json_schema(gen)
}
}
/// Internal representation of a [Backtrace], can be either a native backtrace
/// instance or a vector of serialized frames.
#[derive(Clone, Debug)]
enum BacktraceKind {
Native(NativeBacktrace),
Serialized(Vec<SerializedFrame>),
}
#[cfg(test)]
impl PartialEq for BacktraceKind {
fn eq(&self, _other: &Self) -> bool {
if let (BacktraceKind::Serialized(this), BacktraceKind::Serialized(other)) = (self, _other)
{
return this == other;
}
false
}
}
#[cfg(test)]
impl Eq for BacktraceKind {}
/// Wrapper type for a native backtrace instance.
#[derive(Clone, Debug)]
struct NativeBacktrace {
backtrace: ::backtrace::Backtrace,
/// Pointer to the top frame, this frame and every entry above it on the
/// stack will not be displayed in the printed stack trace.
top_frame: usize,
/// Pointer to the bottom frame, this frame and every entry below it on the
/// stack will not be displayed in the printed stack trace.
bottom_frame: usize,
}
impl NativeBacktrace {
fn new(top_frame: usize) -> Self {
Self {
backtrace: ::backtrace::Backtrace::new_unresolved(),
top_frame,
bottom_frame: bottom_frame(),
}
}
fn resolve(&mut self) {
self.backtrace.resolve();
}
/// Returns the list of frames for this backtrace, truncated to the
/// `top_frame` and `bottom_frame`.
fn frames(&self) -> &'_ [::backtrace::BacktraceFrame] {
let mut frames = self.backtrace.frames();
let top_frame = frames.iter().position(|frame| {
frame.symbols().iter().any(|symbol| {
symbol
.addr()
.map_or(false, |addr| addr as usize == self.top_frame)
})
});
if let Some(top_frame) = top_frame {
if let Some(bottom_frames) = frames.get(top_frame + 1..) {
frames = bottom_frames;
}
}
let bottom_frame = frames.iter().position(|frame| {
frame.symbols().iter().any(|symbol| {
symbol
.addr()
.map_or(false, |addr| addr as usize == self.bottom_frame)
})
});
if let Some(bottom_frame) = bottom_frame {
if let Some(top_frames) = frames.get(..bottom_frame + 1) {
frames = top_frames;
}
}
frames
}
}
thread_local! {
/// This cell holds the address of the function that conceptually sits at the
/// "bottom" of the backtraces created on the current thread (all the frames
/// below this will be hidden when the backtrace is printed)
///
/// This value is thread-local since different threads will generally have
/// different values for the bottom frame address: for the main thread this
/// will be the address of the `main` function, while on worker threads
/// this will be the start function for the thread (see the documentation
/// of [set_bottom_frame] for examples of where to set the bottom frame).
static BOTTOM_FRAME: Cell<Option<usize>> = Cell::new(None);
}
/// Registers a function pointer as the "bottom frame" for this thread: all
/// instances of [Backtrace] created on this thread will omit this function and
/// all entries below it on the stack
///
/// ## Examples
///
/// On the main thread:
/// ```
/// # use rome_diagnostics::set_bottom_frame;
/// # #[allow(clippy::needless_doctest_main)]
/// pub fn main() {
/// set_bottom_frame(main as usize);
///
/// // ...
/// }
/// ```
///
/// On worker threads:
/// ```
/// # use rome_diagnostics::set_bottom_frame;
/// fn worker_thread() {
/// set_bottom_frame(worker_thread as usize);
///
/// // ...
/// }
///
/// std::thread::spawn(worker_thread);
/// ```
pub fn set_bottom_frame(ptr: usize) {
BOTTOM_FRAME.with(|cell| {
cell.set(Some(ptr));
});
}
fn bottom_frame() -> usize {
BOTTOM_FRAME.with(|cell| cell.get().unwrap_or(0))
}
pub(super) fn print_backtrace(
fmt: &mut fmt::Formatter<'_>,
backtrace: &Backtrace,
) -> io::Result<()> {
for (frame_index, frame) in backtrace.frames().iter().enumerate() {
if frame.ip().is_null() {
continue;
}
fmt.write_fmt(format_args!("{frame_index:4}: "))?;
let mut slot = None;
let mut fmt = IndentWriter::wrap(fmt, &mut slot, false, " ");
for symbol in frame.symbols().iter() {
if let Some(name) = symbol.name() {
fmt.write_fmt(format_args!("{name:#}"))?;
}
fmt.write_str("\n")?;
if let Some(filename) = symbol.filename() {
let mut slot = None;
let mut fmt = IndentWriter::wrap(&mut fmt, &mut slot, true, " ");
// Print a hyperlink if the file exists on disk
let href = if filename.exists() {
Some(format!("file:///{}", filename.display()))
} else {
None
};
// Build up the text of the link from the file path, the line number and column number
let mut text = filename.display().to_string();
if let Some(lineno) = symbol.lineno() {
// SAFETY: Writing a `u32` to a string should not fail
write!(text, ":{}", lineno).unwrap();
if let Some(colno) = symbol.colno() {
// SAFETY: Writing a `u32` to a string should not fail
write!(text, ":{}", colno).unwrap();
}
}
if let Some(href) = href {
fmt.write_markup(markup! {
"at "
<Hyperlink href={href}>{text}</Hyperlink>
"\n"
})?;
} else {
fmt.write_markup(markup! {
"at "{text}"\n"
})?;
}
}
}
}
Ok(())
}
/// Serializable representation of a backtrace frame.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(
feature = "schema",
derive(schemars::JsonSchema),
schemars(rename = "BacktraceFrame")
)]
#[cfg_attr(test, derive(Eq, PartialEq))]
struct SerializedFrame {
ip: u64,
symbols: Vec<SerializedSymbol>,
}
impl From<&'_ backtrace::BacktraceFrame> for SerializedFrame {
fn from(frame: &'_ backtrace::BacktraceFrame) -> Self {
Self {
ip: frame.ip() as u64,
symbols: frame.symbols().iter().map(SerializedSymbol::from).collect(),
}
}
}
/// Serializable representation of a backtrace frame symbol.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(
feature = "schema",
derive(schemars::JsonSchema),
schemars(rename = "BacktraceSymbol")
)]
#[cfg_attr(test, derive(Eq, PartialEq))]
struct SerializedSymbol {
name: Option<String>,
filename: Option<PathBuf>,
lineno: Option<u32>,
colno: Option<u32>,
}
impl From<&'_ backtrace::BacktraceSymbol> for SerializedSymbol {
fn from(symbol: &'_ backtrace::BacktraceSymbol) -> Self {
Self {
name: symbol.name().map(|name| format!("{name:#}")),
filename: symbol.filename().map(ToOwned::to_owned),
lineno: symbol.lineno(),
colno: symbol.colno(),
}
}
}
enum BacktraceFrames<'a> {
Native(&'a [::backtrace::BacktraceFrame]),
Serialized(&'a [SerializedFrame]),
}
impl BacktraceFrames<'_> {
fn iter(&self) -> BacktraceFramesIter<'_> {
match self {
Self::Native(inner) => BacktraceFramesIter::Native(inner.iter()),
Self::Serialized(inner) => BacktraceFramesIter::Serialized(inner.iter()),
}
}
fn is_empty(&self) -> bool {
match self {
Self::Native(inner) => inner.is_empty(),
Self::Serialized(inner) => inner.is_empty(),
}
}
}
enum BacktraceFramesIter<'a> {
Native(slice::Iter<'a, ::backtrace::BacktraceFrame>),
Serialized(slice::Iter<'a, SerializedFrame>),
}
impl<'a> Iterator for BacktraceFramesIter<'a> {
type Item = BacktraceFrame<'a>;
fn next(&mut self) -> Option<Self::Item> {
match self {
Self::Native(inner) => inner.next().map(BacktraceFrame::Native),
Self::Serialized(inner) => inner.next().map(BacktraceFrame::Serialized),
}
}
}
enum BacktraceFrame<'a> {
Native(&'a ::backtrace::BacktraceFrame),
Serialized(&'a SerializedFrame),
}
impl BacktraceFrame<'_> {
fn ip(&self) -> *mut c_void {
match self {
Self::Native(inner) => inner.ip(),
Self::Serialized(inner) => inner.ip as *mut c_void,
}
}
fn symbols(&self) -> BacktraceSymbols<'_> {
match self {
Self::Native(inner) => BacktraceSymbols::Native(inner.symbols()),
Self::Serialized(inner) => BacktraceSymbols::Serialized(&inner.symbols),
}
}
}
enum BacktraceSymbols<'a> {
Native(&'a [::backtrace::BacktraceSymbol]),
Serialized(&'a [SerializedSymbol]),
}
impl BacktraceSymbols<'_> {
fn iter(&self) -> BacktraceSymbolsIter<'_> {
match self {
Self::Native(inner) => BacktraceSymbolsIter::Native(inner.iter()),
Self::Serialized(inner) => BacktraceSymbolsIter::Serialized(inner.iter()),
}
}
}
enum BacktraceSymbolsIter<'a> {
Native(slice::Iter<'a, ::backtrace::BacktraceSymbol>),
Serialized(slice::Iter<'a, SerializedSymbol>),
}
impl<'a> Iterator for BacktraceSymbolsIter<'a> {
type Item = BacktraceSymbol<'a>;
fn next(&mut self) -> Option<Self::Item> {
match self {
Self::Native(inner) => inner.next().map(BacktraceSymbol::Native),
Self::Serialized(inner) => inner.next().map(BacktraceSymbol::Serialized),
}
}
}
enum BacktraceSymbol<'a> {
Native(&'a ::backtrace::BacktraceSymbol),
Serialized(&'a SerializedSymbol),
}
impl BacktraceSymbol<'_> {
fn name(&self) -> Option<String> {
match self {
Self::Native(inner) => inner.name().map(|name| format!("{name:#}")),
Self::Serialized(inner) => inner.name.clone(),
}
}
fn filename(&self) -> Option<&Path> {
match self {
Self::Native(inner) => inner.filename(),
Self::Serialized(inner) => inner.filename.as_deref(),
}
}
fn lineno(&self) -> Option<u32> {
match self {
Self::Native(inner) => inner.lineno(),
Self::Serialized(inner) => inner.lineno,
}
}
fn colno(&self) -> Option<u32> {
match self {
Self::Native(inner) => inner.colno(),
Self::Serialized(inner) => inner.colno,
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/src/display/message.rs | crates/rome_diagnostics/src/display/message.rs | use rome_console::fmt::{Formatter, Termcolor};
use rome_console::{markup, MarkupBuf};
use serde::{Deserialize, Serialize};
use termcolor::NoColor;
/// Convenient type that can be used when message and descriptions match, and they need to be
/// displayed using different formatters
///
/// ## Examples
///
/// ```
/// use rome_diagnostics::{Diagnostic, MessageAndDescription};
///
/// #[derive(Debug, Diagnostic)]
/// struct TestDiagnostic {
/// #[message]
/// #[description]
/// message: MessageAndDescription
/// }
/// ```
#[derive(Clone, Deserialize, Serialize)]
pub struct MessageAndDescription {
/// Shown when medium supports custom markup
message: MarkupBuf,
/// Shown when the medium doesn't support markup
description: String,
}
impl MessageAndDescription {
/// It sets a custom message. It updates only the message.
pub fn set_message(&mut self, new_message: MarkupBuf) {
self.message = new_message;
}
/// It sets a custom description. It updates only the description
pub fn set_description(&mut self, new_description: String) {
self.description = new_description;
}
}
impl From<String> for MessageAndDescription {
fn from(description: String) -> Self {
Self {
message: markup! { {description} }.to_owned(),
description,
}
}
}
impl From<MarkupBuf> for MessageAndDescription {
fn from(message: MarkupBuf) -> Self {
let description = markup_to_string(&message);
Self {
message,
description,
}
}
}
impl std::fmt::Display for MessageAndDescription {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.description)
}
}
impl std::fmt::Debug for MessageAndDescription {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self, f)
}
}
impl rome_console::fmt::Display for MessageAndDescription {
fn fmt(&self, fmt: &mut Formatter<'_>) -> std::io::Result<()> {
fmt.write_markup(markup! {{self.message}})
}
}
/// Utility function to transform a [MarkupBuf] into a [String]
pub fn markup_to_string(markup: &MarkupBuf) -> String {
let mut buffer = Vec::new();
let mut write = Termcolor(NoColor::new(&mut buffer));
let mut fmt = Formatter::new(&mut write);
fmt.write_markup(markup! { {markup} })
.expect("to have written in the buffer");
String::from_utf8(buffer).expect("to have convert a buffer into a String")
}
#[cfg(test)]
mod test {
use crate::MessageAndDescription;
#[test]
fn message_size() {
assert_eq!(std::mem::size_of::<MessageAndDescription>(), 48);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros.rs | crates/rome_diagnostics/tests/macros.rs | #[test]
fn test_macros() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/macros/*.rs");
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros/location_eq.rs | crates/rome_diagnostics/tests/macros/location_eq.rs | use rome_diagnostics::Diagnostic;
#[derive(Debug, Diagnostic)]
struct TestDiagnostic {
#[location = Identifier]
location: (),
}
fn main() {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros/category_ident.rs | crates/rome_diagnostics/tests/macros/category_ident.rs | use rome_diagnostics::Diagnostic;
#[derive(Debug, Diagnostic)]
#[diagnostic(category = Identifier)]
struct TestDiagnostic {}
fn main() {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros/severity_lit_str.rs | crates/rome_diagnostics/tests/macros/severity_lit_str.rs | use rome_diagnostics::Diagnostic;
#[derive(Debug, Diagnostic)]
#[diagnostic(severity = "Error")]
struct TestDiagnostic {}
fn main() {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros/unknown_message_attr.rs | crates/rome_diagnostics/tests/macros/unknown_message_attr.rs | use rome_diagnostics::Diagnostic;
#[derive(Debug, Diagnostic)]
#[diagnostic(message(unknown))]
struct TestDiagnostic {}
fn main() {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros/unknown_container_attr.rs | crates/rome_diagnostics/tests/macros/unknown_container_attr.rs | use rome_diagnostics::Diagnostic;
#[derive(Debug, Diagnostic)]
#[diagnostic(unknown_attr)]
struct TestDiagnostic {}
fn main() {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros/unknown_location_attr.rs | crates/rome_diagnostics/tests/macros/unknown_location_attr.rs | use rome_diagnostics::Diagnostic;
#[derive(Debug, Diagnostic)]
struct TestDiagnostic {
#[location(unknown)]
location: (),
}
fn main() {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros/description_syntax_error.rs | crates/rome_diagnostics/tests/macros/description_syntax_error.rs | use rome_diagnostics::Diagnostic;
#[derive(Debug, Diagnostic)]
#[diagnostic(message(description = "text {unclosed"))]
struct TestDiagnostic {}
fn main() {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros/category_paren.rs | crates/rome_diagnostics/tests/macros/category_paren.rs | use rome_diagnostics::Diagnostic;
#[derive(Debug, Diagnostic)]
#[diagnostic(message(description = Ident))]
struct TestDiagnostic {}
fn main() {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros/severity_paren.rs | crates/rome_diagnostics/tests/macros/severity_paren.rs | use rome_diagnostics::Diagnostic;
#[derive(Debug, Diagnostic)]
#[diagnostic(severity(Error))]
struct TestDiagnostic {}
fn main() {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros/error_enum.rs | crates/rome_diagnostics/tests/macros/error_enum.rs | use rome_diagnostics::Diagnostic;
#[derive(Debug, Diagnostic)]
enum ErrorEnum {
Int(u32),
Float(f32),
}
fn main() {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros/description_paren.rs | crates/rome_diagnostics/tests/macros/description_paren.rs | use rome_diagnostics::Diagnostic;
#[derive(Debug, Diagnostic)]
#[diagnostic(message(description("description")))]
struct TestDiagnostic {}
fn main() {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros/tags_comma.rs | crates/rome_diagnostics/tests/macros/tags_comma.rs | use rome_diagnostics::Diagnostic;
#[derive(Debug, Diagnostic)]
#[diagnostic(tags(Identifier, Identifier))]
struct TestDiagnostic {}
fn main() {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros/error_union.rs | crates/rome_diagnostics/tests/macros/error_union.rs | use rome_diagnostics::Diagnostic;
#[derive(Diagnostic)]
union ErrorUnion {
int: u32,
float: f32,
}
fn main() {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros/unknown_field_attr.rs | crates/rome_diagnostics/tests/macros/unknown_field_attr.rs | use rome_diagnostics::Diagnostic;
#[derive(Debug, Diagnostic)]
struct TestDiagnostic {
#[unknown_attr]
field: bool,
}
fn main() {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros/description_ident.rs | crates/rome_diagnostics/tests/macros/description_ident.rs | use rome_diagnostics::Diagnostic;
#[derive(Debug, Diagnostic)]
#[diagnostic(category = Identifier)]
struct TestDiagnostic {}
fn main() {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/tests/macros/tags_eq.rs | crates/rome_diagnostics/tests/macros/tags_eq.rs | use rome_diagnostics::Diagnostic;
#[derive(Debug, Diagnostic)]
#[diagnostic(tags = Identifier)]
struct TestDiagnostic {}
fn main() {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/examples/serde.rs | crates/rome_diagnostics/examples/serde.rs | use rome_console::{markup, ConsoleExt, EnvConsole};
use rome_diagnostics::{Diagnostic, LineIndexBuf, PrintDiagnostic, Resource, Result, SourceCode};
use rome_rowan::{TextRange, TextSize};
use serde_json::Error;
#[derive(Debug, Diagnostic)]
#[diagnostic(category = "internalError/io", tags(INTERNAL))]
struct SerdeDiagnostic {
#[message]
#[description]
message: String,
#[location(resource)]
path: Resource<&'static str>,
#[location(span)]
span: Option<TextRange>,
#[location(source_code)]
source_code: SourceCode<String, LineIndexBuf>,
}
impl SerdeDiagnostic {
fn new(input: &str, error: Error) -> Self {
let line_starts = LineIndexBuf::from_source_text(input);
let line_index = error.line().checked_sub(1);
let span = line_index.and_then(|line_index| {
let line_start = line_starts.get(line_index)?;
let column_index = error.column().checked_sub(1)?;
let column_offset = TextSize::try_from(column_index).ok()?;
let span_start = line_start + column_offset;
Some(TextRange::at(span_start, TextSize::from(0)))
});
Self {
message: error.to_string(),
path: Resource::Memory,
span,
source_code: SourceCode {
text: input.to_string(),
line_starts: Some(line_starts),
},
}
}
}
fn from_str(input: &str) -> Result<serde_json::Value> {
match serde_json::from_str(input) {
Ok(value) => Ok(value),
Err(error) => Err(SerdeDiagnostic::new(input, error).into()),
}
}
pub fn main() {
if let Err(err) = from_str("{\"syntax_error\"") {
EnvConsole::default().error(markup!({ PrintDiagnostic::verbose(&err) }));
};
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/examples/fs.rs | crates/rome_diagnostics/examples/fs.rs | use std::io;
use rome_console::{fmt, markup, ConsoleExt, EnvConsole};
use rome_diagnostics::{
Advices, Diagnostic, Location, LogCategory, PrintDiagnostic, Resource, SourceCode, Visit,
};
use rome_rowan::{TextRange, TextSize};
#[derive(Debug, Diagnostic)]
#[diagnostic(category = "args/fileNotFound", message = "No matching files found")]
struct NotFoundDiagnostic {
#[location(resource)]
path: String,
#[advice]
advices: NotFoundAdvices,
}
#[derive(Debug)]
struct NotFoundAdvices {
pattern_list: Vec<String>,
configuration_path: String,
configuration_span: TextRange,
configuration_source_code: String,
}
impl Advices for NotFoundAdvices {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
visitor.record_log(LogCategory::Info, &"The following files were ignored")?;
let pattern_list: Vec<_> = self
.pattern_list
.iter()
.map(|pattern| pattern as &dyn fmt::Display)
.collect();
visitor.record_list(&pattern_list)?;
visitor.record_log(LogCategory::Info, &"Ignore patterns were defined here")?;
visitor.record_frame(Location {
resource: Some(Resource::File(&self.configuration_path)),
span: Some(self.configuration_span),
source_code: Some(SourceCode {
text: &self.configuration_source_code,
line_starts: None,
}),
})
}
}
pub fn main() {
let diag = NotFoundDiagnostic {
path: String::from("dist/bundle.js"),
advices: NotFoundAdvices {
pattern_list: vec![String::from("dist/**/*.js"), String::from("build/**/*.js")],
configuration_path: String::from("rome.json"),
configuration_span: TextRange::new(TextSize::from(29), TextSize::from(106)),
configuration_source_code: String::from(
"{
\"formatter\": {
\"ignore\": [
\"dist/**/*.js\",
\"build/**/*.js\"
]
}
}",
),
},
};
EnvConsole::default().error(markup!({ PrintDiagnostic::verbose(&diag) }));
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/examples/cli.rs | crates/rome_diagnostics/examples/cli.rs | use std::io;
use rome_console::{markup, ConsoleExt, EnvConsole};
use rome_diagnostics::{Advices, Diagnostic, LogCategory, PrintDiagnostic, Resource, Visit};
use rome_rowan::{TextRange, TextSize};
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "flags/invalid",
message(
description = "Unknown command {command_name}",
message("Unknown command "<Emphasis>{self.command_name}</Emphasis>)
),
tags(FIXABLE),
)]
struct CliDiagnostic {
command_name: String,
#[location(resource)]
path: Resource<&'static str>,
#[location(span)]
span: TextRange,
#[location(source_code)]
source_code: String,
#[advice]
advices: CliAdvices,
}
#[derive(Debug)]
struct CliAdvices {
suggested_name: String,
suggested_command: String,
}
impl Advices for CliAdvices {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
visitor.record_log(
LogCategory::Info,
&markup! {
"Did you mean "<Emphasis>{self.suggested_name}</Emphasis>" instead?"
},
)?;
visitor.record_command(&self.suggested_command)?;
visitor.record_log(LogCategory::Info, &"To see all available commands run")?;
visitor.record_command("rome --help")
}
}
pub fn main() {
let diag = CliDiagnostic {
command_name: String::from("formqt"),
path: Resource::Argv,
span: TextRange::new(TextSize::from(5), TextSize::from(11)),
source_code: String::from("rome formqt file.js"),
advices: CliAdvices {
suggested_name: String::from("format"),
suggested_command: String::from("rome format file.js"),
},
};
EnvConsole::default().error(markup!({ PrintDiagnostic::verbose(&diag) }));
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics/examples/lint.rs | crates/rome_diagnostics/examples/lint.rs | use std::io;
use rome_console::{markup, ConsoleExt, EnvConsole};
use rome_diagnostics::{
Advices, Diagnostic, Location, LogCategory, PrintDiagnostic, Resource, SourceCode, Visit,
};
use rome_rowan::{TextRange, TextSize};
use rome_text_edit::TextEdit;
#[derive(Debug, Diagnostic)]
#[diagnostic(
category = "lint/style/noShoutyConstants",
message = "Redundant constant reference",
tags(FIXABLE)
)]
struct LintDiagnostic {
#[location(resource)]
path: String,
#[location(span)]
span: TextRange,
#[location(source_code)]
source_code: String,
#[advice]
advices: LintAdvices,
#[verbose_advice]
verbose_advices: LintVerboseAdvices,
}
#[derive(Debug)]
struct LintAdvices {
path: String,
declaration_span: TextRange,
source_code: String,
code_action: TextEdit,
}
impl Advices for LintAdvices {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
visitor.record_log(
LogCategory::Info,
&"You should avoid declaring constants with a string that's the same value as the variable name. It introduces a level of unnecessary indirection when it's only two additional characters to inline."
)?;
visitor.record_log(LogCategory::Info, &"This constant is declared here")?;
visitor.record_frame(Location {
resource: Some(Resource::File(&self.path)),
span: Some(self.declaration_span),
source_code: Some(SourceCode {
text: &self.source_code,
line_starts: None,
}),
})?;
visitor.record_log(LogCategory::Info, &"Safe Fix")?;
visitor.record_diff(&self.code_action)
}
}
#[derive(Debug)]
struct LintVerboseAdvices {
path: String,
}
impl Advices for LintVerboseAdvices {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
visitor.record_log(LogCategory::Info, &"Apply this fix using `--apply`:")?;
visitor.record_command(&format!("rome check --apply {}", self.path))
}
}
pub fn main() {
const SOURCE: &str = "const FOO = \"FOO\";
console.log(FOO);";
const FIXED: &str = "console.log(\"FOO\");";
let diag = LintDiagnostic {
path: String::from("style/noShoutyConstants.js"),
span: TextRange::at(TextSize::from(31), TextSize::from(3)),
source_code: String::from(SOURCE),
advices: LintAdvices {
path: String::from("style/noShoutyConstants.js"),
declaration_span: TextRange::at(TextSize::from(6), TextSize::from(3)),
source_code: String::from(SOURCE),
code_action: TextEdit::from_unicode_words(SOURCE, FIXED),
},
verbose_advices: LintVerboseAdvices {
path: String::from("style/noShoutyConstants.js"),
},
};
EnvConsole::default().error(markup!({ PrintDiagnostic::verbose(&diag) }));
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/xtask/libs_bench/bins/contains_iai.rs | xtask/libs_bench/bins/contains_iai.rs | use regex::Regex;
use std::{collections::HashMap, process::Command};
fn main() {
let result = Command::new("cargo")
.args(["bench", "-p", "xtask_libs_bench"])
.output();
let re = Regex::new(r#"(?P<NAME>\w*?)\s*Instructions:\s*(?P<INST>\d*).*\n\s*L1 Accesses:\s*(?P<L1>\d*).*\n\s*L2 Accesses:\s*(?P<L2>\d*).*\n\s*RAM Accesses:\s*(?P<RAM>\d*).*\n\s*Estimated Cycles:\s*(?P<CYCLES>\d*).*"#).unwrap();
let stdout = String::from_utf8(result.unwrap().stdout).unwrap();
let mut tests: HashMap<&str, (isize, isize, isize, isize, isize)> = HashMap::new();
for capture in re.captures_iter(stdout.as_str()) {
let name = capture.name("NAME").unwrap().as_str();
let inst = capture.name("INST").unwrap().as_str().parse().unwrap();
let l1 = capture.name("L1").unwrap().as_str().parse().unwrap();
let l2 = capture.name("L2").unwrap().as_str().parse().unwrap();
let ram = capture.name("RAM").unwrap().as_str().parse().unwrap();
let cycles = capture.name("CYCLES").unwrap().as_str().parse().unwrap();
tests.insert(name, (inst, l1, l2, ram, cycles));
}
for (k, v_setup) in tests.iter() {
if let Some(name) = k.strip_suffix("_setup") {
let v_all = tests[name];
println!("{}", name);
println!(
"\tdiff inst: {} is {} - {}",
v_all.0 - v_setup.0,
v_all.0,
v_setup.0
);
println!(
"\tdiff l1: {} is {} - {}",
v_all.1 - v_setup.1,
v_all.1,
v_setup.1
);
println!(
"\tdiff l2: {} is {} - {}",
v_all.2 - v_setup.2,
v_all.2,
v_setup.2
);
println!(
"\tdiff ram: {} is {} - {}",
v_all.3 - v_setup.3,
v_all.3,
v_setup.3
);
println!(
"\tdiff cycles: {} is {} - {}",
v_all.4 - v_setup.4,
v_all.4,
v_setup.4
);
}
}
}
| 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.