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_console/tests/markup/closing_element_mismatch.rs | crates/rome_console/tests/markup/closing_element_mismatch.rs | fn main() {
rome_console::markup! {
<Emphasis></Error>
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/markup/open_element_missing_prop_value.rs | crates/rome_console/tests/markup/open_element_missing_prop_value.rs | fn main() {
rome_console::markup! {
<Emphasis property />
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/markup/open_element_unfinished_7.rs | crates/rome_console/tests/markup/open_element_unfinished_7.rs | fn main() {
rome_console::markup! {
<Emphasis prop=""
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/markup/invalid_punct.rs | crates/rome_console/tests/markup/invalid_punct.rs | fn main() {
rome_console::markup! {
!
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/markup/open_element_unfinished_1.rs | crates/rome_console/tests/markup/open_element_unfinished_1.rs | fn main() {
rome_console::markup! {
<
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_console/tests/markup/closing_element_standalone.rs | crates/rome_console/tests/markup/closing_element_standalone.rs | fn main() {
rome_console::markup! {
</Emphasis>
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_unicode_table/src/bytes.rs | crates/rome_js_unicode_table/src/bytes.rs | use Dispatch::*;
/// Every handler a byte coming in could be mapped to
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum Dispatch {
/// Error token
ERR,
/// Whitespace
WHS,
/// Exclamation
EXL,
/// Single `'` or Double quote `"`
QOT,
/// ASCII identifier, or `$`, `_`
IDT,
/// Hash `#`
HAS,
/// Percentage `%`
PRC,
/// Ampersand `&`
AMP,
/// Left paren `(`
PNO,
/// Right paren `)`
PNC,
/// Multiply `*`
MUL,
/// Plus `+`
PLS,
/// Comma `,`
COM,
/// Minus `-`
MIN,
/// Dot `.`
PRD,
/// Slash `/`
SLH,
/// Zero 0
ZER,
/// Digit (1-9)
DIG,
/// Colon `:`
COL,
/// Semicolon `;`
SEM,
///`Less than `<`
LSS,
/// Equal `=`
EQL,
/// More than `>`
MOR,
/// Question `?`
QST,
/// At `@`
AT_,
/// Left bracket `[`
BTO,
/// Backslash `\`
BSL,
/// Right bracket `]`
BTC,
/// `^`
CRT,
/// Tick `
TPL,
/// Left curly bracket `{`
BEO,
/// Pipe `|`
PIP,
/// Right curly bracket `}`
BEC,
/// Tilde `~`
TLD,
/// Unicode range (non ASCII)
UNI,
}
// A lookup table mapping any incoming byte to a handler function
// This is taken from the ratel project lexer and modified
// FIXME: Should we ignore the first ascii control chars which are nearly never seen instead of returning Err?
pub(crate) static DISPATCHER: [Dispatch; 256] = [
//0 1 2 3 4 5 6 7 8 9 A B C D E F //
ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, WHS, WHS, WHS, WHS, WHS, ERR, ERR, // 0
ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, // 1
WHS, EXL, QOT, HAS, IDT, PRC, AMP, QOT, PNO, PNC, MUL, PLS, COM, MIN, PRD, SLH, // 2
ZER, DIG, DIG, DIG, DIG, DIG, DIG, DIG, DIG, DIG, COL, SEM, LSS, EQL, MOR, QST, // 3
AT_, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, // 4
IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, BTO, BSL, BTC, CRT, IDT, // 5
TPL, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, // 6
IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, BEO, PIP, BEC, TLD, ERR, // 7
UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, // 8
UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, // 9
UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, // A
UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, // B
UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, // C
UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, // D
UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, // E
UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, UNI, // F
];
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_unicode_table/src/lib.rs | crates/rome_js_unicode_table/src/lib.rs | use crate::bytes::DISPATCHER;
use crate::tables::derived_property::{ID_Continue, ID_Start};
mod bytes;
mod tables;
pub use crate::bytes::Dispatch;
/// Tests if `c` is a valid start of an identifier
#[inline]
pub fn is_id_start(c: char) -> bool {
c == '_' || c == '$' || ID_Start(c)
}
/// Tests if `c` is a valid continuation of an identifier.
#[inline]
pub fn is_id_continue(c: char) -> bool {
c == '$' || c == '\u{200d}' || c == '\u{200c}' || ID_Continue(c)
}
/// Check if `s` is a valid _JavaScript_ identifier.
/// Currently, it doesn't check escaped unicode chars.
///
/// ```
/// use rome_js_unicode_table::is_js_ident;
///
/// assert!(is_js_ident("id0"));
/// assert!(is_js_ident("$id$"));
/// assert!(is_js_ident("_id_"));
///
/// assert!(!is_js_ident("@"));
/// assert!(!is_js_ident("custom-id"));
/// assert!(!is_js_ident("0"));
/// ```
pub fn is_js_ident(s: &str) -> bool {
s.chars().enumerate().all(|(index, c)| {
if index == 0 {
is_id_start(c)
} else {
is_id_continue(c)
}
})
}
/// Looks up a byte in the lookup table.
#[inline]
pub fn lookup_byte(byte: u8) -> Dispatch {
// Safety: the lookup table maps all values of u8, so it's impossible for a u8 to be out of bounds
unsafe { *DISPATCHER.get_unchecked(byte as usize) }
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_unicode_table/src/tables.rs | crates/rome_js_unicode_table/src/tables.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
#![doc = r" Autogenerated file, do not edit by hand."]
#![doc = r" Run `cargo codegen unicode` and recommit this file when Unicode support has changed."]
#![allow(missing_docs, non_upper_case_globals, non_snake_case)]
fn bsearch_range_table(c: char, r: &[(char, char)]) -> bool {
use core::cmp::Ordering::{Equal, Greater, Less};
r.binary_search_by(|&(lo, hi)| {
if lo > c {
Greater
} else if hi < c {
Less
} else {
Equal
}
})
.is_ok()
}
pub mod derived_property {
pub const ID_Continue_table: &[(char, char)] = &[
('0', '9'),
('A', 'Z'),
('_', '_'),
('a', 'z'),
('ª', 'ª'),
('µ', 'µ'),
('·', '·'),
('º', 'º'),
('À', 'Ö'),
('Ø', 'ö'),
('ø', 'ˁ'),
('ˆ', 'ˑ'),
('ˠ', 'ˤ'),
('ˬ', 'ˬ'),
('ˮ', 'ˮ'),
('\u{300}', 'ʹ'),
('Ͷ', 'ͷ'),
('ͺ', 'ͽ'),
('Ϳ', 'Ϳ'),
('Ά', 'Ί'),
('Ό', 'Ό'),
('Ύ', 'Ρ'),
('Σ', 'ϵ'),
('Ϸ', 'ҁ'),
('\u{483}', '\u{487}'),
('Ҋ', 'ԯ'),
('Ա', 'Ֆ'),
('ՙ', 'ՙ'),
('ՠ', 'ֈ'),
('\u{591}', '\u{5bd}'),
('\u{5bf}', '\u{5bf}'),
('\u{5c1}', '\u{5c2}'),
('\u{5c4}', '\u{5c5}'),
('\u{5c7}', '\u{5c7}'),
('א', 'ת'),
('ׯ', 'ײ'),
('\u{610}', '\u{61a}'),
('ؠ', '٩'),
('ٮ', 'ۓ'),
('ە', '\u{6dc}'),
('\u{6df}', '\u{6e8}'),
('\u{6ea}', 'ۼ'),
('ۿ', 'ۿ'),
('ܐ', '\u{74a}'),
('ݍ', 'ޱ'),
('߀', 'ߵ'),
('ߺ', 'ߺ'),
('\u{7fd}', '\u{7fd}'),
('ࠀ', '\u{82d}'),
('ࡀ', '\u{85b}'),
('ࡠ', 'ࡪ'),
('ࡰ', 'ࢇ'),
('ࢉ', 'ࢎ'),
('\u{898}', '\u{8e1}'),
('\u{8e3}', '\u{963}'),
('०', '९'),
('ॱ', 'ঃ'),
('অ', 'ঌ'),
('এ', 'ঐ'),
('ও', 'ন'),
('প', 'র'),
('ল', 'ল'),
('শ', 'হ'),
('\u{9bc}', '\u{9c4}'),
('ে', 'ৈ'),
('ো', 'ৎ'),
('\u{9d7}', '\u{9d7}'),
('ড়', 'ঢ়'),
('য়', '\u{9e3}'),
('০', 'ৱ'),
('ৼ', 'ৼ'),
('\u{9fe}', '\u{9fe}'),
('\u{a01}', 'ਃ'),
('ਅ', 'ਊ'),
('ਏ', 'ਐ'),
('ਓ', 'ਨ'),
('ਪ', 'ਰ'),
('ਲ', 'ਲ਼'),
('ਵ', 'ਸ਼'),
('ਸ', 'ਹ'),
('\u{a3c}', '\u{a3c}'),
('ਾ', '\u{a42}'),
('\u{a47}', '\u{a48}'),
('\u{a4b}', '\u{a4d}'),
('\u{a51}', '\u{a51}'),
('ਖ਼', 'ੜ'),
('ਫ਼', 'ਫ਼'),
('੦', '\u{a75}'),
('\u{a81}', 'ઃ'),
('અ', 'ઍ'),
('એ', 'ઑ'),
('ઓ', 'ન'),
('પ', 'ર'),
('લ', 'ળ'),
('વ', 'હ'),
('\u{abc}', '\u{ac5}'),
('\u{ac7}', 'ૉ'),
('ો', '\u{acd}'),
('ૐ', 'ૐ'),
('ૠ', '\u{ae3}'),
('૦', '૯'),
('ૹ', '\u{aff}'),
('\u{b01}', 'ଃ'),
('ଅ', 'ଌ'),
('ଏ', 'ଐ'),
('ଓ', 'ନ'),
('ପ', 'ର'),
('ଲ', 'ଳ'),
('ଵ', 'ହ'),
('\u{b3c}', '\u{b44}'),
('େ', 'ୈ'),
('ୋ', '\u{b4d}'),
('\u{b55}', '\u{b57}'),
('ଡ଼', 'ଢ଼'),
('ୟ', '\u{b63}'),
('୦', '୯'),
('ୱ', 'ୱ'),
('\u{b82}', 'ஃ'),
('அ', 'ஊ'),
('எ', 'ஐ'),
('ஒ', 'க'),
('ங', 'ச'),
('ஜ', 'ஜ'),
('ஞ', 'ட'),
('ண', 'த'),
('ந', 'ப'),
('ம', 'ஹ'),
('\u{bbe}', 'ூ'),
('ெ', 'ை'),
('ொ', '\u{bcd}'),
('ௐ', 'ௐ'),
('\u{bd7}', '\u{bd7}'),
('௦', '௯'),
('\u{c00}', 'ఌ'),
('ఎ', 'ఐ'),
('ఒ', 'న'),
('ప', 'హ'),
('\u{c3c}', 'ౄ'),
('\u{c46}', '\u{c48}'),
('\u{c4a}', '\u{c4d}'),
('\u{c55}', '\u{c56}'),
('ౘ', 'ౚ'),
('ౝ', 'ౝ'),
('ౠ', '\u{c63}'),
('౦', '౯'),
('ಀ', 'ಃ'),
('ಅ', 'ಌ'),
('ಎ', 'ಐ'),
('ಒ', 'ನ'),
('ಪ', 'ಳ'),
('ವ', 'ಹ'),
('\u{cbc}', 'ೄ'),
('\u{cc6}', 'ೈ'),
('ೊ', '\u{ccd}'),
('\u{cd5}', '\u{cd6}'),
('ೝ', 'ೞ'),
('ೠ', '\u{ce3}'),
('೦', '೯'),
('ೱ', 'ೳ'),
('\u{d00}', 'ഌ'),
('എ', 'ഐ'),
('ഒ', '\u{d44}'),
('െ', 'ൈ'),
('ൊ', 'ൎ'),
('ൔ', '\u{d57}'),
('ൟ', '\u{d63}'),
('൦', '൯'),
('ൺ', 'ൿ'),
('\u{d81}', 'ඃ'),
('අ', 'ඖ'),
('ක', 'න'),
('ඳ', 'ර'),
('ල', 'ල'),
('ව', 'ෆ'),
('\u{dca}', '\u{dca}'),
('\u{dcf}', '\u{dd4}'),
('\u{dd6}', '\u{dd6}'),
('ෘ', '\u{ddf}'),
('෦', '෯'),
('ෲ', 'ෳ'),
('ก', '\u{e3a}'),
('เ', '\u{e4e}'),
('๐', '๙'),
('ກ', 'ຂ'),
('ຄ', 'ຄ'),
('ຆ', 'ຊ'),
('ຌ', 'ຣ'),
('ລ', 'ລ'),
('ວ', 'ຽ'),
('ເ', 'ໄ'),
('ໆ', 'ໆ'),
('\u{ec8}', '\u{ece}'),
('໐', '໙'),
('ໜ', 'ໟ'),
('ༀ', 'ༀ'),
('\u{f18}', '\u{f19}'),
('༠', '༩'),
('\u{f35}', '\u{f35}'),
('\u{f37}', '\u{f37}'),
('\u{f39}', '\u{f39}'),
('༾', 'ཇ'),
('ཉ', 'ཬ'),
('\u{f71}', '\u{f84}'),
('\u{f86}', '\u{f97}'),
('\u{f99}', '\u{fbc}'),
('\u{fc6}', '\u{fc6}'),
('က', '၉'),
('ၐ', '\u{109d}'),
('Ⴀ', 'Ⴥ'),
('Ⴧ', 'Ⴧ'),
('Ⴭ', 'Ⴭ'),
('ა', 'ჺ'),
('ჼ', 'ቈ'),
('ቊ', 'ቍ'),
('ቐ', 'ቖ'),
('ቘ', 'ቘ'),
('ቚ', 'ቝ'),
('በ', 'ኈ'),
('ኊ', 'ኍ'),
('ነ', 'ኰ'),
('ኲ', 'ኵ'),
('ኸ', 'ኾ'),
('ዀ', 'ዀ'),
('ዂ', 'ዅ'),
('ወ', 'ዖ'),
('ዘ', 'ጐ'),
('ጒ', 'ጕ'),
('ጘ', 'ፚ'),
('\u{135d}', '\u{135f}'),
('፩', '፱'),
('ᎀ', 'ᎏ'),
('Ꭰ', 'Ᏽ'),
('ᏸ', 'ᏽ'),
('ᐁ', 'ᙬ'),
('ᙯ', 'ᙿ'),
('ᚁ', 'ᚚ'),
('ᚠ', 'ᛪ'),
('ᛮ', 'ᛸ'),
('ᜀ', '᜕'),
('ᜟ', '᜴'),
('ᝀ', '\u{1753}'),
('ᝠ', 'ᝬ'),
('ᝮ', 'ᝰ'),
('\u{1772}', '\u{1773}'),
('ក', '\u{17d3}'),
('ៗ', 'ៗ'),
('ៜ', '\u{17dd}'),
('០', '៩'),
('\u{180b}', '\u{180d}'),
('\u{180f}', '᠙'),
('ᠠ', 'ᡸ'),
('ᢀ', 'ᢪ'),
('ᢰ', 'ᣵ'),
('ᤀ', 'ᤞ'),
('\u{1920}', 'ᤫ'),
('ᤰ', '\u{193b}'),
('᥆', 'ᥭ'),
('ᥰ', 'ᥴ'),
('ᦀ', 'ᦫ'),
('ᦰ', 'ᧉ'),
('᧐', '᧚'),
('ᨀ', '\u{1a1b}'),
('ᨠ', '\u{1a5e}'),
('\u{1a60}', '\u{1a7c}'),
('\u{1a7f}', '᪉'),
('᪐', '᪙'),
('ᪧ', 'ᪧ'),
('\u{1ab0}', '\u{1abd}'),
('\u{1abf}', '\u{1ace}'),
('\u{1b00}', 'ᭌ'),
('᭐', '᭙'),
('\u{1b6b}', '\u{1b73}'),
('\u{1b80}', '᯳'),
('ᰀ', '\u{1c37}'),
('᱀', '᱉'),
('ᱍ', 'ᱽ'),
('ᲀ', 'ᲈ'),
('Ა', 'Ჺ'),
('Ჽ', 'Ჿ'),
('\u{1cd0}', '\u{1cd2}'),
('\u{1cd4}', 'ᳺ'),
('ᴀ', 'ἕ'),
('Ἐ', 'Ἕ'),
('ἠ', 'ὅ'),
('Ὀ', 'Ὅ'),
('ὐ', 'ὗ'),
('Ὑ', 'Ὑ'),
('Ὓ', 'Ὓ'),
('Ὕ', 'Ὕ'),
('Ὗ', 'ώ'),
('ᾀ', 'ᾴ'),
('ᾶ', 'ᾼ'),
('ι', 'ι'),
('ῂ', 'ῄ'),
('ῆ', 'ῌ'),
('ῐ', 'ΐ'),
('ῖ', 'Ί'),
('ῠ', 'Ῥ'),
('ῲ', 'ῴ'),
('ῶ', 'ῼ'),
('‿', '⁀'),
('⁔', '⁔'),
('ⁱ', 'ⁱ'),
('ⁿ', 'ⁿ'),
('ₐ', 'ₜ'),
('\u{20d0}', '\u{20dc}'),
('\u{20e1}', '\u{20e1}'),
('\u{20e5}', '\u{20f0}'),
('ℂ', 'ℂ'),
('ℇ', 'ℇ'),
('ℊ', 'ℓ'),
('ℕ', 'ℕ'),
('℘', 'ℝ'),
('ℤ', 'ℤ'),
('Ω', 'Ω'),
('ℨ', 'ℨ'),
('K', 'ℹ'),
('ℼ', 'ℿ'),
('ⅅ', 'ⅉ'),
('ⅎ', 'ⅎ'),
('Ⅰ', 'ↈ'),
('Ⰰ', 'ⳤ'),
('Ⳬ', 'ⳳ'),
('ⴀ', 'ⴥ'),
('ⴧ', 'ⴧ'),
('ⴭ', 'ⴭ'),
('ⴰ', 'ⵧ'),
('ⵯ', 'ⵯ'),
('\u{2d7f}', 'ⶖ'),
('ⶠ', 'ⶦ'),
('ⶨ', 'ⶮ'),
('ⶰ', 'ⶶ'),
('ⶸ', 'ⶾ'),
('ⷀ', 'ⷆ'),
('ⷈ', 'ⷎ'),
('ⷐ', 'ⷖ'),
('ⷘ', 'ⷞ'),
('\u{2de0}', '\u{2dff}'),
('々', '〇'),
('〡', '\u{302f}'),
('〱', '〵'),
('〸', '〼'),
('ぁ', 'ゖ'),
('\u{3099}', 'ゟ'),
('ァ', 'ヺ'),
('ー', 'ヿ'),
('ㄅ', 'ㄯ'),
('ㄱ', 'ㆎ'),
('ㆠ', 'ㆿ'),
('ㇰ', 'ㇿ'),
('㐀', '䶿'),
('一', 'ꒌ'),
('ꓐ', 'ꓽ'),
('ꔀ', 'ꘌ'),
('ꘐ', 'ꘫ'),
('Ꙁ', '\u{a66f}'),
('\u{a674}', '\u{a67d}'),
('ꙿ', '\u{a6f1}'),
('ꜗ', 'ꜟ'),
('Ꜣ', 'ꞈ'),
('Ꞌ', 'ꟊ'),
('Ꟑ', 'ꟑ'),
('ꟓ', 'ꟓ'),
('ꟕ', 'ꟙ'),
('ꟲ', 'ꠧ'),
('\u{a82c}', '\u{a82c}'),
('ꡀ', 'ꡳ'),
('ꢀ', '\u{a8c5}'),
('꣐', '꣙'),
('\u{a8e0}', 'ꣷ'),
('ꣻ', 'ꣻ'),
('ꣽ', '\u{a92d}'),
('ꤰ', '꥓'),
('ꥠ', 'ꥼ'),
('\u{a980}', '꧀'),
('ꧏ', '꧙'),
('ꧠ', 'ꧾ'),
('ꨀ', '\u{aa36}'),
('ꩀ', 'ꩍ'),
('꩐', '꩙'),
('ꩠ', 'ꩶ'),
('ꩺ', 'ꫂ'),
('ꫛ', 'ꫝ'),
('ꫠ', 'ꫯ'),
('ꫲ', '\u{aaf6}'),
('ꬁ', 'ꬆ'),
('ꬉ', 'ꬎ'),
('ꬑ', 'ꬖ'),
('ꬠ', 'ꬦ'),
('ꬨ', 'ꬮ'),
('ꬰ', 'ꭚ'),
('ꭜ', 'ꭩ'),
('ꭰ', 'ꯪ'),
('꯬', '\u{abed}'),
('꯰', '꯹'),
('가', '힣'),
('ힰ', 'ퟆ'),
('ퟋ', 'ퟻ'),
('豈', '舘'),
('並', '龎'),
('ff', 'st'),
('ﬓ', 'ﬗ'),
('יִ', 'ﬨ'),
('שׁ', 'זּ'),
('טּ', 'לּ'),
('מּ', 'מּ'),
('נּ', 'סּ'),
('ףּ', 'פּ'),
('צּ', 'ﮱ'),
('ﯓ', 'ﴽ'),
('ﵐ', 'ﶏ'),
('ﶒ', 'ﷇ'),
('ﷰ', 'ﷻ'),
('\u{fe00}', '\u{fe0f}'),
('\u{fe20}', '\u{fe2f}'),
('︳', '︴'),
('﹍', '﹏'),
('ﹰ', 'ﹴ'),
('ﹶ', 'ﻼ'),
('0', '9'),
('A', 'Z'),
('_', '_'),
('a', 'z'),
('ヲ', 'ᄒ'),
('ᅡ', 'ᅦ'),
('ᅧ', 'ᅬ'),
('ᅭ', 'ᅲ'),
('ᅳ', 'ᅵ'),
('𐀀', '𐀋'),
('𐀍', '𐀦'),
('𐀨', '𐀺'),
('𐀼', '𐀽'),
('𐀿', '𐁍'),
('𐁐', '𐁝'),
('𐂀', '𐃺'),
('𐅀', '𐅴'),
('\u{101fd}', '\u{101fd}'),
('𐊀', '𐊜'),
('𐊠', '𐋐'),
('\u{102e0}', '\u{102e0}'),
('𐌀', '𐌟'),
('𐌭', '𐍊'),
('𐍐', '\u{1037a}'),
('𐎀', '𐎝'),
('𐎠', '𐏃'),
('𐏈', '𐏏'),
('𐏑', '𐏕'),
('𐐀', '𐒝'),
('𐒠', '𐒩'),
('𐒰', '𐓓'),
('𐓘', '𐓻'),
('𐔀', '𐔧'),
('𐔰', '𐕣'),
('𐕰', '𐕺'),
('𐕼', '𐖊'),
('𐖌', '𐖒'),
('𐖔', '𐖕'),
('𐖗', '𐖡'),
('𐖣', '𐖱'),
('𐖳', '𐖹'),
('𐖻', '𐖼'),
('𐘀', '𐜶'),
('𐝀', '𐝕'),
('𐝠', '𐝧'),
('𐞀', '𐞅'),
('𐞇', '𐞰'),
('𐞲', '𐞺'),
('𐠀', '𐠅'),
('𐠈', '𐠈'),
('𐠊', '𐠵'),
('𐠷', '𐠸'),
('𐠼', '𐠼'),
('𐠿', '𐡕'),
('𐡠', '𐡶'),
('𐢀', '𐢞'),
('𐣠', '𐣲'),
('𐣴', '𐣵'),
('𐤀', '𐤕'),
('𐤠', '𐤹'),
('𐦀', '𐦷'),
('𐦾', '𐦿'),
('𐨀', '\u{10a03}'),
('\u{10a05}', '\u{10a06}'),
('\u{10a0c}', '𐨓'),
('𐨕', '𐨗'),
('𐨙', '𐨵'),
('\u{10a38}', '\u{10a3a}'),
('\u{10a3f}', '\u{10a3f}'),
('𐩠', '𐩼'),
('𐪀', '𐪜'),
('𐫀', '𐫇'),
('𐫉', '\u{10ae6}'),
('𐬀', '𐬵'),
('𐭀', '𐭕'),
('𐭠', '𐭲'),
('𐮀', '𐮑'),
('𐰀', '𐱈'),
('𐲀', '𐲲'),
('𐳀', '𐳲'),
('𐴀', '\u{10d27}'),
('𐴰', '𐴹'),
('𐺀', '𐺩'),
('\u{10eab}', '\u{10eac}'),
('𐺰', '𐺱'),
('\u{10efd}', '𐼜'),
('𐼧', '𐼧'),
('𐼰', '\u{10f50}'),
('𐽰', '\u{10f85}'),
('𐾰', '𐿄'),
('𐿠', '𐿶'),
('𑀀', '\u{11046}'),
('𑁦', '𑁵'),
('\u{1107f}', '\u{110ba}'),
('\u{110c2}', '\u{110c2}'),
('𑃐', '𑃨'),
('𑃰', '𑃹'),
('\u{11100}', '\u{11134}'),
('𑄶', '𑄿'),
('𑅄', '𑅇'),
('𑅐', '\u{11173}'),
('𑅶', '𑅶'),
('\u{11180}', '𑇄'),
('\u{111c9}', '\u{111cc}'),
('𑇎', '𑇚'),
('𑇜', '𑇜'),
('𑈀', '𑈑'),
('𑈓', '\u{11237}'),
('\u{1123e}', '\u{11241}'),
('𑊀', '𑊆'),
('𑊈', '𑊈'),
('𑊊', '𑊍'),
('𑊏', '𑊝'),
('𑊟', '𑊨'),
('𑊰', '\u{112ea}'),
('𑋰', '𑋹'),
('\u{11300}', '𑌃'),
('𑌅', '𑌌'),
('𑌏', '𑌐'),
('𑌓', '𑌨'),
('𑌪', '𑌰'),
('𑌲', '𑌳'),
('𑌵', '𑌹'),
('\u{1133b}', '𑍄'),
('𑍇', '𑍈'),
('𑍋', '𑍍'),
('𑍐', '𑍐'),
('\u{11357}', '\u{11357}'),
('𑍝', '𑍣'),
('\u{11366}', '\u{1136c}'),
('\u{11370}', '\u{11374}'),
('𑐀', '𑑊'),
('𑑐', '𑑙'),
('\u{1145e}', '𑑡'),
('𑒀', '𑓅'),
('𑓇', '𑓇'),
('𑓐', '𑓙'),
('𑖀', '\u{115b5}'),
('𑖸', '\u{115c0}'),
('𑗘', '\u{115dd}'),
('𑘀', '\u{11640}'),
('𑙄', '𑙄'),
('𑙐', '𑙙'),
('𑚀', '𑚸'),
('𑛀', '𑛉'),
('𑜀', '𑜚'),
('\u{1171d}', '\u{1172b}'),
('𑜰', '𑜹'),
('𑝀', '𑝆'),
('𑠀', '\u{1183a}'),
('𑢠', '𑣩'),
('𑣿', '𑤆'),
('𑤉', '𑤉'),
('𑤌', '𑤓'),
('𑤕', '𑤖'),
('𑤘', '𑤵'),
('𑤷', '𑤸'),
('\u{1193b}', '\u{11943}'),
('𑥐', '𑥙'),
('𑦠', '𑦧'),
('𑦪', '\u{119d7}'),
('\u{119da}', '𑧡'),
('𑧣', '𑧤'),
('𑨀', '\u{11a3e}'),
('\u{11a47}', '\u{11a47}'),
('𑩐', '\u{11a99}'),
('𑪝', '𑪝'),
('𑪰', '𑫸'),
('𑰀', '𑰈'),
('𑰊', '\u{11c36}'),
('\u{11c38}', '𑱀'),
('𑱐', '𑱙'),
('𑱲', '𑲏'),
('\u{11c92}', '\u{11ca7}'),
('𑲩', '\u{11cb6}'),
('𑴀', '𑴆'),
('𑴈', '𑴉'),
('𑴋', '\u{11d36}'),
('\u{11d3a}', '\u{11d3a}'),
('\u{11d3c}', '\u{11d3d}'),
('\u{11d3f}', '\u{11d47}'),
('𑵐', '𑵙'),
('𑵠', '𑵥'),
('𑵧', '𑵨'),
('𑵪', '𑶎'),
('\u{11d90}', '\u{11d91}'),
('𑶓', '𑶘'),
('𑶠', '𑶩'),
('𑻠', '𑻶'),
('\u{11f00}', '𑼐'),
('𑼒', '\u{11f3a}'),
('𑼾', '\u{11f42}'),
('𑽐', '𑽙'),
('𑾰', '𑾰'),
('𒀀', '𒎙'),
('𒐀', '𒑮'),
('𒒀', '𒕃'),
('𒾐', '𒿰'),
('𓀀', '𓐯'),
('\u{13440}', '\u{13455}'),
('𔐀', '𔙆'),
('𖠀', '𖨸'),
('𖩀', '𖩞'),
('𖩠', '𖩩'),
('𖩰', '𖪾'),
('𖫀', '𖫉'),
('𖫐', '𖫭'),
('\u{16af0}', '\u{16af4}'),
('𖬀', '\u{16b36}'),
('𖭀', '𖭃'),
('𖭐', '𖭙'),
('𖭣', '𖭷'),
('𖭽', '𖮏'),
('𖹀', '𖹿'),
('𖼀', '𖽊'),
('\u{16f4f}', '𖾇'),
('\u{16f8f}', '𖾟'),
('𖿠', '𖿡'),
('𖿣', '\u{16fe4}'),
('𖿰', '𖿱'),
('𗀀', '𘟷'),
('𘠀', '𘳕'),
('𘴀', '𘴈'),
('𚿰', '𚿳'),
('𚿵', '𚿻'),
('𚿽', '𚿾'),
('𛀀', '𛄢'),
('𛄲', '𛄲'),
('𛅐', '𛅒'),
('𛅕', '𛅕'),
('𛅤', '𛅧'),
('𛅰', '𛋻'),
('𛰀', '𛱪'),
('𛱰', '𛱼'),
('𛲀', '𛲈'),
('𛲐', '𛲙'),
('\u{1bc9d}', '\u{1bc9e}'),
('\u{1cf00}', '\u{1cf2d}'),
('\u{1cf30}', '\u{1cf46}'),
('\u{1d165}', '\u{1d169}'),
('𝅭', '\u{1d172}'),
('\u{1d17b}', '\u{1d182}'),
('\u{1d185}', '\u{1d18b}'),
('\u{1d1aa}', '\u{1d1ad}'),
('\u{1d242}', '\u{1d244}'),
('𝐀', '𝑔'),
('𝑖', '𝒜'),
('𝒞', '𝒟'),
('𝒢', '𝒢'),
('𝒥', '𝒦'),
('𝒩', '𝒬'),
('𝒮', '𝒹'),
('𝒻', '𝒻'),
('𝒽', '𝓃'),
('𝓅', '𝔅'),
('𝔇', '𝔊'),
('𝔍', '𝔔'),
('𝔖', '𝔜'),
('𝔞', '𝔹'),
('𝔻', '𝔾'),
('𝕀', '𝕄'),
('𝕆', '𝕆'),
('𝕊', '𝕐'),
('𝕒', '𝚥'),
('𝚨', '𝛀'),
('𝛂', '𝛚'),
('𝛜', '𝛺'),
('𝛼', '𝜔'),
('𝜖', '𝜴'),
('𝜶', '𝝎'),
('𝝐', '𝝮'),
('𝝰', '𝞈'),
('𝞊', '𝞨'),
('𝞪', '𝟂'),
('𝟄', '𝟋'),
('𝟎', '𝟿'),
('\u{1da00}', '\u{1da36}'),
('\u{1da3b}', '\u{1da6c}'),
('\u{1da75}', '\u{1da75}'),
('\u{1da84}', '\u{1da84}'),
('\u{1da9b}', '\u{1da9f}'),
('\u{1daa1}', '\u{1daaf}'),
('𝼀', '𝼞'),
('𝼥', '𝼪'),
('\u{1e000}', '\u{1e006}'),
('\u{1e008}', '\u{1e018}'),
('\u{1e01b}', '\u{1e021}'),
('\u{1e023}', '\u{1e024}'),
('\u{1e026}', '\u{1e02a}'),
('𞀰', '𞁭'),
('\u{1e08f}', '\u{1e08f}'),
('𞄀', '𞄬'),
('\u{1e130}', '𞄽'),
('𞅀', '𞅉'),
('𞅎', '𞅎'),
('𞊐', '\u{1e2ae}'),
('𞋀', '𞋹'),
('𞓐', '𞓹'),
('𞟠', '𞟦'),
('𞟨', '𞟫'),
('𞟭', '𞟮'),
('𞟰', '𞟾'),
('𞠀', '𞣄'),
('\u{1e8d0}', '\u{1e8d6}'),
('𞤀', '𞥋'),
('𞥐', '𞥙'),
('𞸀', '𞸃'),
('𞸅', '𞸟'),
('𞸡', '𞸢'),
('𞸤', '𞸤'),
('𞸧', '𞸧'),
('𞸩', '𞸲'),
('𞸴', '𞸷'),
('𞸹', '𞸹'),
('𞸻', '𞸻'),
('𞹂', '𞹂'),
('𞹇', '𞹇'),
('𞹉', '𞹉'),
('𞹋', '𞹋'),
('𞹍', '𞹏'),
('𞹑', '𞹒'),
('𞹔', '𞹔'),
('𞹗', '𞹗'),
('𞹙', '𞹙'),
('𞹛', '𞹛'),
('𞹝', '𞹝'),
('𞹟', '𞹟'),
('𞹡', '𞹢'),
('𞹤', '𞹤'),
('𞹧', '𞹪'),
('𞹬', '𞹲'),
('𞹴', '𞹷'),
('𞹹', '𞹼'),
('𞹾', '𞹾'),
('𞺀', '𞺉'),
('𞺋', '𞺛'),
('𞺡', '𞺣'),
('𞺥', '𞺩'),
('𞺫', '𞺻'),
('🯰', '🯹'),
('𠀀', '𪛟'),
('𪜀', '𫜹'),
('𫝀', '𫠝'),
('𫠠', '𬺡'),
('𬺰', '𮯠'),
('丽', '𪘀'),
('𰀀', '𱍊'),
('𱍐', '𲎯'),
('\u{e0100}', '\u{e01ef}'),
];
pub fn ID_Continue(c: char) -> bool {
super::bsearch_range_table(c, ID_Continue_table)
}
pub const ID_Start_table: &[(char, char)] = &[
('A', 'Z'),
('a', 'z'),
('ª', 'ª'),
('µ', 'µ'),
('º', 'º'),
('À', 'Ö'),
('Ø', 'ö'),
('ø', 'ˁ'),
('ˆ', 'ˑ'),
('ˠ', 'ˤ'),
('ˬ', 'ˬ'),
('ˮ', 'ˮ'),
('Ͱ', 'ʹ'),
('Ͷ', 'ͷ'),
('ͺ', 'ͽ'),
('Ϳ', 'Ϳ'),
('Ά', 'Ά'),
('Έ', 'Ί'),
('Ό', 'Ό'),
('Ύ', 'Ρ'),
('Σ', 'ϵ'),
('Ϸ', 'ҁ'),
('Ҋ', 'ԯ'),
('Ա', 'Ֆ'),
('ՙ', 'ՙ'),
('ՠ', 'ֈ'),
('א', 'ת'),
('ׯ', 'ײ'),
('ؠ', 'ي'),
('ٮ', 'ٯ'),
('ٱ', 'ۓ'),
('ە', 'ە'),
('ۥ', 'ۦ'),
('ۮ', 'ۯ'),
('ۺ', 'ۼ'),
('ۿ', 'ۿ'),
('ܐ', 'ܐ'),
('ܒ', 'ܯ'),
('ݍ', 'ޥ'),
('ޱ', 'ޱ'),
('ߊ', 'ߪ'),
('ߴ', 'ߵ'),
('ߺ', 'ߺ'),
('ࠀ', 'ࠕ'),
('ࠚ', 'ࠚ'),
('ࠤ', 'ࠤ'),
('ࠨ', 'ࠨ'),
('ࡀ', 'ࡘ'),
('ࡠ', 'ࡪ'),
('ࡰ', 'ࢇ'),
('ࢉ', 'ࢎ'),
('ࢠ', 'ࣉ'),
('ऄ', 'ह'),
('ऽ', 'ऽ'),
('ॐ', 'ॐ'),
('क़', 'ॡ'),
('ॱ', 'ঀ'),
('অ', 'ঌ'),
('এ', 'ঐ'),
('ও', 'ন'),
('প', 'র'),
('ল', 'ল'),
('শ', 'হ'),
('ঽ', 'ঽ'),
('ৎ', 'ৎ'),
('ড়', 'ঢ়'),
('য়', 'ৡ'),
('ৰ', 'ৱ'),
('ৼ', 'ৼ'),
('ਅ', 'ਊ'),
('ਏ', 'ਐ'),
('ਓ', 'ਨ'),
('ਪ', 'ਰ'),
('ਲ', 'ਲ਼'),
('ਵ', 'ਸ਼'),
('ਸ', 'ਹ'),
('ਖ਼', 'ੜ'),
('ਫ਼', 'ਫ਼'),
('ੲ', 'ੴ'),
('અ', 'ઍ'),
('એ', 'ઑ'),
('ઓ', 'ન'),
('પ', 'ર'),
('લ', 'ળ'),
('વ', 'હ'),
('ઽ', 'ઽ'),
('ૐ', 'ૐ'),
('ૠ', 'ૡ'),
('ૹ', 'ૹ'),
('ଅ', 'ଌ'),
('ଏ', 'ଐ'),
('ଓ', 'ନ'),
('ପ', 'ର'),
('ଲ', 'ଳ'),
('ଵ', 'ହ'),
('ଽ', 'ଽ'),
('ଡ଼', 'ଢ଼'),
('ୟ', 'ୡ'),
('ୱ', 'ୱ'),
('ஃ', 'ஃ'),
('அ', 'ஊ'),
('எ', 'ஐ'),
('ஒ', 'க'),
('ங', 'ச'),
('ஜ', 'ஜ'),
('ஞ', 'ட'),
('ண', 'த'),
('ந', 'ப'),
('ம', 'ஹ'),
('ௐ', 'ௐ'),
('అ', 'ఌ'),
('ఎ', 'ఐ'),
('ఒ', 'న'),
('ప', 'హ'),
('ఽ', 'ఽ'),
('ౘ', 'ౚ'),
('ౝ', 'ౝ'),
('ౠ', 'ౡ'),
('ಀ', 'ಀ'),
('ಅ', 'ಌ'),
('ಎ', 'ಐ'),
('ಒ', 'ನ'),
('ಪ', 'ಳ'),
('ವ', 'ಹ'),
('ಽ', 'ಽ'),
('ೝ', 'ೞ'),
('ೠ', 'ೡ'),
('ೱ', 'ೲ'),
('ഄ', 'ഌ'),
('എ', 'ഐ'),
('ഒ', 'ഺ'),
('ഽ', 'ഽ'),
('ൎ', 'ൎ'),
('ൔ', 'ൖ'),
('ൟ', 'ൡ'),
('ൺ', 'ൿ'),
('අ', 'ඖ'),
('ක', 'න'),
('ඳ', 'ර'),
('ල', 'ල'),
('ව', 'ෆ'),
('ก', 'ะ'),
('า', 'ำ'),
('เ', 'ๆ'),
('ກ', 'ຂ'),
('ຄ', 'ຄ'),
('ຆ', 'ຊ'),
('ຌ', 'ຣ'),
('ລ', 'ລ'),
('ວ', 'ະ'),
('າ', 'ຳ'),
('ຽ', 'ຽ'),
('ເ', 'ໄ'),
('ໆ', 'ໆ'),
('ໜ', 'ໟ'),
('ༀ', 'ༀ'),
('ཀ', 'ཇ'),
('ཉ', 'ཬ'),
('ྈ', 'ྌ'),
('က', 'ဪ'),
('ဿ', 'ဿ'),
('ၐ', 'ၕ'),
('ၚ', 'ၝ'),
('ၡ', 'ၡ'),
('ၥ', 'ၦ'),
('ၮ', 'ၰ'),
('ၵ', 'ႁ'),
('ႎ', 'ႎ'),
('Ⴀ', 'Ⴥ'),
('Ⴧ', 'Ⴧ'),
('Ⴭ', 'Ⴭ'),
('ა', 'ჺ'),
('ჼ', 'ቈ'),
('ቊ', 'ቍ'),
('ቐ', 'ቖ'),
('ቘ', 'ቘ'),
('ቚ', 'ቝ'),
('በ', 'ኈ'),
('ኊ', 'ኍ'),
('ነ', 'ኰ'),
('ኲ', 'ኵ'),
('ኸ', 'ኾ'),
('ዀ', 'ዀ'),
('ዂ', 'ዅ'),
('ወ', 'ዖ'),
('ዘ', 'ጐ'),
('ጒ', 'ጕ'),
('ጘ', 'ፚ'),
('ᎀ', 'ᎏ'),
('Ꭰ', 'Ᏽ'),
('ᏸ', 'ᏽ'),
('ᐁ', 'ᙬ'),
('ᙯ', 'ᙿ'),
('ᚁ', 'ᚚ'),
('ᚠ', 'ᛪ'),
('ᛮ', 'ᛸ'),
('ᜀ', 'ᜑ'),
('ᜟ', 'ᜱ'),
('ᝀ', 'ᝑ'),
('ᝠ', 'ᝬ'),
('ᝮ', 'ᝰ'),
('ក', 'ឳ'),
('ៗ', 'ៗ'),
('ៜ', 'ៜ'),
('ᠠ', 'ᡸ'),
('ᢀ', 'ᢨ'),
('ᢪ', 'ᢪ'),
('ᢰ', 'ᣵ'),
('ᤀ', 'ᤞ'),
('ᥐ', 'ᥭ'),
('ᥰ', 'ᥴ'),
('ᦀ', 'ᦫ'),
('ᦰ', 'ᧉ'),
('ᨀ', 'ᨖ'),
('ᨠ', 'ᩔ'),
('ᪧ', 'ᪧ'),
('ᬅ', 'ᬳ'),
('ᭅ', 'ᭌ'),
('ᮃ', 'ᮠ'),
('ᮮ', 'ᮯ'),
('ᮺ', 'ᯥ'),
('ᰀ', 'ᰣ'),
('ᱍ', 'ᱏ'),
('ᱚ', 'ᱽ'),
('ᲀ', 'ᲈ'),
('Ა', 'Ჺ'),
('Ჽ', 'Ჿ'),
('ᳩ', 'ᳬ'),
('ᳮ', 'ᳳ'),
('ᳵ', 'ᳶ'),
('ᳺ', 'ᳺ'),
('ᴀ', 'ᶿ'),
('Ḁ', 'ἕ'),
('Ἐ', 'Ἕ'),
('ἠ', 'ὅ'),
('Ὀ', 'Ὅ'),
('ὐ', 'ὗ'),
('Ὑ', 'Ὑ'),
('Ὓ', 'Ὓ'),
('Ὕ', 'Ὕ'),
('Ὗ', 'ώ'),
('ᾀ', 'ᾴ'),
('ᾶ', 'ᾼ'),
('ι', 'ι'),
('ῂ', 'ῄ'),
('ῆ', 'ῌ'),
('ῐ', 'ΐ'),
('ῖ', 'Ί'),
('ῠ', 'Ῥ'),
('ῲ', 'ῴ'),
('ῶ', 'ῼ'),
('ⁱ', 'ⁱ'),
('ⁿ', 'ⁿ'),
('ₐ', 'ₜ'),
('ℂ', 'ℂ'),
('ℇ', 'ℇ'),
('ℊ', 'ℓ'),
('ℕ', 'ℕ'),
('℘', 'ℝ'),
('ℤ', 'ℤ'),
('Ω', 'Ω'),
('ℨ', 'ℨ'),
('K', 'ℹ'),
('ℼ', 'ℿ'),
('ⅅ', 'ⅉ'),
('ⅎ', 'ⅎ'),
('Ⅰ', 'ↈ'),
('Ⰰ', 'ⳤ'),
('Ⳬ', 'ⳮ'),
('Ⳳ', 'ⳳ'),
('ⴀ', 'ⴥ'),
('ⴧ', 'ⴧ'),
('ⴭ', 'ⴭ'),
('ⴰ', 'ⵧ'),
('ⵯ', 'ⵯ'),
('ⶀ', 'ⶖ'),
('ⶠ', 'ⶦ'),
('ⶨ', 'ⶮ'),
('ⶰ', 'ⶶ'),
('ⶸ', 'ⶾ'),
('ⷀ', 'ⷆ'),
('ⷈ', 'ⷎ'),
('ⷐ', 'ⷖ'),
('ⷘ', 'ⷞ'),
('々', '〇'),
('〡', '〩'),
('〱', '〵'),
('〸', '〼'),
('ぁ', 'ゖ'),
('゛', 'ゟ'),
('ァ', 'ヺ'),
('ー', 'ヿ'),
('ㄅ', 'ㄯ'),
('ㄱ', 'ㆎ'),
('ㆠ', 'ㆿ'),
('ㇰ', 'ㇿ'),
('㐀', '䶿'),
('一', 'ꒌ'),
('ꓐ', 'ꓽ'),
('ꔀ', 'ꘌ'),
('ꘐ', 'ꘟ'),
('ꘪ', 'ꘫ'),
('Ꙁ', 'ꙮ'),
('ꙿ', 'ꚝ'),
('ꚠ', 'ꛯ'),
('ꜗ', 'ꜟ'),
('Ꜣ', 'ꞈ'),
('Ꞌ', 'ꟊ'),
('Ꟑ', 'ꟑ'),
('ꟓ', 'ꟓ'),
('ꟕ', 'ꟙ'),
('ꟲ', 'ꠁ'),
('ꠃ', 'ꠅ'),
('ꠇ', 'ꠊ'),
('ꠌ', 'ꠢ'),
('ꡀ', 'ꡳ'),
('ꢂ', 'ꢳ'),
('ꣲ', 'ꣷ'),
('ꣻ', 'ꣻ'),
('ꣽ', 'ꣾ'),
('ꤊ', 'ꤥ'),
('ꤰ', 'ꥆ'),
('ꥠ', 'ꥼ'),
('ꦄ', 'ꦲ'),
('ꧏ', 'ꧏ'),
('ꧠ', 'ꧤ'),
('ꧦ', 'ꧯ'),
('ꧺ', 'ꧾ'),
('ꨀ', 'ꨨ'),
('ꩀ', 'ꩂ'),
('ꩄ', 'ꩋ'),
('ꩠ', 'ꩶ'),
('ꩺ', 'ꩺ'),
('ꩾ', 'ꪯ'),
('ꪱ', 'ꪱ'),
('ꪵ', 'ꪶ'),
('ꪹ', 'ꪽ'),
('ꫀ', 'ꫀ'),
('ꫂ', 'ꫂ'),
('ꫛ', 'ꫝ'),
('ꫠ', 'ꫪ'),
('ꫲ', 'ꫴ'),
('ꬁ', 'ꬆ'),
('ꬉ', 'ꬎ'),
('ꬑ', 'ꬖ'),
('ꬠ', 'ꬦ'),
('ꬨ', 'ꬮ'),
('ꬰ', 'ꭚ'),
('ꭜ', 'ꭩ'),
('ꭰ', 'ꯢ'),
('가', '힣'),
('ힰ', 'ퟆ'),
('ퟋ', 'ퟻ'),
('豈', '舘'),
('並', '龎'),
('ff', 'st'),
('ﬓ', 'ﬗ'),
('יִ', 'יִ'),
('ײַ', 'ﬨ'),
('שׁ', 'זּ'),
('טּ', 'לּ'),
('מּ', 'מּ'),
('נּ', 'סּ'),
('ףּ', 'פּ'),
('צּ', 'ﮱ'),
('ﯓ', 'ﴽ'),
('ﵐ', 'ﶏ'),
('ﶒ', 'ﷇ'),
('ﷰ', 'ﷻ'),
('ﹰ', 'ﹴ'),
('ﹶ', 'ﻼ'),
('A', 'Z'),
('a', 'z'),
('ヲ', 'ᄒ'),
('ᅡ', 'ᅦ'),
('ᅧ', 'ᅬ'),
('ᅭ', 'ᅲ'),
('ᅳ', 'ᅵ'),
('𐀀', '𐀋'),
('𐀍', '𐀦'),
('𐀨', '𐀺'),
('𐀼', '𐀽'),
('𐀿', '𐁍'),
('𐁐', '𐁝'),
('𐂀', '𐃺'),
('𐅀', '𐅴'),
('𐊀', '𐊜'),
('𐊠', '𐋐'),
('𐌀', '𐌟'),
('𐌭', '𐍊'),
('𐍐', '𐍵'),
('𐎀', '𐎝'),
('𐎠', '𐏃'),
('𐏈', '𐏏'),
('𐏑', '𐏕'),
('𐐀', '𐒝'),
('𐒰', '𐓓'),
('𐓘', '𐓻'),
('𐔀', '𐔧'),
('𐔰', '𐕣'),
('𐕰', '𐕺'),
('𐕼', '𐖊'),
('𐖌', '𐖒'),
('𐖔', '𐖕'),
('𐖗', '𐖡'),
('𐖣', '𐖱'),
('𐖳', '𐖹'),
('𐖻', '𐖼'),
('𐘀', '𐜶'),
('𐝀', '𐝕'),
('𐝠', '𐝧'),
('𐞀', '𐞅'),
('𐞇', '𐞰'),
('𐞲', '𐞺'),
('𐠀', '𐠅'),
('𐠈', '𐠈'),
('𐠊', '𐠵'),
('𐠷', '𐠸'),
('𐠼', '𐠼'),
('𐠿', '𐡕'),
('𐡠', '𐡶'),
('𐢀', '𐢞'),
('𐣠', '𐣲'),
('𐣴', '𐣵'),
('𐤀', '𐤕'),
('𐤠', '𐤹'),
('𐦀', '𐦷'),
('𐦾', '𐦿'),
('𐨀', '𐨀'),
('𐨐', '𐨓'),
('𐨕', '𐨗'),
('𐨙', '𐨵'),
('𐩠', '𐩼'),
('𐪀', '𐪜'),
('𐫀', '𐫇'),
('𐫉', '𐫤'),
('𐬀', '𐬵'),
('𐭀', '𐭕'),
('𐭠', '𐭲'),
('𐮀', '𐮑'),
('𐰀', '𐱈'),
('𐲀', '𐲲'),
('𐳀', '𐳲'),
('𐴀', '𐴣'),
('𐺀', '𐺩'),
('𐺰', '𐺱'),
('𐼀', '𐼜'),
('𐼧', '𐼧'),
('𐼰', '𐽅'),
('𐽰', '𐾁'),
('𐾰', '𐿄'),
('𐿠', '𐿶'),
('𑀃', '𑀷'),
('𑁱', '𑁲'),
('𑁵', '𑁵'),
('𑂃', '𑂯'),
('𑃐', '𑃨'),
('𑄃', '𑄦'),
('𑅄', '𑅄'),
('𑅇', '𑅇'),
('𑅐', '𑅲'),
('𑅶', '𑅶'),
('𑆃', '𑆲'),
('𑇁', '𑇄'),
('𑇚', '𑇚'),
('𑇜', '𑇜'),
('𑈀', '𑈑'),
('𑈓', '𑈫'),
('𑈿', '𑉀'),
('𑊀', '𑊆'),
('𑊈', '𑊈'),
('𑊊', '𑊍'),
('𑊏', '𑊝'),
('𑊟', '𑊨'),
('𑊰', '𑋞'),
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_flags/src/lib.rs | crates/rome_flags/src/lib.rs | //! A simple implementation of feature flags.
/// Returns `true` if this is an unstable build of Rome
pub const fn is_unstable() -> bool {
option_env!("ROME_VERSION").is_none()
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_parser/src/prelude.rs | crates/rome_json_parser/src/prelude.rs | pub(crate) use crate::JsonParser;
pub use rome_json_syntax::T;
pub use rome_parser::prelude::*;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_parser/src/lib.rs | crates/rome_json_parser/src/lib.rs | //! Extremely fast, lossless, and error tolerant JSON Parser.
use crate::parser::JsonParser;
use crate::syntax::parse_root;
pub use parser::JsonParserOptions;
use rome_json_factory::JsonSyntaxFactory;
use rome_json_syntax::{JsonLanguage, JsonRoot, JsonSyntaxNode};
pub use rome_parser::prelude::*;
use rome_parser::tree_sink::LosslessTreeSink;
use rome_rowan::{AstNode, NodeCache};
mod lexer;
mod parser;
mod prelude;
mod syntax;
mod token_source;
pub(crate) type JsonLosslessTreeSink<'source> =
LosslessTreeSink<'source, JsonLanguage, JsonSyntaxFactory>;
pub fn parse_json(source: &str, options: JsonParserOptions) -> JsonParse {
let mut cache = NodeCache::default();
parse_json_with_cache(source, &mut cache, options)
}
/// Parses the provided string as JSON program using the provided node cache.
pub fn parse_json_with_cache(
source: &str,
cache: &mut NodeCache,
config: JsonParserOptions,
) -> JsonParse {
tracing::debug_span!("parse").in_scope(move || {
let mut parser = JsonParser::new(source, config);
parse_root(&mut parser);
let (events, diagnostics, trivia) = parser.finish();
let mut tree_sink = JsonLosslessTreeSink::with_cache(source, &trivia, cache);
rome_parser::event::process(&mut tree_sink, events, diagnostics);
let (green, diagnostics) = tree_sink.finish();
JsonParse::new(green, diagnostics)
})
}
/// A utility struct for managing the result of a parser job
#[derive(Debug)]
pub struct JsonParse {
root: JsonSyntaxNode,
diagnostics: Vec<ParseDiagnostic>,
}
impl JsonParse {
pub fn new(root: JsonSyntaxNode, diagnostics: Vec<ParseDiagnostic>) -> JsonParse {
JsonParse { root, diagnostics }
}
/// The syntax node represented by this Parse result
///
/// ```
/// # use rome_json_parser::parse_json;
/// # use rome_json_syntax::JsonSyntaxKind;
/// # use rome_rowan::{AstNode, AstNodeList, SyntaxError};
///
/// # fn main() -> Result<(), SyntaxError> {
/// use rome_json_syntax::JsonSyntaxKind;
/// use rome_json_parser::JsonParserOptions;
/// let parse = parse_json(r#"["a", 1]"#, JsonParserOptions::default());
///
/// // Get the root value
/// let root_value = parse.tree().value()?;
///
/// assert_eq!(root_value.syntax().kind(), JsonSyntaxKind::JSON_ARRAY_VALUE);
///
/// # Ok(())
/// # }
/// ```
pub fn syntax(&self) -> JsonSyntaxNode {
self.root.clone()
}
/// Get the diagnostics which occurred when parsing
pub fn diagnostics(&self) -> &[ParseDiagnostic] {
&self.diagnostics
}
/// Get the diagnostics which occurred when parsing
pub fn into_diagnostics(self) -> Vec<ParseDiagnostic> {
self.diagnostics
}
/// Returns [true] if the parser encountered some errors during the parsing.
pub fn has_errors(&self) -> bool {
self.diagnostics
.iter()
.any(|diagnostic| diagnostic.is_error())
}
/// Convert this parse result into a typed AST node.
///
/// # Panics
/// Panics if the node represented by this parse result mismatches.
pub fn tree(&self) -> JsonRoot {
JsonRoot::unwrap_cast(self.syntax())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_parser/src/token_source.rs | crates/rome_json_parser/src/token_source.rs | use crate::lexer::{Lexer, Token};
use crate::JsonParserOptions;
use rome_json_syntax::JsonSyntaxKind::{EOF, TOMBSTONE};
use rome_json_syntax::{JsonSyntaxKind, TextRange};
use rome_parser::diagnostic::ParseDiagnostic;
use rome_parser::prelude::TokenSource;
use rome_parser::token_source::Trivia;
use rome_rowan::TriviaPieceKind;
pub(crate) struct JsonTokenSource<'source> {
lexer: Lexer<'source>,
trivia: Vec<Trivia>,
current: JsonSyntaxKind,
current_range: TextRange,
preceding_line_break: bool,
config: JsonParserOptions,
}
impl<'source> JsonTokenSource<'source> {
pub fn from_str(source: &'source str, config: JsonParserOptions) -> Self {
let lexer = Lexer::from_str(source).with_config(config);
let mut source = Self {
lexer,
trivia: Vec::new(),
current: TOMBSTONE,
current_range: TextRange::default(),
preceding_line_break: false,
config,
};
source.next_non_trivia_token(true);
source
}
fn next_non_trivia_token(&mut self, first_token: bool) {
let mut trailing = !first_token;
self.preceding_line_break = false;
while let Some(token) = self.lexer.next_token() {
let trivia_kind = TriviaPieceKind::try_from(token.kind());
match trivia_kind {
Err(_) => {
self.set_current_token(token);
// Not trivia
break;
}
Ok(trivia_kind) if trivia_kind.is_comment() && !self.config.allow_comments => {
self.set_current_token(token);
// Not trivia
break;
}
Ok(trivia_kind) => {
if trivia_kind.is_newline() {
trailing = false;
self.preceding_line_break = true;
}
self.trivia
.push(Trivia::new(trivia_kind, token.range(), trailing));
}
}
}
}
fn set_current_token(&mut self, token: Token) {
self.current = token.kind();
self.current_range = token.range()
}
}
impl<'source> TokenSource for JsonTokenSource<'source> {
type Kind = JsonSyntaxKind;
fn current(&self) -> Self::Kind {
self.current
}
fn current_range(&self) -> TextRange {
self.current_range
}
fn text(&self) -> &str {
self.lexer.source()
}
fn has_preceding_line_break(&self) -> bool {
self.preceding_line_break
}
fn bump(&mut self) {
if self.current != EOF {
self.next_non_trivia_token(false)
}
}
fn skip_as_trivia(&mut self) {
if self.current() != EOF {
self.trivia.push(Trivia::new(
TriviaPieceKind::Skipped,
self.current_range(),
false,
));
self.next_non_trivia_token(false)
}
}
fn finish(self) -> (Vec<Trivia>, Vec<ParseDiagnostic>) {
(self.trivia, self.lexer.finish())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_parser/src/parser.rs | crates/rome_json_parser/src/parser.rs | use crate::token_source::JsonTokenSource;
use rome_json_syntax::JsonSyntaxKind;
use rome_parser::diagnostic::merge_diagnostics;
use rome_parser::event::Event;
use rome_parser::prelude::*;
use rome_parser::token_source::Trivia;
use rome_parser::ParserContext;
pub(crate) struct JsonParser<'source> {
context: ParserContext<JsonSyntaxKind>,
source: JsonTokenSource<'source>,
}
#[derive(Default, Debug, Clone, Copy)]
pub struct JsonParserOptions {
pub allow_comments: bool,
}
impl JsonParserOptions {
pub fn with_allow_comments(mut self) -> Self {
self.allow_comments = true;
self
}
}
impl<'source> JsonParser<'source> {
pub fn new(source: &'source str, config: JsonParserOptions) -> Self {
Self {
context: ParserContext::default(),
source: JsonTokenSource::from_str(source, config),
}
}
pub fn finish(
self,
) -> (
Vec<Event<JsonSyntaxKind>>,
Vec<ParseDiagnostic>,
Vec<Trivia>,
) {
let (trivia, lexer_diagnostics) = self.source.finish();
let (events, parse_diagnostics) = self.context.finish();
let diagnostics = merge_diagnostics(lexer_diagnostics, parse_diagnostics);
(events, diagnostics, trivia)
}
}
impl<'source> Parser for JsonParser<'source> {
type Kind = JsonSyntaxKind;
type Source = JsonTokenSource<'source>;
fn context(&self) -> &ParserContext<Self::Kind> {
&self.context
}
fn context_mut(&mut self) -> &mut ParserContext<Self::Kind> {
&mut self.context
}
fn source(&self) -> &Self::Source {
&self.source
}
fn source_mut(&mut self) -> &mut Self::Source {
&mut self.source
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_parser/src/syntax.rs | crates/rome_json_parser/src/syntax.rs | use crate::prelude::*;
use rome_json_syntax::JsonSyntaxKind;
use rome_json_syntax::JsonSyntaxKind::*;
use rome_parser::diagnostic::{expected_any, expected_node};
use rome_parser::parse_recovery::ParseRecovery;
use rome_parser::parsed_syntax::ParsedSyntax::Absent;
use rome_parser::prelude::ParsedSyntax::Present;
use rome_parser::ParserProgress;
use rome_rowan::TextRange;
const VALUE_START: TokenSet<JsonSyntaxKind> = token_set![
T![null],
T![true],
T![false],
JSON_STRING_LITERAL,
JSON_NUMBER_LITERAL,
T!['['],
T!['{'],
];
const VALUE_RECOVERY_SET: TokenSet<JsonSyntaxKind> =
VALUE_START.union(token_set![T![']'], T!['}'], T![,]]);
pub(crate) fn parse_root(p: &mut JsonParser) {
let m = p.start();
let value = match parse_value(p) {
Present(value) => Present(value),
Absent => {
p.error(expected_value(p, p.cur_range()));
match ParseRecovery::new(JSON_BOGUS_VALUE, VALUE_START).recover(p) {
Ok(value) => Present(value),
Err(_) => Absent,
}
}
};
// Process the file to the end, e.g. in cases where there have been multiple values
if !p.at(EOF) {
parse_rest(p, value);
}
m.complete(p, JSON_ROOT);
}
fn parse_value(p: &mut JsonParser) -> ParsedSyntax {
match p.cur() {
T![null] => {
let m = p.start();
p.bump(T![null]);
Present(m.complete(p, JSON_NULL_VALUE))
}
JSON_STRING_LITERAL => {
let m = p.start();
p.bump(JSON_STRING_LITERAL);
Present(m.complete(p, JSON_STRING_VALUE))
}
TRUE_KW | FALSE_KW => {
let m = p.start();
p.bump(p.cur());
Present(m.complete(p, JSON_BOOLEAN_VALUE))
}
JSON_NUMBER_LITERAL => {
let m = p.start();
p.bump(JSON_NUMBER_LITERAL);
Present(m.complete(p, JSON_NUMBER_VALUE))
}
T!['{'] => parse_sequence(p, SequenceKind::Object),
T!['['] => parse_sequence(p, SequenceKind::Array),
IDENT => {
let m = p.start();
p.error(p.err_builder("String values must be double quoted.", p.cur_range()));
p.bump(IDENT);
Present(m.complete(p, JSON_BOGUS_VALUE))
}
_ => Absent,
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
enum SequenceKind {
Array,
Object,
}
impl SequenceKind {
const fn node_kind(&self) -> JsonSyntaxKind {
match self {
SequenceKind::Array => JSON_ARRAY_VALUE,
SequenceKind::Object => JSON_OBJECT_VALUE,
}
}
const fn list_kind(&self) -> JsonSyntaxKind {
match self {
SequenceKind::Array => JSON_ARRAY_ELEMENT_LIST,
SequenceKind::Object => JSON_MEMBER_LIST,
}
}
const fn open_paren(&self) -> JsonSyntaxKind {
match self {
SequenceKind::Array => T!['['],
SequenceKind::Object => T!['{'],
}
}
const fn close_paren(&self) -> JsonSyntaxKind {
match self {
SequenceKind::Array => T![']'],
SequenceKind::Object => T!['}'],
}
}
}
struct Sequence {
kind: SequenceKind,
node: Marker,
list: Marker,
state: SequenceState,
}
enum SequenceState {
Start,
Processing,
Suspended(Option<Marker>),
}
impl Sequence {
fn parse_item(&self, p: &mut JsonParser) -> SequenceItem {
match self.kind {
SequenceKind::Array => parse_array_element(p),
SequenceKind::Object => parse_object_member(p),
}
}
const fn recovery_set(&self) -> TokenSet<JsonSyntaxKind> {
match self.kind {
SequenceKind::Array => VALUE_RECOVERY_SET,
SequenceKind::Object => VALUE_RECOVERY_SET.union(token_set!(T![:])),
}
}
}
fn parse_sequence(p: &mut JsonParser, root_kind: SequenceKind) -> ParsedSyntax {
let mut stack = Vec::new();
let mut current = start_sequence(p, root_kind);
'sequence: loop {
let mut first = match current.state {
SequenceState::Start => true,
SequenceState::Processing => false,
SequenceState::Suspended(marker) => {
if let Some(member_marker) = marker {
debug_assert_eq!(current.kind, SequenceKind::Object);
// Complete the object member
member_marker.complete(p, JSON_MEMBER);
}
current.state = SequenceState::Processing;
false
}
};
let mut progress = ParserProgress::default();
while !p.at(EOF) && !p.at(current.kind.close_paren()) {
if first {
first = false;
} else {
p.expect(T![,]);
}
progress.assert_progressing(p);
match current.parse_item(p) {
SequenceItem::Parsed(Absent) => {
let range = if p.at(T![,]) {
p.cur_range()
} else {
match ParseRecovery::new(JSON_BOGUS_VALUE, current.recovery_set())
.enable_recovery_on_line_break()
.recover(p)
{
Ok(marker) => marker.range(p),
Err(_) => {
p.error(expected_value(p, p.cur_range()));
// We're done for this sequence, unclear how to proceed.
// Continue with parent sequence.
break;
}
}
};
p.error(expected_value(p, range));
}
SequenceItem::Parsed(Present(_)) => {
// continue with next item
}
// Nested Array or object expression
SequenceItem::Recurse(kind, marker) => {
current.state = SequenceState::Suspended(marker);
stack.push(current);
current = start_sequence(p, kind);
continue 'sequence;
}
}
}
current.list.complete(p, current.kind.list_kind());
p.expect(current.kind.close_paren());
let node = current.node.complete(p, current.kind.node_kind());
match stack.pop() {
None => return Present(node),
Some(next) => current = next,
};
}
}
fn start_sequence(p: &mut JsonParser, kind: SequenceKind) -> Sequence {
let node = p.start();
p.expect(kind.open_paren());
let list = p.start();
Sequence {
kind,
node,
list,
state: SequenceState::Start,
}
}
#[derive(Debug)]
enum SequenceItem {
Parsed(ParsedSyntax),
Recurse(SequenceKind, Option<Marker>),
}
fn parse_object_member(p: &mut JsonParser) -> SequenceItem {
let m = p.start();
if parse_member_name(p).is_absent() {
p.error(expected_property(p, p.cur_range()));
if !p.at(T![:]) && !p.at_ts(VALUE_START) {
m.abandon(p);
return SequenceItem::Parsed(Absent);
}
}
p.expect(T![:]);
match parse_sequence_value(p) {
Ok(value) => {
value.or_add_diagnostic(p, expected_value);
SequenceItem::Parsed(Present(m.complete(p, JSON_MEMBER)))
}
Err(kind) => SequenceItem::Recurse(kind, Some(m)),
}
}
fn parse_member_name(p: &mut JsonParser) -> ParsedSyntax {
match p.cur() {
JSON_STRING_LITERAL => {
let m = p.start();
p.bump(JSON_STRING_LITERAL);
Present(m.complete(p, JSON_MEMBER_NAME))
}
IDENT => {
let m = p.start();
p.error(p.err_builder("Property key must be double quoted", p.cur_range()));
p.bump(IDENT);
Present(m.complete(p, JSON_MEMBER_NAME))
}
_ => Absent,
}
}
fn parse_array_element(p: &mut JsonParser) -> SequenceItem {
match parse_sequence_value(p) {
Ok(parsed) => SequenceItem::Parsed(parsed),
Err(kind) => SequenceItem::Recurse(kind, None),
}
}
fn parse_sequence_value(p: &mut JsonParser) -> Result<ParsedSyntax, SequenceKind> {
match p.cur() {
// Special handling for arrays and objects, suspend the current sequence and start parsing
// the nested array or object.
T!['['] => Err(SequenceKind::Array),
T!['{'] => Err(SequenceKind::Object),
_ => Ok(parse_value(p)),
}
}
#[cold]
fn parse_rest(p: &mut JsonParser, value: ParsedSyntax) {
// Wrap the values in an array if there are more than one.
let list = value.precede(p);
while !p.at(EOF) {
let range = match parse_value(p) {
Present(value) => value.range(p),
Absent => ParseRecovery::new(JSON_BOGUS_VALUE, VALUE_START)
.recover(p)
.expect("Expect recovery to succeed because parser isn't at EOF nor at a value.")
.range(p),
};
p.error(
p.err_builder("End of file expected", range)
.hint("Use an array for a sequence of values: `[1, 2]`"),
);
}
list.complete(p, JSON_ARRAY_ELEMENT_LIST)
.precede(p)
.complete(p, JSON_ARRAY_VALUE);
}
fn expected_value(p: &JsonParser, range: TextRange) -> ParseDiagnostic {
expected_any(&["array", "object", "literal"], range).into_diagnostic(p)
}
fn expected_property(p: &JsonParser, range: TextRange) -> ParseDiagnostic {
expected_node("property", range).into_diagnostic(p)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_parser/src/lexer/tests.rs | crates/rome_json_parser/src/lexer/tests.rs | #![cfg(test)]
#![allow(unused_mut, unused_variables, unused_assignments)]
use super::{Lexer, TextSize};
use quickcheck_macros::quickcheck;
use rome_json_syntax::JsonSyntaxKind::{self, EOF};
use std::sync::mpsc::channel;
use std::thread;
use std::time::Duration;
// Assert the result of lexing a piece of source code,
// and make sure the tokens yielded are fully lossless and the source can be reconstructed from only the tokens
macro_rules! assert_lex {
($src:expr, $($kind:ident:$len:expr $(,)?)*) => {{
let mut lexer = Lexer::from_str($src);
let mut idx = 0;
let mut tok_idx = TextSize::default();
let mut new_str = String::with_capacity($src.len());
let tokens: Vec<_> = lexer.collect();
$(
assert_eq!(
tokens[idx].kind,
rome_json_syntax::JsonSyntaxKind::$kind,
"expected token kind {}, but found {:?}",
stringify!($kind),
tokens[idx].kind,
);
assert_eq!(
tokens[idx].range.len(),
TextSize::from($len),
"expected token length of {}, but found {:?} for token {:?}",
$len,
tokens[idx].range.len(),
tokens[idx].kind,
);
new_str.push_str(&$src[tokens[idx].range]);
tok_idx += tokens[idx].range.len();
idx += 1;
)*
if idx < tokens.len() {
panic!(
"expected {} tokens but lexer returned {}, first unexpected token is '{:?}'",
idx,
tokens.len(),
tokens[idx].kind
);
} else {
assert_eq!(idx, tokens.len());
}
assert_eq!($src, new_str, "Failed to reconstruct input");
}};
}
// This is for testing if the lexer is truly lossless
// It parses random strings and puts them back together with the produced tokens and compares
#[quickcheck]
fn losslessness(string: String) -> bool {
// using an mpsc channel allows us to spawn a thread and spawn the lexer there, then if
// it takes more than 2 seconds we panic because it is 100% infinite recursion
let cloned = string.clone();
let (sender, receiver) = channel();
thread::spawn(move || {
let mut lexer = Lexer::from_str(&cloned);
let tokens: Vec<_> = lexer.map(|token| token.range).collect();
sender
.send(tokens)
.expect("Could not send tokens to receiver");
});
let token_ranges = receiver
.recv_timeout(Duration::from_secs(2))
.unwrap_or_else(|_| {
panic!(
"Lexer is infinitely recursing with this code: ->{}<-",
string
)
});
let mut new_str = String::with_capacity(string.len());
let mut idx = TextSize::from(0);
for range in token_ranges {
new_str.push_str(&string[range]);
idx += range.len();
}
string == new_str
}
#[test]
fn empty() {
assert_lex! {
"",
EOF:0
}
}
#[test]
fn int() {
assert_lex! {
"5098382",
JSON_NUMBER_LITERAL:7,
EOF:0
}
}
#[test]
fn float() {
assert_lex! {
"345.893872",
JSON_NUMBER_LITERAL:10,
EOF:0
}
}
#[test]
fn float_invalid() {
assert_lex! {
"345.893872.43322",
ERROR_TOKEN:16,
EOF:0
}
}
#[test]
fn negative() {
assert_lex! {
"-5098382",
JSON_NUMBER_LITERAL:8,
EOF:0
}
}
#[test]
fn minus_without_number() {
assert_lex! {
"-",
ERROR_TOKEN:1,
EOF:0
}
}
#[test]
fn exponent() {
assert_lex! {
"-493e+534",
JSON_NUMBER_LITERAL:9,
EOF:0
}
assert_lex! {
"-493E-534",
JSON_NUMBER_LITERAL:9,
EOF:0
}
}
#[test]
fn multiple_exponent() {
assert_lex! {
"-493e5E3",
ERROR_TOKEN:8,
EOF:0
}
assert_lex! {
"-493e4E45",
ERROR_TOKEN:9,
EOF:0
}
}
#[test]
fn array() {
assert_lex! {
"[1, 2, 3, 4]",
L_BRACK:1,
JSON_NUMBER_LITERAL:1,
COMMA:1
WHITESPACE:1,
JSON_NUMBER_LITERAL:1,
COMMA:1,
WHITESPACE:1,
JSON_NUMBER_LITERAL:1,
COMMA:1,
WHITESPACE:1,
JSON_NUMBER_LITERAL:1,
R_BRACK:1,
EOF:0,
}
}
#[test]
fn object() {
assert_lex! {
r#"{ "key": "value", "other": 4 }"#,
L_CURLY:1,
WHITESPACE:1,
JSON_STRING_LITERAL:5,
COLON:1,
WHITESPACE:1,
JSON_STRING_LITERAL:7,
COMMA:1,
WHITESPACE:1,
JSON_STRING_LITERAL:7,
COLON:1,
WHITESPACE:1,
JSON_NUMBER_LITERAL:1,
WHITESPACE:1,
R_CURLY:1,
EOF:0,
}
}
#[test]
fn basic_string() {
assert_lex! {
r#""A string consisting of ASCII characters only""#,
JSON_STRING_LITERAL:46,
EOF:0
}
}
#[test]
fn single_quote_string() {
assert_lex! {
r#"'A string token using single quotes that are not supported in JSON'"#,
ERROR_TOKEN:67,
EOF:0
}
}
#[test]
fn unterminated_string() {
assert_lex! {
r#""A string without the closing quote"#,
JSON_STRING_LITERAL:35,
EOF:0
}
}
#[test]
fn simple_escape_sequences() {
assert_lex! {
r#""Escaped \t""#,
JSON_STRING_LITERAL:12,
EOF:0
}
assert_lex! {
r#""Escaped \"""#,
JSON_STRING_LITERAL:12,
EOF:0
}
assert_lex! {
r#""Escaped \\""#,
JSON_STRING_LITERAL:12,
EOF:0
}
assert_lex! {
r#""Escaped \/""#,
JSON_STRING_LITERAL:12,
EOF:0
}
assert_lex! {
r#""Escaped \b""#,
JSON_STRING_LITERAL:12,
EOF:0
}
assert_lex! {
r#""Escaped \f""#,
JSON_STRING_LITERAL:12,
EOF:0
}
assert_lex! {
r#""Escaped \n""#,
JSON_STRING_LITERAL:12,
EOF:0
}
assert_lex! {
r#""Escaped \r""#,
JSON_STRING_LITERAL:12,
EOF:0
}
}
#[test]
fn unicode_escape() {
assert_lex! {
r#""Escaped \u002F""#,
JSON_STRING_LITERAL:16,
EOF:0
}
assert_lex! {
r#""Escaped \u002f""#,
JSON_STRING_LITERAL:16,
EOF:0
}
}
#[test]
fn invalid_unicode_escape() {
assert_lex! {
r#""Escaped \u0""#,
ERROR_TOKEN:13,
EOF:0
}
assert_lex! {
r#""Escaped \u002G""#,
ERROR_TOKEN:16,
EOF:0
}
}
#[test]
fn invalid_escape() {
assert_lex! {
r#""\"#,
ERROR_TOKEN:2,
EOF:0
}
assert_lex! {
r#""Invalid escape \'""#,
ERROR_TOKEN:19,
EOF:0
}
}
#[test]
fn single_quote_escape_in_single_quote_string() {
assert_lex! {
r#"'A single \' escape'"#,
ERROR_TOKEN:20,
EOF:0
}
}
#[test]
fn identifiers() {
assert_lex! {
r#"asciiIdentifier"#,
IDENT:15,
EOF:0
}
assert_lex! {
r#"with_underscore_here"#,
IDENT:20,
EOF:0
}
assert_lex! {
r#"with_unicodeàçᨀ"#,
IDENT:19,
EOF:0
}
assert_lex! {
r#"ᨀwith_unicodeàç"#,
IDENT:19,
EOF:0
}
}
#[test]
fn single_line_comments() {
assert_lex! {
"//abc
",
COMMENT:5,
NEWLINE:1,
WHITESPACE:4,
EOF:0
}
assert_lex! {
"//a",
COMMENT:3,
EOF:0
}
}
#[test]
fn block_comment() {
assert_lex! {
"/*
*/",
MULTILINE_COMMENT:13,
EOF:0
}
assert_lex! {
"/* */",
COMMENT:5,
EOF:0
}
assert_lex! {
"/* *",
COMMENT:4,
EOF:0
}
}
#[test]
fn keywords() {
let keywords = vec!["true", "false", "null"];
for keyword in keywords {
let kind = JsonSyntaxKind::from_keyword(keyword).expect(
"Expected `JsonSyntaxKind::from_keyword` to return a kind for keyword {keyword}.",
);
let mut lexer = Lexer::from_str(keyword);
let current = lexer.next_token().expect("To have lexed keyword");
assert_eq!(
current.kind, kind,
"Expected token '{keyword}' to be of kind {:?} but is {:?}.",
kind, current.kind
);
assert_eq!(
current.range.len(),
TextSize::from(keyword.len() as u32),
"Expected lexed keyword to be of len {} but has length {:?}",
keyword.len(),
current.range.len()
);
assert_eq!(lexer.next_token().expect("Expected EOF token").kind, EOF);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_parser/src/lexer/mod.rs | crates/rome_json_parser/src/lexer/mod.rs | //! An extremely fast, lookup table based, JSON lexer which yields SyntaxKind tokens used by the rome-json parser.
#[rustfmt::skip]
mod tests;
use rome_js_unicode_table::{is_id_continue, is_id_start, lookup_byte, Dispatch::*};
use rome_json_syntax::{JsonSyntaxKind, JsonSyntaxKind::*, TextLen, TextRange, TextSize, T};
use rome_parser::diagnostic::ParseDiagnostic;
use std::iter::FusedIterator;
use std::ops::Add;
use crate::JsonParserOptions;
pub struct Token {
kind: JsonSyntaxKind,
range: TextRange,
}
impl Token {
pub fn kind(&self) -> JsonSyntaxKind {
self.kind
}
pub fn range(&self) -> TextRange {
self.range
}
}
/// An extremely fast, lookup table based, lossless JSON lexer
#[derive(Debug)]
pub(crate) struct Lexer<'src> {
/// Source text
source: &'src str,
/// The start byte position in the source text of the next token.
position: usize,
diagnostics: Vec<ParseDiagnostic>,
config: JsonParserOptions,
}
impl<'src> Lexer<'src> {
/// Make a new lexer from a str, this is safe because strs are valid utf8
pub fn from_str(string: &'src str) -> Self {
Self {
source: string,
position: 0,
diagnostics: vec![],
config: JsonParserOptions::default(),
}
}
/// Returns the source code
pub fn source(&self) -> &'src str {
self.source
}
pub fn finish(self) -> Vec<ParseDiagnostic> {
self.diagnostics
}
/// Lexes the next token.
///
/// ## Return
/// Returns its kind and any potential error.
pub(crate) fn next_token(&mut self) -> Option<Token> {
let start = self.text_position();
match self.current_byte() {
Some(current) => {
let kind = self.lex_token(current);
debug_assert!(start < self.text_position(), "Lexer did not progress");
Some(Token {
kind,
range: TextRange::new(start, self.text_position()),
})
}
None if self.position == self.source.len() => {
self.advance(1);
Some(Token {
kind: EOF,
range: TextRange::new(start, start),
})
}
None => None,
}
}
fn text_position(&self) -> TextSize {
TextSize::try_from(self.position).expect("Input to be smaller than 4 GB")
}
/// Bumps the current byte and creates a lexed token of the passed in kind
fn eat_byte(&mut self, tok: JsonSyntaxKind) -> JsonSyntaxKind {
self.advance(1);
tok
}
/// Consume just one newline/line break.
///
/// ## Safety
/// Must be called at a valid UT8 char boundary
fn consume_newline(&mut self) -> bool {
self.assert_at_char_boundary();
match self.current_byte() {
Some(b'\n') => {
self.advance(1);
true
}
Some(b'\r') => {
if self.peek_byte() == Some(b'\n') {
self.advance(2)
} else {
self.advance(1)
}
true
}
_ => false,
}
}
/// Consumes all whitespace until a non-whitespace or a newline is found.
///
/// ## Safety
/// Must be called at a valid UT8 char boundary
fn consume_whitespaces(&mut self) {
self.assert_at_char_boundary();
while let Some(byte) = self.current_byte() {
let dispatch = lookup_byte(byte);
match dispatch {
WHS => match byte {
b'\t' | b' ' => self.advance(1),
b'\r' | b'\n' => {
break;
}
_ => {
let start = self.text_position();
self.advance(1);
self.diagnostics.push(
ParseDiagnostic::new(
"The JSON standard only allows tabs, whitespace, carriage return and line feed whitespace.",
start..self.text_position(),
)
.hint("Use a regular whitespace character instead."),
)
}
},
_ => break,
}
}
}
/// Consume one newline or all whitespace until a non-whitespace or a newline is found.
///
/// ## Safety
/// Must be called at a valid UT8 char boundary
fn consume_newline_or_whitespaces(&mut self) -> JsonSyntaxKind {
if self.consume_newline() {
NEWLINE
} else {
self.consume_whitespaces();
WHITESPACE
}
}
/// Get the UTF8 char which starts at the current byte
///
/// ## Safety
/// Must be called at a valid UT8 char boundary
fn current_char_unchecked(&self) -> char {
// Precautionary measure for making sure the unsafe code below does not read over memory boundary
debug_assert!(!self.is_eof());
self.assert_at_char_boundary();
// Safety: We know this is safe because we require the input to the lexer to be valid utf8 and we always call this when we are at a char
let string = unsafe {
std::str::from_utf8_unchecked(self.source.as_bytes().get_unchecked(self.position..))
};
let chr = if let Some(chr) = string.chars().next() {
chr
} else {
// Safety: we always call this when we are at a valid char, so this branch is completely unreachable
unsafe {
core::hint::unreachable_unchecked();
}
};
chr
}
/// Gets the current byte.
///
/// ## Returns
/// The current byte if the lexer isn't at the end of the file.
#[inline]
fn current_byte(&self) -> Option<u8> {
if self.is_eof() {
None
} else {
Some(self.source.as_bytes()[self.position])
}
}
/// Asserts that the lexer is at a UTF8 char boundary
#[inline]
fn assert_at_char_boundary(&self) {
debug_assert!(self.source.is_char_boundary(self.position));
}
/// Asserts that the lexer is currently positioned at `byte`
#[inline]
fn assert_byte(&self, byte: u8) {
debug_assert_eq!(self.source.as_bytes()[self.position], byte);
}
/// Peeks at the next byte
#[inline]
fn peek_byte(&self) -> Option<u8> {
self.byte_at(1)
}
/// Returns the byte at position `self.position + offset` or `None` if it is out of bounds.
#[inline]
fn byte_at(&self, offset: usize) -> Option<u8> {
self.source.as_bytes().get(self.position + offset).copied()
}
/// Advances the current position by `n` bytes.
#[inline]
fn advance(&mut self, n: usize) {
self.position += n;
}
#[inline]
fn advance_byte_or_char(&mut self, chr: u8) {
if chr.is_ascii() {
self.advance(1);
} else {
self.advance_char_unchecked();
}
}
/// Advances the current position by the current char UTF8 length
///
/// ## Safety
/// Must be called at a valid UT8 char boundary
#[inline]
fn advance_char_unchecked(&mut self) {
let c = self.current_char_unchecked();
self.position += c.len_utf8();
}
/// Returns `true` if the parser is at or passed the end of the file.
#[inline]
fn is_eof(&self) -> bool {
self.position >= self.source.len()
}
/// Lexes the next token
///
/// Guaranteed to not be at the end of the file
// A lookup table of `byte -> fn(l: &mut Lexer) -> Token` is exponentially slower than this approach
fn lex_token(&mut self, current: u8) -> JsonSyntaxKind {
// The speed difference comes from the difference in table size, a 2kb table is easily fit into cpu cache
// While a 16kb table will be ejected from cache very often leading to slowdowns, this also allows LLVM
// to do more aggressive optimizations on the match regarding how to map it to instructions
let dispatched = lookup_byte(current);
match dispatched {
WHS => self.consume_newline_or_whitespaces(),
QOT => self.lex_string_literal(current),
IDT => self.lex_identifier(current),
COM => self.eat_byte(T![,]),
MIN | DIG | ZER => self.lex_number(current),
COL => self.eat_byte(T![:]),
BTO => self.eat_byte(T!['[']),
BTC => self.eat_byte(T![']']),
BEO => self.eat_byte(T!['{']),
BEC => self.eat_byte(T!['}']),
SLH => self.lex_slash(),
UNI => {
let chr = self.current_char_unchecked();
if is_id_start(chr) {
self.lex_identifier(current)
} else {
self.eat_unexpected_character()
}
}
ERR | EXL | HAS | TLD | PIP | TPL | CRT | BSL | AT_ | QST | MOR | LSS | SEM | MUL
| PNO | PNC | PRD | PRC | AMP | EQL | PLS => self.eat_unexpected_character(),
}
}
#[inline]
fn eat_unexpected_character(&mut self) -> JsonSyntaxKind {
self.assert_at_char_boundary();
let char = self.current_char_unchecked();
let err = ParseDiagnostic::new(
format!("unexpected character `{}`", char),
self.text_position()..self.text_position() + char.text_len(),
);
self.diagnostics.push(err);
self.advance(char.len_utf8());
ERROR_TOKEN
}
/// Lexes a JSON number literal
fn lex_number(&mut self, current: u8) -> JsonSyntaxKind {
self.assert_at_char_boundary();
let start = self.text_position();
if current == b'-' {
self.advance(1);
}
let mut state = LexNumberState::FirstDigit;
loop {
state = match self.current_byte() {
Some(b'0') => {
let position = self.text_position();
self.advance(1);
match state {
LexNumberState::FirstDigit
if matches!(self.current_byte(), Some(b'0'..=b'9')) =>
{
LexNumberState::Invalid {
position,
reason: InvalidNumberReason::Octal,
}
}
LexNumberState::FirstDigit => LexNumberState::IntegerPart,
state => state,
}
}
Some(b'0'..=b'9') => {
self.advance(1);
match state {
LexNumberState::FirstDigit => LexNumberState::IntegerPart,
state => state,
}
}
Some(b'.') => {
let position = self.text_position();
self.advance(1);
match state {
LexNumberState::IntegerPart
if matches!(self.current_byte(), Some(b'0'..=b'9')) =>
{
LexNumberState::FractionalPart
}
LexNumberState::IntegerPart => LexNumberState::Invalid {
position: self.text_position(),
reason: InvalidNumberReason::MissingFraction,
},
invalid @ LexNumberState::Invalid { .. } => invalid,
_ => LexNumberState::Invalid {
position,
reason: InvalidNumberReason::Fraction,
},
}
}
Some(b'e' | b'E') => {
let position = self.text_position();
match self.peek_byte() {
Some(b'-' | b'+') => self.advance(2),
_ => self.advance(1),
};
match state {
LexNumberState::IntegerPart | LexNumberState::FractionalPart
if matches!(self.current_byte(), Some(b'0'..=b'9')) =>
{
LexNumberState::Exponent
}
LexNumberState::IntegerPart | LexNumberState::FractionalPart => {
LexNumberState::Invalid {
position: self.text_position(),
reason: InvalidNumberReason::MissingExponent,
}
}
invalid @ LexNumberState::Invalid { .. } => invalid,
_ => LexNumberState::Invalid {
position,
reason: InvalidNumberReason::Exponent,
},
}
}
_ => {
break;
}
}
}
match state {
LexNumberState::IntegerPart
| LexNumberState::FractionalPart
| LexNumberState::Exponent => JSON_NUMBER_LITERAL,
LexNumberState::FirstDigit => {
let err = ParseDiagnostic::new(
"Minus must be followed by a digit",
start..self.text_position(),
);
self.diagnostics.push(err);
ERROR_TOKEN
}
LexNumberState::Invalid { position, reason } => {
let diagnostic = match reason {
InvalidNumberReason::Fraction => ParseDiagnostic::new(
"Invalid fraction part",
position..position + TextSize::from(1),
),
InvalidNumberReason::Exponent => ParseDiagnostic::new(
"Invalid exponent part",
position..position + TextSize::from(1),
),
InvalidNumberReason::Octal => ParseDiagnostic::new(
"The JSON standard doesn't allow octal number notation (numbers starting with zero)",
position..position + TextSize::from(1),
),
InvalidNumberReason::MissingExponent => {
ParseDiagnostic::new( "Missing exponent", start..position)
.detail(position..position + TextSize::from(1), "Expected a digit as the exponent")
}
InvalidNumberReason::MissingFraction => {
ParseDiagnostic::new( "Missing fraction", position..position + TextSize::from(1))
.hint("Remove the `.`")
}
};
self.diagnostics.push(diagnostic);
ERROR_TOKEN
}
}
}
fn lex_string_literal(&mut self, quote: u8) -> JsonSyntaxKind {
// Handle invalid quotes
self.assert_at_char_boundary();
let start = self.text_position();
self.advance(1); // Skip over the quote
let mut state = match quote {
b'\'' => LexStringState::InvalidQuote,
_ => LexStringState::InString,
};
while let Some(chr) = self.current_byte() {
let dispatch = lookup_byte(chr);
match dispatch {
QOT if quote == chr => {
self.advance(1);
state = match state {
LexStringState::InString => LexStringState::Terminated,
state => state,
};
break;
}
// '\t' etc
BSL => {
let escape_start = self.text_position();
self.advance(1);
match self.current_byte() {
Some(b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't') => {
self.advance(1)
}
Some(b'u') => match (self.lex_unicode_escape(), state) {
(Ok(_), _) => {}
(Err(err), LexStringState::InString) => {
self.diagnostics.push(err);
state = LexStringState::InvalidEscapeSequence;
}
(Err(_), _) => {}
},
// Handle escaped `'` but only if this is a single quote string. The whole string will
// be marked as erroneous
Some(b'\'') if quote == b'\'' => {
self.advance(1);
}
Some(_) => {
if matches!(state, LexStringState::InString) {
let c = self.current_char_unchecked();
self.diagnostics.push(
ParseDiagnostic::new(
"Invalid escape sequence",
escape_start..self.text_position() + c.text_len(),
)
.hint(r#"Valid escape sequences are: `\\`, `\/`, `/"`, `\b\`, `\f`, `\n`, `\r`, `\t` or any unicode escape sequence `\uXXXX` where X is hexedecimal number. "#),
);
state = LexStringState::InvalidEscapeSequence;
}
}
None => {
if matches!(state, LexStringState::InString) {
self.diagnostics.push(ParseDiagnostic::new(
"Expected an escape sequence following a backslash, but found none",
escape_start..self.text_position(),
)
.detail(self.text_position()..self.text_position(), "File ends here")
);
state = LexStringState::InvalidEscapeSequence;
}
}
}
}
WHS if matches!(chr, b'\n' | b'\r') => {
let unterminated =
ParseDiagnostic::new("Missing closing quote", start..self.text_position())
.detail(self.position..self.position + 1, "line breaks here");
self.diagnostics.push(unterminated);
return JSON_STRING_LITERAL;
}
UNI => self.advance_char_unchecked(),
// From the spec:
// All code points may be placed within the quotation marks except for the code points that
//must be escaped:
// * quotation mark: (U+0022),
// * reverse solidus (U+005C),
// * and the **control characters U+0000 to U+001F** <- This
ERR | WHS if matches!(state, LexStringState::InString) && chr <= 0x1f => {
self.diagnostics.push(
ParseDiagnostic::new(
format!(
"Control character '\\u{chr:04x}' is not allowed in string literals."
),
self.text_position()..self.text_position() + TextSize::from(1),
)
.hint(format!("Use the escape sequence '\\u{chr:04x}' instead.")),
);
state = LexStringState::InvalidEscapeSequence;
}
_ => self.advance(1),
}
}
match state {
LexStringState::Terminated => JSON_STRING_LITERAL,
LexStringState::InvalidQuote => {
let literal_range = TextRange::new(start, self.text_position());
self.diagnostics.push(
ParseDiagnostic::new(
"JSON standard does not allow single quoted strings",
literal_range,
)
.hint("Use double quotes to escape the string."),
);
ERROR_TOKEN
}
LexStringState::InString => {
let unterminated =
ParseDiagnostic::new("Missing closing quote", start..self.text_position())
.detail(
self.source.text_len()..self.source.text_len(),
"file ends here",
);
self.diagnostics.push(unterminated);
JSON_STRING_LITERAL
}
LexStringState::InvalidEscapeSequence => ERROR_TOKEN,
}
}
/// Lexes a `\u0000` escape sequence. Assumes that the lexer is positioned at the `u` token.
///
/// A unicode escape sequence must consist of 4 hex characters.
fn lex_unicode_escape(&mut self) -> Result<(), ParseDiagnostic> {
self.assert_byte(b'u');
self.assert_at_char_boundary();
let start = self.text_position();
let start = start
// Subtract 1 to get position of `\`
.checked_sub(TextSize::from(1))
.unwrap_or(start);
self.advance(1); // Advance over `u'`
for _ in 0..4 {
match self.current_byte() {
Some(byte) if byte.is_ascii_hexdigit() => self.advance(1),
Some(_) => {
let char = self.current_char_unchecked();
// Reached a non hex digit which is invalid
return Err(ParseDiagnostic::new(
"Invalid unicode sequence",
start..self.text_position(),
)
.detail(self.text_position()..self.text_position().add(char.text_len()), "Non hexadecimal number")
.hint("A unicode escape sequence must consist of 4 hexadecimal numbers: `\\uXXXX`, e.g. `\\u002F' for '/'."));
}
None => {
// Reached the end of the file before processing 4 hex digits
return Err(ParseDiagnostic::new(
"Unicode escape sequence with two few hexadecimal numbers.",
start..self.text_position(),
)
.detail(
self.text_position()..self.text_position(),
"reached the end of the file",
)
.hint("A unicode escape sequence must consist of 4 hexadecimal numbers: `\\uXXXX`, e.g. `\\u002F' for '/'."));
}
}
}
Ok(())
}
/// Implements basic lexing of identifiers without support for escape sequences.
/// This is merely for improved error recovery as identifiers are not valid in JSON.
fn lex_identifier(&mut self, first: u8) -> JsonSyntaxKind {
self.assert_at_char_boundary();
let mut keyword = KeywordMatcher::from_byte(first);
self.advance_byte_or_char(first);
while let Some(byte) = self.current_byte() {
self.current_char_unchecked();
match lookup_byte(byte) {
IDT | DIG | ZER => {
keyword = keyword.next_character(byte);
self.advance(1)
}
UNI => {
let char = self.current_char_unchecked();
keyword = KeywordMatcher::None;
if is_id_continue(char) {
self.advance(char.len_utf8());
} else {
break;
}
}
_ => {
break;
}
}
}
match keyword {
KeywordMatcher::Null => NULL_KW,
KeywordMatcher::True => TRUE_KW,
KeywordMatcher::False => FALSE_KW,
_ => IDENT,
}
}
/// Lexes a comment. Comments are not supported in JSON but it should yield better error recovery.
fn lex_slash(&mut self) -> JsonSyntaxKind {
let start = self.text_position();
match self.peek_byte() {
Some(b'*') => {
// eat `/*`
self.advance(2);
let mut has_newline = false;
while let Some(chr) = self.current_byte() {
match chr {
b'*' if self.peek_byte() == Some(b'/') => {
self.advance(2);
if !self.config.allow_comments {
self.diagnostics.push(ParseDiagnostic::new(
"JSON standard does not allow comments.",
start..self.text_position(),
));
}
if has_newline {
return MULTILINE_COMMENT;
} else {
return COMMENT;
}
}
b'\n' | b'\r' => {
has_newline = true;
self.advance(1)
}
chr => self.advance_byte_or_char(chr),
}
}
let err =
ParseDiagnostic::new("Unterminated block comment", start..self.text_position())
.detail(
self.position..self.position + 1,
"... but the file ends here",
);
self.diagnostics.push(err);
if has_newline {
MULTILINE_COMMENT
} else {
COMMENT
}
}
Some(b'/') => {
self.advance(2);
while let Some(chr) = self.current_byte() {
match chr {
b'\n' | b'\r' => return COMMENT,
chr => self.advance_byte_or_char(chr),
}
}
if !self.config.allow_comments {
self.diagnostics.push(ParseDiagnostic::new(
"JSON standard does not allow comments.",
start..self.text_position(),
));
}
COMMENT
}
_ => self.eat_unexpected_character(),
}
}
pub(crate) fn with_config(mut self, config: JsonParserOptions) -> Self {
self.config = config;
self
}
}
impl Iterator for Lexer<'_> {
type Item = Token;
fn next(&mut self) -> Option<Self::Item> {
self.next_token()
}
}
impl FusedIterator for Lexer<'_> {}
#[derive(Debug, Copy, Clone)]
enum LexNumberState {
/// At the start, after a minus
FirstDigit,
/// Parsing the digits before the exponent or fractional (after .`) part
IntegerPart,
/// Parsing the digits after a `.`
FractionalPart,
/// Parsing the exponent digits (after a `e` or `E`)
Exponent,
/// Parsing the rest of an invalid number
Invalid {
reason: InvalidNumberReason,
position: TextSize,
},
}
#[derive(Copy, Clone, Debug)]
enum InvalidNumberReason {
/// Fraction in an invalid position
Fraction,
/// Exponent in an invalid position
Exponent,
/// Missing digit after an `e` or `E`
MissingExponent,
/// Missing digit after faction (.)
MissingFraction,
/// Number starting with a 0
Octal,
}
#[derive(Copy, Clone, Debug)]
enum LexStringState {
/// When using `'` instead of `"`
InvalidQuote,
/// String that contains an invalid escape sequence
InvalidEscapeSequence,
/// Between the opening `"` and closing `"` quotes.
InString,
/// Properly terminated string
Terminated,
}
enum KeywordMatcher {
MaybeNull(u32),
MaybeFalse(u32),
MaybeTrue(u32),
Null,
False,
True,
None,
}
impl KeywordMatcher {
fn from_byte(c: u8) -> KeywordMatcher {
if c.is_ascii() {
match c {
b'n' => KeywordMatcher::MaybeNull(1),
b't' => KeywordMatcher::MaybeTrue(1),
b'f' => KeywordMatcher::MaybeFalse(1),
_ => KeywordMatcher::None,
}
} else {
KeywordMatcher::None
}
}
fn next_character(self, next: u8) -> KeywordMatcher {
match self {
KeywordMatcher::MaybeNull(position) => match (next, position) {
(b'u', 1) => KeywordMatcher::MaybeNull(2),
(b'l', 2) => KeywordMatcher::MaybeNull(3),
(b'l', 3) => KeywordMatcher::Null,
_ => KeywordMatcher::None,
},
KeywordMatcher::MaybeFalse(position) => match (next, position) {
(b'a', 1) => KeywordMatcher::MaybeFalse(2),
(b'l', 2) => KeywordMatcher::MaybeFalse(3),
(b's', 3) => KeywordMatcher::MaybeFalse(4),
(b'e', 4) => KeywordMatcher::False,
_ => KeywordMatcher::None,
},
KeywordMatcher::MaybeTrue(position) => match (next, position) {
(b'r', 1) => KeywordMatcher::MaybeTrue(2),
(b'u', 2) => KeywordMatcher::MaybeTrue(3),
(b'e', 3) => KeywordMatcher::True,
_ => KeywordMatcher::None,
},
KeywordMatcher::None
| KeywordMatcher::Null
| KeywordMatcher::False
| KeywordMatcher::True => KeywordMatcher::None,
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_parser/tests/spec_test.rs | crates/rome_json_parser/tests/spec_test.rs | use rome_console::fmt::{Formatter, Termcolor};
use rome_console::markup;
use rome_diagnostics::display::PrintDiagnostic;
use rome_diagnostics::termcolor;
use rome_diagnostics::DiagnosticExt;
use rome_json_parser::{parse_json, JsonParserOptions};
use rome_rowan::SyntaxKind;
use std::fmt::Write;
use std::fs;
use std::path::Path;
#[derive(Copy, Clone)]
pub enum ExpectedOutcome {
Pass,
Fail,
Undefined,
}
pub fn run(test_case: &str, _snapshot_name: &str, test_directory: &str, outcome_str: &str) {
let outcome = match outcome_str {
"ok" => ExpectedOutcome::Pass,
"error" => ExpectedOutcome::Fail,
"undefined" => ExpectedOutcome::Undefined,
"allow_comments" => ExpectedOutcome::Pass,
_ => panic!("Invalid expected outcome {outcome_str}"),
};
let test_case_path = Path::new(test_case);
let file_name = test_case_path
.file_name()
.expect("Expected test to have a file name")
.to_str()
.expect("File name to be valid UTF8");
let content = fs::read_to_string(test_case_path)
.expect("Expected test path to be a readable file in UTF8 encoding");
let parse_conifg = JsonParserOptions {
allow_comments: outcome_str == "allow_comments",
};
let parsed = parse_json(&content, parse_conifg);
let formatted_ast = format!("{:#?}", parsed.tree());
let mut snapshot = String::new();
writeln!(snapshot, "\n## Input\n\n```json\n{content}\n```\n\n").unwrap();
writeln!(
snapshot,
r#"## AST
```
{formatted_ast}
```
## CST
```
{:#?}
```
"#,
parsed.syntax()
)
.unwrap();
let diagnostics = parsed.diagnostics();
if !diagnostics.is_empty() {
let mut diagnostics_buffer = termcolor::Buffer::no_color();
let termcolor = &mut Termcolor(&mut diagnostics_buffer);
let mut formatter = Formatter::new(termcolor);
for diagnostic in diagnostics {
let error = diagnostic
.clone()
.with_file_path(file_name)
.with_file_source_code(&content);
formatter
.write_markup(markup! {
{PrintDiagnostic::verbose(&error)}
})
.expect("failed to emit diagnostic");
}
let formatted_diagnostics =
std::str::from_utf8(diagnostics_buffer.as_slice()).expect("non utf8 in error buffer");
if matches!(outcome, ExpectedOutcome::Pass) {
panic!("Expected no errors to be present in a test case that is expected to pass but the following diagnostics are present:\n{formatted_diagnostics}")
}
writeln!(snapshot, "## Diagnostics\n\n```").unwrap();
snapshot.write_str(formatted_diagnostics).unwrap();
writeln!(snapshot, "```\n").unwrap();
}
match outcome {
ExpectedOutcome::Pass => {
let missing_required = formatted_ast.contains("missing (required)");
if missing_required
|| parsed
.syntax()
.descendants()
.any(|node| node.kind().is_bogus())
{
panic!("Parsed tree of a 'OK' test case should not contain any missing required children or bogus nodes");
}
}
ExpectedOutcome::Fail => {
if parsed.diagnostics().is_empty() {
panic!("Failing test must have diagnostics");
}
}
_ => {}
}
insta::with_settings!({
prepend_module_to_snapshot => false,
snapshot_path => &test_directory,
}, {
insta::assert_snapshot!(file_name, snapshot);
});
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_parser/tests/spec_tests.rs | crates/rome_json_parser/tests/spec_tests.rs | #![allow(non_snake_case)]
mod spec_test;
mod ok {
//! Tests that must pass according to the JSON specification
tests_macros::gen_tests! {"tests/json_test_suite/ok/*.json", crate::spec_test::run, "ok"}
}
mod err {
//! Tests that must fail according to the JSON specification
tests_macros::gen_tests! {"tests/json_test_suite/err/*.json", crate::spec_test::run, "error"}
}
mod undefined {
//! parsers are free to accept or reject content
tests_macros::gen_tests! {"tests/json_test_suite/undefined/*.json", crate::spec_test::run, "undefined"}
}
mod allow_comments {
//! Tests should pass even with comments in json
tests_macros::gen_tests! {"tests/json_test_suite/allow_comments/*.json", crate::spec_test::run, "allow_comments"}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_control_flow/src/builder.rs | crates/rome_control_flow/src/builder.rs | use rome_rowan::{Language, SyntaxElement, SyntaxNode};
use crate::{
BasicBlock, ControlFlowGraph, ExceptionHandler, ExceptionHandlerKind, Instruction,
InstructionKind,
};
/// Identifier for a block in a [ControlFlowGraph]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct BlockId {
index: u32,
}
impl BlockId {
/// Returns the index of the block in the function
pub fn index(self) -> u32 {
self.index
}
}
/// Helper struct for building an instance of [ControlFlowGraph], the builder
/// keeps track of an "insertion cursor" within the graph where [Instruction]
/// should be added
pub struct FunctionBuilder<L: Language> {
result: ControlFlowGraph<L>,
exception_target: Vec<ExceptionHandler>,
block_cursor: BlockId,
}
impl<L: Language> FunctionBuilder<L> {
/// Create a new [FunctionBuilder] instance from a function node
pub fn new(node: SyntaxNode<L>) -> Self {
Self {
result: ControlFlowGraph::new(node),
exception_target: Vec::new(),
block_cursor: BlockId { index: 0 },
}
}
/// Finishes building the function
pub fn finish(mut self) -> ControlFlowGraph<L> {
// Append the implicit return instruction that resumes execution of the
// parent procedure when control flow reaches the end of a function
self.append_return();
self.result
}
/// Allocate a new empty block, returning its [BlockId]
pub fn append_block(&mut self) -> BlockId {
let index = self
.result
.blocks
.len()
.try_into()
.expect("BlockId overflow");
let mut has_catch_handler = false;
self.result.blocks.push(BasicBlock::new(
// The exception handlers for a block are all the handlers in the
// current exception stack up to the first catch handler
self.exception_target
.iter()
.rev()
.copied()
.take_while(|handler| {
let has_previous_catch = has_catch_handler;
has_catch_handler |= matches!(handler.kind, ExceptionHandlerKind::Catch);
!has_previous_catch
}),
// The cleanup handlers for a block are all the handlers in the
// current exception stack with the catch handlers filtered out
self.exception_target
.iter()
.rev()
.filter_map(|handler| match handler.kind {
ExceptionHandlerKind::Finally => Some(*handler),
ExceptionHandlerKind::Catch => None,
}),
));
BlockId { index }
}
/// Get the [BlockId] at the current position of the cursor
pub fn cursor(&self) -> BlockId {
self.block_cursor
}
/// Move the cursor to the end of `block`
pub fn set_cursor(&mut self, block: BlockId) {
debug_assert!(block.index < self.result.blocks.len() as u32);
self.block_cursor = block;
}
/// Push a block as a target on the "exception stack": all blocks created
/// with this builder will automatically declare an exception edge towards
/// the topmost entry in this stack
pub fn push_exception_target(&mut self, kind: ExceptionHandlerKind, target: BlockId) {
self.exception_target.push(ExceptionHandler {
kind,
target: target.index(),
});
}
/// Remove the topmost entry from the exception stack
pub fn pop_exception_target(&mut self) {
self.exception_target.pop();
}
/// Insert an instruction at the current position of the cursor
fn append_instruction(&mut self, kind: InstructionKind) -> InstructionBuilder<L> {
let index = self.block_cursor.index as usize;
let block = &mut self.result.blocks[index];
let index = block.instructions.len();
block.instructions.push(Instruction { kind, node: None });
InstructionBuilder(&mut block.instructions[index])
}
pub fn append_statement(&mut self) -> InstructionBuilder<L> {
self.append_instruction(InstructionKind::Statement)
}
pub fn append_return(&mut self) -> InstructionBuilder<L> {
self.append_instruction(InstructionKind::Return)
}
pub fn append_jump(&mut self, conditional: bool, block: BlockId) -> InstructionBuilder<L> {
self.append_instruction(InstructionKind::Jump {
conditional,
block,
finally_fallthrough: false,
})
}
pub fn append_finally_fallthrough(&mut self, block: BlockId) -> InstructionBuilder<L> {
self.append_instruction(InstructionKind::Jump {
conditional: false,
block,
finally_fallthrough: true,
})
}
}
pub struct InstructionBuilder<'a, L: Language>(&'a mut Instruction<L>);
impl<'a, L: Language> InstructionBuilder<'a, L> {
pub fn with_node(mut self, node: impl Into<SyntaxElement<L>>) -> Self {
self.0.node = Some(node.into());
self
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_control_flow/src/lib.rs | crates/rome_control_flow/src/lib.rs | #![deny(rustdoc::broken_intra_doc_links)]
use std::{
collections::HashMap,
fmt::{self, Display, Formatter},
};
use rome_rowan::{Language, SyntaxElement, SyntaxNode};
pub mod builder;
use crate::builder::BlockId;
/// The [ControlFlowGraph] is an auxiliary data structure to the syntax tree,
/// representing the execution order of statements and expressions in a given
/// function as a graph of [BasicBlock]
#[derive(Debug, Clone)]
pub struct ControlFlowGraph<L: Language> {
/// List of blocks that make up this function
pub blocks: Vec<BasicBlock<L>>,
/// The function node this CFG was built for in the syntax tree
pub node: SyntaxNode<L>,
}
impl<L: Language> ControlFlowGraph<L> {
fn new(node: SyntaxNode<L>) -> Self {
ControlFlowGraph {
blocks: vec![BasicBlock::new(None, None)],
node,
}
}
}
/// A basic block represents an atomic unit of control flow, a flat list of
/// instructions that will be executed linearly when a function is run.
///
/// Note, however, that while the instructions that comprise a basic block are
/// guaranteed to be executed in order from the start towards the end, the
/// block may not be executed entirely if a jump or return instruction is
/// encountered.
#[derive(Debug, Clone)]
pub struct BasicBlock<L: Language> {
pub instructions: Vec<Instruction<L>>,
/// List of handlers to execute when an exception is thrown from this block
pub exception_handlers: Vec<ExceptionHandler>,
/// List of handlers to execute when the function returns from this block
pub cleanup_handlers: Vec<ExceptionHandler>,
}
impl<L: Language> BasicBlock<L> {
fn new(
exception_handlers: impl IntoIterator<Item = ExceptionHandler>,
cleanup_handlers: impl IntoIterator<Item = ExceptionHandler>,
) -> Self {
Self {
instructions: Vec::new(),
exception_handlers: exception_handlers.into_iter().collect(),
cleanup_handlers: cleanup_handlers.into_iter().collect(),
}
}
}
/// Instructions are used to represent statements or expressions being executed
/// as side effects, as well as potential divergence points for the control flow.
///
/// Each node has an associated kind, as well as an optional syntax node: the
/// node is useful to emit diagnostics but does not have a semantic value, and
/// is optional. The code generating the control flow graph may emit
/// instructions that do not correspond to any node in the syntax tree, to model
/// the control flow of the program accurately.
#[derive(Debug, Clone)]
pub struct Instruction<L: Language> {
pub kind: InstructionKind,
pub node: Option<SyntaxElement<L>>,
}
/// The different types of supported [Instruction]
#[derive(Copy, Clone, Debug)]
pub enum InstructionKind {
/// Indicates the [SyntaxNode](rome_rowan::SyntaxNode) associated with this
/// instruction is to be evaluated at this point in the program
Statement,
/// This instruction may cause the control flow to diverge towards `block`,
/// either unconditionally if `conditional` is set to `false`, or after
/// evaluating the associated syntax node otherwise
Jump {
conditional: bool,
block: BlockId,
/// Set to `true` for the terminating jump instruction out of a
/// `finally` clause, the target block can be reinterpreted to the next
/// exception handler instead if the control flow is currently unwinding
finally_fallthrough: bool,
},
/// This instruction causes the control flow to unconditionally abort the
/// execution of the function, for example is JavaScript this can be
/// triggered by a `return` or `throw` statement
Return,
}
#[derive(Debug, Clone, Copy)]
pub struct ExceptionHandler {
pub kind: ExceptionHandlerKind,
pub target: u32,
}
#[derive(Debug, Clone, Copy)]
pub enum ExceptionHandlerKind {
Catch,
Finally,
}
/// The Display implementation for [ControlFlowGraph] prints a flowchart in
/// mermaid.js syntax
///
/// By default the graph is printed in "simple" mode where each basic block is
/// represented as a node in the graph:
///
/// ```mermaid
/// flowchart TB
/// block_0["<b>block_0</b><br/>Statement(JS_VARIABLE_DECLARATION 38..47)<br/>Jump { block: 1 }"]
/// block_1["<b>block_1</b><br/>Jump { condition: JS_BINARY_EXPRESSION 49..58, block: 2 }<br/>Jump { block: 3 }"]
/// block_2["<b>block_2</b><br/>Statement(JS_POST_UPDATE_EXPRESSION 60..63)"]
/// block_3["<b>block_3</b><br/>Statement(JS_EXPRESSION_STATEMENT 260..277)"]
///
/// block_0 --> block_1
/// block_1 -- "JS_BINARY_EXPRESSION 49..58" --> block_2
/// block_1 --> block_3
/// ```
///
/// However the graph can also be printed in "detailed" mode by formatting it
/// in alternate mode using `{:#}`, this will print each basic block as a
/// subgraph instead:
///
/// ```mermaid
/// flowchart TB
/// subgraph block_0
/// direction TB
/// block_0_inst_0["Statement(JS_VARIABLE_DECLARATION 38..47)"]
/// block_0_inst_0 --> block_0_inst_1["Jump { block: 1 }"]
/// end
/// subgraph block_1
/// direction TB
/// block_1_inst_0["Jump { condition: JS_BINARY_EXPRESSION 49..58, block: 2 }"]
/// block_1_inst_0 --> block_1_inst_1["Jump { block: 3 }"]
/// end
/// subgraph block_2
/// direction TB
/// block_2_inst_0["Statement(JS_POST_UPDATE_EXPRESSION 60..63)"]
/// end
/// subgraph block_3
/// direction TB
/// block_3_inst_0["Statement(JS_EXPRESSION_STATEMENT 260..277)"]
/// end
///
/// block_0_inst_1 --> block_1
/// block_1_inst_0 -- "JS_BINARY_EXPRESSION 49..58" --> block_2
/// block_1_inst_1 --> block_3
/// ```
impl<L: Language> Display for ControlFlowGraph<L> {
fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
writeln!(fmt, "flowchart TB")?;
let mut links = HashMap::new();
for (id, block) in self.blocks.iter().enumerate() {
if fmt.alternate() {
writeln!(fmt, " subgraph block_{id}")?;
writeln!(fmt, " direction TB")?;
} else {
write!(fmt, " block_{id}[\"<b>block_{id}</b><br/>")?;
}
for (index, inst) in block.instructions.iter().enumerate() {
if fmt.alternate() {
write!(fmt, " ")?;
if let Some(index) = index.checked_sub(1) {
write!(fmt, "block_{id}_inst_{index} --> ")?;
}
writeln!(fmt, "block_{id}_inst_{index}[\"{inst}\"]")?;
} else {
if index > 0 {
write!(fmt, "<br/>")?;
}
write!(fmt, "{inst}")?;
}
if let InstructionKind::Jump {
conditional, block, ..
} = inst.kind
{
let condition = inst
.node
.as_ref()
.filter(|_| conditional)
.map(|node| (node.kind(), node.text_trimmed_range()));
links.insert((id, index, block.index()), condition);
}
}
if fmt.alternate() {
writeln!(fmt, " end")?;
} else {
writeln!(fmt, "\"]")?;
}
}
writeln!(fmt)?;
for ((id, index, to), condition) in links {
write!(fmt, " block_{id}")?;
if fmt.alternate() {
write!(fmt, "_inst_{index}")?;
}
if let Some((cond, range)) = condition {
write!(fmt, " -- \"{cond:?} {range:?}\"")?;
}
writeln!(fmt, " --> block_{to}")?;
}
Ok(())
}
}
impl<L: Language> Display for Instruction<L> {
fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
match self.kind {
InstructionKind::Statement => {
if let Some(node) = &self.node {
write!(
fmt,
"Statement({:?} {:?})",
node.kind(),
node.text_trimmed_range()
)
} else {
write!(fmt, "Statement")
}
}
InstructionKind::Jump {
conditional: true,
block,
..
} if self.node.is_some() => {
// SAFETY: Checked by the above call to `is_some`
let node = self.node.as_ref().unwrap();
write!(
fmt,
"Jump {{ condition: {:?} {:?}, block: {} }}",
node.kind(),
node.text_trimmed_range(),
block.index()
)
}
InstructionKind::Jump { block, .. } => {
write!(fmt, "Jump {{ block: {} }}", block.index())
}
InstructionKind::Return => {
if let Some(node) = &self.node {
write!(
fmt,
"Return({:?} {:?})",
node.kind(),
node.text_trimmed_range()
)
} else {
write!(fmt, "Return")
}
}
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/tests_macros/src/lib.rs | crates/tests_macros/src/lib.rs | use case::CaseExt;
use globwalk::{GlobWalker, GlobWalkerBuilder};
use proc_macro::TokenStream;
use proc_macro2::Span;
use proc_macro_error::*;
use quote::*;
use std::{
collections::HashMap,
ffi::OsStr,
path::{Component, Path, PathBuf},
};
use syn::parse::ParseStream;
struct Arguments {
pattern: syn::ExprLit,
called_function: syn::Path,
file_type: syn::ExprLit,
}
struct Variables {
test_name: String,
test_full_path: String,
test_expected_fullpath: String,
test_directory: String,
}
struct AllFiles(GlobWalker);
impl Iterator for AllFiles {
type Item = Result<PathBuf, &'static str>;
fn next(&mut self) -> Option<Self::Item> {
loop {
match self.0.next() {
Some(Ok(entry)) => {
let file_name = match entry.file_name().to_str().ok_or("File name not UTF8") {
Ok(v) => v,
Err(e) => return Some(Err(e)),
};
if file_name.contains("expected") {
continue;
}
let meta = match entry.metadata().map_err(|_| "Cannot open file") {
Ok(v) => v,
Err(e) => return Some(Err(e)),
};
if meta.is_file() {
let path = entry.path().to_path_buf();
break Some(Ok(path));
}
}
_ => break None,
}
}
}
}
fn transform_file_name(input: &str) -> String {
let mut result = String::new();
for char in input.chars() {
match char {
'-' | '.' | '@' | '+' => {
result.push('_');
}
char if char.is_uppercase() => {
result.push('_');
result.extend(char.to_lowercase());
}
char => {
result.push(char);
}
}
}
let is_keyword = matches!(
result.as_str(),
"await"
| "break"
| "try"
| "do"
| "for"
| "return"
| "if"
| "while"
| "in"
| "async"
| "else"
| "as"
| "abstract"
| "enum"
| "static"
| "yield"
| "type"
| "super"
| "typeof"
| "const"
);
let is_number = result
.chars()
.next()
.unwrap()
.to_string()
.parse::<u32>()
.is_ok();
if is_keyword {
result.push('_');
} else if is_number {
result = "_".to_string() + &result;
}
result
}
#[derive(Default)]
struct Modules {
modules: HashMap<String, Modules>,
tests: Vec<proc_macro2::TokenStream>,
}
impl Modules {
fn insert<'a>(
&mut self,
mut path: impl Iterator<Item = &'a str>,
test: proc_macro2::TokenStream,
) {
match path.next() {
Some(module) => {
let name = transform_file_name(module);
self.modules.entry(name).or_default().insert(path, test);
}
None => {
self.tests.push(test);
}
}
}
fn print(self, output: &mut proc_macro2::TokenStream) {
for (name, module) in self.modules {
let name = syn::Ident::new(&name, Span::call_site());
let mut stream = proc_macro2::TokenStream::new();
module.print(&mut stream);
output.extend(quote! {
mod #name { #stream }
});
}
output.extend(self.tests);
}
}
impl Arguments {
fn get_all_files(&self) -> Result<AllFiles, &str> {
let base = std::env::var("CARGO_MANIFEST_DIR")
.map_err(|_| "Cannot find CARGO_MANIFEST_DIR. Are you using cargo?")?;
let glob = match &self.pattern.lit {
syn::Lit::Str(v) => v.value(),
_ => return Err("Only string literals supported"),
};
let walker = GlobWalkerBuilder::new(base, glob)
.build()
.map_err(|_| "Cannot walk the requested glob")?;
Ok(AllFiles(walker))
}
fn get_variables<P: AsRef<Path>>(path: P) -> Option<Variables> {
let path = path.as_ref();
let file_stem = path.file_stem()?;
let file_stem = file_stem.to_str()?;
let test_name = format!(
"{}{}",
file_stem.to_snake(),
if let Some(extension) = path.extension().and_then(|ext| ext.to_str()) {
format!("_{}", extension)
} else {
"".to_string()
}
);
let test_directory = path.parent().unwrap().display().to_string();
let test_full_path = path.display().to_string();
let extension = match path.extension() {
Some(ext) => format!(".{}", ext.to_str().unwrap_or("")),
None => "".into(),
};
let mut test_expected_file = path.to_path_buf();
test_expected_file.pop();
test_expected_file.push(format!("{}.expected{}", file_stem, extension));
let test_expected_fullpath = test_expected_file.display().to_string();
Some(Variables {
test_name,
test_full_path,
test_expected_fullpath,
test_directory,
})
}
pub fn gen(&self) -> Result<TokenStream, &str> {
let files = self.get_all_files()?;
let mut modules = Modules::default();
for file in files.flatten() {
let Variables {
test_name,
test_full_path,
test_expected_fullpath,
test_directory,
} = Arguments::get_variables(file).ok_or("Cannot generate variables for this file")?;
let test_name = transform_file_name(&test_name);
let path = Path::new(&test_full_path)
.parent()
.into_iter()
.flat_map(|path| path.components())
.map(Component::as_os_str)
.filter_map(OsStr::to_str)
.skip_while(|item| *item != "specs");
let span = self.pattern.lit.span();
let test_name = syn::Ident::new(&test_name, span);
let f = &self.called_function;
let file_type = &self.file_type;
modules.insert(
path,
quote! {
#[test]
pub fn #test_name () {
let test_file = #test_full_path;
let test_expected_file = #test_expected_fullpath;
let file_type = #file_type;
let test_directory = #test_directory;
#f(test_file, test_expected_file, test_directory, file_type);
}
},
);
}
let mut output = proc_macro2::TokenStream::new();
modules.print(&mut output);
Ok(output.into())
}
}
impl syn::parse::Parse for Arguments {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
let path: syn::ExprLit = input.parse()?;
let _: syn::Token!(,) = input.parse()?;
let call: syn::Path = input.parse()?;
let _: syn::Token!(,) = input.parse()?;
let file_type: syn::ExprLit = input.parse()?;
Ok(Arguments {
pattern: path,
called_function: call,
file_type,
})
}
}
#[proc_macro]
#[proc_macro_error]
pub fn gen_tests(input: TokenStream) -> TokenStream {
let args = syn::parse_macro_input!(input as Arguments);
match args.gen() {
Ok(tokens) => tokens,
Err(e) => abort!(e, "{}", e),
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_factory/src/lib.rs | crates/rome_js_factory/src/lib.rs | use rome_js_syntax::JsLanguage;
use rome_rowan::TreeBuilder;
mod generated;
pub use crate::generated::JsSyntaxFactory;
pub mod make;
// Re-exported for tests
#[doc(hidden)]
pub use rome_js_syntax as syntax;
pub type JsSyntaxTreeBuilder = TreeBuilder<'static, JsLanguage, JsSyntaxFactory>;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_factory/src/make.rs | crates/rome_js_factory/src/make.rs | use std::fmt::Display;
use rome_js_syntax::{JsSyntaxKind, JsSyntaxToken, TriviaPieceKind};
use rome_rowan::TriviaPiece;
pub use crate::generated::node_factory::*;
/// Create a new identifier token with no attached trivia
pub fn ident(text: &str) -> JsSyntaxToken {
JsSyntaxToken::new_detached(JsSyntaxKind::IDENT, text, [], [])
}
/// Create a new identifier token with no attached trivia
pub fn jsx_ident(text: &str) -> JsSyntaxToken {
JsSyntaxToken::new_detached(JsSyntaxKind::JSX_IDENT, text, [], [])
}
/// Create a new string literal token with no attached trivia
pub fn js_string_literal(text: &str) -> JsSyntaxToken {
JsSyntaxToken::new_detached(
JsSyntaxKind::JS_STRING_LITERAL,
&format!("\"{text}\""),
[],
[],
)
}
/// Create a new string literal token with no attached trivia
pub fn jsx_string_literal(text: &str) -> JsSyntaxToken {
JsSyntaxToken::new_detached(
JsSyntaxKind::JSX_STRING_LITERAL,
&format!("\"{text}\""),
[],
[],
)
}
/// Create a new string literal token with no attached trivia
pub fn js_number_literal<N>(text: N) -> JsSyntaxToken
where
N: Display + Copy,
{
JsSyntaxToken::new_detached(JsSyntaxKind::JS_NUMBER_LITERAL, &text.to_string(), [], [])
}
/// Create a new token with the specified syntax kind and no attached trivia
pub fn token(kind: JsSyntaxKind) -> JsSyntaxToken {
if let Some(text) = kind.to_string() {
JsSyntaxToken::new_detached(kind, text, [], [])
} else {
panic!("token kind {kind:?} cannot be transformed to text")
}
}
/// Create a new token with the specified syntax kind, and a whitespace trivia
/// piece on both the leading and trailing positions
pub fn token_decorated_with_space(kind: JsSyntaxKind) -> JsSyntaxToken {
if let Some(text) = kind.to_string() {
JsSyntaxToken::new_detached(
kind,
&format!(" {text} "),
[TriviaPiece::new(TriviaPieceKind::Whitespace, 1)],
[TriviaPiece::new(TriviaPieceKind::Whitespace, 1)],
)
} else {
panic!("token kind {kind:?} cannot be transformed to text")
}
}
pub fn eof() -> JsSyntaxToken {
JsSyntaxToken::new_detached(JsSyntaxKind::EOF, "", [], [])
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_factory/src/generated.rs | crates/rome_js_factory/src/generated.rs | #[rustfmt::skip]
pub(super) mod syntax_factory;
#[rustfmt::skip]
pub(crate) mod node_factory;
pub use syntax_factory::JsSyntaxFactory;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_factory/src/generated/syntax_factory.rs | crates/rome_js_factory/src/generated/syntax_factory.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use rome_js_syntax::{JsSyntaxKind, JsSyntaxKind::*, T, *};
use rome_rowan::{AstNode, ParsedChildren, RawNodeSlots, RawSyntaxNode, SyntaxFactory, SyntaxKind};
#[derive(Debug)]
pub struct JsSyntaxFactory;
impl SyntaxFactory for JsSyntaxFactory {
type Kind = JsSyntaxKind;
#[allow(unused_mut)]
fn make_syntax(
kind: Self::Kind,
children: ParsedChildren<Self::Kind>,
) -> RawSyntaxNode<Self::Kind> {
match kind {
JS_BOGUS
| JS_BOGUS_ASSIGNMENT
| JS_BOGUS_BINDING
| JS_BOGUS_EXPRESSION
| JS_BOGUS_IMPORT_ASSERTION_ENTRY
| JS_BOGUS_MEMBER
| JS_BOGUS_NAMED_IMPORT_SPECIFIER
| JS_BOGUS_PARAMETER
| JS_BOGUS_STATEMENT
| TS_BOGUS_TYPE => RawSyntaxNode::new(kind, children.into_iter().map(Some)),
JS_ACCESSOR_MODIFIER => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<1usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T![accessor] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_ACCESSOR_MODIFIER.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_ACCESSOR_MODIFIER, children)
}
JS_ARRAY_ASSIGNMENT_PATTERN => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T!['['] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if JsArrayAssignmentPatternElementList::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T![']'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_ARRAY_ASSIGNMENT_PATTERN.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_ARRAY_ASSIGNMENT_PATTERN, children)
}
JS_ARRAY_ASSIGNMENT_PATTERN_REST_ELEMENT => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<2usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T ! [...] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyJsAssignmentPattern::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_ARRAY_ASSIGNMENT_PATTERN_REST_ELEMENT.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_ARRAY_ASSIGNMENT_PATTERN_REST_ELEMENT, children)
}
JS_ARRAY_BINDING_PATTERN => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T!['['] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if JsArrayBindingPatternElementList::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T![']'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_ARRAY_BINDING_PATTERN.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_ARRAY_BINDING_PATTERN, children)
}
JS_ARRAY_BINDING_PATTERN_REST_ELEMENT => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<2usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T ! [...] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyJsBindingPattern::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_ARRAY_BINDING_PATTERN_REST_ELEMENT.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_ARRAY_BINDING_PATTERN_REST_ELEMENT, children)
}
JS_ARRAY_EXPRESSION => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T!['['] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if JsArrayElementList::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T![']'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_ARRAY_EXPRESSION.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_ARRAY_EXPRESSION, children)
}
JS_ARRAY_HOLE => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<0usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_ARRAY_HOLE.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_ARRAY_HOLE, children)
}
JS_ARROW_FUNCTION_EXPRESSION => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<6usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T![async] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if TsTypeParameters::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyJsArrowFunctionParameters::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if TsReturnTypeAnnotation::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [=>] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyJsFunctionBody::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_ARROW_FUNCTION_EXPRESSION.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_ARROW_FUNCTION_EXPRESSION, children)
}
JS_ASSIGNMENT_EXPRESSION => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if AnyJsAssignmentPattern::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if matches!(
element.kind(),
T ! [=]
| T ! [+=]
| T ! [-=]
| T ! [*=]
| T ! [/=]
| T ! [%=]
| T ! [**=]
| T ! [>>=]
| T ! [<<=]
| T ! [>>>=]
| T ! [&=]
| T ! [|=]
| T ! [^=]
| T ! [&&=]
| T ! [||=]
| T ! [??=]
) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyJsExpression::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_ASSIGNMENT_EXPRESSION.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_ASSIGNMENT_EXPRESSION, children)
}
JS_ASSIGNMENT_WITH_DEFAULT => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if AnyJsAssignmentPattern::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [=] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyJsExpression::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_ASSIGNMENT_WITH_DEFAULT.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_ASSIGNMENT_WITH_DEFAULT, children)
}
JS_AWAIT_EXPRESSION => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<2usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T![await] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyJsExpression::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_AWAIT_EXPRESSION.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_AWAIT_EXPRESSION, children)
}
JS_BIGINT_LITERAL_EXPRESSION => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<1usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == JS_BIGINT_LITERAL {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_BIGINT_LITERAL_EXPRESSION.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_BIGINT_LITERAL_EXPRESSION, children)
}
JS_BINARY_EXPRESSION => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if AnyJsExpression::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if matches!(
element.kind(),
T ! [<]
| T ! [>]
| T ! [<=]
| T ! [>=]
| T ! [==]
| T ! [===]
| T ! [!=]
| T ! [!==]
| T ! [+]
| T ! [-]
| T ! [*]
| T ! [/]
| T ! [%]
| T ! [**]
| T ! [<<]
| T ! [>>]
| T ! [>>>]
| T ! [&]
| T ! [|]
| T ! [^]
) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyJsExpression::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_BINARY_EXPRESSION.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_BINARY_EXPRESSION, children)
}
JS_BINDING_PATTERN_WITH_DEFAULT => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if AnyJsBindingPattern::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [=] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyJsExpression::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_BINDING_PATTERN_WITH_DEFAULT.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_BINDING_PATTERN_WITH_DEFAULT, children)
}
JS_BLOCK_STATEMENT => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T!['{'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if JsStatementList::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T!['}'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_BLOCK_STATEMENT.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_BLOCK_STATEMENT, children)
}
JS_BOOLEAN_LITERAL_EXPRESSION => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<1usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if matches!(element.kind(), T![true] | T![false]) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_BOOLEAN_LITERAL_EXPRESSION.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_BOOLEAN_LITERAL_EXPRESSION, children)
}
JS_BREAK_STATEMENT => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T![break] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == IDENT {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [;] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_BREAK_STATEMENT.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_BREAK_STATEMENT, children)
}
JS_CALL_ARGUMENTS => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T!['('] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if JsCallArgumentList::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T![')'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_CALL_ARGUMENTS.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_CALL_ARGUMENTS, children)
}
JS_CALL_EXPRESSION => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<4usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if AnyJsExpression::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [?.] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if TsTypeArguments::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if JsCallArguments::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_CALL_EXPRESSION.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_CALL_EXPRESSION, children)
}
JS_CASE_CLAUSE => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<4usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T![case] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyJsExpression::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [:] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if JsStatementList::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_CASE_CLAUSE.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_CASE_CLAUSE, children)
}
JS_CATCH_CLAUSE => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T![catch] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if JsCatchDeclaration::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if JsBlockStatement::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_CATCH_CLAUSE.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JS_CATCH_CLAUSE, children)
}
JS_CATCH_DECLARATION => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<4usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T!['('] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyJsBindingPattern::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if TsTypeAnnotation::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T![')'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JS_CATCH_DECLARATION.to_bogus(),
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_factory/src/generated/node_factory.rs | crates/rome_js_factory/src/generated/node_factory.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
#![allow(clippy::redundant_closure)]
#![allow(clippy::too_many_arguments)]
use rome_js_syntax::{
JsSyntaxElement as SyntaxElement, JsSyntaxNode as SyntaxNode, JsSyntaxToken as SyntaxToken, *,
};
use rome_rowan::AstNode;
pub fn js_accessor_modifier(modifier_token: SyntaxToken) -> JsAccessorModifier {
JsAccessorModifier::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_ACCESSOR_MODIFIER,
[Some(SyntaxElement::Token(modifier_token))],
))
}
pub fn js_array_assignment_pattern(
l_brack_token: SyntaxToken,
elements: JsArrayAssignmentPatternElementList,
r_brack_token: SyntaxToken,
) -> JsArrayAssignmentPattern {
JsArrayAssignmentPattern::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_ARRAY_ASSIGNMENT_PATTERN,
[
Some(SyntaxElement::Token(l_brack_token)),
Some(SyntaxElement::Node(elements.into_syntax())),
Some(SyntaxElement::Token(r_brack_token)),
],
))
}
pub fn js_array_assignment_pattern_rest_element(
dotdotdot_token: SyntaxToken,
pattern: AnyJsAssignmentPattern,
) -> JsArrayAssignmentPatternRestElement {
JsArrayAssignmentPatternRestElement::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_ARRAY_ASSIGNMENT_PATTERN_REST_ELEMENT,
[
Some(SyntaxElement::Token(dotdotdot_token)),
Some(SyntaxElement::Node(pattern.into_syntax())),
],
))
}
pub fn js_array_binding_pattern(
l_brack_token: SyntaxToken,
elements: JsArrayBindingPatternElementList,
r_brack_token: SyntaxToken,
) -> JsArrayBindingPattern {
JsArrayBindingPattern::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_ARRAY_BINDING_PATTERN,
[
Some(SyntaxElement::Token(l_brack_token)),
Some(SyntaxElement::Node(elements.into_syntax())),
Some(SyntaxElement::Token(r_brack_token)),
],
))
}
pub fn js_array_binding_pattern_rest_element(
dotdotdot_token: SyntaxToken,
pattern: AnyJsBindingPattern,
) -> JsArrayBindingPatternRestElement {
JsArrayBindingPatternRestElement::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_ARRAY_BINDING_PATTERN_REST_ELEMENT,
[
Some(SyntaxElement::Token(dotdotdot_token)),
Some(SyntaxElement::Node(pattern.into_syntax())),
],
))
}
pub fn js_array_expression(
l_brack_token: SyntaxToken,
elements: JsArrayElementList,
r_brack_token: SyntaxToken,
) -> JsArrayExpression {
JsArrayExpression::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_ARRAY_EXPRESSION,
[
Some(SyntaxElement::Token(l_brack_token)),
Some(SyntaxElement::Node(elements.into_syntax())),
Some(SyntaxElement::Token(r_brack_token)),
],
))
}
pub fn js_array_hole() -> JsArrayHole {
JsArrayHole::unwrap_cast(SyntaxNode::new_detached(JsSyntaxKind::JS_ARRAY_HOLE, []))
}
pub fn js_arrow_function_expression(
parameters: AnyJsArrowFunctionParameters,
fat_arrow_token: SyntaxToken,
body: AnyJsFunctionBody,
) -> JsArrowFunctionExpressionBuilder {
JsArrowFunctionExpressionBuilder {
parameters,
fat_arrow_token,
body,
async_token: None,
type_parameters: None,
return_type_annotation: None,
}
}
pub struct JsArrowFunctionExpressionBuilder {
parameters: AnyJsArrowFunctionParameters,
fat_arrow_token: SyntaxToken,
body: AnyJsFunctionBody,
async_token: Option<SyntaxToken>,
type_parameters: Option<TsTypeParameters>,
return_type_annotation: Option<TsReturnTypeAnnotation>,
}
impl JsArrowFunctionExpressionBuilder {
pub fn with_async_token(mut self, async_token: SyntaxToken) -> Self {
self.async_token = Some(async_token);
self
}
pub fn with_type_parameters(mut self, type_parameters: TsTypeParameters) -> Self {
self.type_parameters = Some(type_parameters);
self
}
pub fn with_return_type_annotation(
mut self,
return_type_annotation: TsReturnTypeAnnotation,
) -> Self {
self.return_type_annotation = Some(return_type_annotation);
self
}
pub fn build(self) -> JsArrowFunctionExpression {
JsArrowFunctionExpression::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_ARROW_FUNCTION_EXPRESSION,
[
self.async_token.map(|token| SyntaxElement::Token(token)),
self.type_parameters
.map(|token| SyntaxElement::Node(token.into_syntax())),
Some(SyntaxElement::Node(self.parameters.into_syntax())),
self.return_type_annotation
.map(|token| SyntaxElement::Node(token.into_syntax())),
Some(SyntaxElement::Token(self.fat_arrow_token)),
Some(SyntaxElement::Node(self.body.into_syntax())),
],
))
}
}
pub fn js_assignment_expression(
left: AnyJsAssignmentPattern,
operator_token_token: SyntaxToken,
right: AnyJsExpression,
) -> JsAssignmentExpression {
JsAssignmentExpression::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_ASSIGNMENT_EXPRESSION,
[
Some(SyntaxElement::Node(left.into_syntax())),
Some(SyntaxElement::Token(operator_token_token)),
Some(SyntaxElement::Node(right.into_syntax())),
],
))
}
pub fn js_assignment_with_default(
pattern: AnyJsAssignmentPattern,
eq_token: SyntaxToken,
default: AnyJsExpression,
) -> JsAssignmentWithDefault {
JsAssignmentWithDefault::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_ASSIGNMENT_WITH_DEFAULT,
[
Some(SyntaxElement::Node(pattern.into_syntax())),
Some(SyntaxElement::Token(eq_token)),
Some(SyntaxElement::Node(default.into_syntax())),
],
))
}
pub fn js_await_expression(
await_token: SyntaxToken,
argument: AnyJsExpression,
) -> JsAwaitExpression {
JsAwaitExpression::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_AWAIT_EXPRESSION,
[
Some(SyntaxElement::Token(await_token)),
Some(SyntaxElement::Node(argument.into_syntax())),
],
))
}
pub fn js_bigint_literal_expression(value_token: SyntaxToken) -> JsBigintLiteralExpression {
JsBigintLiteralExpression::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_BIGINT_LITERAL_EXPRESSION,
[Some(SyntaxElement::Token(value_token))],
))
}
pub fn js_binary_expression(
left: AnyJsExpression,
operator_token_token: SyntaxToken,
right: AnyJsExpression,
) -> JsBinaryExpression {
JsBinaryExpression::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_BINARY_EXPRESSION,
[
Some(SyntaxElement::Node(left.into_syntax())),
Some(SyntaxElement::Token(operator_token_token)),
Some(SyntaxElement::Node(right.into_syntax())),
],
))
}
pub fn js_binding_pattern_with_default(
pattern: AnyJsBindingPattern,
eq_token: SyntaxToken,
default: AnyJsExpression,
) -> JsBindingPatternWithDefault {
JsBindingPatternWithDefault::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_BINDING_PATTERN_WITH_DEFAULT,
[
Some(SyntaxElement::Node(pattern.into_syntax())),
Some(SyntaxElement::Token(eq_token)),
Some(SyntaxElement::Node(default.into_syntax())),
],
))
}
pub fn js_block_statement(
l_curly_token: SyntaxToken,
statements: JsStatementList,
r_curly_token: SyntaxToken,
) -> JsBlockStatement {
JsBlockStatement::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_BLOCK_STATEMENT,
[
Some(SyntaxElement::Token(l_curly_token)),
Some(SyntaxElement::Node(statements.into_syntax())),
Some(SyntaxElement::Token(r_curly_token)),
],
))
}
pub fn js_boolean_literal_expression(value_token_token: SyntaxToken) -> JsBooleanLiteralExpression {
JsBooleanLiteralExpression::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_BOOLEAN_LITERAL_EXPRESSION,
[Some(SyntaxElement::Token(value_token_token))],
))
}
pub fn js_break_statement(break_token: SyntaxToken) -> JsBreakStatementBuilder {
JsBreakStatementBuilder {
break_token,
label_token: None,
semicolon_token: None,
}
}
pub struct JsBreakStatementBuilder {
break_token: SyntaxToken,
label_token: Option<SyntaxToken>,
semicolon_token: Option<SyntaxToken>,
}
impl JsBreakStatementBuilder {
pub fn with_label_token(mut self, label_token: SyntaxToken) -> Self {
self.label_token = Some(label_token);
self
}
pub fn with_semicolon_token(mut self, semicolon_token: SyntaxToken) -> Self {
self.semicolon_token = Some(semicolon_token);
self
}
pub fn build(self) -> JsBreakStatement {
JsBreakStatement::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_BREAK_STATEMENT,
[
Some(SyntaxElement::Token(self.break_token)),
self.label_token.map(|token| SyntaxElement::Token(token)),
self.semicolon_token
.map(|token| SyntaxElement::Token(token)),
],
))
}
}
pub fn js_call_arguments(
l_paren_token: SyntaxToken,
args: JsCallArgumentList,
r_paren_token: SyntaxToken,
) -> JsCallArguments {
JsCallArguments::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_CALL_ARGUMENTS,
[
Some(SyntaxElement::Token(l_paren_token)),
Some(SyntaxElement::Node(args.into_syntax())),
Some(SyntaxElement::Token(r_paren_token)),
],
))
}
pub fn js_call_expression(
callee: AnyJsExpression,
arguments: JsCallArguments,
) -> JsCallExpressionBuilder {
JsCallExpressionBuilder {
callee,
arguments,
optional_chain_token: None,
type_arguments: None,
}
}
pub struct JsCallExpressionBuilder {
callee: AnyJsExpression,
arguments: JsCallArguments,
optional_chain_token: Option<SyntaxToken>,
type_arguments: Option<TsTypeArguments>,
}
impl JsCallExpressionBuilder {
pub fn with_optional_chain_token(mut self, optional_chain_token: SyntaxToken) -> Self {
self.optional_chain_token = Some(optional_chain_token);
self
}
pub fn with_type_arguments(mut self, type_arguments: TsTypeArguments) -> Self {
self.type_arguments = Some(type_arguments);
self
}
pub fn build(self) -> JsCallExpression {
JsCallExpression::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_CALL_EXPRESSION,
[
Some(SyntaxElement::Node(self.callee.into_syntax())),
self.optional_chain_token
.map(|token| SyntaxElement::Token(token)),
self.type_arguments
.map(|token| SyntaxElement::Node(token.into_syntax())),
Some(SyntaxElement::Node(self.arguments.into_syntax())),
],
))
}
}
pub fn js_case_clause(
case_token: SyntaxToken,
test: AnyJsExpression,
colon_token: SyntaxToken,
consequent: JsStatementList,
) -> JsCaseClause {
JsCaseClause::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_CASE_CLAUSE,
[
Some(SyntaxElement::Token(case_token)),
Some(SyntaxElement::Node(test.into_syntax())),
Some(SyntaxElement::Token(colon_token)),
Some(SyntaxElement::Node(consequent.into_syntax())),
],
))
}
pub fn js_catch_clause(catch_token: SyntaxToken, body: JsBlockStatement) -> JsCatchClauseBuilder {
JsCatchClauseBuilder {
catch_token,
body,
declaration: None,
}
}
pub struct JsCatchClauseBuilder {
catch_token: SyntaxToken,
body: JsBlockStatement,
declaration: Option<JsCatchDeclaration>,
}
impl JsCatchClauseBuilder {
pub fn with_declaration(mut self, declaration: JsCatchDeclaration) -> Self {
self.declaration = Some(declaration);
self
}
pub fn build(self) -> JsCatchClause {
JsCatchClause::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_CATCH_CLAUSE,
[
Some(SyntaxElement::Token(self.catch_token)),
self.declaration
.map(|token| SyntaxElement::Node(token.into_syntax())),
Some(SyntaxElement::Node(self.body.into_syntax())),
],
))
}
}
pub fn js_catch_declaration(
l_paren_token: SyntaxToken,
binding: AnyJsBindingPattern,
r_paren_token: SyntaxToken,
) -> JsCatchDeclarationBuilder {
JsCatchDeclarationBuilder {
l_paren_token,
binding,
r_paren_token,
type_annotation: None,
}
}
pub struct JsCatchDeclarationBuilder {
l_paren_token: SyntaxToken,
binding: AnyJsBindingPattern,
r_paren_token: SyntaxToken,
type_annotation: Option<TsTypeAnnotation>,
}
impl JsCatchDeclarationBuilder {
pub fn with_type_annotation(mut self, type_annotation: TsTypeAnnotation) -> Self {
self.type_annotation = Some(type_annotation);
self
}
pub fn build(self) -> JsCatchDeclaration {
JsCatchDeclaration::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_CATCH_DECLARATION,
[
Some(SyntaxElement::Token(self.l_paren_token)),
Some(SyntaxElement::Node(self.binding.into_syntax())),
self.type_annotation
.map(|token| SyntaxElement::Node(token.into_syntax())),
Some(SyntaxElement::Token(self.r_paren_token)),
],
))
}
}
pub fn js_class_declaration(
decorators: JsDecoratorList,
class_token: SyntaxToken,
id: AnyJsBinding,
l_curly_token: SyntaxToken,
members: JsClassMemberList,
r_curly_token: SyntaxToken,
) -> JsClassDeclarationBuilder {
JsClassDeclarationBuilder {
decorators,
class_token,
id,
l_curly_token,
members,
r_curly_token,
abstract_token: None,
type_parameters: None,
extends_clause: None,
implements_clause: None,
}
}
pub struct JsClassDeclarationBuilder {
decorators: JsDecoratorList,
class_token: SyntaxToken,
id: AnyJsBinding,
l_curly_token: SyntaxToken,
members: JsClassMemberList,
r_curly_token: SyntaxToken,
abstract_token: Option<SyntaxToken>,
type_parameters: Option<TsTypeParameters>,
extends_clause: Option<JsExtendsClause>,
implements_clause: Option<TsImplementsClause>,
}
impl JsClassDeclarationBuilder {
pub fn with_abstract_token(mut self, abstract_token: SyntaxToken) -> Self {
self.abstract_token = Some(abstract_token);
self
}
pub fn with_type_parameters(mut self, type_parameters: TsTypeParameters) -> Self {
self.type_parameters = Some(type_parameters);
self
}
pub fn with_extends_clause(mut self, extends_clause: JsExtendsClause) -> Self {
self.extends_clause = Some(extends_clause);
self
}
pub fn with_implements_clause(mut self, implements_clause: TsImplementsClause) -> Self {
self.implements_clause = Some(implements_clause);
self
}
pub fn build(self) -> JsClassDeclaration {
JsClassDeclaration::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_CLASS_DECLARATION,
[
Some(SyntaxElement::Node(self.decorators.into_syntax())),
self.abstract_token.map(|token| SyntaxElement::Token(token)),
Some(SyntaxElement::Token(self.class_token)),
Some(SyntaxElement::Node(self.id.into_syntax())),
self.type_parameters
.map(|token| SyntaxElement::Node(token.into_syntax())),
self.extends_clause
.map(|token| SyntaxElement::Node(token.into_syntax())),
self.implements_clause
.map(|token| SyntaxElement::Node(token.into_syntax())),
Some(SyntaxElement::Token(self.l_curly_token)),
Some(SyntaxElement::Node(self.members.into_syntax())),
Some(SyntaxElement::Token(self.r_curly_token)),
],
))
}
}
pub fn js_class_export_default_declaration(
decorators: JsDecoratorList,
class_token: SyntaxToken,
l_curly_token: SyntaxToken,
members: JsClassMemberList,
r_curly_token: SyntaxToken,
) -> JsClassExportDefaultDeclarationBuilder {
JsClassExportDefaultDeclarationBuilder {
decorators,
class_token,
l_curly_token,
members,
r_curly_token,
abstract_token: None,
id: None,
type_parameters: None,
extends_clause: None,
implements_clause: None,
}
}
pub struct JsClassExportDefaultDeclarationBuilder {
decorators: JsDecoratorList,
class_token: SyntaxToken,
l_curly_token: SyntaxToken,
members: JsClassMemberList,
r_curly_token: SyntaxToken,
abstract_token: Option<SyntaxToken>,
id: Option<AnyJsBinding>,
type_parameters: Option<TsTypeParameters>,
extends_clause: Option<JsExtendsClause>,
implements_clause: Option<TsImplementsClause>,
}
impl JsClassExportDefaultDeclarationBuilder {
pub fn with_abstract_token(mut self, abstract_token: SyntaxToken) -> Self {
self.abstract_token = Some(abstract_token);
self
}
pub fn with_id(mut self, id: AnyJsBinding) -> Self {
self.id = Some(id);
self
}
pub fn with_type_parameters(mut self, type_parameters: TsTypeParameters) -> Self {
self.type_parameters = Some(type_parameters);
self
}
pub fn with_extends_clause(mut self, extends_clause: JsExtendsClause) -> Self {
self.extends_clause = Some(extends_clause);
self
}
pub fn with_implements_clause(mut self, implements_clause: TsImplementsClause) -> Self {
self.implements_clause = Some(implements_clause);
self
}
pub fn build(self) -> JsClassExportDefaultDeclaration {
JsClassExportDefaultDeclaration::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_CLASS_EXPORT_DEFAULT_DECLARATION,
[
Some(SyntaxElement::Node(self.decorators.into_syntax())),
self.abstract_token.map(|token| SyntaxElement::Token(token)),
Some(SyntaxElement::Token(self.class_token)),
self.id
.map(|token| SyntaxElement::Node(token.into_syntax())),
self.type_parameters
.map(|token| SyntaxElement::Node(token.into_syntax())),
self.extends_clause
.map(|token| SyntaxElement::Node(token.into_syntax())),
self.implements_clause
.map(|token| SyntaxElement::Node(token.into_syntax())),
Some(SyntaxElement::Token(self.l_curly_token)),
Some(SyntaxElement::Node(self.members.into_syntax())),
Some(SyntaxElement::Token(self.r_curly_token)),
],
))
}
}
pub fn js_class_expression(
decorators: JsDecoratorList,
class_token: SyntaxToken,
l_curly_token: SyntaxToken,
members: JsClassMemberList,
r_curly_token: SyntaxToken,
) -> JsClassExpressionBuilder {
JsClassExpressionBuilder {
decorators,
class_token,
l_curly_token,
members,
r_curly_token,
id: None,
type_parameters: None,
extends_clause: None,
implements_clause: None,
}
}
pub struct JsClassExpressionBuilder {
decorators: JsDecoratorList,
class_token: SyntaxToken,
l_curly_token: SyntaxToken,
members: JsClassMemberList,
r_curly_token: SyntaxToken,
id: Option<AnyJsBinding>,
type_parameters: Option<TsTypeParameters>,
extends_clause: Option<JsExtendsClause>,
implements_clause: Option<TsImplementsClause>,
}
impl JsClassExpressionBuilder {
pub fn with_id(mut self, id: AnyJsBinding) -> Self {
self.id = Some(id);
self
}
pub fn with_type_parameters(mut self, type_parameters: TsTypeParameters) -> Self {
self.type_parameters = Some(type_parameters);
self
}
pub fn with_extends_clause(mut self, extends_clause: JsExtendsClause) -> Self {
self.extends_clause = Some(extends_clause);
self
}
pub fn with_implements_clause(mut self, implements_clause: TsImplementsClause) -> Self {
self.implements_clause = Some(implements_clause);
self
}
pub fn build(self) -> JsClassExpression {
JsClassExpression::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_CLASS_EXPRESSION,
[
Some(SyntaxElement::Node(self.decorators.into_syntax())),
Some(SyntaxElement::Token(self.class_token)),
self.id
.map(|token| SyntaxElement::Node(token.into_syntax())),
self.type_parameters
.map(|token| SyntaxElement::Node(token.into_syntax())),
self.extends_clause
.map(|token| SyntaxElement::Node(token.into_syntax())),
self.implements_clause
.map(|token| SyntaxElement::Node(token.into_syntax())),
Some(SyntaxElement::Token(self.l_curly_token)),
Some(SyntaxElement::Node(self.members.into_syntax())),
Some(SyntaxElement::Token(self.r_curly_token)),
],
))
}
}
pub fn js_computed_member_assignment(
object: AnyJsExpression,
l_brack_token: SyntaxToken,
member: AnyJsExpression,
r_brack_token: SyntaxToken,
) -> JsComputedMemberAssignment {
JsComputedMemberAssignment::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_COMPUTED_MEMBER_ASSIGNMENT,
[
Some(SyntaxElement::Node(object.into_syntax())),
Some(SyntaxElement::Token(l_brack_token)),
Some(SyntaxElement::Node(member.into_syntax())),
Some(SyntaxElement::Token(r_brack_token)),
],
))
}
pub fn js_computed_member_expression(
object: AnyJsExpression,
l_brack_token: SyntaxToken,
member: AnyJsExpression,
r_brack_token: SyntaxToken,
) -> JsComputedMemberExpressionBuilder {
JsComputedMemberExpressionBuilder {
object,
l_brack_token,
member,
r_brack_token,
optional_chain_token: None,
}
}
pub struct JsComputedMemberExpressionBuilder {
object: AnyJsExpression,
l_brack_token: SyntaxToken,
member: AnyJsExpression,
r_brack_token: SyntaxToken,
optional_chain_token: Option<SyntaxToken>,
}
impl JsComputedMemberExpressionBuilder {
pub fn with_optional_chain_token(mut self, optional_chain_token: SyntaxToken) -> Self {
self.optional_chain_token = Some(optional_chain_token);
self
}
pub fn build(self) -> JsComputedMemberExpression {
JsComputedMemberExpression::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_COMPUTED_MEMBER_EXPRESSION,
[
Some(SyntaxElement::Node(self.object.into_syntax())),
self.optional_chain_token
.map(|token| SyntaxElement::Token(token)),
Some(SyntaxElement::Token(self.l_brack_token)),
Some(SyntaxElement::Node(self.member.into_syntax())),
Some(SyntaxElement::Token(self.r_brack_token)),
],
))
}
}
pub fn js_computed_member_name(
l_brack_token: SyntaxToken,
expression: AnyJsExpression,
r_brack_token: SyntaxToken,
) -> JsComputedMemberName {
JsComputedMemberName::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_COMPUTED_MEMBER_NAME,
[
Some(SyntaxElement::Token(l_brack_token)),
Some(SyntaxElement::Node(expression.into_syntax())),
Some(SyntaxElement::Token(r_brack_token)),
],
))
}
pub fn js_conditional_expression(
test: AnyJsExpression,
question_mark_token: SyntaxToken,
consequent: AnyJsExpression,
colon_token: SyntaxToken,
alternate: AnyJsExpression,
) -> JsConditionalExpression {
JsConditionalExpression::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_CONDITIONAL_EXPRESSION,
[
Some(SyntaxElement::Node(test.into_syntax())),
Some(SyntaxElement::Token(question_mark_token)),
Some(SyntaxElement::Node(consequent.into_syntax())),
Some(SyntaxElement::Token(colon_token)),
Some(SyntaxElement::Node(alternate.into_syntax())),
],
))
}
pub fn js_constructor_class_member(
modifiers: JsConstructorModifierList,
name: JsLiteralMemberName,
parameters: JsConstructorParameters,
body: JsFunctionBody,
) -> JsConstructorClassMember {
JsConstructorClassMember::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_CONSTRUCTOR_CLASS_MEMBER,
[
Some(SyntaxElement::Node(modifiers.into_syntax())),
Some(SyntaxElement::Node(name.into_syntax())),
Some(SyntaxElement::Node(parameters.into_syntax())),
Some(SyntaxElement::Node(body.into_syntax())),
],
))
}
pub fn js_constructor_parameters(
l_paren_token: SyntaxToken,
parameters: JsConstructorParameterList,
r_paren_token: SyntaxToken,
) -> JsConstructorParameters {
JsConstructorParameters::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_CONSTRUCTOR_PARAMETERS,
[
Some(SyntaxElement::Token(l_paren_token)),
Some(SyntaxElement::Node(parameters.into_syntax())),
Some(SyntaxElement::Token(r_paren_token)),
],
))
}
pub fn js_continue_statement(continue_token: SyntaxToken) -> JsContinueStatementBuilder {
JsContinueStatementBuilder {
continue_token,
label_token: None,
semicolon_token: None,
}
}
pub struct JsContinueStatementBuilder {
continue_token: SyntaxToken,
label_token: Option<SyntaxToken>,
semicolon_token: Option<SyntaxToken>,
}
impl JsContinueStatementBuilder {
pub fn with_label_token(mut self, label_token: SyntaxToken) -> Self {
self.label_token = Some(label_token);
self
}
pub fn with_semicolon_token(mut self, semicolon_token: SyntaxToken) -> Self {
self.semicolon_token = Some(semicolon_token);
self
}
pub fn build(self) -> JsContinueStatement {
JsContinueStatement::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_CONTINUE_STATEMENT,
[
Some(SyntaxElement::Token(self.continue_token)),
self.label_token.map(|token| SyntaxElement::Token(token)),
self.semicolon_token
.map(|token| SyntaxElement::Token(token)),
],
))
}
}
pub fn js_debugger_statement(debugger_token: SyntaxToken) -> JsDebuggerStatementBuilder {
JsDebuggerStatementBuilder {
debugger_token,
semicolon_token: None,
}
}
pub struct JsDebuggerStatementBuilder {
debugger_token: SyntaxToken,
semicolon_token: Option<SyntaxToken>,
}
impl JsDebuggerStatementBuilder {
pub fn with_semicolon_token(mut self, semicolon_token: SyntaxToken) -> Self {
self.semicolon_token = Some(semicolon_token);
self
}
pub fn build(self) -> JsDebuggerStatement {
JsDebuggerStatement::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_DEBUGGER_STATEMENT,
[
Some(SyntaxElement::Token(self.debugger_token)),
self.semicolon_token
.map(|token| SyntaxElement::Token(token)),
],
))
}
}
pub fn js_decorator(at_token: SyntaxToken, expression: AnyJsDecorator) -> JsDecorator {
JsDecorator::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_DECORATOR,
[
Some(SyntaxElement::Token(at_token)),
Some(SyntaxElement::Node(expression.into_syntax())),
],
))
}
pub fn js_default_clause(
default_token: SyntaxToken,
colon_token: SyntaxToken,
consequent: JsStatementList,
) -> JsDefaultClause {
JsDefaultClause::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_DEFAULT_CLAUSE,
[
Some(SyntaxElement::Token(default_token)),
Some(SyntaxElement::Token(colon_token)),
Some(SyntaxElement::Node(consequent.into_syntax())),
],
))
}
pub fn js_default_import_specifier(
local_name: AnyJsBinding,
trailing_comma_token: SyntaxToken,
) -> JsDefaultImportSpecifier {
JsDefaultImportSpecifier::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_DEFAULT_IMPORT_SPECIFIER,
[
Some(SyntaxElement::Node(local_name.into_syntax())),
Some(SyntaxElement::Token(trailing_comma_token)),
],
))
}
pub fn js_directive(value_token: SyntaxToken) -> JsDirectiveBuilder {
JsDirectiveBuilder {
value_token,
semicolon_token: None,
}
}
pub struct JsDirectiveBuilder {
value_token: SyntaxToken,
semicolon_token: Option<SyntaxToken>,
}
impl JsDirectiveBuilder {
pub fn with_semicolon_token(mut self, semicolon_token: SyntaxToken) -> Self {
self.semicolon_token = Some(semicolon_token);
self
}
pub fn build(self) -> JsDirective {
JsDirective::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_DIRECTIVE,
[
Some(SyntaxElement::Token(self.value_token)),
self.semicolon_token
.map(|token| SyntaxElement::Token(token)),
],
))
}
}
pub fn js_do_while_statement(
do_token: SyntaxToken,
body: AnyJsStatement,
while_token: SyntaxToken,
l_paren_token: SyntaxToken,
test: AnyJsExpression,
r_paren_token: SyntaxToken,
) -> JsDoWhileStatementBuilder {
JsDoWhileStatementBuilder {
do_token,
body,
while_token,
l_paren_token,
test,
r_paren_token,
semicolon_token: None,
}
}
pub struct JsDoWhileStatementBuilder {
do_token: SyntaxToken,
body: AnyJsStatement,
while_token: SyntaxToken,
l_paren_token: SyntaxToken,
test: AnyJsExpression,
r_paren_token: SyntaxToken,
semicolon_token: Option<SyntaxToken>,
}
impl JsDoWhileStatementBuilder {
pub fn with_semicolon_token(mut self, semicolon_token: SyntaxToken) -> Self {
self.semicolon_token = Some(semicolon_token);
self
}
pub fn build(self) -> JsDoWhileStatement {
JsDoWhileStatement::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_DO_WHILE_STATEMENT,
[
Some(SyntaxElement::Token(self.do_token)),
Some(SyntaxElement::Node(self.body.into_syntax())),
Some(SyntaxElement::Token(self.while_token)),
Some(SyntaxElement::Token(self.l_paren_token)),
Some(SyntaxElement::Node(self.test.into_syntax())),
Some(SyntaxElement::Token(self.r_paren_token)),
self.semicolon_token
.map(|token| SyntaxElement::Token(token)),
],
))
}
}
pub fn js_else_clause(else_token: SyntaxToken, alternate: AnyJsStatement) -> JsElseClause {
JsElseClause::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_ELSE_CLAUSE,
[
Some(SyntaxElement::Token(else_token)),
Some(SyntaxElement::Node(alternate.into_syntax())),
],
))
}
pub fn js_empty_class_member(semicolon_token: SyntaxToken) -> JsEmptyClassMember {
JsEmptyClassMember::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_EMPTY_CLASS_MEMBER,
[Some(SyntaxElement::Token(semicolon_token))],
))
}
pub fn js_empty_statement(semicolon_token: SyntaxToken) -> JsEmptyStatement {
JsEmptyStatement::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_EMPTY_STATEMENT,
[Some(SyntaxElement::Token(semicolon_token))],
))
}
pub fn js_export(
decorators: JsDecoratorList,
export_token: SyntaxToken,
export_clause: AnyJsExportClause,
) -> JsExport {
JsExport::unwrap_cast(SyntaxNode::new_detached(
JsSyntaxKind::JS_EXPORT,
[
Some(SyntaxElement::Node(decorators.into_syntax())),
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_suppression/src/lib.rs | crates/rome_suppression/src/lib.rs | use rome_diagnostics::{Category, Diagnostic};
use rome_rowan::{TextRange, TextSize};
/// Single instance of a suppression comment, with the following syntax:
///
/// `// rome-ignore { <category> { (<value>) }? }+: <reason>`
///
/// The category broadly describes what feature is being suppressed (formatting,
/// linting, ...) with the value being and optional, category-specific name of
/// a specific element to disable (for instance a specific lint name). A single
/// suppression may specify one or more categories + values, for instance to
/// disable multiple lints at once
///
/// A suppression must specify a reason: this part has no semantic meaning but
/// is required to document why a particular feature is being disable for this
/// line (lint false-positive, specific formatting requirements, ...)
#[derive(Debug, PartialEq, Eq)]
pub struct Suppression<'a> {
/// List of categories for this suppression
///
/// Categories are pair of the category name +
/// an optional category value
pub categories: Vec<(&'a Category, Option<&'a str>)>,
/// Reason for this suppression comment to exist
pub reason: &'a str,
}
pub fn parse_suppression_comment(
base: &str,
) -> impl Iterator<Item = Result<Suppression, SuppressionDiagnostic>> {
let (head, mut comment) = base.split_at(2);
let is_block_comment = match head {
"//" => false,
"/*" => {
comment = comment
.strip_suffix("*/")
.or_else(|| comment.strip_suffix(&['*', '/']))
.unwrap_or(comment);
true
}
token => panic!("comment with unknown opening token {token:?}, from {comment}"),
};
comment.lines().filter_map(move |line| {
// Eat start of line whitespace
let mut line = line.trim_start();
// If we're in a block comment eat stars, then whitespace again
if is_block_comment {
line = line.trim_start_matches('*').trim_start()
}
const PATTERNS: [[char; 2]; 11] = [
['r', 'R'],
['o', 'O'],
['m', 'M'],
['e', 'E'],
['-', '_'],
['i', 'I'],
['g', 'G'],
['n', 'N'],
['o', 'O'],
['r', 'R'],
['e', 'E'],
];
// Checks for `/rome[-_]ignore/i` without a regex, or skip the line
// entirely if it doesn't match
for pattern in PATTERNS {
line = line.strip_prefix(pattern)?;
}
let line = line.trim_start();
Some(
parse_suppression_line(line).map_err(|err| SuppressionDiagnostic {
message: err.message,
// Adjust the position of the diagnostic in the whole comment
span: err.span + offset_from(base, line),
}),
)
})
}
#[derive(Clone, Debug, PartialEq, Eq, Diagnostic)]
#[diagnostic(category = "suppressions/parse")]
pub struct SuppressionDiagnostic {
#[message]
#[description]
message: SuppressionDiagnosticKind,
#[location(span)]
span: TextRange,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum SuppressionDiagnosticKind {
MissingColon,
ParseCategory(String),
MissingCategory,
MissingParen,
}
impl std::fmt::Display for SuppressionDiagnosticKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SuppressionDiagnosticKind::MissingColon => write!(
f,
"unexpected token, expected one of ':', '(' or whitespace"
),
SuppressionDiagnosticKind::ParseCategory(category) => {
write!(f, "failed to parse category {category:?}")
}
SuppressionDiagnosticKind::MissingCategory => {
write!(f, "unexpected token, expected one of ':' or whitespace")
}
SuppressionDiagnosticKind::MissingParen => write!(f, "unexpected token, expected ')'"),
}
}
}
impl rome_console::fmt::Display for SuppressionDiagnosticKind {
fn fmt(&self, fmt: &mut rome_console::fmt::Formatter) -> std::io::Result<()> {
match self {
SuppressionDiagnosticKind::MissingColon => write!(
fmt,
"unexpected token, expected one of ':', '(' or whitespace"
),
SuppressionDiagnosticKind::ParseCategory(category) => {
write!(fmt, "failed to parse category {category:?}")
}
SuppressionDiagnosticKind::MissingCategory => {
write!(fmt, "unexpected token, expected one of ':' or whitespace")
}
SuppressionDiagnosticKind::MissingParen => {
write!(fmt, "unexpected token, expected ')'")
}
}
}
}
/// Parse the `{ <category> { (<value>) }? }+: <reason>` section of a suppression line
fn parse_suppression_line(base: &str) -> Result<Suppression, SuppressionDiagnostic> {
let mut line = base;
let mut categories = Vec::new();
loop {
// Find either a colon opening parenthesis or space
let separator = line
.find(|c: char| c == ':' || c == '(' || c.is_whitespace())
.ok_or_else(|| SuppressionDiagnostic {
message: SuppressionDiagnosticKind::MissingColon,
span: TextRange::at(offset_from(base, line), TextSize::of(line)),
})?;
let (category, rest) = line.split_at(separator);
let category = category.trim_end();
let category: Option<&'static Category> = if !category.is_empty() {
let category = category.parse().map_err(|()| SuppressionDiagnostic {
message: SuppressionDiagnosticKind::ParseCategory(category.into()),
span: TextRange::at(offset_from(base, category), TextSize::of(category)),
})?;
Some(category)
} else {
None
};
// Skip over and match the separator
let (separator, rest) = rest.split_at(1);
match separator {
// Colon token: stop parsing categories
":" => {
if let Some(category) = category {
categories.push((category, None));
}
line = rest.trim_start();
break;
}
// Paren token: parse a category + value
"(" => {
let category = category.ok_or_else(|| SuppressionDiagnostic {
message: SuppressionDiagnosticKind::MissingCategory,
span: TextRange::at(
offset_from(base, line),
offset_from(line, separator) + TextSize::of(separator),
),
})?;
let paren = rest.find(')').ok_or_else(|| SuppressionDiagnostic {
message: SuppressionDiagnosticKind::MissingParen,
span: TextRange::at(offset_from(base, rest), TextSize::of(rest)),
})?;
let (value, rest) = rest.split_at(paren);
let value = value.trim();
categories.push((category, Some(value)));
line = rest.strip_prefix(')').unwrap().trim_start();
}
// Whitespace: push a category without value
_ => {
if let Some(category) = category {
categories.push((category, None));
}
line = rest.trim_start();
}
}
}
let reason = line.trim_end();
Ok(Suppression { categories, reason })
}
/// Returns the byte offset of `substr` within `base`
///
/// # Safety
///
/// `substr` must be a substring of `base`, or calling this method will result
/// in undefined behavior.
fn offset_from(base: &str, substr: &str) -> TextSize {
let base_len = base.len();
assert!(substr.len() <= base_len);
let base = base.as_ptr();
let substr = substr.as_ptr();
let offset = unsafe { substr.offset_from(base) };
// SAFETY: converting from `isize` to `usize` can only fail if `offset` is
// negative, meaning `base` is either a substring of `substr` or the two
// string slices are unrelated
let offset = usize::try_from(offset).expect("usize underflow");
assert!(offset <= base_len);
// SAFETY: the conversion from `usize` to `TextSize` can fail if `offset`
// is larger than 2^32
TextSize::try_from(offset).expect("TextSize overflow")
}
#[cfg(test)]
mod tests {
use rome_diagnostics::category;
use rome_rowan::{TextRange, TextSize};
use crate::{offset_from, SuppressionDiagnostic, SuppressionDiagnosticKind};
use super::{parse_suppression_comment, Suppression};
#[test]
fn parse_simple_suppression() {
assert_eq!(
parse_suppression_comment("// rome-ignore parse: explanation1").collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![(category!("parse"), None)],
reason: "explanation1"
})],
);
assert_eq!(
parse_suppression_comment("/** rome-ignore parse: explanation2 */").collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![(category!("parse"), None)],
reason: "explanation2"
})],
);
assert_eq!(
parse_suppression_comment(
"/**
* rome-ignore parse: explanation3
*/"
)
.collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![(category!("parse"), None)],
reason: "explanation3"
})],
);
assert_eq!(
parse_suppression_comment(
"/**
* hello
* rome-ignore parse: explanation4
*/"
)
.collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![(category!("parse"), None)],
reason: "explanation4"
})],
);
}
#[test]
fn parse_unclosed_block_comment_suppressions() {
assert_eq!(
parse_suppression_comment("/* rome-ignore format: explanation").collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![(category!("format"), None)],
reason: "explanation"
})],
);
assert_eq!(
parse_suppression_comment("/* rome-ignore format: explanation *").collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![(category!("format"), None)],
reason: "explanation"
})],
);
assert_eq!(
parse_suppression_comment("/* rome-ignore format: explanation /").collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![(category!("format"), None)],
reason: "explanation"
})],
);
}
#[test]
fn parse_multiple_suppression() {
assert_eq!(
parse_suppression_comment("// rome-ignore parse(foo) parse(dog): explanation")
.collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![
(category!("parse"), Some("foo")),
(category!("parse"), Some("dog"))
],
reason: "explanation"
})],
);
assert_eq!(
parse_suppression_comment("/** rome-ignore parse(bar) parse(cat): explanation */")
.collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![
(category!("parse"), Some("bar")),
(category!("parse"), Some("cat"))
],
reason: "explanation"
})],
);
assert_eq!(
parse_suppression_comment(
"/**
* rome-ignore parse(yes) parse(frog): explanation
*/"
)
.collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![
(category!("parse"), Some("yes")),
(category!("parse"), Some("frog"))
],
reason: "explanation"
})],
);
assert_eq!(
parse_suppression_comment(
"/**
* hello
* rome-ignore parse(wow) parse(fish): explanation
*/"
)
.collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![
(category!("parse"), Some("wow")),
(category!("parse"), Some("fish"))
],
reason: "explanation"
})],
);
}
#[test]
fn parse_multiple_suppression_categories() {
assert_eq!(
parse_suppression_comment("// rome-ignore format lint: explanation")
.collect::<Vec<_>>(),
vec![Ok(Suppression {
categories: vec![(category!("format"), None), (category!("lint"), None)],
reason: "explanation"
})],
);
}
#[test]
fn check_offset_from() {
const BASE: &str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua";
assert_eq!(offset_from(BASE, BASE), TextSize::from(0));
let (_, substr) = BASE.split_at(55);
assert_eq!(offset_from(BASE, substr), TextSize::from(55));
let (_, substr) = BASE.split_at(BASE.len());
assert_eq!(offset_from(BASE, substr), TextSize::of(BASE));
}
#[test]
fn diagnostic_missing_colon() {
assert_eq!(
parse_suppression_comment("// rome-ignore format explanation").collect::<Vec<_>>(),
vec![Err(SuppressionDiagnostic {
message: SuppressionDiagnosticKind::MissingColon,
span: TextRange::new(TextSize::from(22), TextSize::from(33))
})],
);
}
#[test]
fn diagnostic_missing_paren() {
assert_eq!(
parse_suppression_comment("// rome-ignore format(:").collect::<Vec<_>>(),
vec![Err(SuppressionDiagnostic {
message: SuppressionDiagnosticKind::MissingParen,
span: TextRange::new(TextSize::from(22), TextSize::from(23))
})],
);
}
#[test]
fn diagnostic_missing_category() {
assert_eq!(
parse_suppression_comment("// rome-ignore (value): explanation").collect::<Vec<_>>(),
vec![Err(SuppressionDiagnostic {
message: SuppressionDiagnosticKind::MissingCategory,
span: TextRange::new(TextSize::from(15), TextSize::from(16))
})],
);
}
#[test]
fn diagnostic_unknown_category() {
assert_eq!(
parse_suppression_comment("// rome-ignore unknown: explanation").collect::<Vec<_>>(),
vec![Err(SuppressionDiagnostic {
message: SuppressionDiagnosticKind::ParseCategory(String::from("unknown")),
span: TextRange::new(TextSize::from(15), TextSize::from(22))
})],
);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_parser/src/prelude.rs | crates/rome_css_parser/src/prelude.rs | pub use rome_css_syntax::T;
pub use rome_parser::prelude::*;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_parser/src/lib.rs | crates/rome_css_parser/src/lib.rs | //! Extremely fast, lossless, and error tolerant CSS Parser.
use crate::parser::CssParser;
use crate::syntax::parse_root;
pub use parser::CssParserOptions;
use rome_css_factory::CssSyntaxFactory;
use rome_css_syntax::{CssLanguage, CssRoot, CssSyntaxNode};
pub use rome_parser::prelude::*;
use rome_parser::tree_sink::LosslessTreeSink;
use rome_rowan::{AstNode, NodeCache};
mod lexer;
mod parser;
mod prelude;
mod syntax;
mod token_source;
pub(crate) type CssLosslessTreeSink<'source> =
LosslessTreeSink<'source, CssLanguage, CssSyntaxFactory>;
pub fn parse_css(source: &str, options: CssParserOptions) -> CssParse {
let mut cache = NodeCache::default();
parse_css_with_cache(source, &mut cache, options)
}
/// Parses the provided string as CSS program using the provided node cache.
pub fn parse_css_with_cache(
source: &str,
cache: &mut NodeCache,
config: CssParserOptions,
) -> CssParse {
tracing::debug_span!("parse").in_scope(move || {
let mut parser = CssParser::new(source, config);
parse_root(&mut parser);
let (events, diagnostics, trivia) = parser.finish();
let mut tree_sink = CssLosslessTreeSink::with_cache(source, &trivia, cache);
rome_parser::event::process(&mut tree_sink, events, diagnostics);
let (green, diagnostics) = tree_sink.finish();
CssParse::new(green, diagnostics)
})
}
/// A utility struct for managing the result of a parser job
#[derive(Debug)]
pub struct CssParse {
root: CssSyntaxNode,
diagnostics: Vec<ParseDiagnostic>,
}
impl CssParse {
pub fn new(root: CssSyntaxNode, diagnostics: Vec<ParseDiagnostic>) -> CssParse {
CssParse { root, diagnostics }
}
/// The syntax node represented by this Parse result
///
/// ```
/// # use rome_css_parser::parse_css;
/// # use rome_css_syntax::CssSyntaxKind;
/// # use rome_rowan::{AstNode, AstNodeList, SyntaxError};
///
/// # fn main() -> Result<(), SyntaxError> {
/// use rome_css_syntax::CssSyntaxKind;
/// use rome_css_parser::CssParserOptions;
/// let parse = parse_css(r#""#, CssParserOptions::default());
///
/// let root_value = parse.tree().rules();
///
/// assert_eq!(root_value.syntax().kind(), CssSyntaxKind::CSS_RULE_LIST);
///
/// # Ok(())
/// # }
/// ```
pub fn syntax(&self) -> CssSyntaxNode {
self.root.clone()
}
/// Get the diagnostics which occurred when parsing
pub fn diagnostics(&self) -> &[ParseDiagnostic] {
&self.diagnostics
}
/// Get the diagnostics which occurred when parsing
pub fn into_diagnostics(self) -> Vec<ParseDiagnostic> {
self.diagnostics
}
/// Returns [true] if the parser encountered some errors during the parsing.
pub fn has_errors(&self) -> bool {
self.diagnostics
.iter()
.any(|diagnostic| diagnostic.is_error())
}
/// Convert this parse result into a typed AST node.
///
/// # Panics
/// Panics if the node represented by this parse result mismatches.
pub fn tree(&self) -> CssRoot {
CssRoot::unwrap_cast(self.syntax())
}
}
#[cfg(test)]
mod tests {
use crate::{parse_css, CssParserOptions};
#[test]
fn parser_smoke_test() {
let src = r#"
"#;
let _css = parse_css(src, CssParserOptions::default());
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_parser/src/token_source.rs | crates/rome_css_parser/src/token_source.rs | use crate::lexer::{Lexer, Token};
use crate::CssParserOptions;
use rome_css_syntax::CssSyntaxKind::{EOF, TOMBSTONE};
use rome_css_syntax::{CssSyntaxKind, TextRange};
use rome_parser::diagnostic::ParseDiagnostic;
use rome_parser::prelude::TokenSource;
use rome_parser::token_source::Trivia;
use rome_rowan::TriviaPieceKind;
pub(crate) struct CssTokenSource<'source> {
lexer: Lexer<'source>,
trivia: Vec<Trivia>,
current: CssSyntaxKind,
current_range: TextRange,
preceding_line_break: bool,
config: CssParserOptions,
}
impl<'source> CssTokenSource<'source> {
pub fn from_str(source: &'source str, config: CssParserOptions) -> Self {
let lexer = Lexer::from_str(source).with_config(config);
let mut source = Self {
lexer,
trivia: Vec::new(),
current: TOMBSTONE,
current_range: TextRange::default(),
preceding_line_break: false,
config,
};
source.next_non_trivia_token(true);
source
}
fn next_non_trivia_token(&mut self, first_token: bool) {
let mut trailing = !first_token;
self.preceding_line_break = false;
while let Some(token) = self.lexer.next_token() {
let trivia_kind = TriviaPieceKind::try_from(token.kind());
match trivia_kind {
Err(_) => {
self.set_current_token(token);
// Not trivia
break;
}
Ok(trivia_kind)
if trivia_kind.is_single_line_comment()
&& !self.config.allow_single_line_comments =>
{
self.set_current_token(token);
// Not trivia
break;
}
Ok(trivia_kind) => {
if trivia_kind.is_newline() {
trailing = false;
self.preceding_line_break = true;
}
self.trivia
.push(Trivia::new(trivia_kind, token.range(), trailing));
}
}
}
}
fn set_current_token(&mut self, token: Token) {
self.current = token.kind();
self.current_range = token.range()
}
}
impl<'source> TokenSource for CssTokenSource<'source> {
type Kind = CssSyntaxKind;
fn current(&self) -> Self::Kind {
self.current
}
fn current_range(&self) -> TextRange {
self.current_range
}
fn text(&self) -> &str {
self.lexer.source()
}
fn has_preceding_line_break(&self) -> bool {
self.preceding_line_break
}
fn bump(&mut self) {
if self.current != EOF {
self.next_non_trivia_token(false)
}
}
fn skip_as_trivia(&mut self) {
if self.current() != EOF {
self.trivia.push(Trivia::new(
TriviaPieceKind::Skipped,
self.current_range(),
false,
));
self.next_non_trivia_token(false)
}
}
fn finish(self) -> (Vec<Trivia>, Vec<ParseDiagnostic>) {
(self.trivia, self.lexer.finish())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_parser/src/parser.rs | crates/rome_css_parser/src/parser.rs | use crate::token_source::CssTokenSource;
use rome_css_syntax::CssSyntaxKind;
use rome_parser::diagnostic::merge_diagnostics;
use rome_parser::event::Event;
use rome_parser::prelude::*;
use rome_parser::token_source::Trivia;
use rome_parser::ParserContext;
pub(crate) struct CssParser<'source> {
context: ParserContext<CssSyntaxKind>,
source: CssTokenSource<'source>,
}
#[derive(Default, Debug, Clone, Copy)]
pub struct CssParserOptions {
pub allow_single_line_comments: bool,
}
impl CssParserOptions {
pub fn with_allow_single_line_comments(mut self) -> Self {
self.allow_single_line_comments = true;
self
}
}
impl<'source> CssParser<'source> {
pub fn new(source: &'source str, config: CssParserOptions) -> Self {
Self {
context: ParserContext::default(),
source: CssTokenSource::from_str(source, config),
}
}
pub fn finish(self) -> (Vec<Event<CssSyntaxKind>>, Vec<ParseDiagnostic>, Vec<Trivia>) {
let (trivia, lexer_diagnostics) = self.source.finish();
let (events, parse_diagnostics) = self.context.finish();
let diagnostics = merge_diagnostics(lexer_diagnostics, parse_diagnostics);
(events, diagnostics, trivia)
}
}
impl<'source> Parser for CssParser<'source> {
type Kind = CssSyntaxKind;
type Source = CssTokenSource<'source>;
fn context(&self) -> &ParserContext<Self::Kind> {
&self.context
}
fn context_mut(&mut self) -> &mut ParserContext<Self::Kind> {
&mut self.context
}
fn source(&self) -> &Self::Source {
&self.source
}
fn source_mut(&mut self) -> &mut Self::Source {
&mut self.source
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_parser/src/syntax.rs | crates/rome_css_parser/src/syntax.rs | use crate::parser::CssParser;
use rome_css_syntax::CssSyntaxKind::*;
use rome_parser::Parser;
pub(crate) fn parse_root(p: &mut CssParser) {
let m = p.start();
let rules = p.start();
rules.complete(p, CSS_RULE_LIST);
m.complete(p, CSS_ROOT);
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_parser/src/lexer/tests.rs | crates/rome_css_parser/src/lexer/tests.rs | #![cfg(test)]
#![allow(unused_mut, unused_variables, unused_assignments)]
use super::{Lexer, TextSize};
use quickcheck_macros::quickcheck;
use std::sync::mpsc::channel;
use std::thread;
use std::time::Duration;
// Assert the result of lexing a piece of source code,
// and make sure the tokens yielded are fully lossless and the source can be reconstructed from only the tokens
macro_rules! assert_lex {
($src:expr, $($kind:ident:$len:expr $(,)?)*) => {{
let mut lexer = Lexer::from_str($src);
let mut idx = 0;
let mut tok_idx = TextSize::default();
let mut new_str = String::with_capacity($src.len());
let tokens: Vec<_> = lexer.collect();
$(
assert_eq!(
tokens[idx].kind,
rome_css_syntax::CssSyntaxKind::$kind,
"expected token kind {}, but found {:?}",
stringify!($kind),
tokens[idx].kind,
);
assert_eq!(
tokens[idx].range.len(),
TextSize::from($len),
"expected token length of {}, but found {:?} for token {:?}",
$len,
tokens[idx].range.len(),
tokens[idx].kind,
);
new_str.push_str(&$src[tokens[idx].range]);
tok_idx += tokens[idx].range.len();
idx += 1;
)*
if idx < tokens.len() {
panic!(
"expected {} tokens but lexer returned {}, first unexpected token is '{:?}'",
idx,
tokens.len(),
tokens[idx].kind
);
} else {
assert_eq!(idx, tokens.len());
}
assert_eq!($src, new_str, "Failed to reconstruct input");
}};
}
// This is for testing if the lexer is truly lossless
// It parses random strings and puts them back together with the produced tokens and compares
#[quickcheck]
fn losslessness(string: String) -> bool {
// using an mpsc channel allows us to spawn a thread and spawn the lexer there, then if
// it takes more than 2 seconds we panic because it is 100% infinite recursion
let cloned = string.clone();
let (sender, receiver) = channel();
thread::spawn(move || {
let mut lexer = Lexer::from_str(&cloned);
let tokens: Vec<_> = lexer.map(|token| token.range).collect();
sender
.send(tokens)
.expect("Could not send tokens to receiver");
});
let token_ranges = receiver
.recv_timeout(Duration::from_secs(2))
.unwrap_or_else(|_| {
panic!(
"Lexer is infinitely recursing with this code: ->{}<-",
string
)
});
let mut new_str = String::with_capacity(string.len());
let mut idx = TextSize::from(0);
for range in token_ranges {
new_str.push_str(&string[range]);
idx += range.len();
}
string == new_str
}
#[test]
fn empty() {
assert_lex! {
"",
EOF:0
}
}
#[test]
fn string() {
assert_lex! {
"'5098382'",
CSS_STRING_LITERAL:9,
EOF:0
}
// double quote
assert_lex! {
r#"'hel"lo"'"#,
CSS_STRING_LITERAL:9,
EOF:0
}
// escaped quote
assert_lex! {
r#"'hel\'lo\''"#,
CSS_STRING_LITERAL:11,
EOF:0
}
// escaped quote
assert_lex! {
r#""hel\"lo\"""#,
CSS_STRING_LITERAL:11,
EOF:0
}
// unicode
assert_lex! {
"'юникод'",
CSS_STRING_LITERAL:14,
EOF:0
}
// missing single closing quote
assert_lex! {
"'he",
ERROR_TOKEN:3,
EOF:0
}
// missing double closing quote
assert_lex! {
r#""he"#,
ERROR_TOKEN:3,
EOF:0
}
// line break
assert_lex! {
r#"'he
"#,
ERROR_TOKEN:3,
NEWLINE:1,
WHITESPACE:4,
EOF:0
}
// line break
assert_lex! {
r#"'he
'"#,
ERROR_TOKEN:3,
NEWLINE:1,
WHITESPACE:4,
ERROR_TOKEN:1,
EOF:0
}
assert_lex! {
r#""Escaped \n""#,
CSS_STRING_LITERAL:12,
EOF:0
}
assert_lex! {
r#""Escaped \r""#,
CSS_STRING_LITERAL:12,
EOF:0
}
// invalid escape sequence
assert_lex! {
r#"'\0'"#,
ERROR_TOKEN:4,
EOF:0
}
}
#[test]
fn number() {
assert_lex! {
"5098382",
CSS_NUMBER_LITERAL:7,
EOF:0
}
assert_lex! {
"509.382",
CSS_NUMBER_LITERAL:7,
EOF:0
}
assert_lex! {
".382",
CSS_NUMBER_LITERAL:4,
EOF:0
}
assert_lex! {
"+123",
CSS_NUMBER_LITERAL:4,
EOF:0
}
assert_lex! {
"-123",
CSS_NUMBER_LITERAL:4,
EOF:0
}
assert_lex! {
"+123",
CSS_NUMBER_LITERAL:4,
EOF:0
}
assert_lex! {
"123e10",
CSS_NUMBER_LITERAL:6,
EOF:0
}
assert_lex! {
"123e+10",
CSS_NUMBER_LITERAL:7,
EOF:0
}
assert_lex! {
"123e-10",
CSS_NUMBER_LITERAL:7,
EOF:0
}
assert_lex! {
"123E10",
CSS_NUMBER_LITERAL:6,
EOF:0
}
assert_lex! {
"123E+10",
CSS_NUMBER_LITERAL:7,
EOF:0
}
assert_lex! {
"123E-10",
CSS_NUMBER_LITERAL:7,
EOF:0
}
}
#[test]
fn cdo_and_cdc() {
assert_lex! {
"<!-- -->",
CDO:4,
WHITESPACE:1,
CDC:3
EOF:0
}
}
#[test]
fn dimension() {
assert_lex! {
"100vh",
CSS_NUMBER_LITERAL:3,
IDENT:2,
EOF:0
}
}
#[test]
fn keywords() {
assert_lex! {
"media keyframes important from",
MEDIA_KW:5,
WHITESPACE:1,
KEYFRAMES_KW:9,
WHITESPACE:1,
IMPORTANT_KW:9,
WHITESPACE:1,
FROM_KW:4,
EOF:0
}
}
#[test]
fn identifier() {
assert_lex! {
"--",
MINUS:1,
MINUS:1,
EOF:0
}
assert_lex! {
"i4f5g7",
IDENT:6,
EOF:0
}
assert_lex! {
"class",
IDENT:5,
EOF:0
}
assert_lex! {
r#"cl\aass"#,
IDENT:7,
EOF:0
}
assert_lex! {
r#"\ccl\aass"#,
IDENT:9,
EOF:0
}
assert_lex! {
"-class",
IDENT:6,
EOF:0
}
assert_lex! {
r#"-cl\aass"#,
IDENT:8,
EOF:0
}
assert_lex! {
r#"-\acl\aass"#,
IDENT:10,
EOF:0
}
assert_lex! {
"--property",
CSS_CUSTOM_PROPERTY:10,
EOF:0
}
assert_lex! {
r#"--prop\eerty"#,
CSS_CUSTOM_PROPERTY:12,
EOF:0
}
assert_lex! {
r#"--\pprop\eerty"#,
CSS_CUSTOM_PROPERTY:14,
EOF:0
}
}
#[test]
fn single_line_comments() {
assert_lex! {
"//abc
",
COMMENT:5,
NEWLINE:1,
WHITESPACE:4,
EOF:0
}
assert_lex! {
"//a",
COMMENT:3,
EOF:0
}
}
#[test]
fn block_comment() {
assert_lex! {
"/*
*/",
MULTILINE_COMMENT:13,
EOF:0
}
assert_lex! {
"/* */",
COMMENT:5,
EOF:0
}
assert_lex! {
"/* *",
COMMENT:4,
EOF:0
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_parser/src/lexer/mod.rs | crates/rome_css_parser/src/lexer/mod.rs | //! An extremely fast, lookup table based, СSS lexer which yields SyntaxKind tokens used by the rome-css parser.
#[rustfmt::skip]
mod tests;
use crate::CssParserOptions;
use rome_css_syntax::{CssSyntaxKind, CssSyntaxKind::*, TextLen, TextRange, TextSize, T};
use rome_js_unicode_table::{is_id_continue, is_id_start, lookup_byte, Dispatch::*};
use rome_parser::diagnostic::ParseDiagnostic;
use std::char::REPLACEMENT_CHARACTER;
use std::iter::FusedIterator;
pub struct Token {
kind: CssSyntaxKind,
range: TextRange,
}
impl Token {
pub fn kind(&self) -> CssSyntaxKind {
self.kind
}
pub fn range(&self) -> TextRange {
self.range
}
}
/// An extremely fast, lookup table based, lossless CSS lexer
#[derive(Debug)]
pub(crate) struct Lexer<'src> {
/// Source text
source: &'src str,
/// The start byte position in the source text of the next token.
position: usize,
diagnostics: Vec<ParseDiagnostic>,
config: CssParserOptions,
}
impl<'src> Lexer<'src> {
/// Make a new lexer from a str, this is safe because strs are valid utf8
pub fn from_str(source: &'src str) -> Self {
Self {
source,
position: 0,
diagnostics: vec![],
config: CssParserOptions::default(),
}
}
pub(crate) fn with_config(mut self, config: CssParserOptions) -> Self {
self.config = config;
self
}
/// Returns the source code
pub fn source(&self) -> &'src str {
self.source
}
pub fn finish(self) -> Vec<ParseDiagnostic> {
self.diagnostics
}
/// Lexes the next token.
///
/// ## Return
/// Returns its kind.
pub(crate) fn next_token(&mut self) -> Option<Token> {
let start = self.text_position();
match self.current_byte() {
Some(current) => {
let kind = self.lex_token(current);
debug_assert!(start < self.text_position(), "Lexer did not progress");
Some(Token {
kind,
range: TextRange::new(start, self.text_position()),
})
}
None if self.position == self.source.len() => {
self.advance(1);
Some(Token {
kind: EOF,
range: TextRange::new(start, start),
})
}
None => None,
}
}
fn text_position(&self) -> TextSize {
TextSize::try_from(self.position).expect("Input to be smaller than 4 GB")
}
/// Bumps the current byte and creates a lexed token of the passed in kind
fn eat_byte(&mut self, tok: CssSyntaxKind) -> CssSyntaxKind {
self.advance(1);
tok
}
/// Consume just one newline/line break.
///
/// ## Safety
/// Must be called at a valid UT8 char boundary
fn consume_newline(&mut self) -> bool {
self.assert_current_char_boundary();
match self.current_byte() {
Some(b'\n') => {
self.advance(1);
true
}
Some(b'\r') => {
if self.peek_byte() == Some(b'\n') {
self.advance(2)
} else {
self.advance(1)
}
true
}
_ => false,
}
}
/// Consumes all whitespace until a non-whitespace or a newline is found.
///
/// ## Safety
/// Must be called at a valid UT8 char boundary
fn consume_whitespaces(&mut self) {
self.assert_current_char_boundary();
while let Some(byte) = self.current_byte() {
let dispatch = lookup_byte(byte);
match dispatch {
WHS => match byte {
b'\t' | b' ' => self.advance(1),
b'\r' | b'\n' => {
break;
}
_ => {
let start = self.text_position();
self.advance(1);
self.diagnostics.push(
ParseDiagnostic::new(
"The CSS standard only allows tabs, whitespace, carriage return and line feed whitespace.",
start..self.text_position(),
)
.hint("Use a regular whitespace character instead."),
)
}
},
_ => break,
}
}
}
/// Consume one newline or all whitespace until a non-whitespace or a newline is found.
///
/// ## Safety
/// Must be called at a valid UT8 char boundary
fn consume_newline_or_whitespaces(&mut self) -> CssSyntaxKind {
if self.consume_newline() {
NEWLINE
} else {
self.consume_whitespaces();
WHITESPACE
}
}
/// Get the UTF8 char which starts at the current byte
///
/// ## Safety
/// Must be called at a valid UT8 char boundary
fn current_char_unchecked(&self) -> char {
self.char_unchecked_at(0)
}
/// Gets the current byte.
///
/// ## Returns
/// The current byte if the lexer isn't at the end of the file.
#[inline]
fn current_byte(&self) -> Option<u8> {
if self.is_eof() {
None
} else {
Some(self.source.as_bytes()[self.position])
}
}
/// Asserts that the lexer is at current a UTF8 char boundary
#[inline]
fn assert_current_char_boundary(&self) {
debug_assert!(self.source.is_char_boundary(self.position));
}
/// Peeks at the next byte
#[inline]
fn peek_byte(&self) -> Option<u8> {
self.byte_at(1)
}
/// Peek the UTF8 char which starts at the current byte
///
/// ## Safety
/// Must be called at a valid UT8 char boundary
fn peek_char_unchecked(&self) -> char {
self.char_unchecked_at(1)
}
/// Returns the byte at position `self.position + offset` or `None` if it is out of bounds.
#[inline]
fn byte_at(&self, offset: usize) -> Option<u8> {
self.source.as_bytes().get(self.position + offset).copied()
}
/// Asserts that the lexer is at a UTF8 char boundary
#[inline]
fn assert_at_char_boundary(&self, offset: usize) {
debug_assert!(self.source.is_char_boundary(self.position + offset));
}
/// Get the UTF8 char which starts at the current byte
///
/// ## Safety
/// Must be called at a valid UT8 char boundary
fn char_unchecked_at(&self, offset: usize) -> char {
// Precautionary measure for making sure the unsafe code below does not read over memory boundary
debug_assert!(!self.is_eof());
self.assert_at_char_boundary(offset);
// Safety: We know this is safe because we require the input to the lexer to be valid utf8 and we always call this when we are at a char
let string = unsafe {
std::str::from_utf8_unchecked(
self.source
.as_bytes()
.get_unchecked((self.position + offset)..),
)
};
let chr = if let Some(chr) = string.chars().next() {
chr
} else {
// Safety: we always call this when we are at a valid char, so this branch is completely unreachable
unsafe {
core::hint::unreachable_unchecked();
}
};
chr
}
/// Check if the lexer is at a valid escape. U+005C REVERSE SOLIDUS (\)
fn is_valid_escape_at(&self, offset: usize) -> bool {
match self.byte_at(offset) {
Some(b'\n' | b'\r') | None => false,
Some(_) => true,
}
}
/// Advances the current position by `n` bytes.
#[inline]
fn advance(&mut self, n: usize) {
self.position += n;
}
#[inline]
fn advance_byte_or_char(&mut self, chr: u8) {
if chr.is_ascii() {
self.advance(1);
} else {
self.advance_char_unchecked();
}
}
/// Advances the current position by the current char UTF8 length
///
/// ## Safety
/// Must be called at a valid UT8 char boundary
#[inline]
fn advance_char_unchecked(&mut self) {
let c = self.current_char_unchecked();
self.position += c.len_utf8();
}
/// Returns `true` if the parser is at or passed the end of the file.
#[inline]
fn is_eof(&self) -> bool {
self.position >= self.source.len()
}
/// Lexes the next token
///
/// Guaranteed to not be at the end of the file
// A lookup table of `byte -> fn(l: &mut Lexer) -> Token` is exponentially slower than this approach
fn lex_token(&mut self, current: u8) -> CssSyntaxKind {
// The speed difference comes from the difference in table size, a 2kb table is easily fit into cpu cache
// While a 16kb table will be ejected from cache very often leading to slowdowns, this also allows LLVM
// to do more aggressive optimizations on the match regarding how to map it to instructions
let dispatched = lookup_byte(current);
match dispatched {
WHS => self.consume_newline_or_whitespaces(),
QOT => self.lex_string_literal(current),
SLH => self.lex_slash(),
DIG => self.lex_number(current),
MIN => {
if self.is_number_start() {
return self.lex_number(current);
}
// GREATER-THAN SIGN (->), consume them and return a CDC.
if self.peek_byte() == Some(b'-') {
if self.byte_at(2) == Some(b'>') {
self.advance(3);
return CDC;
}
// --custom-property
if self.is_ident_start() {
self.advance(2);
self.lex_identifier();
return CSS_CUSTOM_PROPERTY;
}
}
// -identifier
if self.is_ident_start() {
self.advance(1);
return self.lex_identifier();
}
self.eat_byte(T![-])
}
PLS => {
if self.is_number_start() {
self.lex_number(current)
} else {
self.eat_byte(T![+])
}
}
PRD => {
if self.is_number_start() {
self.lex_number(current)
} else {
self.eat_byte(T![.])
}
}
LSS => {
// If the next 3 input code points are U+0021 EXCLAMATION MARK U+002D
// HYPHEN-MINUS U+002D HYPHEN-MINUS (!--), consume them and return a CDO.
if self.peek_byte() == Some(b'!')
&& self.byte_at(2) == Some(b'-')
&& self.byte_at(3) == Some(b'-')
{
self.advance(4);
return CDO;
}
self.eat_byte(T![<])
}
IDT | UNI | BSL if self.is_ident_start() => self.lex_identifier(),
MUL => self.eat_byte(T![*]),
COL => self.eat_byte(T![:]),
AT_ => self.eat_byte(T![@]),
HAS => self.eat_byte(T![#]),
PNO => self.eat_byte(T!['(']),
PNC => self.eat_byte(T![')']),
BEO => self.eat_byte(T!['{']),
BEC => self.eat_byte(T!['}']),
BTO => self.eat_byte(T!('[')),
BTC => self.eat_byte(T![']']),
COM => self.eat_byte(T![,]),
_ => self.eat_unexpected_character(),
}
}
fn lex_string_literal(&mut self, quote: u8) -> CssSyntaxKind {
self.assert_current_char_boundary();
let start = self.text_position();
self.advance(1); // Skip over the quote
let mut state = LexStringState::InString;
while let Some(chr) = self.current_byte() {
let dispatch = lookup_byte(chr);
match dispatch {
QOT if quote == chr => {
self.advance(1);
state = match state {
LexStringState::InString => LexStringState::Terminated,
state => state,
};
break;
}
// '\t' etc
BSL => {
let escape_start = self.text_position();
self.advance(1);
match self.current_byte() {
Some(b'\n' | b'\r') => self.advance(1),
// Handle escaped `'` but only if this is a end quote string.
Some(b'\'') if quote == b'\'' => {
self.advance(1);
}
// Handle escaped `'` but only if this is a end quote string.
Some(b'"') if quote == b'"' => {
self.advance(1);
}
Some(c) if c.is_ascii_hexdigit() => {
// SAFETY: We know that the current byte is a hex digit.
let mut hex = (c as char).to_digit(16).unwrap();
self.advance(1);
// Consume as many hex digits as possible, but no more than 5.
// Note that this means 1-6 hex digits have been consumed in total.
for _ in 0..5 {
let Some(digit) = self.current_byte()
.and_then(|c| {
if c.is_ascii_hexdigit() {
(c as char).to_digit(16)
} else {
None
}
}) else { break; };
self.advance(1);
hex = hex * 16 + digit;
}
// Interpret the hex digits as a hexadecimal number. If this number is zero, or
// is for a surrogate, or is greater than the maximum allowed code point, return
// U+FFFD REPLACEMENT CHARACTER (�).
let hex = match hex {
// If this number is zero
0 => REPLACEMENT_CHARACTER,
// or is for a surrogate
55296..=57343 => REPLACEMENT_CHARACTER,
// or is greater than the maximum allowed code point
1114112.. => REPLACEMENT_CHARACTER,
_ => char::from_u32(hex).unwrap_or(REPLACEMENT_CHARACTER),
};
if hex == REPLACEMENT_CHARACTER {
state = LexStringState::InvalidEscapeSequence;
let diagnostic = ParseDiagnostic::new(
"Invalid escape sequence",
escape_start..self.text_position(),
);
self.diagnostics.push(diagnostic);
}
}
Some(chr) => {
self.advance_byte_or_char(chr);
}
None => {}
}
}
WHS if matches!(chr, b'\n' | b'\r') => {
let unterminated =
ParseDiagnostic::new("Missing closing quote", start..self.text_position())
.detail(self.position..self.position + 1, "line breaks here");
self.diagnostics.push(unterminated);
return ERROR_TOKEN;
}
// we don't need to handle IDT because it's always len 1.
UNI => self.advance_char_unchecked(),
_ => self.advance(1),
}
}
match state {
LexStringState::Terminated => CSS_STRING_LITERAL,
LexStringState::InString => {
let unterminated =
ParseDiagnostic::new("Missing closing quote", start..self.text_position())
.detail(
self.source.text_len()..self.source.text_len(),
"file ends here",
);
self.diagnostics.push(unterminated);
ERROR_TOKEN
}
LexStringState::InvalidEscapeSequence => ERROR_TOKEN,
}
}
/// Lexes a CSS number literal
fn lex_number(&mut self, current: u8) -> CssSyntaxKind {
debug_assert!(self.is_number_start());
if matches!(current, b'+' | b'-') {
self.advance(1);
}
// While the next input code point is a digit, consume it.
self.consume_number();
// If the next 2 input code points are U+002E FULL STOP (.) followed by a digit...
if matches!(self.current_byte(), Some(b'.'))
&& self.peek_byte().map_or(false, |byte| byte.is_ascii_digit())
{
// Consume them.
self.advance(2);
// While the next input code point is a digit, consume it.
self.consume_number()
}
// If the next 2 or 3 input code points are U+0045 LATIN CAPITAL LETTER E (E) or
// U+0065 LATIN SMALL LETTER E (e), optionally followed by U+002D HYPHEN-MINUS
// (-) or U+002B PLUS SIGN (+), followed by a digit, then:
if matches!(self.current_byte(), Some(b'e') | Some(b'E')) {
match (self.peek_byte(), self.byte_at(2)) {
(Some(b'-') | Some(b'+'), Some(byte)) if byte.is_ascii_digit() => {
// Consume them.
self.advance(3);
// While the next input code point is a digit, consume it.
self.consume_number()
}
(Some(byte), _) if byte.is_ascii_digit() => {
// Consume them.
self.advance(2);
// While the next input code point is a digit, consume it.
self.consume_number()
}
_ => {}
}
}
CSS_NUMBER_LITERAL
}
fn consume_number(&mut self) {
// While the next input code point is a digit, consume it.
while let Some(b'0'..=b'9') = self.current_byte() {
self.advance(1);
}
}
fn lex_identifier(&mut self) -> CssSyntaxKind {
// Note to keep the buffer large enough to fit every possible keyword that
// the lexer can return
let mut buf = [0u8; 20];
let count = self.consume_ident_sequence(&mut buf);
match &buf[..count] {
b"media" => MEDIA_KW,
b"keyframes" => KEYFRAMES_KW,
b"not" => NOT_KW,
b"and" => AND_KW,
b"only" => ONLY_KW,
b"or" => OR_KW,
b"i" => I_KW,
b"important" => IMPORTANT_KW,
b"from" => FROM_KW,
b"to" => TO_KW,
b"var" => VAR_KW,
_ => IDENT,
}
}
/// Consume a ident sequence.
fn consume_ident_sequence(&mut self, buf: &mut [u8]) -> usize {
debug_assert!(self.is_ident_start());
let mut idx = 0;
let mut is_first = true;
// Repeatedly consume the next input code point from the stream.
loop {
let Some(current) = self.current_byte() else {
break;
};
let dispatched = lookup_byte(current);
let chr = match dispatched {
// name code point
UNI | IDT => {
// SAFETY: We know that the current byte is a valid unicode code point
let chr = self.current_char_unchecked();
let is_id = if is_first {
is_first = false;
is_id_start(chr)
} else {
is_id_continue(chr)
};
if is_id {
chr
} else {
break;
}
}
// SAFETY: We know that the current byte is a number and we can use cast.
DIG | ZER if !is_first => current as char,
// U+005C REVERSE SOLIDUS (\)
// If the first and second code points are a valid escape, continue consume.
// Otherwise, break.
BSL if self.is_valid_escape_at(1) => '\\',
_ => break,
};
let len = chr.len_utf8();
self.advance(len);
if let Some(buf) = buf.get_mut(idx..idx + 4) {
let res = chr.encode_utf8(buf);
idx += res.len();
}
}
idx
}
/// Lexes a comment.
fn lex_slash(&mut self) -> CssSyntaxKind {
let start = self.text_position();
match self.peek_byte() {
Some(b'*') => {
// eat `/*`
self.advance(2);
let mut has_newline = false;
while let Some(chr) = self.current_byte() {
match chr {
b'*' if self.peek_byte() == Some(b'/') => {
self.advance(2);
if has_newline {
return MULTILINE_COMMENT;
} else {
return COMMENT;
}
}
b'\n' | b'\r' => {
has_newline = true;
self.advance(1)
}
chr => self.advance_byte_or_char(chr),
}
}
let err =
ParseDiagnostic::new("Unterminated block comment", start..self.text_position())
.detail(
self.position..self.position + 1,
"... but the file ends here",
);
self.diagnostics.push(err);
if has_newline {
MULTILINE_COMMENT
} else {
COMMENT
}
}
Some(b'/') => {
self.advance(2);
while let Some(chr) = self.current_byte() {
match chr {
b'\n' | b'\r' => return COMMENT,
chr => self.advance_byte_or_char(chr),
}
}
COMMENT
}
_ => self.eat_unexpected_character(),
}
}
#[inline]
fn eat_unexpected_character(&mut self) -> CssSyntaxKind {
self.assert_current_char_boundary();
let char = self.current_char_unchecked();
let err = ParseDiagnostic::new(
format!("unexpected character `{}`", char),
self.text_position()..self.text_position() + char.text_len(),
);
self.diagnostics.push(err);
self.advance(char.len_utf8());
ERROR_TOKEN
}
/// Check if the lexer starts a number.
fn is_number_start(&self) -> bool {
match self.current_byte() {
Some(b'+') | Some(b'-') => match self.peek_byte() {
// If the second code point is a digit, return true.
Some(byte) if byte.is_ascii_digit() => true,
// Otherwise, if the second code point is a U+002E FULL STOP (.) and the
// third code point is a digit, return true.
Some(b'.') if self.byte_at(2).map_or(false, |byte| byte.is_ascii_digit()) => true,
_ => false,
},
Some(b'.') => match self.peek_byte() {
// If the second code point is a digit, return true.
Some(byte) if byte.is_ascii_digit() => true,
_ => false,
},
Some(byte) => byte.is_ascii_digit(),
_ => false,
}
}
/// Check if the lexer starts an identifier.
fn is_ident_start(&self) -> bool {
let Some(current) = self.current_byte() else {
return false;
};
// Look at the first code point:
match lookup_byte(current) {
// U+002D HYPHEN-MINUS
MIN => {
let Some(next) = self.peek_byte() else {
return false;
};
match lookup_byte(next) {
MIN => {
let Some(next) = self.byte_at(2) else {
return false;
};
match lookup_byte(next) {
// If the third code point is a name-start code point
// return true.
UNI | IDT if is_id_start(self.char_unchecked_at(2)) => true,
// or the third and fourth code points are a valid escape
// return true.
BSL => self.is_valid_escape_at(3),
_ => false,
}
}
// If the second code point is a name-start code point
// return true.
UNI | IDT if is_id_start(self.peek_char_unchecked()) => true,
// or the second and third code points are a valid escape
// return true.
BSL => self.is_valid_escape_at(2),
_ => false,
}
}
UNI | IDT if is_id_start(self.current_char_unchecked()) => true,
// U+005C REVERSE SOLIDUS (\)
// If the first and second code points are a valid escape, return true. Otherwise,
// return false.
BSL => self.is_valid_escape_at(1),
_ => false,
}
}
}
impl Iterator for Lexer<'_> {
type Item = Token;
fn next(&mut self) -> Option<Self::Item> {
self.next_token()
}
}
impl FusedIterator for Lexer<'_> {}
#[derive(Copy, Clone, Debug)]
enum LexStringState {
/// String that contains an invalid escape sequence
InvalidEscapeSequence,
/// Between the opening `"` and closing `"` quotes.
InString,
/// Properly terminated string
Terminated,
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_parser/tests/spec_test.rs | crates/rome_css_parser/tests/spec_test.rs | use rome_console::fmt::{Formatter, Termcolor};
use rome_console::markup;
use rome_css_parser::{parse_css, CssParserOptions};
use rome_diagnostics::display::PrintDiagnostic;
use rome_diagnostics::termcolor;
use rome_diagnostics::DiagnosticExt;
use rome_rowan::SyntaxKind;
use std::fmt::Write;
use std::fs;
use std::path::Path;
#[derive(Copy, Clone)]
pub enum ExpectedOutcome {
Pass,
Fail,
Undefined,
}
pub fn run(test_case: &str, _snapshot_name: &str, test_directory: &str, outcome_str: &str) {
let outcome = match outcome_str {
"ok" => ExpectedOutcome::Pass,
"error" => ExpectedOutcome::Fail,
"undefined" => ExpectedOutcome::Undefined,
"allow_single_line_comments" => ExpectedOutcome::Pass,
_ => panic!("Invalid expected outcome {outcome_str}"),
};
let test_case_path = Path::new(test_case);
let file_name = test_case_path
.file_name()
.expect("Expected test to have a file name")
.to_str()
.expect("File name to be valid UTF8");
let content = fs::read_to_string(test_case_path)
.expect("Expected test path to be a readable file in UTF8 encoding");
let parse_config = CssParserOptions {
allow_single_line_comments: outcome_str == "allow_single_line_comments",
};
let parsed = parse_css(&content, parse_config);
let formatted_ast = format!("{:#?}", parsed.tree());
let mut snapshot = String::new();
writeln!(snapshot, "\n## Input\n\n```css\n{content}\n```\n\n").unwrap();
writeln!(
snapshot,
r#"## AST
```
{formatted_ast}
```
## CST
```
{:#?}
```
"#,
parsed.syntax()
)
.unwrap();
let diagnostics = parsed.diagnostics();
if !diagnostics.is_empty() {
let mut diagnostics_buffer = termcolor::Buffer::no_color();
let termcolor = &mut Termcolor(&mut diagnostics_buffer);
let mut formatter = Formatter::new(termcolor);
for diagnostic in diagnostics {
let error = diagnostic
.clone()
.with_file_path(file_name)
.with_file_source_code(&content);
formatter
.write_markup(markup! {
{PrintDiagnostic::verbose(&error)}
})
.expect("failed to emit diagnostic");
}
let formatted_diagnostics =
std::str::from_utf8(diagnostics_buffer.as_slice()).expect("non utf8 in error buffer");
if matches!(outcome, ExpectedOutcome::Pass) {
panic!("Expected no errors to be present in a test case that is expected to pass but the following diagnostics are present:\n{formatted_diagnostics}")
}
writeln!(snapshot, "## Diagnostics\n\n```").unwrap();
snapshot.write_str(formatted_diagnostics).unwrap();
writeln!(snapshot, "```\n").unwrap();
}
match outcome {
ExpectedOutcome::Pass => {
let missing_required = formatted_ast.contains("missing (required)");
if missing_required
|| parsed
.syntax()
.descendants()
.any(|node| node.kind().is_bogus())
{
panic!("Parsed tree of a 'OK' test case should not contain any missing required children or bogus nodes");
}
}
ExpectedOutcome::Fail => {
if parsed.diagnostics().is_empty() {
panic!("Failing test must have diagnostics");
}
}
_ => {}
}
insta::with_settings!({
prepend_module_to_snapshot => false,
snapshot_path => &test_directory,
}, {
insta::assert_snapshot!(file_name, snapshot);
});
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_parser/tests/spec_tests.rs | crates/rome_css_parser/tests/spec_tests.rs | #![allow(non_snake_case)]
mod spec_test;
mod ok {
//! Tests that must pass according to the CSS specification
tests_macros::gen_tests! {"tests/css_test_suite/ok/*.css", crate::spec_test::run, "ok"}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_factory/src/lib.rs | crates/rome_json_factory/src/lib.rs | pub use crate::generated::JsonSyntaxFactory;
use rome_json_syntax::JsonLanguage;
use rome_rowan::TreeBuilder;
mod generated;
// Re-exported for tests
#[doc(hidden)]
pub use rome_json_syntax as syntax;
pub type JsonSyntaxTreeBuilder = TreeBuilder<'static, JsonLanguage, JsonSyntaxFactory>;
pub use generated::node_factory as make;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_factory/src/generated.rs | crates/rome_json_factory/src/generated.rs | #[rustfmt::skip]
pub(super) mod syntax_factory;
#[rustfmt::skip]
pub mod node_factory;
pub use syntax_factory::JsonSyntaxFactory;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_factory/src/generated/syntax_factory.rs | crates/rome_json_factory/src/generated/syntax_factory.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use rome_json_syntax::{JsonSyntaxKind, JsonSyntaxKind::*, T, *};
use rome_rowan::{AstNode, ParsedChildren, RawNodeSlots, RawSyntaxNode, SyntaxFactory, SyntaxKind};
#[derive(Debug)]
pub struct JsonSyntaxFactory;
impl SyntaxFactory for JsonSyntaxFactory {
type Kind = JsonSyntaxKind;
#[allow(unused_mut)]
fn make_syntax(
kind: Self::Kind,
children: ParsedChildren<Self::Kind>,
) -> RawSyntaxNode<Self::Kind> {
match kind {
JSON_BOGUS | JSON_BOGUS_VALUE => {
RawSyntaxNode::new(kind, children.into_iter().map(Some))
}
JSON_ARRAY_VALUE => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T!['['] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if JsonArrayElementList::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T![']'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JSON_ARRAY_VALUE.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JSON_ARRAY_VALUE, children)
}
JSON_BOOLEAN_VALUE => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<1usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if matches!(element.kind(), T![true] | T![false]) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JSON_BOOLEAN_VALUE.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JSON_BOOLEAN_VALUE, children)
}
JSON_MEMBER => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if JsonMemberName::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T ! [:] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if AnyJsonValue::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JSON_MEMBER.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JSON_MEMBER, children)
}
JSON_MEMBER_NAME => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<1usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == JSON_STRING_LITERAL {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JSON_MEMBER_NAME.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JSON_MEMBER_NAME, children)
}
JSON_NULL_VALUE => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<1usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T![null] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JSON_NULL_VALUE.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JSON_NULL_VALUE, children)
}
JSON_NUMBER_VALUE => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<1usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == JSON_NUMBER_LITERAL {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JSON_NUMBER_VALUE.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JSON_NUMBER_VALUE, children)
}
JSON_OBJECT_VALUE => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<3usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == T!['{'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if JsonMemberList::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T!['}'] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JSON_OBJECT_VALUE.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JSON_OBJECT_VALUE, children)
}
JSON_ROOT => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<2usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if AnyJsonValue::can_cast(element.kind()) {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if let Some(element) = ¤t_element {
if element.kind() == T![EOF] {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JSON_ROOT.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JSON_ROOT, children)
}
JSON_STRING_VALUE => {
let mut elements = (&children).into_iter();
let mut slots: RawNodeSlots<1usize> = RawNodeSlots::default();
let mut current_element = elements.next();
if let Some(element) = ¤t_element {
if element.kind() == JSON_STRING_LITERAL {
slots.mark_present();
current_element = elements.next();
}
}
slots.next_slot();
if current_element.is_some() {
return RawSyntaxNode::new(
JSON_STRING_VALUE.to_bogus(),
children.into_iter().map(Some),
);
}
slots.into_node(JSON_STRING_VALUE, children)
}
JSON_ARRAY_ELEMENT_LIST => Self::make_separated_list_syntax(
kind,
children,
AnyJsonValue::can_cast,
T ! [,],
false,
),
JSON_MEMBER_LIST => Self::make_separated_list_syntax(
kind,
children,
JsonMember::can_cast,
T ! [,],
false,
),
_ => unreachable!("Is {:?} a token?", kind),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_factory/src/generated/node_factory.rs | crates/rome_json_factory/src/generated/node_factory.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
#![allow(clippy::redundant_closure)]
#![allow(clippy::too_many_arguments)]
use rome_json_syntax::{
JsonSyntaxElement as SyntaxElement, JsonSyntaxNode as SyntaxNode,
JsonSyntaxToken as SyntaxToken, *,
};
use rome_rowan::AstNode;
pub fn json_array_value(
l_brack_token: SyntaxToken,
r_brack_token: SyntaxToken,
) -> JsonArrayValueBuilder {
JsonArrayValueBuilder {
l_brack_token,
r_brack_token,
elements: None,
}
}
pub struct JsonArrayValueBuilder {
l_brack_token: SyntaxToken,
r_brack_token: SyntaxToken,
elements: Option<JsonArrayElementList>,
}
impl JsonArrayValueBuilder {
pub fn with_elements(mut self, elements: JsonArrayElementList) -> Self {
self.elements = Some(elements);
self
}
pub fn build(self) -> JsonArrayValue {
JsonArrayValue::unwrap_cast(SyntaxNode::new_detached(
JsonSyntaxKind::JSON_ARRAY_VALUE,
[
Some(SyntaxElement::Token(self.l_brack_token)),
self.elements
.map(|token| SyntaxElement::Node(token.into_syntax())),
Some(SyntaxElement::Token(self.r_brack_token)),
],
))
}
}
pub fn json_boolean_value(value_token_token: SyntaxToken) -> JsonBooleanValue {
JsonBooleanValue::unwrap_cast(SyntaxNode::new_detached(
JsonSyntaxKind::JSON_BOOLEAN_VALUE,
[Some(SyntaxElement::Token(value_token_token))],
))
}
pub fn json_member(
name: JsonMemberName,
colon_token: SyntaxToken,
value: AnyJsonValue,
) -> JsonMember {
JsonMember::unwrap_cast(SyntaxNode::new_detached(
JsonSyntaxKind::JSON_MEMBER,
[
Some(SyntaxElement::Node(name.into_syntax())),
Some(SyntaxElement::Token(colon_token)),
Some(SyntaxElement::Node(value.into_syntax())),
],
))
}
pub fn json_member_name(value_token: SyntaxToken) -> JsonMemberName {
JsonMemberName::unwrap_cast(SyntaxNode::new_detached(
JsonSyntaxKind::JSON_MEMBER_NAME,
[Some(SyntaxElement::Token(value_token))],
))
}
pub fn json_null_value(value_token: SyntaxToken) -> JsonNullValue {
JsonNullValue::unwrap_cast(SyntaxNode::new_detached(
JsonSyntaxKind::JSON_NULL_VALUE,
[Some(SyntaxElement::Token(value_token))],
))
}
pub fn json_number_value(value_token: SyntaxToken) -> JsonNumberValue {
JsonNumberValue::unwrap_cast(SyntaxNode::new_detached(
JsonSyntaxKind::JSON_NUMBER_VALUE,
[Some(SyntaxElement::Token(value_token))],
))
}
pub fn json_object_value(
l_curly_token: SyntaxToken,
r_curly_token: SyntaxToken,
) -> JsonObjectValueBuilder {
JsonObjectValueBuilder {
l_curly_token,
r_curly_token,
json_member_list: None,
}
}
pub struct JsonObjectValueBuilder {
l_curly_token: SyntaxToken,
r_curly_token: SyntaxToken,
json_member_list: Option<JsonMemberList>,
}
impl JsonObjectValueBuilder {
pub fn with_json_member_list(mut self, json_member_list: JsonMemberList) -> Self {
self.json_member_list = Some(json_member_list);
self
}
pub fn build(self) -> JsonObjectValue {
JsonObjectValue::unwrap_cast(SyntaxNode::new_detached(
JsonSyntaxKind::JSON_OBJECT_VALUE,
[
Some(SyntaxElement::Token(self.l_curly_token)),
self.json_member_list
.map(|token| SyntaxElement::Node(token.into_syntax())),
Some(SyntaxElement::Token(self.r_curly_token)),
],
))
}
}
pub fn json_root(value: AnyJsonValue, eof_token: SyntaxToken) -> JsonRoot {
JsonRoot::unwrap_cast(SyntaxNode::new_detached(
JsonSyntaxKind::JSON_ROOT,
[
Some(SyntaxElement::Node(value.into_syntax())),
Some(SyntaxElement::Token(eof_token)),
],
))
}
pub fn json_string_value(value_token: SyntaxToken) -> JsonStringValue {
JsonStringValue::unwrap_cast(SyntaxNode::new_detached(
JsonSyntaxKind::JSON_STRING_VALUE,
[Some(SyntaxElement::Token(value_token))],
))
}
pub fn json_array_element_list<I, S>(items: I, separators: S) -> JsonArrayElementList
where
I: IntoIterator<Item = AnyJsonValue>,
I::IntoIter: ExactSizeIterator,
S: IntoIterator<Item = JsonSyntaxToken>,
S::IntoIter: ExactSizeIterator,
{
let mut items = items.into_iter();
let mut separators = separators.into_iter();
let length = items.len() + separators.len();
JsonArrayElementList::unwrap_cast(SyntaxNode::new_detached(
JsonSyntaxKind::JSON_ARRAY_ELEMENT_LIST,
(0..length).map(|index| {
if index % 2 == 0 {
Some(items.next()?.into_syntax().into())
} else {
Some(separators.next()?.into())
}
}),
))
}
pub fn json_member_list<I, S>(items: I, separators: S) -> JsonMemberList
where
I: IntoIterator<Item = JsonMember>,
I::IntoIter: ExactSizeIterator,
S: IntoIterator<Item = JsonSyntaxToken>,
S::IntoIter: ExactSizeIterator,
{
let mut items = items.into_iter();
let mut separators = separators.into_iter();
let length = items.len() + separators.len();
JsonMemberList::unwrap_cast(SyntaxNode::new_detached(
JsonSyntaxKind::JSON_MEMBER_LIST,
(0..length).map(|index| {
if index % 2 == 0 {
Some(items.next()?.into_syntax().into())
} else {
Some(separators.next()?.into())
}
}),
))
}
pub fn json_bogus<I>(slots: I) -> JsonBogus
where
I: IntoIterator<Item = Option<SyntaxElement>>,
I::IntoIter: ExactSizeIterator,
{
JsonBogus::unwrap_cast(SyntaxNode::new_detached(JsonSyntaxKind::JSON_BOGUS, slots))
}
pub fn json_bogus_value<I>(slots: I) -> JsonBogusValue
where
I: IntoIterator<Item = Option<SyntaxElement>>,
I::IntoIter: ExactSizeIterator,
{
JsonBogusValue::unwrap_cast(SyntaxNode::new_detached(
JsonSyntaxKind::JSON_BOGUS_VALUE,
slots,
))
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_deserialize/src/diagnostics.rs | crates/rome_deserialize/src/diagnostics.rs | use rome_console::fmt::Display;
use rome_console::{markup, MarkupBuf};
use rome_diagnostics::location::AsSpan;
use rome_diagnostics::{Advices, Diagnostic, LogCategory, MessageAndDescription, Severity, Visit};
use rome_rowan::{SyntaxError, TextRange};
use serde::{Deserialize, Serialize};
/// Diagnostic emitted during the deserialization
#[derive(Debug, Serialize, Clone, Deserialize, Diagnostic)]
#[diagnostic(category = "deserialize")]
pub struct DeserializationDiagnostic {
#[message]
#[description]
reason: MessageAndDescription,
#[location(span)]
range: Option<TextRange>,
#[advice]
deserialization_advice: DeserializationAdvice,
#[severity]
severity: Severity,
}
impl DeserializationDiagnostic {
pub fn new(reason: impl Display) -> Self {
Self {
reason: markup! {{reason}}.to_owned().into(),
range: None,
deserialization_advice: DeserializationAdvice::default(),
severity: Severity::Error,
}
}
/// Emitted when the type of a value is incorrect.
pub fn new_incorrect_type_for_value(
key_name: impl Display,
expected_type: impl Display,
range: impl AsSpan,
) -> Self {
Self::new(markup! {
"The value of key "<Emphasis>{{key_name}}</Emphasis>" is incorrect. Expected a "<Emphasis>{{expected_type}}"."</Emphasis>
}).with_range(range)
}
/// Emitted when a generic node has an incorrect type
pub fn new_incorrect_type(expected_type: impl Display, range: impl AsSpan) -> Self {
Self::new(markup! {
"Incorrect type, expected a "<Emphasis>{{expected_type}}"."</Emphasis>
})
.with_range(range)
}
/// Emitted when there's an unknown key, against a set of known ones
pub fn new_unknown_key(
key_name: impl Display,
range: impl AsSpan,
known_members: &[&str],
) -> Self {
Self::new(markup!("Found an unknown key `"<Emphasis>{{ key_name }}</Emphasis>"`." ))
.with_range(range)
.note_with_list("Accepted keys", known_members)
}
/// Emitted when there's an unknown value, against a set of known ones
pub fn new_unknown_value(
variant_name: impl Display,
range: impl AsSpan,
known_variants: &[&str],
) -> Self {
Self::new(markup! {"Found an unknown value `"<Emphasis>{{ variant_name }}</Emphasis>"`."})
.with_range(range)
.note_with_list("Accepted values:", known_variants)
}
/// Adds a range to the diagnostic
pub fn with_range(mut self, span: impl AsSpan) -> Self {
self.range = span.as_span();
self
}
/// Adds a note to the diagnostic
pub fn with_note(mut self, message: impl Display) -> Self {
self.deserialization_advice
.notes
.push((markup! {{message}}.to_owned(), vec![]));
self
}
/// Changes the severity of the diagnostic
pub fn with_custom_severity(mut self, severity: Severity) -> Self {
self.severity = severity;
self
}
/// Adds a note with a list of strings
pub fn note_with_list(mut self, message: impl Display, list: &[impl Display]) -> Self {
self.deserialization_advice.notes.push((
markup! {{message}}.to_owned(),
list.iter()
.map(|message| markup! {{message}}.to_owned())
.collect::<Vec<_>>(),
));
self
}
}
impl From<SyntaxError> for DeserializationDiagnostic {
fn from(_: SyntaxError) -> Self {
DeserializationDiagnostic::new("Syntax error")
}
}
#[derive(Debug, Default, Clone, Deserialize, Serialize)]
pub struct DeserializationAdvice {
notes: Vec<(MarkupBuf, Vec<MarkupBuf>)>,
}
impl DeserializationAdvice {
pub fn note(mut self, message: impl Display) -> Self {
self.notes
.push((markup! {{message}}.to_owned(), Vec::new()));
self
}
}
impl Advices for DeserializationAdvice {
fn record(&self, visitor: &mut dyn Visit) -> std::io::Result<()> {
for (message, known_keys) in &self.notes {
visitor.record_log(LogCategory::Info, message)?;
if !known_keys.is_empty() {
let list: Vec<_> = known_keys
.iter()
.map(|message| message as &dyn Display)
.collect();
visitor.record_list(&list)?;
}
}
Ok(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_deserialize/src/visitor.rs | crates/rome_deserialize/src/visitor.rs | use crate::DeserializationDiagnostic;
use rome_rowan::{Language, SyntaxNode};
/// Generic trait to implement when resolving the configuration from a generic language
pub trait VisitNode<L: Language>: Sized {
/// Called when visiting the key of a member
fn visit_member_name(
&mut self,
_node: &SyntaxNode<L>,
_diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
unimplemented!("you should implement visit_member_name")
}
/// Called when visiting the value of a member
fn visit_member_value(
&mut self,
_node: &SyntaxNode<L>,
_diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
unimplemented!("you should implement visit_member_value")
}
/// Called when visiting a list of key-value.
///
/// The implementor should loop through the list and call this function by passing two nodes,
/// the key/name as first argument, and the value as second argument.
fn visit_map(
&mut self,
_key: &SyntaxNode<L>,
_value: &SyntaxNode<L>,
_diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
unimplemented!("you should implement visit_map")
}
/// Called when visiting a list of elements.
///
/// The implementor should loop through the list and call this function by passing the encountered nodes.
fn visit_array_member(
&mut self,
_element: &SyntaxNode<L>,
_diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
unimplemented!("you should implement visit_array_member")
}
}
impl<L: Language> VisitNode<L> for () {
fn visit_map(
&mut self,
_key: &SyntaxNode<L>,
_value: &SyntaxNode<L>,
_diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
Some(())
}
fn visit_member_name(
&mut self,
_node: &SyntaxNode<L>,
_diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
Some(())
}
fn visit_member_value(
&mut self,
_node: &SyntaxNode<L>,
_diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
Some(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_deserialize/src/lib.rs | crates/rome_deserialize/src/lib.rs | mod diagnostics;
mod visitor;
pub mod json;
pub mod string_set;
pub use diagnostics::{DeserializationAdvice, DeserializationDiagnostic};
use rome_diagnostics::Error;
pub use string_set::{deserialize_string_set, serialize_string_set, StringSet};
pub use visitor::VisitNode;
/// A small type to interrogate the result of a JSON deserialization
#[derive(Default)]
pub struct Deserialized<P> {
diagnostics: Vec<Error>,
deserialized: P,
}
impl<P> Deserialized<P> {
/// [DeserializationDiagnostic] are converted into [Error]
pub fn new(deserialized: P, diagnostics: Vec<DeserializationDiagnostic>) -> Self {
Self {
deserialized,
diagnostics: diagnostics.into_iter().map(Error::from).collect(),
}
}
/// Consumes self to return the diagnostics
pub fn into_diagnostics(self) -> Vec<Error> {
self.diagnostics
}
pub fn diagnostics(&self) -> &[Error] {
self.diagnostics.as_slice()
}
/// Consumes self and returns the deserialized result
pub fn into_deserialized(self) -> P {
self.deserialized
}
pub fn has_errors(&self) -> bool {
!self.diagnostics.is_empty()
}
/// Consume itself to return the parsed result and its diagnostics
pub fn consume(self) -> (P, Vec<Error>) {
(self.deserialized, self.diagnostics)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_deserialize/src/json.rs | crates/rome_deserialize/src/json.rs | use crate::{DeserializationDiagnostic, Deserialized, VisitNode};
use indexmap::IndexSet;
use rome_console::markup;
use rome_diagnostics::{DiagnosticExt, Error};
use rome_json_parser::{parse_json, JsonParserOptions};
use rome_json_syntax::{
AnyJsonValue, JsonArrayValue, JsonBooleanValue, JsonLanguage, JsonMemberName, JsonNumberValue,
JsonObjectValue, JsonRoot, JsonStringValue, JsonSyntaxNode,
};
use rome_rowan::{AstNode, AstSeparatedList, SyntaxNodeCast, TextRange, TokenText};
use std::num::ParseIntError;
/// Main trait to
pub trait JsonDeserialize: Sized {
/// It accepts a JSON AST and a visitor. The visitor is the [default](Default) implementation of the data
/// type that implements this trait.
fn deserialize_from_ast(
root: &JsonRoot,
visitor: &mut impl VisitJsonNode,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()>;
}
impl JsonDeserialize for () {
fn deserialize_from_ast(
_root: &JsonRoot,
_visitor: &mut impl VisitJsonNode,
_diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
Some(())
}
}
/// Convenient trait that contains utility functions to work with [JsonLanguage]
pub trait VisitJsonNode: VisitNode<JsonLanguage> {
/// Convenient function to use inside [visit_map].
///
/// It casts key to [JsonMemberName] and verifies that key name is correct by calling
/// [visit_member_name].
///
/// It casts the value to [AnyJsonValue].
///
/// ## Errors
///
/// The function will emit a generic diagnostic if [visit_member_name] is not implemented by
/// the visitor that calls this function.
fn get_key_and_value(
&mut self,
key: &JsonSyntaxNode,
value: &JsonSyntaxNode,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<(TokenText, AnyJsonValue)> {
let member = key.clone().cast::<JsonMemberName>()?;
self.visit_member_name(member.syntax(), diagnostics)?;
let name = member.inner_string_text().ok()?;
let value = value.clone().cast::<AnyJsonValue>()?;
Some((name, value))
}
/// It attempts to map a [AnyJsonValue] to a string.
///
/// Use this function when you want to map a string to an enum type.
///
/// ## Errors
///
/// The function will emit a generic diagnostic if the `visitor` doesn't implement [visit_member_value]
fn map_to_known_string<T>(
&self,
value: &AnyJsonValue,
name: &str,
visitor: &mut T,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()>
where
T: VisitNode<JsonLanguage>,
{
let value = JsonStringValue::cast_ref(value.syntax()).or_else(|| {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type_for_value(
name,
"string",
value.range(),
));
None
})?;
visitor.visit_member_value(value.syntax(), diagnostics)?;
Some(())
}
/// It attempts to map a [AnyJsonValue] to a [String].
///
/// ## Errors
///
/// It emits an error if `value` can't be cast to a [JsonStringValue]
fn map_to_string(
&self,
value: &AnyJsonValue,
name: &str,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<String> {
JsonStringValue::cast_ref(value.syntax())
.and_then(|node| Some(node.inner_string_text().ok()?.to_string()))
.or_else(|| {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type_for_value(
name,
"string",
value.range(),
));
None
})
}
/// It attempts to map a [AnyJsonValue] to a [u8].
///
/// ## Errors
///
/// It will fail if:
/// - `value` can't be cast to [JsonNumberValue]
/// - the value of the node can't be parsed to [u8]
fn map_to_u8(
&self,
value: &AnyJsonValue,
name: &str,
maximum: u8,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<u8> {
let value = JsonNumberValue::cast_ref(value.syntax()).or_else(|| {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type_for_value(
name,
"number",
value.range(),
));
None
})?;
let value = value.value_token().ok()?;
let result = value.text_trimmed().parse::<u8>().map_err(|err| {
emit_diagnostic_form_number(
err,
value.text_trimmed(),
value.text_trimmed_range(),
maximum,
)
});
match result {
Ok(number) => Some(number),
Err(err) => {
diagnostics.push(err);
None
}
}
}
/// It attempts to map a [AnyJsonValue] to a [usize].
///
/// ## Errors
///
/// It will fail if:
/// - `value` can't be cast to [JsonNumberValue]
/// - the value of the node can't be parsed to [usize]
fn map_to_usize(
&self,
value: &AnyJsonValue,
name: &str,
maximum: usize,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<usize> {
let value = JsonNumberValue::cast_ref(value.syntax()).or_else(|| {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type_for_value(
name,
"number",
value.range(),
));
None
})?;
let value = value.value_token().ok()?;
let result = value.text_trimmed().parse::<usize>().map_err(|err| {
emit_diagnostic_form_number(
err,
value.text_trimmed(),
value.text_trimmed_range(),
maximum,
)
});
match result {
Ok(number) => Some(number),
Err(err) => {
diagnostics.push(err);
None
}
}
}
/// It attempts to map a [AnyJsonValue] to a [u16].
///
/// ## Errors
///
/// It will fail if:
/// - `value` can't be cast to [JsonNumberValue]
/// - the value of the node can't be parsed to [u16]
fn map_to_u16(
&self,
value: &AnyJsonValue,
name: &str,
maximum: u16,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<u16> {
let value = JsonNumberValue::cast_ref(value.syntax())
.ok_or_else(|| {
DeserializationDiagnostic::new_incorrect_type_for_value(
name,
"number",
value.range(),
)
})
.ok()?;
let value = value.value_token().ok()?;
let result = value.text_trimmed().parse::<u16>().map_err(|err| {
emit_diagnostic_form_number(
err,
value.text_trimmed(),
value.text_trimmed_range(),
maximum,
)
});
match result {
Ok(number) => Some(number),
Err(err) => {
diagnostics.push(err);
None
}
}
}
/// It attempts to map a [AnyJsonValue] to a [u64].
///
/// ## Errors
///
/// It will fail if:
/// - `value` can't be cast to [JsonNumberValue]
/// - the value of the node can't be parsed to [u64]
fn map_to_u64(
&self,
value: &AnyJsonValue,
name: &str,
maximum: u64,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<u64> {
let value = JsonNumberValue::cast_ref(value.syntax()).or_else(|| {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type_for_value(
name,
"number",
value.range(),
));
None
})?;
let value = value.value_token().ok()?;
let result = value.text_trimmed().parse::<u64>().map_err(|err| {
emit_diagnostic_form_number(
err,
value.text_trimmed(),
value.text_trimmed_range(),
maximum,
)
});
match result {
Ok(number) => Some(number),
Err(err) => {
diagnostics.push(err);
None
}
}
}
/// It attempts to cast [AnyJsonValue] to a [bool]
///
/// ## Errors
///
/// The function emits a diagnostic if `value` can't be cast to [JsonBooleanValue]
fn map_to_boolean(
&self,
value: &AnyJsonValue,
name: &str,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<bool> {
JsonBooleanValue::cast_ref(value.syntax())
.and_then(|value| Some(value.value_token().ok()?.text_trimmed() == "true"))
.or_else(|| {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type_for_value(
name,
"boolean",
value.range(),
));
None
})
}
/// It attempts to map a [AnyJsonValue] to a [IndexSet] of [String].
///
/// ## Errors
///
/// The function emit diagnostics if:
/// - `value` can't be cast to [JsonArrayValue]
/// - any element of the of the array can't be cast to [JsonStringValue]
fn map_to_index_set_string(
&self,
value: &AnyJsonValue,
name: &str,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<IndexSet<String>> {
let array = JsonArrayValue::cast_ref(value.syntax()).or_else(|| {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type_for_value(
name,
"array",
value.range(),
));
None
})?;
let mut elements = IndexSet::new();
if array.elements().is_empty() {
return None;
}
for element in array.elements() {
let element = element.ok()?;
match element {
AnyJsonValue::JsonStringValue(value) => {
elements.insert(value.inner_string_text().ok()?.to_string());
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"string",
element.range(),
));
}
}
}
Some(elements)
}
/// It attempts to map a [AnyJsonValue] to a [Vec] of [String].
///
/// ## Errors
///
/// The function emit diagnostics if:
/// - `value` can't be cast to [JsonArrayValue]
/// - any element of the of the array can't be cast to [JsonStringValue]
fn map_to_array_of_strings(
&self,
value: &AnyJsonValue,
name: &str,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<Vec<String>> {
let array = JsonArrayValue::cast_ref(value.syntax()).or_else(|| {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type_for_value(
name,
"array",
value.range(),
));
None
})?;
let mut elements = Vec::new();
if array.elements().is_empty() {
return None;
}
for element in array.elements() {
let element = element.ok()?;
match element {
AnyJsonValue::JsonStringValue(value) => {
elements.push(value.inner_string_text().ok()?.to_string());
}
_ => {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type(
"string",
element.range(),
));
}
}
}
Some(elements)
}
/// It attempts to map [AnyJsonValue] to a generic map.
///
/// Use this function when the value of your member is another object, and this object
/// needs to be mapped to another type.
///
/// This function will loop though the list of elements and call [visit_map] on each pair
/// of `name` and `value`.
///
/// ## Errors
/// This function will emit diagnostics if:
/// - the `value` can't be cast to [JsonObjectValue]
fn map_to_object<T>(
&mut self,
value: &AnyJsonValue,
name: &str,
visitor: &mut T,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()>
where
T: VisitNode<JsonLanguage>,
{
let value = JsonObjectValue::cast_ref(value.syntax()).or_else(|| {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type_for_value(
name,
"object",
value.range(),
));
None
})?;
for element in value.json_member_list() {
let element = element.ok()?;
visitor.visit_map(
element.name().ok()?.syntax(),
element.value().ok()?.syntax(),
diagnostics,
)?;
}
Some(())
}
fn map_to_array<V>(
&mut self,
value: &AnyJsonValue,
name: &str,
visitor: &mut V,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()>
where
V: VisitNode<JsonLanguage>,
{
let array = JsonArrayValue::cast_ref(value.syntax()).or_else(|| {
diagnostics.push(DeserializationDiagnostic::new_incorrect_type_for_value(
name,
"array",
value.range(),
));
None
})?;
if array.elements().is_empty() {
return None;
}
for element in array.elements() {
let element = element.ok()?;
visitor.visit_array_member(element.syntax(), diagnostics);
}
Some(())
}
}
impl VisitJsonNode for () {}
fn emit_diagnostic_form_number(
parse_error: ParseIntError,
value_text: &str,
value_range: TextRange,
maximum: impl rome_console::fmt::Display,
) -> DeserializationDiagnostic {
let diagnostic =
DeserializationDiagnostic::new(parse_error.to_string()).with_range(value_range);
if value_text.starts_with('-') {
diagnostic.with_note(markup! {"Value can't be negative"})
} else {
diagnostic.with_note(markup! {"Maximum value accepted is "{{maximum}}})
}
}
/// Convenient function to check if the current [JsonMemberName] belongs to a sub set of
/// `allowed_keys`
pub fn has_only_known_keys(
node: &JsonSyntaxNode,
allowed_keys: &[&str],
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
node.clone().cast::<JsonMemberName>().and_then(|node| {
let key_name = node.inner_string_text().ok()?;
if allowed_keys.contains(&key_name.text()) {
Some(())
} else {
diagnostics.push(DeserializationDiagnostic::new_unknown_key(
key_name.text(),
node.range(),
allowed_keys,
));
None
}
})
}
/// Convenient function that returns a [JsonStringValue] from a generic node, and checks
/// if it's content matches the `allowed_keys`.
///
/// Useful when when you're parsing an `enum` and you still need to verify the value of the node, but
/// still need it.
pub fn with_only_known_variants(
node: &JsonSyntaxNode,
allowed_keys: &[&str],
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<JsonStringValue> {
node.clone().cast::<JsonStringValue>().and_then(|node| {
let key_name = node.inner_string_text().ok()?;
if allowed_keys.contains(&key_name.text()) {
Some(node)
} else {
diagnostics.push(DeserializationDiagnostic::new_unknown_value(
key_name.text(),
node.range(),
allowed_keys,
));
None
}
})
}
/// It attempts to parse and deserialize a source file in JSON. Diagnostics from the parse phase
/// are consumed and joined with the diagnostics emitted during the deserialization.
///
/// The data structure that needs to be deserialized needs to implement three important traits:
/// - [Default], to create a first instance of the data structure;
/// - [JsonDeserialize], a trait to begin the deserialization from JSON AST;
/// - [VisitNode], to visit values inside a JSON file;
/// - [VisitJsonNode], to inherit a series of useful functions to handle specifically
/// JSON values;
///
/// ## Examples
///
/// ```
/// use rome_deserialize::{DeserializationDiagnostic, VisitNode, Deserialized};
/// use rome_deserialize::json::deserialize_from_json_str;
/// use rome_deserialize::json::{with_only_known_variants, has_only_known_keys, JsonDeserialize, VisitJsonNode};
/// use rome_json_syntax::{JsonLanguage, JsonSyntaxNode};
/// use rome_json_syntax::JsonRoot;
/// use rome_rowan::AstNode;
///
/// #[derive(Default, Debug, Eq, PartialEq)]
/// struct NewConfiguration {
/// lorem: bool
/// }
///
/// impl VisitJsonNode for NewConfiguration {}
///
/// impl VisitNode<JsonLanguage> for NewConfiguration {
/// fn visit_member_name(&mut self, node: &JsonSyntaxNode, diagnostics: &mut Vec<DeserializationDiagnostic>) -> Option<()> {
/// has_only_known_keys(node, &["lorem"], diagnostics)
/// }
///
/// fn visit_map(&mut self, key: &JsonSyntaxNode, value: &JsonSyntaxNode, diagnostics: &mut Vec<DeserializationDiagnostic>) -> Option<()> {
/// let (key, value) = self.get_key_and_value(key, value, diagnostics)?;
///
/// match key.text() {
/// "lorem" => {
/// self.lorem = self.map_to_boolean(&value, key.text(), diagnostics)?
/// }
/// _ => {}
/// }
/// Some(())
/// }
/// }
///
/// impl NewConfiguration {
/// fn parse(root: JsonRoot) -> Deserialized<Self> {
/// use rome_deserialize::Deserialized;
/// let mut output = Self::default();
/// let mut diagnostics = vec![];
/// NewConfiguration::deserialize_from_ast(&root, &mut output, &mut diagnostics);
/// Deserialized::new(output, diagnostics)
/// }
/// }
///
///
/// impl JsonDeserialize for NewConfiguration {
/// fn deserialize_from_ast(root: &JsonRoot, visitor: &mut impl VisitJsonNode, diagnostics: &mut Vec<DeserializationDiagnostic>) -> Option<()> {
/// let object = root.value().ok()?;
/// let object = object.as_json_object_value()?;
/// for member in object.json_member_list() {
/// let member = member.ok()?;
/// visitor.visit_map(member.name().ok()?.syntax(), member.value().ok()?.syntax(), diagnostics)?;
/// }
/// Some(())
/// }
/// }
///
/// use rome_json_parser::JsonParserOptions;
/// # fn main() -> Result<(), DeserializationDiagnostic> {
/// let source = r#"{ "lorem": true }"#;
/// let deserialized = deserialize_from_json_str::<NewConfiguration>(&source, JsonParserOptions::default());
/// assert!(!deserialized.has_errors());
/// assert_eq!(deserialized.into_deserialized(), NewConfiguration { lorem: true });
/// # Ok(())
/// # }
///
///
/// ```
pub fn deserialize_from_json_str<Output>(
source: &str,
options: JsonParserOptions,
) -> Deserialized<Output>
where
Output: Default + VisitJsonNode + JsonDeserialize,
{
let mut output = Output::default();
let mut diagnostics = vec![];
let parse = parse_json(source, options);
Output::deserialize_from_ast(&parse.tree(), &mut output, &mut diagnostics);
let mut errors = parse
.into_diagnostics()
.into_iter()
.map(Error::from)
.collect::<Vec<_>>();
errors.extend(
diagnostics
.into_iter()
.map(|diagnostic| diagnostic.with_file_source_code(source))
.collect::<Vec<_>>(),
);
Deserialized {
diagnostics: errors,
deserialized: output,
}
}
/// Attempts to deserialize a JSON AST, given the `Output`.
pub fn deserialize_from_json_ast<Output>(parse: &JsonRoot) -> Deserialized<Output>
where
Output: Default + VisitJsonNode + JsonDeserialize,
{
let mut output = Output::default();
let mut diagnostics = vec![];
Output::deserialize_from_ast(parse, &mut output, &mut diagnostics);
Deserialized {
diagnostics: diagnostics.into_iter().map(Error::from).collect::<Vec<_>>(),
deserialized: output,
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_deserialize/src/string_set.rs | crates/rome_deserialize/src/string_set.rs | use indexmap::IndexSet;
use serde::de::{SeqAccess, Visitor};
use serde::ser::SerializeSeq;
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
use std::str::FromStr;
#[derive(Default, Debug, Deserialize, Serialize, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct StringSet(
#[serde(
deserialize_with = "crate::deserialize_string_set",
serialize_with = "crate::serialize_string_set"
)]
pub IndexSet<String>,
);
impl StringSet {
pub fn new(index_set: IndexSet<String>) -> Self {
Self(index_set)
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.len() == 0
}
pub fn index_set(&self) -> &IndexSet<String> {
&self.0
}
pub fn into_index_set(self) -> IndexSet<String> {
self.0
}
pub fn extend(&mut self, entries: impl IntoIterator<Item = String>) {
self.0.extend(entries);
}
}
/// Some documentation
pub fn deserialize_string_set<'de, D>(deserializer: D) -> Result<IndexSet<String>, D::Error>
where
D: serde::de::Deserializer<'de>,
{
struct IndexVisitor {
marker: PhantomData<fn() -> IndexSet<String>>,
}
impl IndexVisitor {
fn new() -> Self {
IndexVisitor {
marker: PhantomData,
}
}
}
impl<'de> Visitor<'de> for IndexVisitor {
type Value = IndexSet<String>;
// Format a message stating what data this Visitor expects to receive.
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("expecting a sequence")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut index_set = IndexSet::with_capacity(seq.size_hint().unwrap_or(0));
while let Some(value) = seq.next_element()? {
index_set.insert(value);
}
Ok(index_set)
}
}
deserializer.deserialize_seq(IndexVisitor::new())
}
pub fn serialize_string_set<S>(string_set: &IndexSet<String>, s: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
let mut sequence = s.serialize_seq(Some(string_set.len()))?;
let iter = string_set.into_iter();
for global in iter {
sequence.serialize_element(&global)?;
}
sequence.end()
}
impl FromStr for StringSet {
type Err = String;
fn from_str(_s: &str) -> Result<Self, Self::Err> {
Ok(StringSet::default())
}
}
impl From<IndexSet<String>> for StringSet {
fn from(value: IndexSet<String>) -> Self {
Self::new(value)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_test_utils/src/lib.rs | crates/rome_test_utils/src/lib.rs | use json_comments::StripComments;
use rome_analyze::{AnalyzerAction, AnalyzerOptions};
use rome_console::fmt::{Formatter, Termcolor};
use rome_console::markup;
use rome_diagnostics::termcolor::Buffer;
use rome_diagnostics::{DiagnosticExt, Error, PrintDiagnostic};
use rome_json_parser::{JsonParserOptions, ParseDiagnostic};
use rome_rowan::{SyntaxKind, SyntaxNode, SyntaxSlot};
use rome_service::configuration::to_analyzer_configuration;
use rome_service::settings::{Language, WorkspaceSettings};
use rome_service::Configuration;
use similar::TextDiff;
use std::ffi::{c_int, OsStr};
use std::fmt::Write;
use std::path::Path;
use std::sync::Once;
pub fn scripts_from_json(extension: &OsStr, input_code: &str) -> Option<Vec<String>> {
if extension == "json" || extension == "jsonc" {
let input_code = StripComments::new(input_code.as_bytes());
let scripts: Vec<String> = serde_json::from_reader(input_code).ok()?;
Some(scripts)
} else {
None
}
}
pub fn create_analyzer_options(
input_file: &Path,
diagnostics: &mut Vec<String>,
) -> AnalyzerOptions {
let mut options = AnalyzerOptions::default();
// We allow a test file to configure its rule using a special
// file with the same name as the test but with extension ".options.json"
// that configures that specific rule.
let options_file = input_file.with_extension("options.json");
if let Ok(json) = std::fs::read_to_string(options_file.clone()) {
let deserialized = rome_deserialize::json::deserialize_from_json_str::<Configuration>(
json.as_str(),
JsonParserOptions::default(),
);
if deserialized.has_errors() {
diagnostics.extend(
deserialized
.into_diagnostics()
.into_iter()
.map(|diagnostic| {
diagnostic_to_string(
options_file.file_stem().unwrap().to_str().unwrap(),
&json,
diagnostic,
)
})
.collect::<Vec<_>>(),
);
None
} else {
let configuration = deserialized.into_deserialized();
let mut settings = WorkspaceSettings::default();
settings.merge_with_configuration(configuration).unwrap();
let configuration =
to_analyzer_configuration(&settings.linter, &settings.languages, |_| vec![]);
options = AnalyzerOptions {
configuration,
..AnalyzerOptions::default()
};
Some(json)
}
} else {
None
};
options
}
pub fn diagnostic_to_string(name: &str, source: &str, diag: Error) -> String {
let error = diag.with_file_path(name).with_file_source_code(source);
let text = markup_to_string(rome_console::markup! {
{PrintDiagnostic::verbose(&error)}
});
text
}
fn markup_to_string(markup: rome_console::Markup) -> String {
let mut buffer = Vec::new();
let mut write =
rome_console::fmt::Termcolor(rome_diagnostics::termcolor::NoColor::new(&mut buffer));
let mut fmt = Formatter::new(&mut write);
fmt.write_markup(markup).unwrap();
String::from_utf8(buffer).unwrap()
}
// Check that all red / green nodes have correctly been released on exit
extern "C" fn check_leaks() {
if let Some(report) = rome_rowan::check_live() {
panic!("\n{report}")
}
}
pub fn register_leak_checker() {
// Import the atexit function from libc
extern "C" {
fn atexit(f: extern "C" fn()) -> c_int;
}
// Use an atomic Once to register the check_leaks function to be called
// when the process exits
static ONCE: Once = Once::new();
ONCE.call_once(|| unsafe {
countme::enable(true);
atexit(check_leaks);
});
}
pub fn code_fix_to_string<L: Language>(source: &str, action: AnalyzerAction<L>) -> String {
let (_, text_edit) = action.mutation.as_text_edits().unwrap_or_default();
let output = text_edit.new_string(source);
let diff = TextDiff::from_lines(source, &output);
let mut diff = diff.unified_diff();
diff.context_radius(3);
diff.to_string()
}
/// The test runner for the analyzer is currently designed to have a
/// one-to-one mapping between test case and analyzer rules.
/// So each testing file will be run through the analyzer with only the rule
/// corresponding to the directory name. E.g., `style/useWhile/test.js`
/// will be analyzed with just the `style/useWhile` rule.
pub fn parse_test_path(file: &Path) -> (&str, &str) {
let rule_folder = file.parent().unwrap();
let rule_name = rule_folder.file_name().unwrap();
let group_folder = rule_folder.parent().unwrap();
let group_name = group_folder.file_name().unwrap();
(group_name.to_str().unwrap(), rule_name.to_str().unwrap())
}
/// This check is used in the parser test to ensure it doesn't emit
/// bogus nodes without diagnostics, and in the analyzer tests to
/// check the syntax trees resulting from code actions are correct
pub fn has_bogus_nodes_or_empty_slots<L: Language>(node: &SyntaxNode<L>) -> bool {
node.descendants().any(|descendant| {
let kind = descendant.kind();
if kind.is_bogus() {
return true;
}
if kind.is_list() {
return descendant
.slots()
.any(|slot| matches!(slot, SyntaxSlot::Empty));
}
false
})
}
/// This function analyzes the parsing result of a file and panic with a
/// detailed message if it contains any error-level diagnostic, bogus nodes,
/// empty list slots or missing required children
pub fn assert_errors_are_absent<L: Language>(
program: &SyntaxNode<L>,
diagnostics: &[ParseDiagnostic],
path: &Path,
) {
let debug_tree = format!("{:?}", program);
let has_missing_children = debug_tree.contains("missing (required)");
if diagnostics.is_empty() && !has_bogus_nodes_or_empty_slots(program) && !has_missing_children {
return;
}
let mut buffer = Buffer::no_color();
for diagnostic in diagnostics {
let error = diagnostic
.clone()
.with_file_path(path.to_str().unwrap())
.with_file_source_code(program.to_string());
Formatter::new(&mut Termcolor(&mut buffer))
.write_markup(markup! {
{PrintDiagnostic::verbose(&error)}
})
.unwrap();
}
panic!("There should be no errors in the file {:?} but the following errors where present:\n{}\n\nParsed tree:\n{:#?}",
path.display(),
std::str::from_utf8(buffer.as_slice()).unwrap(),
&program
);
}
pub fn write_analyzer_snapshot(
snapshot: &mut String,
input_code: &str,
diagnostics: &[String],
code_fixes: &[String],
) {
writeln!(snapshot, "# Input").unwrap();
writeln!(snapshot, "```js").unwrap();
writeln!(snapshot, "{}", input_code).unwrap();
writeln!(snapshot, "```").unwrap();
writeln!(snapshot).unwrap();
if !diagnostics.is_empty() {
writeln!(snapshot, "# Diagnostics").unwrap();
for diagnostic in diagnostics {
writeln!(snapshot, "```").unwrap();
writeln!(snapshot, "{}", diagnostic).unwrap();
writeln!(snapshot, "```").unwrap();
writeln!(snapshot).unwrap();
}
}
if !code_fixes.is_empty() {
writeln!(snapshot, "# Actions").unwrap();
for action in code_fixes {
writeln!(snapshot, "```diff").unwrap();
writeln!(snapshot, "{}", action).unwrap();
writeln!(snapshot, "```").unwrap();
writeln!(snapshot).unwrap();
}
}
}
pub fn write_transformation_snapshot(
snapshot: &mut String,
input_code: &str,
transformations: &[String],
extension: &str,
) {
writeln!(snapshot, "# Input").unwrap();
writeln!(snapshot, "```{}", extension).unwrap();
writeln!(snapshot, "{}", input_code).unwrap();
writeln!(snapshot, "```").unwrap();
writeln!(snapshot).unwrap();
if !transformations.is_empty() {
writeln!(snapshot, "# Transformations").unwrap();
for transformation in transformations {
writeln!(snapshot, "```{}", extension).unwrap();
writeln!(snapshot, "{}", transformation).unwrap();
writeln!(snapshot, "```").unwrap();
writeln!(snapshot).unwrap();
}
}
}
pub enum CheckActionType {
Suppression,
Lint,
}
impl CheckActionType {
pub const fn is_suppression(&self) -> bool {
matches!(self, Self::Suppression)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/syntax_rewriter.rs | crates/rome_js_formatter/src/syntax_rewriter.rs | use crate::comments::is_type_comment;
use crate::parentheses::AnyJsParenthesized;
use rome_formatter::{TransformSourceMap, TransformSourceMapBuilder};
use rome_js_syntax::{
AnyJsAssignment, AnyJsExpression, AnyTsType, JsLanguage, JsLogicalExpression, JsSyntaxKind,
JsSyntaxNode,
};
use rome_rowan::syntax::SyntaxTrivia;
use rome_rowan::{
chain_trivia_pieces, AstNode, SyntaxKind, SyntaxRewriter, SyntaxToken, TextSize,
VisitNodeSignal,
};
use std::collections::BTreeSet;
pub(super) fn transform(root: JsSyntaxNode) -> (JsSyntaxNode, TransformSourceMap) {
let mut rewriter = JsFormatSyntaxRewriter::with_offset(root.text_range().start());
let transformed = rewriter.transform(root);
(transformed, rewriter.finish())
}
#[derive(Default)]
struct JsFormatSyntaxRewriter {
source_map: TransformSourceMapBuilder,
/// Stores a map of the positions at which a `(` paren has been removed.
/// This is necessary for correctly computing the source offsets for nested parenthesized expressions with whitespace:
///
/// ```javascript
/// function f() {
/// return (
/// (
/// // prettier-ignore
/// /* $FlowFixMe(>=0.53.0) */
/// <JSX />
/// )
/// );
/// }
/// ```
/// The rewriter first removes any leading whitespace from the `JsxTagExpression`'s leading trivia.
/// However, it then removes the leading/trailing whitespace of the inner `(` as well when handling the outer
/// parenthesized expressions but the ranges of the `(` trailing trivia pieces no longer match the source ranges because
/// they are now off by 1 because of the removed `(`.
l_paren_source_position: BTreeSet<TextSize>,
}
impl JsFormatSyntaxRewriter {
pub fn with_offset(offset: TextSize) -> Self {
JsFormatSyntaxRewriter {
source_map: TransformSourceMapBuilder::with_offset(offset),
..Default::default()
}
}
}
impl JsFormatSyntaxRewriter {
/// Replaces parenthesized expression that:
/// * have no syntax error: has no missing required child or no skipped token trivia attached to the left or right paren
/// * inner expression isn't an bogus node
/// * no closure or type cast comment
///
/// with the inner expression.
///
/// ## Trivia Overview
///
/// We have to spend extra attention on the handling of the trivia attached to the left and right parentheses:
///
/// ```javascript
/// statement;
/// /* leading l-paren */ ( /* trailing l-paren */
/// /* leading a */ a + b /* trailing b */
/// /* leading r-paren */ ) /* trailing r-paren */
/// ```
///
/// The implementation pre-appends the left parenthesis's trivia to the leading trivia of the expression's first token,
/// and appends the right parenthesis's trivia to the trailing trivia of the expression's last token. So the trivia (ignoring whitespace)
/// after the transform for the above example is:
///
/// * `a`: `/* leading l-paren */ /* trailing l-paren */ /* leading a */`
/// * `b`: `/* trailing b */ /* leading r-paren */ /* trailing r-paren */`
///
/// The fact that the implementation appends the right parenthesis's leading trivia to the last token's trailing
/// trivia is slightly inconsistent with our [rome_rowan::SyntaxToken::trailing_trivia] definition as it can now happen that the
/// trailing trivia contains line breaks. In practice, this isn't a problem for the formatter.
///
/// ## Leading Whitespace Trivia
///
/// The formatter counts the new lines in a node's leading trivia to determine if it should e.g. insert an
/// empty new line between two statements. This is why it is necessary to remove any whitespace
/// between the left parentheses and the token to avoid the insertion of additional new lines if there was a line break
/// after the left parentheses or
///
/// ```javascript
/// a
/// (
/// Long &&
/// Longer &&
/// )
/// ```
///
/// would become
///
/// ```javascript
/// a
///
/// (
/// Long &&
/// Longer &&
/// )
/// ```
///
/// because the `Long` has two leading new lines after removing parentheses, the one after `a` and the one after the opening `(`.
///
/// However, it is important to leave at least one leading new line in front of the token's leading trivia if there's a comment in the leading trivia because
/// because we want that leading comments that are preceded by a line break to be formatted on their own line.
///
/// ```javascript
/// (
/// // comment
/// a
/// )
/// ```
///
/// Keep the line break before the `// comment` or the formatter will format the comment on the same line as the `(` token
///
/// ```javascript
/// ( // comment
/// a
/// )
/// ```
///
/// Which may turn `//comment` into a trailing comment that then gets formatted differently on the next formatting pass, resulting in instability issues.
fn visit_parenthesized(
&mut self,
parenthesized: AnyJsParenthesized,
) -> VisitNodeSignal<JsLanguage> {
let (l_paren, inner, r_paren) = match (
parenthesized.l_paren_token(),
parenthesized.inner(),
parenthesized.r_paren_token(),
) {
(Ok(l_paren), Ok(inner), Ok(r_paren)) => {
let prev_token = l_paren.prev_token();
// Keep parentheses around unknown expressions. Rome can't know the precedence.
if inner.kind().is_bogus()
// Don't remove parentheses if the expression is a decorator
|| inner.grand_parent().map_or(false, |node| node.kind() == JsSyntaxKind::JS_DECORATOR)
// Don't remove parentheses if they have skipped trivia. We don't know for certain what the intended syntax is.
// Nor if there's a leading type cast comment
|| has_type_cast_comment_or_skipped(&l_paren.leading_trivia())
|| prev_token.map_or(false, |prev_token| has_type_cast_comment_or_skipped(&prev_token.trailing_trivia()))
|| r_paren.leading_trivia().has_skipped()
{
return VisitNodeSignal::Traverse(parenthesized.into_syntax());
} else {
(l_paren, inner, r_paren)
}
}
_ => {
// At least one missing child, handle as a regular node
return VisitNodeSignal::Traverse(parenthesized.into_syntax());
}
};
self.source_map.push_source_text(l_paren.text());
let inner_trimmed_range = inner.text_trimmed_range();
// Store away the inner offset because the new returned inner might be a detached node
let original_inner_offset = inner.text_range().start();
let inner = self.transform(inner);
let inner_offset = original_inner_offset - inner.text_range().start();
match inner.first_token() {
// This can only happen if we have `()` which is highly unlikely to ever be the case.
// Return the parenthesized expression as is. This will be formatted as verbatim
None => {
let updated = match parenthesized {
AnyJsParenthesized::JsParenthesizedExpression(expression) => {
// SAFETY: Safe because the rewriter never rewrites an expression to a non expression.
expression
.with_expression(AnyJsExpression::unwrap_cast(inner))
.into_syntax()
}
AnyJsParenthesized::JsParenthesizedAssignment(assignment) => {
// SAFETY: Safe because the rewriter never rewrites an assignment to a non assignment.
assignment
.with_assignment(AnyJsAssignment::unwrap_cast(inner))
.into_syntax()
}
AnyJsParenthesized::TsParenthesizedType(ty) => {
ty.with_ty(AnyTsType::unwrap_cast(inner)).into_syntax()
}
};
self.source_map.push_source_text(r_paren.text());
VisitNodeSignal::Replace(updated)
}
Some(first_token) => {
self.source_map.extend_trimmed_node_range(
inner_trimmed_range,
parenthesized.syntax().text_trimmed_range(),
);
let l_paren_trimmed_range = l_paren.text_trimmed_range();
self.source_map.add_deleted_range(l_paren_trimmed_range);
self.l_paren_source_position
.insert(l_paren_trimmed_range.start());
let mut l_paren_trailing = l_paren.trailing_trivia().pieces().peekable();
// Skip over leading whitespace
while let Some(piece) = l_paren_trailing.peek() {
if piece.is_whitespace() {
self.source_map.add_deleted_range(piece.text_range());
l_paren_trailing.next();
} else {
break;
}
}
let l_paren_trailing_non_whitespace_trivia = l_paren_trailing
.peek()
.map_or(false, |piece| piece.is_skipped() || piece.is_comments());
let l_paren_trivia =
chain_trivia_pieces(l_paren.leading_trivia().pieces(), l_paren_trailing);
let mut leading_trivia = first_token.leading_trivia().pieces().peekable();
let mut first_new_line = None;
let mut inner_offset = inner_offset;
// if !is_parent_parenthesized {
// The leading whitespace before the opening parens replaces the whitespace before the node.
while let Some(trivia) = leading_trivia.peek() {
if self
.l_paren_source_position
.contains(&(trivia.text_range().start() + inner_offset))
{
inner_offset += TextSize::from(1);
}
if trivia.is_newline() && first_new_line.is_none() {
first_new_line = Some((
trivia.text_range() + inner_offset,
leading_trivia.next().unwrap(),
));
} else if trivia.is_whitespace() || trivia.is_newline() {
self.source_map
.add_deleted_range(trivia.text_range() + inner_offset);
leading_trivia.next();
} else {
break;
}
}
// Remove all leading new lines directly in front of the token but keep the leading new-line if it precedes a skipped token trivia or a comment.
if !l_paren_trailing_non_whitespace_trivia
&& leading_trivia.peek().is_none()
&& first_new_line.is_some()
{
let (inner_offset, _) = first_new_line.take().unwrap();
self.source_map.add_deleted_range(inner_offset);
}
// }
let leading_trivia = chain_trivia_pieces(
first_new_line.map(|(_, trivia)| trivia).into_iter(),
leading_trivia,
);
let new_leading = chain_trivia_pieces(l_paren_trivia, leading_trivia);
let new_first = first_token.with_leading_trivia_pieces(new_leading);
// SAFETY: Calling `unwrap` is safe because we know that `inner_first` is part of the `inner` subtree.
let updated = inner
.replace_child(first_token.into(), new_first.into())
.unwrap();
let r_paren_trivia = chain_trivia_pieces(
r_paren.leading_trivia().pieces(),
r_paren.trailing_trivia().pieces(),
);
// SAFETY: Calling `unwrap` is safe because `last_token` only returns `None` if a node's subtree
// doesn't contain ANY token, but we know that the subtree contains at least the first token.
let last_token = updated.last_token().unwrap();
let new_last = last_token.append_trivia_pieces(r_paren_trivia);
self.source_map
.add_deleted_range(r_paren.text_trimmed_range());
self.source_map.push_source_text(r_paren.text());
// SAFETY: Calling `unwrap` is safe because we know that `last_token` is part of the `updated` subtree.
VisitNodeSignal::Replace(
updated
.replace_child(last_token.into(), new_last.into())
.unwrap(),
)
}
}
}
/// Re-balances right-recursive logical expressions with the same operator to be left recursive (relies on the parentheses removal)
///
/// ```javascript
/// a && (b && c)
/// ```
///
/// has the tree (parentheses omitted)
///
/// ```text
/// &&
/// a &&
/// b c
/// ```
///
/// This transform re-balances the tree so that it becomes left-recursive
///
/// ```text
/// &&
/// && c
/// a b
/// ```
///
/// This is required so that the binary like expression formatting only has to resolve left recursive expressions.
fn visit_logical_expression(
&mut self,
logical: JsLogicalExpression,
) -> VisitNodeSignal<JsLanguage> {
match (logical.left(), logical.operator_token(), logical.right()) {
(Ok(left), Ok(operator), Ok(right)) => {
let left_key = left.syntax().key();
let operator_key = operator.key();
let right_key = right.syntax().key();
// SAFETY: Safe because the rewriter never rewrites an expression to a non expression.
let left = AnyJsExpression::unwrap_cast(self.transform(left.into_syntax()));
let operator = self.visit_token(operator);
// SAFETY: Safe because the rewriter never rewrites an expression to a non expression.
let right = AnyJsExpression::unwrap_cast(self.transform(right.into_syntax()));
let updated = match right {
AnyJsExpression::JsLogicalExpression(right_logical) => {
match (
right_logical.left(),
right_logical.operator_token(),
right_logical.right(),
) {
(Ok(right_left), Ok(right_operator), Ok(right_right))
if right_operator.kind() == operator.kind() =>
{
logical
.with_left(
rome_js_factory::make::js_logical_expression(
left, operator, right_left,
)
.into(),
)
.with_operator_token_token(right_operator)
.with_right(right_right)
}
// Don't re-balance a logical expression that has syntax errors
_ => logical
.with_left(left)
.with_operator_token_token(operator)
.with_right(right_logical.into()),
}
}
// Don't re-balance logical expressions with different operators
// Avoid updating the node if none of the children have changed to avoid
// re-spinning all parents.
right => {
if left.syntax().key() != left_key
|| operator.key() != operator_key
|| right.syntax().key() != right_key
{
logical
.with_left(left)
.with_operator_token_token(operator)
.with_right(right)
} else {
logical
}
}
};
VisitNodeSignal::Replace(updated.into_syntax())
}
_ => VisitNodeSignal::Traverse(logical.into_syntax()),
}
}
pub(crate) fn finish(self) -> TransformSourceMap {
self.source_map.finish()
}
}
impl SyntaxRewriter for JsFormatSyntaxRewriter {
type Language = JsLanguage;
fn visit_node(&mut self, node: JsSyntaxNode) -> VisitNodeSignal<Self::Language> {
match node.kind() {
kind if AnyJsParenthesized::can_cast(kind) => {
let parenthesized = AnyJsParenthesized::unwrap_cast(node);
self.visit_parenthesized(parenthesized)
}
JsSyntaxKind::JS_LOGICAL_EXPRESSION => {
let logical = JsLogicalExpression::unwrap_cast(node);
self.visit_logical_expression(logical)
}
_ => VisitNodeSignal::Traverse(node),
}
}
fn visit_token(&mut self, token: SyntaxToken<Self::Language>) -> SyntaxToken<Self::Language> {
self.source_map.push_source_text(token.text());
token
}
}
fn has_type_cast_comment_or_skipped(trivia: &SyntaxTrivia<JsLanguage>) -> bool {
trivia.pieces().any(|piece| {
if let Some(comment) = piece.as_comments() {
is_type_comment(&comment)
} else {
piece.is_skipped()
}
})
}
#[cfg(test)]
mod tests {
use super::JsFormatSyntaxRewriter;
use crate::{format_node, JsFormatOptions, TextRange};
use rome_formatter::{SourceMarker, TransformSourceMap};
use rome_js_parser::{parse, parse_module, JsParserOptions};
use rome_js_syntax::{
JsArrayExpression, JsBinaryExpression, JsExpressionStatement, JsFileSource,
JsIdentifierExpression, JsLogicalExpression, JsSequenceExpression,
JsStringLiteralExpression, JsSyntaxNode, JsUnaryExpression, JsxTagExpression,
};
use rome_rowan::{AstNode, SyntaxRewriter, TextSize};
#[test]
fn rebalances_logical_expressions() {
let root = parse_module("a && (b && c)", JsParserOptions::default()).syntax();
let transformed = JsFormatSyntaxRewriter::default().transform(root.clone());
// Changed the root tree
assert_ne!(&transformed, &root);
// Removes parentheses
assert_eq!(&transformed.text().to_string(), "a && b && c");
let mut logical_expressions: Vec<_> = transformed
.descendants()
.filter_map(JsLogicalExpression::cast)
.collect();
assert_eq!(logical_expressions.len(), 2);
let left = logical_expressions.pop().unwrap();
let top = logical_expressions.pop().unwrap();
assert_eq!(top.left().unwrap().syntax(), left.syntax());
assert_eq!(&top.right().unwrap().text(), "c");
assert_eq!(left.left().unwrap().text(), "a");
assert_eq!(left.right().unwrap().text(), "b");
}
#[test]
fn only_rebalances_logical_expressions_with_same_operator() {
let root = parse_module("a && (b || c)", JsParserOptions::default()).syntax();
let transformed = JsFormatSyntaxRewriter::default().transform(root);
// Removes parentheses
assert_eq!(&transformed.text().to_string(), "a && b || c");
let logical_expressions: Vec<_> = transformed
.descendants()
.filter_map(JsLogicalExpression::cast)
.collect();
assert_eq!(logical_expressions.len(), 2);
let top = logical_expressions.first().unwrap();
let right = logical_expressions.last().unwrap();
assert_eq!(top.left().unwrap().text(), "a");
assert_eq!(top.right().unwrap().syntax(), right.syntax());
assert_eq!(right.left().unwrap().text(), "b");
assert_eq!(right.right().unwrap().text(), "c");
}
#[test]
fn single_parentheses() {
let (transformed, source_map) = source_map_test("(a)");
assert_eq!(&transformed.text(), "a");
let identifier = transformed
.descendants()
.find_map(JsIdentifierExpression::cast)
.unwrap();
assert_eq!(source_map.trimmed_source_text(identifier.syntax()), "(a)");
}
#[test]
fn nested_parentheses() {
let (transformed, source_map) = source_map_test("((a))");
assert_eq!(&transformed.text(), "a");
let identifier = transformed
.descendants()
.find_map(JsIdentifierExpression::cast)
.unwrap();
assert_eq!(source_map.trimmed_source_text(identifier.syntax()), "((a))");
}
#[test]
fn test_logical_expression_source_map() {
let (transformed, source_map) = source_map_test("(a && (b && c))");
let logical_expressions: Vec<_> = transformed
.descendants()
.filter_map(JsLogicalExpression::cast)
.collect();
assert_eq!(2, logical_expressions.len());
assert_eq!(
source_map.trimmed_source_text(logical_expressions[0].syntax()),
"(a && (b && c))"
);
assert_eq!(
source_map.trimmed_source_text(logical_expressions[1].syntax()),
"a && (b"
);
}
#[test]
fn adjacent_nodes() {
let (transformed, source_map) = source_map_test("(a + b)");
assert_eq!(&transformed.text(), "a + b");
let identifiers: Vec<_> = transformed
.descendants()
.filter_map(JsIdentifierExpression::cast)
.collect();
assert_eq!(2, identifiers.len());
// Parentheses should be associated with the binary expression
assert_eq!(source_map.trimmed_source_text(identifiers[0].syntax()), "a");
assert_eq!(source_map.trimmed_source_text(identifiers[1].syntax()), "b");
let binary = transformed
.descendants()
.find_map(JsBinaryExpression::cast)
.unwrap();
assert_eq!(source_map.trimmed_source_text(binary.syntax()), "(a + b)")
}
#[test]
fn intersecting_ranges() {
let (transformed, source_map) = source_map_test("(interface, \"foo\");");
assert_eq!(&transformed.text(), "interface, \"foo\";");
let string_literal = transformed
.descendants()
.find_map(JsStringLiteralExpression::cast)
.unwrap();
assert_eq!(
source_map.trimmed_source_text(string_literal.syntax()),
"\"foo\""
);
let sequence = transformed
.descendants()
.find_map(JsSequenceExpression::cast)
.unwrap();
assert_eq!(
source_map.trimmed_source_text(sequence.syntax()),
"(interface, \"foo\")"
);
}
#[test]
fn deep() {
let src = r#"[
(2*n)/(r-l), 0, (r+l)/(r-l), 0,
0, (2*n)/(t-b), (t+b)/(t-b), 0,
0, 0, -(f+n)/(f-n), -(2*f*n)/(f-n),
0, 0, -1, 0,
];"#;
let (transformed, source_map) = source_map_test(src);
let array = transformed
.descendants()
.find_map(JsArrayExpression::cast)
.unwrap();
assert_eq!(
source_map.trimmed_source_text(array.syntax()),
r#"[
(2*n)/(r-l), 0, (r+l)/(r-l), 0,
0, (2*n)/(t-b), (t+b)/(t-b), 0,
0, 0, -(f+n)/(f-n), -(2*f*n)/(f-n),
0, 0, -1, 0,
]"#
);
}
#[test]
fn enclosing_node() {
let (transformed, source_map) = source_map_test("(a + b);");
assert_eq!(&transformed.text(), "a + b;");
let expression_statement = transformed
.descendants()
.find_map(JsExpressionStatement::cast)
.unwrap();
assert_eq!(
source_map.trimmed_source_text(expression_statement.syntax()),
"(a + b);"
);
}
#[test]
fn trailing_whitespace() {
let (transformed, source_map) = source_map_test("(a + b );");
assert_eq!(&transformed.text(), "a + b ;");
let binary = transformed
.descendants()
.find_map(JsBinaryExpression::cast)
.unwrap();
assert_eq!(
source_map.trimmed_source_text(binary.syntax()),
"(a + b )"
);
}
#[test]
fn first_token_leading_whitespace() {
let (transformed, _) = source_map_test("a;\n(\n a + b);");
// Trims the leading whitespace in front of the expression's first token.
assert_eq!(&transformed.text(), "a;\na + b;");
}
#[test]
fn first_token_leading_whitespace_before_comment() {
let (transformed, _) = source_map_test("a;(\n\n/* comment */\n a + b);");
// Keeps at least one new line before a leading comment.
assert_eq!(&transformed.text(), "a;\n/* comment */\n a + b;");
}
#[test]
fn comments() {
let (transformed, source_map) =
source_map_test("/* outer */ (/* left */ a + b /* right */) /* outer end */;");
assert_eq!(
&transformed.text(),
"/* outer */ /* left */ a + b /* right */ /* outer end */;"
);
let binary = transformed
.descendants()
.find_map(JsBinaryExpression::cast)
.unwrap();
assert_eq!(
source_map.trimmed_source_text(binary.syntax()),
"(/* left */ a + b /* right */)"
);
}
#[test]
fn parentheses() {
let (transformed, source_map) = source_map_test(
r#"!(
/* foo */
x
);
!(
x // foo
);
!(
/* foo */
x + y
);
!(
x + y
/* foo */
);
!(
x + y // foo
);"#,
);
let unary_expressions = transformed
.descendants()
.filter_map(JsUnaryExpression::cast)
.collect::<Vec<_>>();
assert_eq!(unary_expressions.len(), 5);
assert_eq!(
source_map.trimmed_source_text(unary_expressions[0].syntax()),
r#"!(
/* foo */
x
)"#
);
assert_eq!(
source_map.source_range(unary_expressions[1].syntax().text_range()),
TextRange::new(TextSize::from(21), TextSize::from(36))
);
assert_eq!(
source_map.trimmed_source_text(unary_expressions[1].syntax()),
r#"!(
x // foo
)"#
);
assert_eq!(
source_map.trimmed_source_text(unary_expressions[2].syntax()),
r#"!(
/* foo */
x + y
)"#
);
assert_eq!(
source_map.trimmed_source_text(unary_expressions[3].syntax()),
r#"!(
x + y
/* foo */
)"#
);
assert_eq!(
source_map.trimmed_source_text(unary_expressions[4].syntax()),
r#"!(
x + y // foo
)"#
);
}
#[test]
fn nested_parentheses_with_whitespace() {
let (transformed, source_map) = source_map_test(
r#"function f() {
return (
(
// prettier-ignore
/* $FlowFixMe(>=0.53.0) */
<JSX />
)
);
}"#,
);
let tag_expression = transformed
.descendants()
.find_map(JsxTagExpression::cast)
.unwrap();
assert_eq!(
source_map.trimmed_source_text(tag_expression.syntax()),
r#"(
(
// prettier-ignore
/* $FlowFixMe(>=0.53.0) */
<JSX />
)
)"#
);
}
fn source_map_test(input: &str) -> (JsSyntaxNode, TransformSourceMap) {
let tree = parse(input, JsFileSource::jsx(), JsParserOptions::default()).syntax();
let mut rewriter = JsFormatSyntaxRewriter::default();
let transformed = rewriter.transform(tree);
let source_map = rewriter.finish();
(transformed, source_map)
}
#[test]
fn mappings() {
let (transformed, source_map) = source_map_test("(((a * b) * c)) / 3");
let formatted =
format_node(JsFormatOptions::new(JsFileSource::default()), &transformed).unwrap();
let printed = formatted.print().unwrap();
assert_eq!(printed.as_code(), "(a * b * c) / 3;\n");
let mapped = source_map.map_printed(printed);
let markers = mapped.into_sourcemap();
assert_eq!(
markers,
vec![
// `(`
SourceMarker {
source: TextSize::from(3),
dest: TextSize::from(0)
},
// `a`
SourceMarker {
source: TextSize::from(3),
dest: TextSize::from(1)
},
// ` `
SourceMarker {
source: TextSize::from(4),
dest: TextSize::from(2)
},
// `*`
SourceMarker {
source: TextSize::from(5),
dest: TextSize::from(3)
},
// ` `
SourceMarker {
source: TextSize::from(6),
dest: TextSize::from(4)
},
// `b`
SourceMarker {
source: TextSize::from(7),
dest: TextSize::from(5)
},
// ` `
SourceMarker {
source: TextSize::from(9),
dest: TextSize::from(6)
},
// `*`
SourceMarker {
source: TextSize::from(10),
dest: TextSize::from(7)
},
// ` `
SourceMarker {
source: TextSize::from(11),
dest: TextSize::from(8)
},
// `c`
SourceMarker {
source: TextSize::from(12),
dest: TextSize::from(9)
},
// `)`
SourceMarker {
source: TextSize::from(15),
dest: TextSize::from(10),
},
// ` `
SourceMarker {
source: TextSize::from(15),
dest: TextSize::from(11),
},
// `/`
SourceMarker {
source: TextSize::from(16),
dest: TextSize::from(12),
},
// ` `
SourceMarker {
source: TextSize::from(17),
dest: TextSize::from(13),
},
// `3`
SourceMarker {
source: TextSize::from(18),
dest: TextSize::from(14),
},
// `;`
SourceMarker {
source: TextSize::from(19),
dest: TextSize::from(15),
},
// `\n`
SourceMarker {
source: TextSize::from(19),
dest: TextSize::from(16),
},
]
);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/prelude.rs | crates/rome_js_formatter/src/prelude.rs | //! This module provides important and useful traits to help to format tokens and nodes
//! when implementing a syntax formatter.
pub(crate) use crate::{
comments::JsComments, AsFormat as _, FormatNodeRule, FormattedIterExt, JsFormatContext,
JsFormatter,
};
pub use rome_formatter::prelude::*;
pub use rome_formatter::separated::TrailingSeparator;
pub use rome_rowan::{AstNode as _, AstNodeList as _, AstSeparatedList as _};
pub(crate) use crate::separated::FormatAstSeparatedListExtension;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/lib.rs | crates/rome_js_formatter/src/lib.rs | //! Rome's official JavaScript formatter.
//!
//! ## Implement the formatter
//!
//! Our formatter is node based. Meaning that each AST node knows how to format itself. In order to implement
//! the formatting, a node has to implement the trait `FormatNode`.
//!
//! `rome` has an automatic code generation that creates automatically the files out of the grammar.
//! By default, all implementations will format verbatim,
//! meaning that the formatter will print tokens and trivia as they are (`format_verbatim`).
//!
//! Our formatter has its own [internal IR](https://en.wikipedia.org/wiki/Intermediate_representation), it creates its own abstraction from an AST.
//!
//! The developer won't be creating directly this IR, but they will use a series of utilities that will help
//! to create this IR. The whole IR is represented by the `enum` `FormatElement`.
//!
//! ### Best Practices
//!
//! 1. Use the `*Fields` struct to extract all the tokens/nodes
//! ```rust,ignore
//! #[derive(Debug, Clone, Default)]
//! pub struct FormatJsExportDefaultExpressionClause;
//!
//! impl FormatNodeRule<JsExportDefaultExpressionClause> for FormatJsExportDefaultExpressionClauses {
//! fn fmt_fields(&self, node: &JsExportDefaultExpressionClause, f: &mut JsFormatter) -> FormatResult<()> {
//! let JsExportDefaultExpressionClauseFields {
//! default_token,
//! expression,
//! semicolon_token,
//! } = node.as_fields();
//! }
//! }
//! ```
//! 2. When using `.as_fields()` with the destructuring, don't use the `..` feature. Prefer extracting all fields and ignore them
//! using the `_`
//! ```rust,ignore
//! #[derive(Debug, Clone, Default)]
//! pub struct FormatJsExportDefaultExpressionClause;
//!
//! impl FormatNodeRule<JsExportDefaultExpressionClause> for FormatJsExportDefaultExpressionClauses {
//! fn fmt_fields(&self, node: &JsExportDefaultExpressionClause, f: &mut JsFormatter) -> FormatResult<()> {
//! let JsExportDefaultExpressionClauseFields {
//! default_token,
//! expression: _,
//! semicolon_token
//! } = node.as_fields();
//! }
//! }
//! ```
//! The reason why we want to promote this pattern is because we want to make explicit when a token/node is excluded;
//! 3. Use the APIs provided by `builders.rs`, `formatter` and `format_extensions.rs`.
//! 1. `builders.rs` exposes a series of utilities to craft the formatter IR; please refer to their internal
//! documentation to understand what the utilities are for;
//! 2. `formatter` exposes a set of functions to help to format some recurring patterns; please refer to their internal
//! documentation to understand how to use them and when;
//! 3. `format_extensions.rs`: with these traits, we give the ability to nodes and tokens to implements certain methods
//! that are exposed based on its type. If you have a good IDE support, this feature will help you. For example:
//!
//! ```rust,ignore
//! #[derive(Debug, Clone, Default)]
//! pub struct FormatJsExportDefaultExpressionClause;
//!
//! impl FormatNodeRule<JsExportDefaultExpressionClause> for FormatJsExportDefaultExpressionClauses{
//! fn fmt_fields(&self, node: &JsExportDefaultExpressionClause, f: &mut JsFormatter) -> FormatResult<()> {
//! let JsExportDefaultExpressionClauseFields {
//! default_token,
//! expression, // it's a mandatory node
//! semicolon_token, // this is not a mandatory node
//! } = node.as_fields();
//! let element = expression.format();
//!
//! if let Some(expression) = &expression? {
//! write!(f, [expression.format(), space()])?;
//! }
//!
//! if let Some(semicolon) = &semicolon_token {
//! write!(f, [semicolon.format()])?;
//! } else {
//! write!(f, [space()])?;
//! }
//! }
//! }
//! ```
//!
//! 4. Use the [playground](https://play.rome.tools) to inspect the code that you want to format.
//! It helps you to understand which nodes need to be implemented/modified
//! in order to implement formatting. Alternatively, you can locally run the playground by following
//! the [playground instructions](https://github.com/rome/tools/blob/main/website/playground/README.md).
//! 5. Use the `quick_test.rs` file in `tests/` directory.
//! function to test you snippet straight from your IDE, without running the whole test suite. The test
//! is ignored on purpose, so you won't need to worry about the CI breaking.
//!
//! ## Testing
//!
//! We use [insta.rs](https://insta.rs/docs) for our snapshot tests, please make sure you read its documentation to learn the basics of snapshot testing.
//! You should install the companion [`cargo-insta`](https://insta.rs/docs/cli/) command to assist with snapshot reviewing.
//!
//! Directories are divided by language, so when creating a new test file, make sure to have the correct file
//! under the correct folder:
//! - `JavaScript` => `js/` directory
//! - `TypeScript` => `ts/` directory
//! - `JSX` => `jsx/` directory
//! - `TSX` => `ts/` directory
//!
//! To create a new snapshot test for JavaScript, create a new file to `crates/rome_js_formatter/tests/specs/js/`, e.g. `arrow_with_spaces.js`
//!
//! ```javascript
//! const foo = () => {
//! return bar
//! }
//! ```
//!
//! Files processed as modules must go inside the `module/` directory, files processed as script must go inside the
//! `script/` directory.
//!
//! Run the following command to generate the new snapshot (the snapshot tests are generated by a procedure macro so we need to recompile the tests):
//!
//! ```bash
//! touch crates/rome_js_formatter/tests/spec_tests.rs && cargo test -p rome_js_formatter formatter
//! ```
//!
//! For better test driven development flow, start the formatter tests with [`cargo-watch`](https://crates.io/crates/cargo-watch):
//!
//! ```bash
//! cargo watch -i '*.new' -x 'test -p rome_js_formatter formatter'
//! ```
//!
//! After test execution, you will get a new `arrow.js.snap.new` file.
//!
//! To actually update the snapshot, run `cargo insta review` to interactively review and accept the pending snapshot. `arrow.js.snap.new` will be replaced with `arrow.js.snap`
//!
//! Sometimes, you need to verify the formatting for different cases/options. In order to do that, create a folder with
//! the cases you need to verify. If we needed to follow the previous example:
//!
//! 1. create a folder called `arrow_with_spaces/` and move the JS file there;
//! 2. then create a file called `options.json`
//! 3. The content would be something like:
//! ```json
//! {
//! "cases": [
//! {
//! "line_width": 120,
//! "indent_style": {"Space": 4}
//! }
//! ]
//! }
//! ````
//! 4. the `cases` keyword is mandatory;
//! 5. then each object of the array will contain the matrix of options you'd want to test.
//! In this case the test suite will run a **second test case** with `line_width` to 120 and `ident_style` with 4 spaces
//! 6. when the test suite is run, you will have two outputs in your snapshot: the default one and the custom one
//!
//! ### Debugging Test Failures
//!
//! There are four cases when a test is not correct:
//! - you try to print/format the same token multiple times; the formatter will check at runtime when a test is run;
//! - some tokens haven't been printed; usually you will have this information inside the snapshot, under a section
//! called `"Unimplemented tokens/nodes"`; a test, in order to be valid, can't have that section;
//!
//! If removing a token is the actual behaviour (removing some parenthesis or a semicolon), then the correct way
//! to do it by using the formatter API [rome_formatter::trivia::format_removed];
//! - the emitted code is not a valid program anymore, the test suite will parse again the emitted code and it will
//! fail if there are syntax errors;
//! - the emitted code, when formatted again, differs from the original; this usually happens when removing/adding new
//! elements, and the grouping is not correctly set;
mod cst;
mod js;
mod jsx;
mod prelude;
mod ts;
pub mod utils;
#[rustfmt::skip]
mod generated;
pub mod comments;
pub mod context;
mod parentheses;
pub(crate) mod separated;
mod syntax_rewriter;
use rome_formatter::format_element::tag::Label;
use rome_formatter::prelude::*;
use rome_formatter::{
comments::Comments, write, CstFormatContext, Format, FormatLanguage, FormatToken,
TransformSourceMap,
};
use rome_formatter::{Buffer, FormatOwnedWithRule, FormatRefWithRule, Formatted, Printed};
use rome_js_syntax::{
AnyJsDeclaration, AnyJsStatement, JsLanguage, JsSyntaxKind, JsSyntaxNode, JsSyntaxToken,
};
use rome_rowan::TextRange;
use rome_rowan::{AstNode, SyntaxNode};
use crate::comments::JsCommentStyle;
use crate::context::{JsFormatContext, JsFormatOptions};
use crate::cst::FormatJsSyntaxNode;
use crate::syntax_rewriter::transform;
/// Used to get an object that knows how to format this object.
pub(crate) trait AsFormat<Context> {
type Format<'a>: rome_formatter::Format<Context>
where
Self: 'a;
/// Returns an object that is able to format this object.
fn format(&self) -> Self::Format<'_>;
}
/// Implement [AsFormat] for references to types that implement [AsFormat].
impl<T, C> AsFormat<C> for &T
where
T: AsFormat<C>,
{
type Format<'a> = T::Format<'a> where Self: 'a;
fn format(&self) -> Self::Format<'_> {
AsFormat::format(&**self)
}
}
/// Implement [AsFormat] for [SyntaxResult] where `T` implements [AsFormat].
///
/// Useful to format mandatory AST fields without having to unwrap the value first.
impl<T, C> AsFormat<C> for rome_rowan::SyntaxResult<T>
where
T: AsFormat<C>,
{
type Format<'a> = rome_rowan::SyntaxResult<T::Format<'a>> where Self: 'a;
fn format(&self) -> Self::Format<'_> {
match self {
Ok(value) => Ok(value.format()),
Err(err) => Err(*err),
}
}
}
/// Implement [AsFormat] for [Option] when `T` implements [AsFormat]
///
/// Allows to call format on optional AST fields without having to unwrap the field first.
impl<T, C> AsFormat<C> for Option<T>
where
T: AsFormat<C>,
{
type Format<'a> = Option<T::Format<'a>> where Self: 'a;
fn format(&self) -> Self::Format<'_> {
self.as_ref().map(|value| value.format())
}
}
/// Used to convert this object into an object that can be formatted.
///
/// The difference to [AsFormat] is that this trait takes ownership of `self`.
pub(crate) trait IntoFormat<Context> {
type Format: rome_formatter::Format<Context>;
fn into_format(self) -> Self::Format;
}
impl<T, Context> IntoFormat<Context> for rome_rowan::SyntaxResult<T>
where
T: IntoFormat<Context>,
{
type Format = rome_rowan::SyntaxResult<T::Format>;
fn into_format(self) -> Self::Format {
self.map(IntoFormat::into_format)
}
}
/// Implement [IntoFormat] for [Option] when `T` implements [IntoFormat]
///
/// Allows to call format on optional AST fields without having to unwrap the field first.
impl<T, Context> IntoFormat<Context> for Option<T>
where
T: IntoFormat<Context>,
{
type Format = Option<T::Format>;
fn into_format(self) -> Self::Format {
self.map(IntoFormat::into_format)
}
}
/// Formatting specific [Iterator] extensions
pub(crate) trait FormattedIterExt {
/// Converts every item to an object that knows how to format it.
fn formatted<Context>(self) -> FormattedIter<Self, Self::Item, Context>
where
Self: Iterator + Sized,
Self::Item: IntoFormat<Context>,
{
FormattedIter {
inner: self,
options: std::marker::PhantomData,
}
}
}
impl<I> FormattedIterExt for I where I: std::iter::Iterator {}
pub(crate) struct FormattedIter<Iter, Item, Context>
where
Iter: Iterator<Item = Item>,
{
inner: Iter,
options: std::marker::PhantomData<Context>,
}
impl<Iter, Item, Context> std::iter::Iterator for FormattedIter<Iter, Item, Context>
where
Iter: Iterator<Item = Item>,
Item: IntoFormat<Context>,
{
type Item = Item::Format;
fn next(&mut self) -> Option<Self::Item> {
Some(self.inner.next()?.into_format())
}
}
impl<Iter, Item, Context> std::iter::FusedIterator for FormattedIter<Iter, Item, Context>
where
Iter: std::iter::FusedIterator<Item = Item>,
Item: IntoFormat<Context>,
{
}
impl<Iter, Item, Context> std::iter::ExactSizeIterator for FormattedIter<Iter, Item, Context>
where
Iter: Iterator<Item = Item> + std::iter::ExactSizeIterator,
Item: IntoFormat<Context>,
{
}
pub(crate) type JsFormatter<'buf> = Formatter<'buf, JsFormatContext>;
/// Rule for formatting a JavaScript [AstNode].
pub(crate) trait FormatNodeRule<N>
where
N: AstNode<Language = JsLanguage>,
{
fn fmt(&self, node: &N, f: &mut JsFormatter) -> FormatResult<()> {
if self.is_suppressed(node, f) {
return write!(f, [format_suppressed_node(node.syntax())]);
}
self.fmt_leading_comments(node, f)?;
self.fmt_node(node, f)?;
self.fmt_dangling_comments(node, f)?;
self.fmt_trailing_comments(node, f)
}
/// Formats the node without comments. Ignores any suppression comments.
fn fmt_node(&self, node: &N, f: &mut JsFormatter) -> FormatResult<()> {
let needs_parentheses = self.needs_parentheses(node);
if needs_parentheses {
write!(f, [text("(")])?;
}
self.fmt_fields(node, f)?;
if needs_parentheses {
write!(f, [text(")")])?;
}
Ok(())
}
/// Formats the node's fields.
fn fmt_fields(&self, item: &N, f: &mut JsFormatter) -> FormatResult<()>;
/// Returns whether the node requires parens.
fn needs_parentheses(&self, item: &N) -> bool {
let _ = item;
false
}
/// Returns `true` if the node has a suppression comment and should use the same formatting as in the source document.
fn is_suppressed(&self, node: &N, f: &JsFormatter) -> bool {
f.context().comments().is_suppressed(node.syntax())
}
/// Formats the [leading comments](rome_formatter::comments#leading-comments) of the node.
///
/// You may want to override this method if you want to manually handle the formatting of comments
/// inside of the `fmt_fields` method or customize the formatting of the leading comments.
fn fmt_leading_comments(&self, node: &N, f: &mut JsFormatter) -> FormatResult<()> {
format_leading_comments(node.syntax()).fmt(f)
}
/// Formats the [dangling comments](rome_formatter::comments#dangling-comments) of the node.
///
/// You should override this method if the node handled by this rule can have dangling comments because the
/// default implementation formats the dangling comments at the end of the node, which isn't ideal but ensures that
/// no comments are dropped.
///
/// A node can have dangling comments if all its children are tokens or if all node childrens are optional.
fn fmt_dangling_comments(&self, node: &N, f: &mut JsFormatter) -> FormatResult<()> {
format_dangling_comments(node.syntax())
.with_soft_block_indent()
.fmt(f)
}
/// Formats the [trailing comments](rome_formatter::comments#trailing-comments) of the node.
///
/// You may want to override this method if you want to manually handle the formatting of comments
/// inside of the `fmt_fields` method or customize the formatting of the trailing comments.
fn fmt_trailing_comments(&self, node: &N, f: &mut JsFormatter) -> FormatResult<()> {
format_trailing_comments(node.syntax()).fmt(f)
}
}
/// Rule for formatting an bogus node.
pub(crate) trait FormatBogusNodeRule<N>
where
N: AstNode<Language = JsLanguage>,
{
fn fmt(&self, node: &N, f: &mut JsFormatter) -> FormatResult<()> {
format_bogus_node(node.syntax()).fmt(f)
}
}
/// Format implementation specific to JavaScript tokens.
pub(crate) type FormatJsSyntaxToken = FormatToken<JsFormatContext>;
impl AsFormat<JsFormatContext> for JsSyntaxToken {
type Format<'a> = FormatRefWithRule<'a, JsSyntaxToken, FormatJsSyntaxToken>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(self, FormatJsSyntaxToken::default())
}
}
impl IntoFormat<JsFormatContext> for JsSyntaxToken {
type Format = FormatOwnedWithRule<JsSyntaxToken, FormatJsSyntaxToken>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(self, FormatJsSyntaxToken::default())
}
}
#[derive(Debug, Clone)]
pub struct JsFormatLanguage {
options: JsFormatOptions,
}
impl JsFormatLanguage {
pub fn new(options: JsFormatOptions) -> Self {
Self { options }
}
}
impl FormatLanguage for JsFormatLanguage {
type SyntaxLanguage = JsLanguage;
type Context = JsFormatContext;
type FormatRule = FormatJsSyntaxNode;
fn transform(
&self,
root: &SyntaxNode<Self::SyntaxLanguage>,
) -> Option<(SyntaxNode<Self::SyntaxLanguage>, TransformSourceMap)> {
Some(transform(root.clone()))
}
fn is_range_formatting_node(&self, node: &JsSyntaxNode) -> bool {
let kind = node.kind();
// Do not format variable declaration nodes, format the whole statement instead
if matches!(kind, JsSyntaxKind::JS_VARIABLE_DECLARATION) {
return false;
}
AnyJsStatement::can_cast(kind)
|| AnyJsDeclaration::can_cast(kind)
|| matches!(
kind,
JsSyntaxKind::JS_DIRECTIVE | JsSyntaxKind::JS_EXPORT | JsSyntaxKind::JS_IMPORT
)
}
fn options(&self) -> &JsFormatOptions {
&self.options
}
fn create_context(
self,
root: &JsSyntaxNode,
source_map: Option<TransformSourceMap>,
) -> Self::Context {
let comments = Comments::from_node(root, &JsCommentStyle, source_map.as_ref());
JsFormatContext::new(self.options, comments).with_source_map(source_map)
}
}
/// 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 [JsFormatContext], 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(
options: JsFormatOptions,
root: &JsSyntaxNode,
range: TextRange,
) -> FormatResult<Printed> {
rome_formatter::format_range(root, range, JsFormatLanguage::new(options))
}
/// Formats a JavaScript (and its super languages) file based on its features.
///
/// It returns a [Formatted] result, which the user can use to override a file.
pub fn format_node(
options: JsFormatOptions,
root: &JsSyntaxNode,
) -> FormatResult<Formatted<JsFormatContext>> {
rome_formatter::format_node(root, JsFormatLanguage::new(options))
}
/// Formats a single node within a file, supported by Rome.
///
/// This runs a simple heuristic to determine the initial indentation
/// level of the node based on the provided [JsFormatContext], 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
pub fn format_sub_tree(options: JsFormatOptions, root: &JsSyntaxNode) -> FormatResult<Printed> {
rome_formatter::format_sub_tree(root, JsFormatLanguage::new(options))
}
#[derive(Copy, Clone, Debug)]
pub(crate) enum JsLabels {
MemberChain,
}
impl Label for JsLabels {
fn id(&self) -> u64 {
*self as u64
}
fn debug_name(&self) -> &'static str {
match self {
JsLabels::MemberChain => "MemberChain",
}
}
}
#[cfg(test)]
mod tests {
use super::format_range;
use crate::context::JsFormatOptions;
use rome_formatter::IndentStyle;
use rome_js_parser::{parse, parse_script, JsParserOptions};
use rome_js_syntax::JsFileSource;
use rome_rowan::{TextRange, TextSize};
#[test]
fn test_range_formatting() {
let input = "
while(
true
) {
function func() {
func( /* comment */
);
let array =
[ 1
, 2];
}
function func2()
{
const no_format = () => {};
}
}
";
// Start the formatting range two characters before the "let" keywords,
// in the middle of the indentation whitespace for the line
let range_start = TextSize::try_from(input.find("let").unwrap() - 2).unwrap();
let range_end = TextSize::try_from(input.find("const").unwrap()).unwrap();
let tree = parse_script(input, JsParserOptions::default());
let result = format_range(
JsFormatOptions::new(JsFileSource::js_script())
.with_indent_style(IndentStyle::Space(4)),
&tree.syntax(),
TextRange::new(range_start, range_end),
);
let result = result.expect("range formatting failed");
assert_eq!(
result.as_code(),
"function func() {\n func(/* comment */);\n\n let array = [1, 2];\n }\n\n function func2() {\n const no_format = () => {};\n }"
);
assert_eq!(
result.range(),
Some(TextRange::new(
range_start - TextSize::from(56),
range_end + TextSize::from(40)
))
);
}
#[test]
fn test_range_formatting_indentation() {
let input = "
function() {
const veryLongIdentifierToCauseALineBreak = { veryLongKeyToCauseALineBreak: 'veryLongValueToCauseALineBreak' }
}
";
let range_start = TextSize::try_from(input.find("const").unwrap()).unwrap();
let range_end = TextSize::try_from(input.find('}').unwrap()).unwrap();
let tree = parse_script(input, JsParserOptions::default());
let result = format_range(
JsFormatOptions::new(JsFileSource::js_script())
.with_indent_style(IndentStyle::Space(4)),
&tree.syntax(),
TextRange::new(range_start, range_end),
);
let result = result.expect("range formatting failed");
// As a result of the indentation normalization, the number of spaces within
// the object expression is currently rounded down from an odd indentation level
assert_eq!(
result.as_code(),
"const veryLongIdentifierToCauseALineBreak = {\n veryLongKeyToCauseALineBreak: \"veryLongValueToCauseALineBreak\",\n };"
);
assert_eq!(
result.range(),
Some(TextRange::new(range_start, range_end + TextSize::from(1)))
);
}
#[test]
fn test_range_formatting_whitespace() {
let input = " ";
let range_start = TextSize::from(5);
let range_end = TextSize::from(5);
let tree = parse_script(input, JsParserOptions::default());
let result = format_range(
JsFormatOptions::new(JsFileSource::js_script())
.with_indent_style(IndentStyle::Space(4)),
&tree.syntax(),
TextRange::new(range_start, range_end),
);
let result = result.expect("range formatting failed");
assert_eq!(result.as_code(), "");
assert_eq!(result.range(), Some(TextRange::new(range_start, range_end)));
}
#[test]
fn test_range_formatting_middle_of_token() {
let input = r#"/* */ function Foo(){
/**/
}
"#;
let range = TextRange::new(TextSize::from(16), TextSize::from(28));
debug_assert_eq!(
&input[range],
r#"oo(){
/**/
}"#
);
let tree = parse_script(input, JsParserOptions::default());
let result = format_range(
JsFormatOptions::new(JsFileSource::js_script())
.with_indent_style(IndentStyle::Space(4)),
&tree.syntax(),
range,
)
.expect("Range formatting failed");
assert_eq!(
result.as_code(),
r#"/* */ function Foo() {
/**/
}"#
);
assert_eq!(
result.range(),
Some(TextRange::new(TextSize::from(0), TextSize::from(28)))
)
}
#[test]
fn range_formatting_trailing_comments() {
let input = r#"let fn =a((x ) => {
quux (); //
});
"#;
let range = TextRange::new(TextSize::from(28), TextSize::from(41));
debug_assert_eq!(&input[range], r#" quux (); //"#);
let tree = parse_script(input, JsParserOptions::default());
let result = format_range(
JsFormatOptions::new(JsFileSource::js_script())
.with_indent_style(IndentStyle::Space(4)),
&tree.syntax(),
range,
)
.expect("Range formatting failed");
assert_eq!(result.as_code(), r#"quux(); //"#);
assert_eq!(
result.range(),
Some(TextRange::new(TextSize::from(30), TextSize::from(41)))
)
}
#[test]
fn format_range_out_of_bounds() {
let src = "statement();";
let syntax = JsFileSource::js_module();
let tree = parse(src, syntax, JsParserOptions::default());
let result = format_range(
JsFormatOptions::new(syntax),
&tree.syntax(),
TextRange::new(TextSize::from(0), TextSize::of(src) + TextSize::from(5)),
);
assert!(result.is_err());
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/comments.rs | crates/rome_js_formatter/src/comments.rs | use crate::prelude::*;
use crate::utils::AnyJsConditional;
use rome_diagnostics_categories::category;
use rome_formatter::comments::is_doc_comment;
use rome_formatter::{
comments::{
CommentKind, CommentPlacement, CommentStyle, CommentTextPosition, Comments,
DecoratedComment, SourceComment,
},
write,
};
use rome_js_syntax::suppression::parse_suppression_comment;
use rome_js_syntax::JsSyntaxKind::JS_EXPORT;
use rome_js_syntax::{
AnyJsClass, AnyJsName, AnyJsRoot, AnyJsStatement, JsArrayHole, JsArrowFunctionExpression,
JsBlockStatement, JsCallArguments, JsCatchClause, JsEmptyStatement, JsFinallyClause,
JsFormalParameter, JsFunctionBody, JsIdentifierExpression, JsIfStatement, JsLanguage,
JsSyntaxKind, JsSyntaxNode, JsVariableDeclarator, JsWhileStatement, TsInterfaceDeclaration,
};
use rome_rowan::{AstNode, SyntaxNodeOptionExt, SyntaxTriviaPieceComments, TextLen};
pub type JsComments = Comments<JsLanguage>;
#[derive(Default)]
pub struct FormatJsLeadingComment;
impl FormatRule<SourceComment<JsLanguage>> for FormatJsLeadingComment {
type Context = JsFormatContext;
fn fmt(
&self,
comment: &SourceComment<JsLanguage>,
f: &mut Formatter<Self::Context>,
) -> FormatResult<()> {
if is_doc_comment(comment.piece()) {
let mut source_offset = comment.piece().text_range().start();
let mut lines = comment.piece().text().lines();
// SAFETY: Safe, `is_doc_comment` only returns `true` for multiline comments
let first_line = lines.next().unwrap();
write!(f, [dynamic_text(first_line.trim_end(), source_offset)])?;
source_offset += first_line.text_len();
// Indent the remaining lines by one space so that all `*` are aligned.
write!(
f,
[align(
1,
&format_once(|f| {
for line in lines {
write!(
f,
[hard_line_break(), dynamic_text(line.trim(), source_offset)]
)?;
source_offset += line.text_len();
}
Ok(())
})
)]
)
} else {
write!(f, [comment.piece().as_piece()])
}
}
}
#[derive(Eq, PartialEq, Copy, Clone, Debug, Default)]
pub struct JsCommentStyle;
impl CommentStyle for JsCommentStyle {
type Language = JsLanguage;
fn is_suppression(text: &str) -> bool {
parse_suppression_comment(text)
.filter_map(Result::ok)
.flat_map(|suppression| suppression.categories)
.any(|(key, _)| key == category!("format"))
}
fn get_comment_kind(comment: &SyntaxTriviaPieceComments<JsLanguage>) -> CommentKind {
if comment.text().starts_with("/*") {
if comment.has_newline() {
CommentKind::Block
} else {
CommentKind::InlineBlock
}
} else {
CommentKind::Line
}
}
fn place_comment(
&self,
comment: DecoratedComment<Self::Language>,
) -> CommentPlacement<Self::Language> {
match comment.text_position() {
CommentTextPosition::EndOfLine => handle_typecast_comment(comment)
.or_else(handle_function_declaration_comment)
.or_else(handle_conditional_comment)
.or_else(handle_if_statement_comment)
.or_else(handle_while_comment)
.or_else(handle_try_comment)
.or_else(handle_class_comment)
.or_else(handle_method_comment)
.or_else(handle_for_comment)
.or_else(handle_root_comments)
.or_else(handle_array_hole_comment)
.or_else(handle_variable_declarator_comment)
.or_else(handle_parameter_comment)
.or_else(handle_labelled_statement_comment)
.or_else(handle_call_expression_comment)
.or_else(handle_continue_break_comment)
.or_else(handle_mapped_type_comment)
.or_else(handle_switch_default_case_comment)
.or_else(handle_import_export_specifier_comment),
CommentTextPosition::OwnLine => handle_member_expression_comment(comment)
.or_else(handle_function_declaration_comment)
.or_else(handle_if_statement_comment)
.or_else(handle_while_comment)
.or_else(handle_try_comment)
.or_else(handle_class_comment)
.or_else(handle_method_comment)
.or_else(handle_for_comment)
.or_else(handle_root_comments)
.or_else(handle_parameter_comment)
.or_else(handle_array_hole_comment)
.or_else(handle_labelled_statement_comment)
.or_else(handle_call_expression_comment)
.or_else(handle_mapped_type_comment)
.or_else(handle_continue_break_comment)
.or_else(handle_union_type_comment)
.or_else(handle_import_export_specifier_comment),
CommentTextPosition::SameLine => handle_if_statement_comment(comment)
.or_else(handle_while_comment)
.or_else(handle_for_comment)
.or_else(handle_root_comments)
.or_else(handle_after_arrow_param_comment)
.or_else(handle_array_hole_comment)
.or_else(handle_call_expression_comment)
.or_else(handle_continue_break_comment)
.or_else(handle_class_comment),
}
}
}
/// Force end of line type cast comments to remain leading comments of the next node, if any
fn handle_typecast_comment(comment: DecoratedComment<JsLanguage>) -> CommentPlacement<JsLanguage> {
match comment.following_node() {
Some(following_node) if is_type_comment(comment.piece()) => {
CommentPlacement::leading(following_node.clone(), comment)
}
_ => CommentPlacement::Default(comment),
}
}
fn handle_after_arrow_param_comment(
comment: DecoratedComment<JsLanguage>,
) -> CommentPlacement<JsLanguage> {
let is_next_arrow = comment
.following_token()
.map_or(false, |token| token.kind() == JsSyntaxKind::FAT_ARROW);
// Makes comments after the `(` and `=>` dangling comments
// ```javascript
// () /* comment */ => true
// ```
if JsArrowFunctionExpression::can_cast(comment.enclosing_node().kind()) && is_next_arrow {
CommentPlacement::dangling(comment.enclosing_node().clone(), comment)
} else {
CommentPlacement::Default(comment)
}
}
/// Handles array hole comments. Array holes have no token so all comments
/// become trailing comments by default. Override it that all comments are leading comments.
fn handle_array_hole_comment(
comment: DecoratedComment<JsLanguage>,
) -> CommentPlacement<JsLanguage> {
if let Some(array_hole) = comment.preceding_node().and_then(JsArrayHole::cast_ref) {
CommentPlacement::leading(array_hole.into_syntax(), comment)
} else {
CommentPlacement::Default(comment)
}
}
fn handle_call_expression_comment(
comment: DecoratedComment<JsLanguage>,
) -> CommentPlacement<JsLanguage> {
// Make comments between the callee and the arguments leading comments of the first argument.
// ```javascript
// a /* comment */ (call)
// ```
if let Some(arguments) = comment.following_node().and_then(JsCallArguments::cast_ref) {
return if let Some(Ok(first)) = arguments.args().first() {
CommentPlacement::leading(first.into_syntax(), comment)
} else {
CommentPlacement::dangling(arguments.into_syntax(), comment)
};
}
CommentPlacement::Default(comment)
}
fn handle_continue_break_comment(
comment: DecoratedComment<JsLanguage>,
) -> CommentPlacement<JsLanguage> {
let enclosing = comment.enclosing_node();
// Make comments between the `continue` and label token trailing comments
// ```javascript
// continue /* comment */ a;
// ```
// This differs from Prettier because other ASTs use an identifier for the label whereas Rome uses
// a token.
match enclosing.kind() {
JsSyntaxKind::JS_CONTINUE_STATEMENT | JsSyntaxKind::JS_BREAK_STATEMENT => {
match enclosing.parent() {
// Make it the trailing of the parent if this is a single-statement body
// to prevent that the comment becomes a trailing comment of the parent when re-formatting
// ```javascript
// for (;;) continue /* comment */;
// ```
Some(parent)
if matches!(
parent.kind(),
JsSyntaxKind::JS_FOR_STATEMENT
| JsSyntaxKind::JS_FOR_OF_STATEMENT
| JsSyntaxKind::JS_FOR_IN_STATEMENT
| JsSyntaxKind::JS_WHILE_STATEMENT
| JsSyntaxKind::JS_DO_WHILE_STATEMENT
| JsSyntaxKind::JS_IF_STATEMENT
| JsSyntaxKind::JS_WITH_STATEMENT
| JsSyntaxKind::JS_LABELED_STATEMENT
) =>
{
CommentPlacement::trailing(parent, comment)
}
_ => CommentPlacement::trailing(enclosing.clone(), comment),
}
}
_ => CommentPlacement::Default(comment),
}
}
/// Moves line comments after the `default` keyword into the block statement:
///
/// ```javascript
/// switch (x) {
/// default: // comment
/// {
/// break;
/// }
/// ```
///
/// All other same line comments become `Dangling` comments that are handled inside of the default case
/// formatting
fn handle_switch_default_case_comment(
comment: DecoratedComment<JsLanguage>,
) -> CommentPlacement<JsLanguage> {
match (comment.enclosing_node().kind(), comment.following_node()) {
(JsSyntaxKind::JS_DEFAULT_CLAUSE, Some(following)) => {
match JsBlockStatement::cast_ref(following) {
Some(block) if comment.kind().is_line() => {
place_block_statement_comment(block, comment)
}
_ => CommentPlacement::dangling(comment.enclosing_node().clone(), comment),
}
}
_ => CommentPlacement::Default(comment),
}
}
fn handle_labelled_statement_comment(
comment: DecoratedComment<JsLanguage>,
) -> CommentPlacement<JsLanguage> {
match comment.enclosing_node().kind() {
JsSyntaxKind::JS_LABELED_STATEMENT => {
CommentPlacement::leading(comment.enclosing_node().clone(), comment)
}
_ => CommentPlacement::Default(comment),
}
}
fn handle_class_comment(comment: DecoratedComment<JsLanguage>) -> CommentPlacement<JsLanguage> {
// Make comments following after the `extends` or `implements` keyword trailing comments
// of the preceding extends, type parameters, or id.
// ```javascript
// class a9 extends
// /* comment */
// b {
// constructor() {}
// }
// ```
if matches!(
comment.enclosing_node().kind(),
JsSyntaxKind::JS_EXTENDS_CLAUSE
| JsSyntaxKind::TS_IMPLEMENTS_CLAUSE
| JsSyntaxKind::TS_EXTENDS_CLAUSE
) {
if comment.preceding_node().is_none() && !comment.text_position().is_same_line() {
if let Some(sibling) = comment.enclosing_node().prev_sibling() {
return CommentPlacement::trailing(sibling, comment);
}
}
return CommentPlacement::Default(comment);
}
// ```javascript
// @decorator
// // comment
// class Foo {}
// ```
if (AnyJsClass::can_cast(comment.enclosing_node().kind())
&& comment
.following_token()
.map_or(false, |token| token.kind() == JsSyntaxKind::CLASS_KW))
// ```javascript
// @decorator
// // comment
// export class Foo {}
// ```
|| comment.enclosing_node().kind() == JS_EXPORT
{
if let Some(preceding) = comment.preceding_node() {
if preceding.kind() == JsSyntaxKind::JS_DECORATOR {
return CommentPlacement::trailing(preceding.clone(), comment);
}
}
}
let first_member = if let Some(class) = AnyJsClass::cast_ref(comment.enclosing_node()) {
class.members().first().map(AstNode::into_syntax)
} else if let Some(interface) = TsInterfaceDeclaration::cast_ref(comment.enclosing_node()) {
interface.members().first().map(AstNode::into_syntax)
} else {
return CommentPlacement::Default(comment);
};
if comment.text_position().is_same_line() {
// Handle same line comments in empty class bodies
// ```javascript
// class Test { /* comment */ }
// ```
if comment
.following_token()
.map_or(false, |token| token.kind() == JsSyntaxKind::R_CURLY)
&& first_member.is_none()
{
return CommentPlacement::dangling(comment.enclosing_node().clone(), comment);
} else {
return CommentPlacement::Default(comment);
}
}
if let Some(following) = comment.following_node() {
// Make comments preceding the first member leading comments of the member
// ```javascript
// class Test { /* comment */
// prop;
// }
// ```
if let Some(member) = first_member {
if following == &member {
return CommentPlacement::leading(member, comment);
}
}
if let Some(preceding) = comment.preceding_node() {
// Make all comments between the id/type parameters and the extends clause trailing comments
// of the id/type parameters
//
// ```javascript
// class Test
//
// /* comment */ extends B {}
// ```
if matches!(
following.kind(),
JsSyntaxKind::JS_EXTENDS_CLAUSE
| JsSyntaxKind::TS_IMPLEMENTS_CLAUSE
| JsSyntaxKind::TS_EXTENDS_CLAUSE
) && !comment.text_position().is_same_line()
{
return CommentPlacement::trailing(preceding.clone(), comment);
}
}
} else if first_member.is_none() {
// Handle the case where there are no members, attach the comments as dangling comments.
// ```javascript
// class Test // comment
// {
// }
// ```
return CommentPlacement::dangling(comment.enclosing_node().clone(), comment);
}
CommentPlacement::Default(comment)
}
fn handle_method_comment(comment: DecoratedComment<JsLanguage>) -> CommentPlacement<JsLanguage> {
let enclosing = comment.enclosing_node();
let is_method = matches!(
enclosing.kind(),
JsSyntaxKind::JS_METHOD_CLASS_MEMBER
| JsSyntaxKind::JS_METHOD_OBJECT_MEMBER
| JsSyntaxKind::JS_SETTER_CLASS_MEMBER
| JsSyntaxKind::JS_GETTER_CLASS_MEMBER
| JsSyntaxKind::JS_SETTER_OBJECT_MEMBER
| JsSyntaxKind::JS_GETTER_OBJECT_MEMBER
| JsSyntaxKind::JS_CONSTRUCTOR_CLASS_MEMBER
);
if !is_method {
return CommentPlacement::Default(comment);
}
// Move end of line and own line comments before the method body into the function
// ```javascript
// class Test {
// method() /* test */
// {}
// }
// ```
if let Some(following) = comment.following_node() {
if let Some(body) = JsFunctionBody::cast_ref(following) {
if let Some(directive) = body.directives().first() {
return CommentPlacement::leading(directive.into_syntax(), comment);
}
let first_non_empty = body
.statements()
.iter()
.find(|statement| !matches!(statement, AnyJsStatement::JsEmptyStatement(_)));
return match first_non_empty {
None => CommentPlacement::dangling(body.into_syntax(), comment),
Some(statement) => CommentPlacement::leading(statement.into_syntax(), comment),
};
}
}
CommentPlacement::Default(comment)
}
/// Handle a all comments document.
/// See `blank.js`
fn handle_root_comments(comment: DecoratedComment<JsLanguage>) -> CommentPlacement<JsLanguage> {
if let Some(root) = AnyJsRoot::cast_ref(comment.enclosing_node()) {
let is_blank = match &root {
AnyJsRoot::JsExpressionSnipped(_) => false,
AnyJsRoot::JsModule(module) => {
module.directives().is_empty() && module.items().is_empty()
}
AnyJsRoot::JsScript(script) => {
script.directives().is_empty() && script.statements().is_empty()
}
};
if is_blank {
return CommentPlacement::leading(root.into_syntax(), comment);
}
}
CommentPlacement::Default(comment)
}
fn handle_member_expression_comment(
comment: DecoratedComment<JsLanguage>,
) -> CommentPlacement<JsLanguage> {
let following = match comment.following_node() {
Some(following)
if matches!(
comment.enclosing_node().kind(),
JsSyntaxKind::JS_STATIC_MEMBER_EXPRESSION
| JsSyntaxKind::JS_COMPUTED_MEMBER_EXPRESSION
) =>
{
following
}
_ => return CommentPlacement::Default(comment),
};
// ```javascript
// a
// /* comment */.b
// a
// /* comment */[b]
// ```
if AnyJsName::can_cast(following.kind()) || JsIdentifierExpression::can_cast(following.kind()) {
CommentPlacement::leading(comment.enclosing_node().clone(), comment)
} else {
CommentPlacement::Default(comment)
}
}
fn handle_function_declaration_comment(
comment: DecoratedComment<JsLanguage>,
) -> CommentPlacement<JsLanguage> {
let is_function_declaration = matches!(
comment.enclosing_node().kind(),
JsSyntaxKind::JS_FUNCTION_DECLARATION
| JsSyntaxKind::JS_FUNCTION_EXPORT_DEFAULT_DECLARATION
);
let following = match comment.following_node() {
Some(following) if is_function_declaration => following,
_ => return CommentPlacement::Default(comment),
};
// Make comments between the `)` token and the function body leading comments
// of the first non empty statement or dangling comments of the body.
// ```javascript
// function test() /* comment */ {
// console.log("Hy");
// }
// ```
if let Some(body) = JsFunctionBody::cast_ref(following) {
match body
.statements()
.iter()
.find(|statement| !matches!(statement, AnyJsStatement::JsEmptyStatement(_)))
{
Some(first) => CommentPlacement::leading(first.into_syntax(), comment),
None => CommentPlacement::dangling(body.into_syntax(), comment),
}
} else {
CommentPlacement::Default(comment)
}
}
fn handle_conditional_comment(
comment: DecoratedComment<JsLanguage>,
) -> CommentPlacement<JsLanguage> {
let enclosing = comment.enclosing_node();
let (conditional, following) = match (
AnyJsConditional::cast_ref(enclosing),
comment.following_node(),
) {
(Some(conditional), Some(following)) => (conditional, following),
_ => {
return CommentPlacement::Default(comment);
}
};
// Make end of line comments that come after the operator leading comments of the consequent / alternate.
// ```javascript
// a
// // becomes leading of consequent
// ? { x: 5 } :
// {};
//
// a
// ? { x: 5 }
// : // becomes leading of alternate
// {};
//
// a // remains trailing, because it directly follows the node
// ? { x: 5 }
// : {};
// ```
let token = comment.piece().as_piece().token();
let is_after_operator = conditional.colon_token().as_ref() == Ok(&token)
|| conditional.question_mark_token().as_ref() == Ok(&token);
if is_after_operator {
return CommentPlacement::leading(following.clone(), comment);
}
CommentPlacement::Default(comment)
}
fn handle_if_statement_comment(
comment: DecoratedComment<JsLanguage>,
) -> CommentPlacement<JsLanguage> {
fn handle_else_clause(
comment: DecoratedComment<JsLanguage>,
consequent: JsSyntaxNode,
if_statement: JsSyntaxNode,
) -> CommentPlacement<JsLanguage> {
// Make all comments trailing comments of the `consequent` if the `consequent` is a `JsBlockStatement`
// ```javascript
// if (test) {
//
// } /* comment */ else if (b) {
// test
// }
// /* comment */ else if(c) {
//
// } /*comment */ else {
//
// }
// ```
if consequent.kind() == JsSyntaxKind::JS_BLOCK_STATEMENT {
return CommentPlacement::trailing(consequent, comment);
}
// Handle end of line comments that aren't stretching over multiple lines.
// Make them dangling comments of the consequent expression
//
// ```javascript
// if (cond1) expr1; // comment A
// else if (cond2) expr2; // comment A
// else expr3;
//
// if (cond1) expr1; /* comment */ else expr2;
//
// if (cond1) expr1; /* b */
// else if (cond2) expr2; /* b */
// else expr3; /* b*/
// ```
if !comment.kind().is_block()
&& !comment.text_position().is_own_line()
&& comment.preceding_node().is_some()
{
return CommentPlacement::dangling(consequent, comment);
}
// ```javascript
// if (cond1) expr1;
//
// /* comment */ else expr2;
//
// if (cond) expr; /*
// a multiline comment */
// else b;
//
// if (6) // comment
// true
// else // comment
// {true}
// ```
CommentPlacement::dangling(if_statement, comment)
}
match (comment.enclosing_node().kind(), comment.following_node()) {
(JsSyntaxKind::JS_IF_STATEMENT, Some(following)) => {
let if_statement = JsIfStatement::unwrap_cast(comment.enclosing_node().clone());
if let Some(preceding) = comment.preceding_node() {
// Test if this is a comment right before the condition's `)`
if comment
.following_token()
.map_or(false, |token| token.kind() == JsSyntaxKind::R_PAREN)
{
return CommentPlacement::trailing(preceding.clone(), comment);
}
// Handle comments before `else`
if following.kind() == JsSyntaxKind::JS_ELSE_CLAUSE {
let consequent = preceding.clone();
let if_statement = comment.enclosing_node().clone();
return handle_else_clause(comment, consequent, if_statement);
}
}
// Move comments coming before the `{` inside of the block
//
// ```javascript
// if (cond) /* test */ {
// }
// ```
if let Some(block_statement) = JsBlockStatement::cast_ref(following) {
return place_block_statement_comment(block_statement, comment);
}
// Don't attach comments to empty statements
// ```javascript
// if (cond) /* test */ ;
// ```
if let Some(preceding) = comment.preceding_node() {
if JsEmptyStatement::can_cast(following.kind()) {
return CommentPlacement::trailing(preceding.clone(), comment);
}
}
// Move comments coming before an if chain inside the body of the first non chain if.
//
// ```javascript
// if (cond1) /* test */ if (other) { a }
// ```
if let Some(if_statement) = JsIfStatement::cast_ref(following) {
if let Ok(nested_consequent) = if_statement.consequent() {
return place_leading_statement_comment(nested_consequent, comment);
}
}
// Make all comments after the condition's `)` leading comments
// ```javascript
// if (5) // comment
// true
//
// ```
if let Ok(consequent) = if_statement.consequent() {
if consequent.syntax() == following {
return CommentPlacement::leading(following.clone(), comment);
}
}
}
(JsSyntaxKind::JS_ELSE_CLAUSE, _) => {
if let Some(if_statement) = comment
.enclosing_node()
.parent()
.and_then(JsIfStatement::cast)
{
if let Ok(consequent) = if_statement.consequent() {
return handle_else_clause(
comment,
consequent.into_syntax(),
if_statement.into_syntax(),
);
}
}
}
_ => {
// fall through
}
}
CommentPlacement::Default(comment)
}
fn handle_while_comment(comment: DecoratedComment<JsLanguage>) -> CommentPlacement<JsLanguage> {
let (while_statement, following) = match (
JsWhileStatement::cast_ref(comment.enclosing_node()),
comment.following_node(),
) {
(Some(while_statement), Some(following)) => (while_statement, following),
_ => return CommentPlacement::Default(comment),
};
if let Some(preceding) = comment.preceding_node() {
// Test if this is a comment right before the condition's `)`
if comment
.following_token()
.map_or(false, |token| token.kind() == JsSyntaxKind::R_PAREN)
{
return CommentPlacement::trailing(preceding.clone(), comment);
}
}
// Move comments coming before the `{` inside of the block
//
// ```javascript
// while (cond) /* test */ {
// }
// ```
if let Some(block) = JsBlockStatement::cast_ref(following) {
return place_block_statement_comment(block, comment);
}
// Don't attach comments to empty statements
// ```javascript
// if (cond) /* test */ ;
// ```
if let Some(preceding) = comment.preceding_node() {
if JsEmptyStatement::can_cast(following.kind()) {
return CommentPlacement::trailing(preceding.clone(), comment);
}
}
// Make all comments after the condition's `)` leading comments
// ```javascript
// while (5) // comment
// true
//
// ```
if let Ok(body) = while_statement.body() {
if body.syntax() == following {
return CommentPlacement::leading(body.into_syntax(), comment);
}
}
CommentPlacement::Default(comment)
}
fn handle_try_comment(comment: DecoratedComment<JsLanguage>) -> CommentPlacement<JsLanguage> {
let following = match comment.following_node() {
Some(following)
if matches!(
comment.enclosing_node().kind(),
JsSyntaxKind::JS_TRY_STATEMENT | JsSyntaxKind::JS_TRY_FINALLY_STATEMENT
) =>
{
// Move comments before the `catch` or `finally` inside of the body
// ```javascript
// try {
// }
// catch(e) {
// }
// // Comment 7
// finally {}
// ```
let body = if let Some(catch) = JsCatchClause::cast_ref(following) {
catch.body()
} else if let Some(finally) = JsFinallyClause::cast_ref(following) {
finally.body()
} else {
// Use an err, so that the following code skips over it
Err(rome_rowan::SyntaxError::MissingRequiredChild)
};
//
// ```javascript
// try {
// } /* comment catch {
// }
// ```
if let Ok(body) = body {
return place_block_statement_comment(body, comment);
}
following
}
Some(following)
if matches!(
comment.enclosing_node().kind(),
JsSyntaxKind::JS_CATCH_CLAUSE | JsSyntaxKind::JS_FINALLY_CLAUSE
) =>
{
following
}
_ => return CommentPlacement::Default(comment),
};
// Move comments coming before the `{` inside of the block
//
// ```javascript
// try /* test */ {
// }
// ```
if let Some(block) = JsBlockStatement::cast_ref(following) {
return place_block_statement_comment(block, comment);
}
CommentPlacement::Default(comment)
}
fn handle_for_comment(comment: DecoratedComment<JsLanguage>) -> CommentPlacement<JsLanguage> {
let enclosing = comment.enclosing_node();
let is_for_in_or_of = matches!(
enclosing.kind(),
JsSyntaxKind::JS_FOR_OF_STATEMENT | JsSyntaxKind::JS_FOR_IN_STATEMENT
);
if !is_for_in_or_of && !matches!(enclosing.kind(), JsSyntaxKind::JS_FOR_STATEMENT) {
return CommentPlacement::Default(comment);
}
if comment.text_position().is_own_line() && is_for_in_or_of {
CommentPlacement::leading(enclosing.clone(), comment)
}
// Don't attach comments to empty statement
// ```javascript
// for /* comment */ (;;);
// for (;;a++) /* comment */;
// ```
else if comment.following_node().map_or(false, |following| {
JsEmptyStatement::can_cast(following.kind())
}) {
if let Some(preceding) = comment.preceding_node() {
CommentPlacement::trailing(preceding.clone(), comment)
} else {
CommentPlacement::dangling(comment.enclosing_node().clone(), comment)
}
} else {
CommentPlacement::Default(comment)
}
}
fn handle_variable_declarator_comment(
comment: DecoratedComment<JsLanguage>,
) -> CommentPlacement<JsLanguage> {
let following = match comment.following_node() {
Some(following) => following,
None => return CommentPlacement::Default(comment),
};
fn is_complex_value(value: &JsSyntaxNode) -> bool {
matches!(
value.kind(),
JsSyntaxKind::JS_OBJECT_EXPRESSION
| JsSyntaxKind::JS_ARRAY_EXPRESSION
| JsSyntaxKind::JS_TEMPLATE_EXPRESSION
| JsSyntaxKind::TS_OBJECT_TYPE
| JsSyntaxKind::TS_UNION_TYPE
)
}
let enclosing = comment.enclosing_node();
match enclosing.kind() {
JsSyntaxKind::JS_ASSIGNMENT_EXPRESSION | JsSyntaxKind::TS_TYPE_ALIAS_DECLARATION => {
// Makes all comments preceding objects/arrays/templates or block comments leading comments of these nodes.
// ```javascript
// let a = // comment
// { };
// ```
if is_complex_value(following) || !comment.kind().is_line() {
return CommentPlacement::leading(following.clone(), comment);
}
}
JsSyntaxKind::JS_VARIABLE_DECLARATOR => {
let variable_declarator = JsVariableDeclarator::unwrap_cast(enclosing.clone());
match variable_declarator.initializer() {
// ```javascript
// let obj2 // Comment
// = {
// key: 'val'
// }
// ```
Some(initializer)
if initializer.syntax() == following
&& initializer
.expression()
.map_or(false, |expression| is_complex_value(expression.syntax())) =>
{
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/cst.rs | crates/rome_js_formatter/src/cst.rs | use crate::prelude::*;
use rome_formatter::{FormatOwnedWithRule, FormatRefWithRule};
use crate::{AsFormat, IntoFormat, JsFormatContext};
use rome_js_syntax::{map_syntax_node, JsSyntaxNode};
#[derive(Debug, Copy, Clone, Default)]
pub struct FormatJsSyntaxNode;
impl rome_formatter::FormatRule<JsSyntaxNode> for FormatJsSyntaxNode {
type Context = JsFormatContext;
fn fmt(&self, node: &JsSyntaxNode, f: &mut JsFormatter) -> FormatResult<()> {
map_syntax_node!(node.clone(), node => node.format().fmt(f))
}
}
impl AsFormat<JsFormatContext> for JsSyntaxNode {
type Format<'a> = FormatRefWithRule<'a, JsSyntaxNode, FormatJsSyntaxNode>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(self, FormatJsSyntaxNode)
}
}
impl IntoFormat<JsFormatContext> for JsSyntaxNode {
type Format = FormatOwnedWithRule<JsSyntaxNode, FormatJsSyntaxNode>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(self, FormatJsSyntaxNode)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/parentheses.rs | crates/rome_js_formatter/src/parentheses.rs | //! JavaScript supports parenthesizing expressions, assignments, and TypeScript types.
//! Parenthesizing an expression can be desired to change the precedence of an expression or to ease
//! readability.
//!
//! Rome is opinionated about which parentheses to keep or where to insert parentheses.
//! It removes parentheses that aren't necessary to keep the same semantics as in the source document, nor aren't improving readability.
//! Rome also inserts parentheses around nodes where we believe that they're helpful to improve readability.
//!
//! The [NeedsParentheses] trait forms the foundation of Rome's parentheses formatting and is implemented
//! by all nodes supporting parentheses (expressions, assignments, and types). The trait's main method
//! is the [NeedsParentheses::needs_parentheses]
//! method that implements the rules when a node requires parentheses.
//! A node requires parentheses to:
//! * improve readability: `a << b << 3` is harder to read than `(a << b) << 3`
//! * form valid syntax: `class A extends 3 + 3 {}` isn't valid, but `class A extends (3 + 3) {}` is
//! * preserve operator precedence: `(a + 3) * 4` has a different meaning than `a + 3 * 4`
//!
//! The challenge of formatting parenthesized nodes is that a tree with parentheses and a tree without
//! parentheses (that have the same semantics) must result in the same output. For example,
//! formatting `(a + 3) + 5` must yield the same formatted output as `a + 3 + 5` or `a + (3 + 5)` or even
//! `(((a + 3) + 5))` even though all these trees differ by the number of parenthesized expressions.
//!
//! There are two measures taken by Rome to ensure formatting is stable regardless of the number of parenthesized nodes in a tree:
//!
//! ## Removing parenthesized nodes
//!
//! The JavaScript formatter [pre-processes](crate:JsFormatSyntaxRewriter] the input CST and removes all parenthesized expressions, assignments, and types except if:
//! * The parenthesized node has a syntax error (skipped token trivia, missing inner expression)
//! * The node has a directly preceding closure type cast comment
//! * The inner expression is a bogus node
//!
//! Removing the parenthesized nodes has the benefit that a input tree with parentheses and an input tree
//! without parentheses have the same structure for as far as the formatter is concerned and thus,
//! the formatter makes the same decisions for both trees.
//!
//! ## Parentheses insertion
//! The parentheses that get removed by the pre-processing step are re-inserted by the [crate::FormatNodeRule].
//! The rule inserts parentheses for each node where [crate::FormatNodeRule::needs_parentheses] returns true.
use crate::utils::{AnyJsBinaryLikeExpression, AnyJsBinaryLikeLeftExpression};
use rome_js_syntax::{
AnyJsAssignment, AnyJsAssignmentPattern, AnyJsExpression, AnyJsFunctionBody,
AnyJsLiteralExpression, AnyTsReturnType, AnyTsType, JsArrowFunctionExpression,
JsAssignmentExpression, JsBinaryExpression, JsBinaryOperator, JsComputedMemberAssignment,
JsComputedMemberExpression, JsConditionalExpression, JsLanguage, JsParenthesizedAssignment,
JsParenthesizedExpression, JsPrivateName, JsSequenceExpression, JsStaticMemberAssignment,
JsStaticMemberExpression, JsSyntaxKind, JsSyntaxNode, JsSyntaxToken, TsConditionalType,
TsConstructorType, TsFunctionType, TsIndexedAccessType, TsIntersectionTypeElementList,
TsParenthesizedType, TsUnionTypeVariantList,
};
use rome_rowan::{declare_node_union, match_ast, AstNode, AstSeparatedList, SyntaxResult};
/// Node that may be parenthesized to ensure it forms valid syntax or to improve readability
pub trait NeedsParentheses: AstNode<Language = JsLanguage> {
fn needs_parentheses(&self) -> bool {
self.syntax()
.parent()
.map_or(false, |parent| self.needs_parentheses_with_parent(&parent))
}
/// Returns `true` if this node requires parentheses to form valid syntax or improve readability.
///
/// Returns `false` if the parentheses can be omitted safely without changing semantics.
fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool;
}
impl NeedsParentheses for AnyJsLiteralExpression {
#[inline]
fn needs_parentheses(&self) -> bool {
match self {
AnyJsLiteralExpression::JsBigintLiteralExpression(big_int) => {
big_int.needs_parentheses()
}
AnyJsLiteralExpression::JsBooleanLiteralExpression(boolean) => {
boolean.needs_parentheses()
}
AnyJsLiteralExpression::JsNullLiteralExpression(null_literal) => {
null_literal.needs_parentheses()
}
AnyJsLiteralExpression::JsNumberLiteralExpression(number_literal) => {
number_literal.needs_parentheses()
}
AnyJsLiteralExpression::JsRegexLiteralExpression(regex) => regex.needs_parentheses(),
AnyJsLiteralExpression::JsStringLiteralExpression(string) => string.needs_parentheses(),
}
}
#[inline]
fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool {
match self {
AnyJsLiteralExpression::JsBigintLiteralExpression(big_int) => {
big_int.needs_parentheses_with_parent(parent)
}
AnyJsLiteralExpression::JsBooleanLiteralExpression(boolean) => {
boolean.needs_parentheses_with_parent(parent)
}
AnyJsLiteralExpression::JsNullLiteralExpression(null_literal) => {
null_literal.needs_parentheses_with_parent(parent)
}
AnyJsLiteralExpression::JsNumberLiteralExpression(number_literal) => {
number_literal.needs_parentheses_with_parent(parent)
}
AnyJsLiteralExpression::JsRegexLiteralExpression(regex) => {
regex.needs_parentheses_with_parent(parent)
}
AnyJsLiteralExpression::JsStringLiteralExpression(string) => {
string.needs_parentheses_with_parent(parent)
}
}
}
}
impl NeedsParentheses for AnyJsExpression {
fn needs_parentheses(&self) -> bool {
match self {
AnyJsExpression::JsImportMetaExpression(meta) => meta.needs_parentheses(),
AnyJsExpression::AnyJsLiteralExpression(literal) => literal.needs_parentheses(),
AnyJsExpression::JsArrayExpression(array) => array.needs_parentheses(),
AnyJsExpression::JsArrowFunctionExpression(arrow) => arrow.needs_parentheses(),
AnyJsExpression::JsAssignmentExpression(assignment) => assignment.needs_parentheses(),
AnyJsExpression::JsAwaitExpression(await_expression) => {
await_expression.needs_parentheses()
}
AnyJsExpression::JsBinaryExpression(binary) => binary.needs_parentheses(),
AnyJsExpression::JsCallExpression(call) => call.needs_parentheses(),
AnyJsExpression::JsClassExpression(class) => class.needs_parentheses(),
AnyJsExpression::JsComputedMemberExpression(member) => member.needs_parentheses(),
AnyJsExpression::JsConditionalExpression(conditional) => {
conditional.needs_parentheses()
}
AnyJsExpression::JsFunctionExpression(function) => function.needs_parentheses(),
AnyJsExpression::JsIdentifierExpression(identifier) => identifier.needs_parentheses(),
AnyJsExpression::JsImportCallExpression(import_call) => import_call.needs_parentheses(),
AnyJsExpression::JsInExpression(in_expression) => in_expression.needs_parentheses(),
AnyJsExpression::JsInstanceofExpression(instanceof) => instanceof.needs_parentheses(),
AnyJsExpression::JsLogicalExpression(logical) => logical.needs_parentheses(),
AnyJsExpression::JsNewExpression(new) => new.needs_parentheses(),
AnyJsExpression::JsObjectExpression(object) => object.needs_parentheses(),
AnyJsExpression::JsParenthesizedExpression(parenthesized) => {
parenthesized.needs_parentheses()
}
AnyJsExpression::JsPostUpdateExpression(update) => update.needs_parentheses(),
AnyJsExpression::JsPreUpdateExpression(update) => update.needs_parentheses(),
AnyJsExpression::JsSequenceExpression(sequence) => sequence.needs_parentheses(),
AnyJsExpression::JsStaticMemberExpression(member) => member.needs_parentheses(),
AnyJsExpression::JsSuperExpression(sup) => sup.needs_parentheses(),
AnyJsExpression::JsTemplateExpression(template) => template.needs_parentheses(),
AnyJsExpression::JsThisExpression(this) => this.needs_parentheses(),
AnyJsExpression::JsUnaryExpression(unary) => unary.needs_parentheses(),
AnyJsExpression::JsBogusExpression(bogus) => bogus.needs_parentheses(),
AnyJsExpression::JsYieldExpression(yield_expression) => {
yield_expression.needs_parentheses()
}
AnyJsExpression::JsxTagExpression(jsx) => jsx.needs_parentheses(),
AnyJsExpression::JsNewTargetExpression(target) => target.needs_parentheses(),
AnyJsExpression::TsAsExpression(as_expression) => as_expression.needs_parentheses(),
AnyJsExpression::TsSatisfiesExpression(satisfies_expression) => {
satisfies_expression.needs_parentheses()
}
AnyJsExpression::TsNonNullAssertionExpression(non_null) => non_null.needs_parentheses(),
AnyJsExpression::TsTypeAssertionExpression(type_assertion) => {
type_assertion.needs_parentheses()
}
AnyJsExpression::TsInstantiationExpression(arguments) => arguments.needs_parentheses(),
}
}
fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool {
match self {
AnyJsExpression::JsImportMetaExpression(meta) => {
meta.needs_parentheses_with_parent(parent)
}
AnyJsExpression::AnyJsLiteralExpression(literal) => {
literal.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsArrayExpression(array) => {
array.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsArrowFunctionExpression(arrow) => {
arrow.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsAssignmentExpression(assignment) => {
assignment.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsAwaitExpression(await_expression) => {
await_expression.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsBinaryExpression(binary) => {
binary.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsCallExpression(call) => call.needs_parentheses_with_parent(parent),
AnyJsExpression::JsClassExpression(class) => {
class.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsComputedMemberExpression(member) => {
member.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsConditionalExpression(conditional) => {
conditional.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsFunctionExpression(function) => {
function.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsIdentifierExpression(identifier) => {
identifier.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsImportCallExpression(import_call) => {
import_call.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsInExpression(in_expression) => {
in_expression.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsInstanceofExpression(instanceof) => {
instanceof.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsLogicalExpression(logical) => {
logical.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsNewExpression(new) => new.needs_parentheses_with_parent(parent),
AnyJsExpression::JsObjectExpression(object) => {
object.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsParenthesizedExpression(parenthesized) => {
parenthesized.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsPostUpdateExpression(update) => {
update.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsPreUpdateExpression(update) => {
update.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsSequenceExpression(sequence) => {
sequence.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsStaticMemberExpression(member) => {
member.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsSuperExpression(sup) => sup.needs_parentheses_with_parent(parent),
AnyJsExpression::JsTemplateExpression(template) => {
template.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsThisExpression(this) => this.needs_parentheses_with_parent(parent),
AnyJsExpression::JsUnaryExpression(unary) => {
unary.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsBogusExpression(bogus) => {
bogus.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsYieldExpression(yield_expression) => {
yield_expression.needs_parentheses_with_parent(parent)
}
AnyJsExpression::JsxTagExpression(jsx) => jsx.needs_parentheses_with_parent(parent),
AnyJsExpression::JsNewTargetExpression(target) => {
target.needs_parentheses_with_parent(parent)
}
AnyJsExpression::TsAsExpression(as_expression) => {
as_expression.needs_parentheses_with_parent(parent)
}
AnyJsExpression::TsSatisfiesExpression(satisfies_expression) => {
satisfies_expression.needs_parentheses_with_parent(parent)
}
AnyJsExpression::TsNonNullAssertionExpression(non_null) => {
non_null.needs_parentheses_with_parent(parent)
}
AnyJsExpression::TsTypeAssertionExpression(type_assertion) => {
type_assertion.needs_parentheses_with_parent(parent)
}
AnyJsExpression::TsInstantiationExpression(expr) => {
expr.needs_parentheses_with_parent(parent)
}
}
}
}
declare_node_union! {
pub(crate) AnyJsExpressionLeftSide = AnyJsExpression | JsPrivateName | AnyJsAssignmentPattern
}
impl NeedsParentheses for AnyJsExpressionLeftSide {
fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool {
match self {
AnyJsExpressionLeftSide::AnyJsExpression(expression) => {
expression.needs_parentheses_with_parent(parent)
}
AnyJsExpressionLeftSide::JsPrivateName(_) => false,
AnyJsExpressionLeftSide::AnyJsAssignmentPattern(assignment) => {
assignment.needs_parentheses_with_parent(parent)
}
}
}
}
/// Returns the left most expression of `expression`.
///
/// For example, returns `a` for `(a ? b : c) + d` because it first resolves the
/// left hand expression of the binary expression, then resolves to the inner expression of the parenthesized
/// expression, and finally resolves to the test condition of the conditional expression.
pub(crate) fn resolve_left_most_expression(
expression: &AnyJsExpression,
) -> AnyJsExpressionLeftSide {
let mut current: AnyJsExpressionLeftSide = expression.clone().into();
loop {
match get_expression_left_side(¤t) {
None => {
break current;
}
Some(left) => {
current = left;
}
}
}
}
/// Returns the left side of an expression (an expression where the first child is a `Node` or [None]
/// if the expression has no left side.
pub(crate) fn get_expression_left_side(
current: &AnyJsExpressionLeftSide,
) -> Option<AnyJsExpressionLeftSide> {
use AnyJsExpression::*;
match current {
AnyJsExpressionLeftSide::AnyJsExpression(expression) => {
let left_expression = match expression {
JsSequenceExpression(sequence) => sequence.left().ok(),
JsStaticMemberExpression(member) => member.object().ok(),
JsComputedMemberExpression(member) => member.object().ok(),
JsTemplateExpression(template) => template.tag(),
JsNewExpression(new) => new.callee().ok(),
JsCallExpression(call) => call.callee().ok(),
JsConditionalExpression(conditional) => conditional.test().ok(),
TsAsExpression(as_expression) => as_expression.expression().ok(),
TsSatisfiesExpression(satisfies_expression) => {
satisfies_expression.expression().ok()
}
TsNonNullAssertionExpression(non_null) => non_null.expression().ok(),
JsAssignmentExpression(assignment) => {
return assignment.left().ok().map(AnyJsExpressionLeftSide::from)
}
JsPostUpdateExpression(expression) => {
return expression.operand().ok().map(|assignment| {
AnyJsExpressionLeftSide::from(AnyJsAssignmentPattern::AnyJsAssignment(
assignment,
))
})
}
expression => {
return AnyJsBinaryLikeExpression::cast(expression.syntax().clone()).and_then(
|binary_like| match binary_like.left().ok() {
Some(AnyJsBinaryLikeLeftExpression::AnyJsExpression(expression)) => {
Some(AnyJsExpressionLeftSide::from(expression))
}
Some(AnyJsBinaryLikeLeftExpression::JsPrivateName(name)) => {
Some(AnyJsExpressionLeftSide::from(name))
}
None => None,
},
);
}
};
left_expression.map(AnyJsExpressionLeftSide::from)
}
AnyJsExpressionLeftSide::AnyJsAssignmentPattern(pattern) => {
use AnyJsAssignment::*;
let left = match pattern {
AnyJsAssignmentPattern::AnyJsAssignment(assignment) => match assignment {
JsComputedMemberAssignment(computed) => {
return computed.object().ok().map(AnyJsExpressionLeftSide::from)
}
JsStaticMemberAssignment(member) => {
return member.object().ok().map(AnyJsExpressionLeftSide::from)
}
TsAsAssignment(parent) => parent.assignment().ok(),
TsSatisfiesAssignment(parent) => parent.assignment().ok(),
TsNonNullAssertionAssignment(parent) => parent.assignment().ok(),
TsTypeAssertionAssignment(parent) => parent.assignment().ok(),
JsParenthesizedAssignment(_)
| JsIdentifierAssignment(_)
| JsBogusAssignment(_) => None,
},
AnyJsAssignmentPattern::JsArrayAssignmentPattern(_)
| AnyJsAssignmentPattern::JsObjectAssignmentPattern(_) => None,
};
left.map(|assignment| {
AnyJsExpressionLeftSide::from(AnyJsAssignmentPattern::AnyJsAssignment(assignment))
})
}
AnyJsExpressionLeftSide::JsPrivateName(_) => None,
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub(crate) enum FirstInStatementMode {
/// Considers [JsExpressionStatement] and the body of [JsArrowFunctionExpression] as the first statement.
ExpressionStatementOrArrow,
/// Considers [JsExpressionStatement] and [JsExportDefaultExpressionClause] as the first statement.
ExpressionOrExportDefault,
}
/// Returns `true` if this node is at the start of an expression (depends on the passed `mode`).
///
/// Traverses upwards the tree for as long as the `node` is the left most expression until the node isn't
/// the left most node or reached a statement.
pub(crate) fn is_first_in_statement(node: JsSyntaxNode, mode: FirstInStatementMode) -> bool {
let mut current = node;
while let Some(parent) = current.parent() {
let parent = match parent.kind() {
JsSyntaxKind::JS_EXPRESSION_STATEMENT => {
return true;
}
JsSyntaxKind::JS_STATIC_MEMBER_EXPRESSION
| JsSyntaxKind::JS_STATIC_MEMBER_ASSIGNMENT
| JsSyntaxKind::JS_TEMPLATE_EXPRESSION
| JsSyntaxKind::JS_CALL_EXPRESSION
| JsSyntaxKind::JS_NEW_EXPRESSION
| JsSyntaxKind::TS_AS_EXPRESSION
| JsSyntaxKind::TS_SATISFIES_EXPRESSION
| JsSyntaxKind::TS_NON_NULL_ASSERTION_EXPRESSION => parent,
JsSyntaxKind::JS_SEQUENCE_EXPRESSION => {
let sequence = JsSequenceExpression::unwrap_cast(parent);
let is_left = sequence.left().map(AstNode::into_syntax).as_ref() == Ok(¤t);
if is_left {
sequence.into_syntax()
} else {
break;
}
}
JsSyntaxKind::JS_COMPUTED_MEMBER_EXPRESSION => {
let member_expression = JsComputedMemberExpression::unwrap_cast(parent);
let is_object = member_expression
.object()
.map(AstNode::into_syntax)
.as_ref()
== Ok(¤t);
if is_object {
member_expression.into_syntax()
} else {
break;
}
}
JsSyntaxKind::JS_COMPUTED_MEMBER_ASSIGNMENT => {
let assignment = JsComputedMemberAssignment::unwrap_cast(parent);
let is_object =
assignment.object().map(AstNode::into_syntax).as_ref() == Ok(¤t);
if is_object {
assignment.into_syntax()
} else {
break;
}
}
JsSyntaxKind::JS_ASSIGNMENT_EXPRESSION => {
let assignment = JsAssignmentExpression::unwrap_cast(parent);
let is_left = assignment.left().map(AstNode::into_syntax).as_ref() == Ok(¤t);
if is_left {
assignment.into_syntax()
} else {
break;
}
}
JsSyntaxKind::JS_CONDITIONAL_EXPRESSION => {
let conditional = JsConditionalExpression::unwrap_cast(parent);
if conditional.test().map(AstNode::into_syntax).as_ref() == Ok(¤t) {
conditional.into_syntax()
} else {
break;
}
}
JsSyntaxKind::JS_ARROW_FUNCTION_EXPRESSION
if mode == FirstInStatementMode::ExpressionStatementOrArrow =>
{
let arrow = JsArrowFunctionExpression::unwrap_cast(parent);
let is_body = arrow.body().map_or(false, |body| match body {
AnyJsFunctionBody::AnyJsExpression(expression) => {
expression.syntax() == ¤t
}
_ => false,
});
if is_body {
return true;
}
break;
}
JsSyntaxKind::JS_EXPORT_DEFAULT_EXPRESSION_CLAUSE
if mode == FirstInStatementMode::ExpressionOrExportDefault =>
{
return true;
}
kind if AnyJsBinaryLikeExpression::can_cast(kind) => {
let binary_like = AnyJsBinaryLikeExpression::unwrap_cast(parent);
let is_left = binary_like.left().map_or(false, |left| match left {
AnyJsBinaryLikeLeftExpression::AnyJsExpression(expression) => {
expression.syntax() == ¤t
}
_ => false,
});
if is_left {
binary_like.into_syntax()
} else {
break;
}
}
_ => break,
};
current = parent;
}
false
}
/// Implements the shared logic for when parentheses are necessary for [JsPreUpdateExpression], [JsPostUpdateExpression], or [JsUnaryExpression] expressions.
/// Each expression may implement node specific rules, which is why calling `needs_parens` on the node is preferred.
pub(crate) fn unary_like_expression_needs_parentheses(
expression: &JsSyntaxNode,
parent: &JsSyntaxNode,
) -> bool {
debug_assert!(matches!(
expression.kind(),
JsSyntaxKind::JS_PRE_UPDATE_EXPRESSION
| JsSyntaxKind::JS_POST_UPDATE_EXPRESSION
| JsSyntaxKind::JS_UNARY_EXPRESSION
));
debug_assert_is_parent(expression, parent);
if let Some(binary) = JsBinaryExpression::cast_ref(parent) {
matches!(binary.operator(), Ok(JsBinaryOperator::Exponent))
&& binary.left().map(AstNode::into_syntax).as_ref() == Ok(expression)
} else {
update_or_lower_expression_needs_parentheses(expression, parent)
}
}
/// Returns `true` if an expression with lower precedence than an update expression needs parentheses.
///
/// This is generally the case if the expression is used in a left hand side, or primary expression context.
pub(crate) fn update_or_lower_expression_needs_parentheses(
expression: &JsSyntaxNode,
parent: &JsSyntaxNode,
) -> bool {
debug_assert_is_expression(expression);
debug_assert_is_parent(expression, parent);
match parent.kind() {
JsSyntaxKind::JS_EXTENDS_CLAUSE => true,
_ => match parent.kind() {
JsSyntaxKind::TS_NON_NULL_ASSERTION_EXPRESSION => true,
_ => {
is_callee(expression, parent)
|| is_member_object(expression, parent)
|| is_tag(expression, parent)
}
},
}
}
/// Returns `true` if `node< is the `object` of a [JsStaticMemberExpression] or [JsComputedMemberExpression]
pub(crate) fn is_member_object(node: &JsSyntaxNode, parent: &JsSyntaxNode) -> bool {
debug_assert_is_expression(node);
debug_assert_is_parent(node, parent);
match_ast! {
match parent {
// Only allows expression in the `object` child.
JsStaticMemberExpression(_) => true,
JsStaticMemberAssignment(_) => true,
JsComputedMemberExpression(member_expression) => {
member_expression
.object()
.map(AstNode::into_syntax)
.as_ref()
== Ok(node)
},
JsComputedMemberAssignment(assignment) => {
assignment
.object()
.map(AstNode::into_syntax)
.as_ref()
== Ok(node)
},
_ => false,
}
}
}
/// Returns `true` if `node` is the `callee` of a [JsNewExpression] or [JsCallExpression].
pub(crate) fn is_callee(node: &JsSyntaxNode, parent: &JsSyntaxNode) -> bool {
debug_assert_is_expression(node);
debug_assert_is_parent(node, parent);
// It isn't necessary to test if the node is the `callee` because the nodes only
// allow expressions in the `callee` position;
matches!(
parent.kind(),
JsSyntaxKind::JS_CALL_EXPRESSION | JsSyntaxKind::JS_NEW_EXPRESSION
)
}
/// Returns `true` if `node` is the `test` of a [JsConditionalExpression].
///
/// # Examples
///
/// ```text
/// is_conditional_test(`a`, `a ? b : c`) -> true
/// is_conditional_test(`b`, `a ? b : c`) -> false
/// ```
pub(crate) fn is_conditional_test(node: &JsSyntaxNode, parent: &JsSyntaxNode) -> bool {
match_ast! {
match parent {
JsConditionalExpression(conditional) => {
conditional
.test()
.map(AstNode::into_syntax)
.as_ref()
== Ok(node)
},
_ => false
}
}
}
pub(crate) fn is_arrow_function_body(node: &JsSyntaxNode, parent: &JsSyntaxNode) -> bool {
debug_assert_is_expression(node);
match_ast! {
match parent {
JsArrowFunctionExpression(arrow) => {
match arrow.body() {
Ok(AnyJsFunctionBody::AnyJsExpression(expression)) => {
expression.syntax() == node
}
_ => false,
}
},
_ => false
}
}
}
/// Returns `true` if `node` is the `tag` of a [JsTemplate] expression
pub(crate) fn is_tag(node: &JsSyntaxNode, parent: &JsSyntaxNode) -> bool {
debug_assert_is_expression(node);
debug_assert_is_parent(node, parent);
matches!(parent.kind(), JsSyntaxKind::JS_TEMPLATE_EXPRESSION)
}
/// Returns `true` if `node` is a spread `...node`
pub(crate) fn is_spread(node: &JsSyntaxNode, parent: &JsSyntaxNode) -> bool {
debug_assert_is_expression(node);
debug_assert_is_parent(node, parent);
matches!(
parent.kind(),
JsSyntaxKind::JSX_SPREAD_CHILD
| JsSyntaxKind::JS_SPREAD
| JsSyntaxKind::JSX_SPREAD_ATTRIBUTE
)
}
/// Returns `true` if a TS primary type needs parentheses
pub(crate) fn operator_type_or_higher_needs_parens(
node: &JsSyntaxNode,
parent: &JsSyntaxNode,
) -> bool {
debug_assert_is_parent(node, parent);
match parent.kind() {
JsSyntaxKind::TS_ARRAY_TYPE
| JsSyntaxKind::TS_TYPE_OPERATOR_TYPE
| JsSyntaxKind::TS_REST_TUPLE_TYPE_ELEMENT
| JsSyntaxKind::TS_OPTIONAL_TUPLE_TYPE_ELEMENT => true,
JsSyntaxKind::TS_INDEXED_ACCESS_TYPE => {
let indexed = TsIndexedAccessType::unwrap_cast(parent.clone());
indexed.object_type().map(AstNode::into_syntax).as_ref() == Ok(node)
}
_ => false,
}
}
/// Tests if `node` is the check type of a [TsConditionalType]
///
/// ```javascript
/// type s = A extends string ? string : number // true for `A`, false for `string` and `number`
/// ```
pub(crate) fn is_check_type(node: &JsSyntaxNode, parent: &JsSyntaxNode) -> bool {
debug_assert_is_parent(node, parent);
match parent.kind() {
JsSyntaxKind::TS_CONDITIONAL_TYPE => {
let conditional = TsConditionalType::unwrap_cast(parent.clone());
conditional.check_type().map(AstNode::into_syntax).as_ref() == Ok(node)
}
_ => false,
}
}
/// Tests if `node` is the extends type of a [TsConditionalType]
///
/// ```javascript
/// type s = A extends string ? boolean : number // true for `string`, false for `A`, `boolean` and `number`
/// ```
fn is_extends_type(node: &JsSyntaxNode, parent: &JsSyntaxNode) -> bool {
debug_assert_is_parent(node, parent);
match parent.kind() {
JsSyntaxKind::TS_CONDITIONAL_TYPE => {
let conditional = TsConditionalType::unwrap_cast(parent.clone());
conditional
.extends_type()
.map(AstNode::into_syntax)
.as_ref()
== Ok(node)
}
_ => false,
}
}
/// Tests if `node` includes inferred return types with extends constraints
///
/// ```javascript
/// type Type<A> = A extends ((a: string) => infer B extends string) ? B : never; // true
/// ```
pub(crate) fn is_includes_inferred_return_types_with_extends_constraints(
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/format.rs | crates/rome_js_formatter/src/format.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use crate::{Format, FormatElement, FormatNode, Formatter};
use rome_formatter::FormatResult;
impl Format for rome_js_syntax::JsScript {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsModule {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsExpressionSnipped {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsDirective {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsBlockStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsBreakStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsClassDeclaration {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsContinueStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsDebuggerStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsDoWhileStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsEmptyStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsExpressionStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsForInStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsForOfStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsForStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsIfStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsLabeledStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsReturnStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsSwitchStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsThrowStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsTryFinallyStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsTryStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsVariableStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsWhileStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsWithStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsFunctionDeclaration {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsEnumDeclaration {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsTypeAliasDeclaration {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsInterfaceDeclaration {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsDeclareFunctionDeclaration {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsDeclareStatement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsModuleDeclaration {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsExternalModuleDeclaration {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsGlobalDeclaration {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsImportEqualsDeclaration {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsElseClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsVariableDeclaration {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsForVariableDeclaration {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsVariableDeclarator {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsCaseClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsDefaultClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsCatchClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsFinallyClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsCatchDeclaration {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsTypeAnnotation {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::ImportMeta {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsArrayExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsArrowFunctionExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsAssignmentExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsAwaitExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsBinaryExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsCallExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsClassExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsComputedMemberExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsConditionalExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsFunctionExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsIdentifierExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsImportCallExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsInExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsInstanceofExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsLogicalExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsNewExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsObjectExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsParenthesizedExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsPostUpdateExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsPreUpdateExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsSequenceExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsStaticMemberExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsSuperExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsThisExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsUnaryExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsYieldExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::NewTarget {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsTemplate {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsTypeAssertionExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsAsExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsNonNullAssertionExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsxTagExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsTypeArguments {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsTemplateChunkElement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsTemplateElement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsCallArguments {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsYieldArgument {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsTypeParameters {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsParameters {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsReturnTypeAnnotation {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsFunctionBody {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsSpread {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsArrayHole {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsReferenceIdentifier {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsPrivateName {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsLiteralMemberName {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsComputedMemberName {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsPropertyObjectMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsMethodObjectMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsGetterObjectMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsSetterObjectMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsShorthandPropertyObjectMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsExtendsClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsImplementsClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsClassExportDefaultDeclaration {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsPrivateClassMemberName {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsConstructorClassMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsStaticInitializationBlockClassMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsPropertyClassMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsMethodClassMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsGetterClassMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsSetterClassMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsConstructorSignatureClassMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsPropertySignatureClassMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsMethodSignatureClassMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsGetterSignatureClassMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsSetterSignatureClassMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsIndexSignatureClassMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsEmptyClassMember {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsStaticModifier {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsDeclareModifier {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsReadonlyModifier {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsAbstractModifier {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsOverrideModifier {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsAccessibilityModifier {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsConstructorParameters {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsRestParameter {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsPropertyParameter {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsInitializerClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsOptionalPropertyAnnotation {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsDefinitePropertyAnnotation {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsIndexSignatureParameter {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsIdentifierAssignment {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsStaticMemberAssignment {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsComputedMemberAssignment {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsParenthesizedAssignment {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsNonNullAssertionAssignment {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsAsAssignment {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsTypeAssertionAssignment {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsAssignmentWithDefault {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsArrayAssignmentPattern {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsObjectAssignmentPattern {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsArrayAssignmentPatternRestElement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsObjectAssignmentPatternShorthandProperty {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsObjectAssignmentPatternProperty {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsObjectAssignmentPatternRest {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsIdentifierBinding {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsBindingPatternWithDefault {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsArrayBindingPattern {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsObjectBindingPattern {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsArrayBindingPatternRestElement {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsObjectBindingPatternProperty {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsObjectBindingPatternRest {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsObjectBindingPatternShorthandProperty {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsStringLiteralExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsNumberLiteralExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsBigIntLiteralExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsBooleanLiteralExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsNullLiteralExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsRegexLiteralExpression {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsVariableDeclarationClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsDefiniteVariableAnnotation {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsExport {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsImport {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsImportBareClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsImportNamedClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsImportDefaultClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsImportNamespaceClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsModuleSource {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsImportAssertion {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsDefaultImportSpecifier {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsNamedImportSpecifiers {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsNamespaceImportSpecifier {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsShorthandNamedImportSpecifier {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsNamedImportSpecifier {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsLiteralExportName {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsImportAssertionEntry {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsExportDefaultDeclarationClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsExportDefaultExpressionClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsExportNamedClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsExportFromClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsExportNamedFromClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsExportAsNamespaceClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsExportAssignmentClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::TsExportDeclareClause {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsFunctionExportDefaultDeclaration {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsExportNamedShorthandSpecifier {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsExportNamedSpecifier {
fn format(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
self.format_node(formatter)
}
}
impl Format for rome_js_syntax::JsExportAsClause {
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/context.rs | crates/rome_js_formatter/src/context.rs | use crate::comments::{FormatJsLeadingComment, JsCommentStyle, JsComments};
use crate::context::trailing_comma::TrailingComma;
use rome_deserialize::json::with_only_known_variants;
use rome_deserialize::{DeserializationDiagnostic, VisitNode};
use rome_formatter::printer::PrinterOptions;
use rome_formatter::token::string::Quote;
use rome_formatter::{
CstFormatContext, FormatContext, FormatElement, FormatOptions, IndentStyle, LineWidth,
TransformSourceMap,
};
use rome_js_syntax::{AnyJsFunctionBody, JsFileSource, JsLanguage};
use rome_json_syntax::JsonLanguage;
use rome_rowan::SyntaxNode;
use std::fmt;
use std::fmt::Debug;
use std::rc::Rc;
use std::str::FromStr;
pub mod trailing_comma;
#[derive(Debug, Clone)]
pub struct JsFormatContext {
options: JsFormatOptions,
/// The comments of the nodes and tokens in the program.
comments: Rc<JsComments>,
/// Stores the formatted content of one function body.
///
/// Used during formatting of call arguments where function expressions and arrow function expressions
/// are formatted a second time if they are the first or last call argument.
///
/// Caching the body in the call arguments formatting is important. It minimises the cases
/// where the algorithm is quadratic, in case the function or arrow expression contains another
/// call expression with a function or call expression as first or last argument.
///
/// It's sufficient to only store a single cached body to cover the vast majority of cases
/// (there's no exception in any of our tests nor benchmark tests). The only case not covered is when
/// a parameter has an initializer that contains a call expression:
///
/// ```javascript
/// test((
/// problematic = test(() => body)
/// ) => {});
/// ```
///
/// This should be rare enough for us not to care about it.
cached_function_body: Option<(AnyJsFunctionBody, FormatElement)>,
source_map: Option<TransformSourceMap>,
}
impl JsFormatContext {
pub fn new(options: JsFormatOptions, comments: JsComments) -> Self {
Self {
options,
comments: Rc::new(comments),
cached_function_body: None,
source_map: None,
}
}
/// Returns the formatted content for the passed function body if it is cached or `None` if the currently
/// cached content belongs to another function body or the cache is empty.
///
/// See [JsFormatContext::cached_function_body] for more in depth documentation.
pub(crate) fn get_cached_function_body(
&self,
body: &AnyJsFunctionBody,
) -> Option<FormatElement> {
self.cached_function_body
.as_ref()
.and_then(|(expected_body, formatted)| {
if expected_body == body {
Some(formatted.clone())
} else {
None
}
})
}
/// Sets the currently cached formatted function body.
///
/// See [JsFormatContext::cached_function_body] for more in depth documentation.
pub(crate) fn set_cached_function_body(
&mut self,
body: &AnyJsFunctionBody,
formatted: FormatElement,
) {
self.cached_function_body = Some((body.clone(), formatted))
}
pub fn with_source_map(mut self, source_map: Option<TransformSourceMap>) -> Self {
self.source_map = source_map;
self
}
}
#[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)]
pub struct TabWidth(u8);
impl From<u8> for TabWidth {
fn from(value: u8) -> Self {
TabWidth(value)
}
}
impl From<TabWidth> for u8 {
fn from(width: TabWidth) -> Self {
width.0
}
}
impl FormatContext for JsFormatContext {
type Options = JsFormatOptions;
fn options(&self) -> &Self::Options {
&self.options
}
fn source_map(&self) -> Option<&TransformSourceMap> {
self.source_map.as_ref()
}
}
impl CstFormatContext for JsFormatContext {
type Language = JsLanguage;
type Style = JsCommentStyle;
type CommentRule = FormatJsLeadingComment;
fn comments(&self) -> &JsComments {
&self.comments
}
}
#[derive(Debug, Clone)]
pub struct JsFormatOptions {
/// The indent style.
indent_style: IndentStyle,
/// What's the max width of a line. Defaults to 80.
line_width: LineWidth,
/// The style for quotes. Defaults to double.
quote_style: QuoteStyle,
/// The style for JSX quotes. Defaults to double.
jsx_quote_style: QuoteStyle,
/// When properties in objects are quoted. Defaults to as-needed.
quote_properties: QuoteProperties,
/// Print trailing commas wherever possible in multi-line comma-separated syntactic structures. Defaults to "all".
trailing_comma: TrailingComma,
/// Whether the formatter prints semicolons for all statements, class members, and type members or only when necessary because of [ASI](https://tc39.es/ecma262/multipage/ecmascript-language-lexical-grammar.html#sec-automatic-semicolon-insertion).
semicolons: Semicolons,
/// Whether to add non-necessary parentheses to arrow functions. Defaults to "always".
arrow_parentheses: ArrowParentheses,
/// Information related to the current file
source_type: JsFileSource,
}
impl JsFormatOptions {
pub fn new(source_type: JsFileSource) -> Self {
Self {
source_type,
indent_style: IndentStyle::default(),
line_width: LineWidth::default(),
quote_style: QuoteStyle::default(),
jsx_quote_style: QuoteStyle::default(),
quote_properties: QuoteProperties::default(),
trailing_comma: TrailingComma::default(),
semicolons: Semicolons::default(),
arrow_parentheses: ArrowParentheses::default(),
}
}
pub fn with_arrow_parentheses(mut self, arrow_parentheses: ArrowParentheses) -> Self {
self.arrow_parentheses = arrow_parentheses;
self
}
pub fn with_indent_style(mut self, indent_style: IndentStyle) -> Self {
self.indent_style = indent_style;
self
}
pub fn with_line_width(mut self, line_width: LineWidth) -> Self {
self.line_width = line_width;
self
}
pub fn with_quote_style(mut self, quote_style: QuoteStyle) -> Self {
self.quote_style = quote_style;
self
}
pub fn with_jsx_quote_style(mut self, jsx_quote_style: QuoteStyle) -> Self {
self.jsx_quote_style = jsx_quote_style;
self
}
pub fn with_quote_properties(mut self, quote_properties: QuoteProperties) -> Self {
self.quote_properties = quote_properties;
self
}
pub fn with_trailing_comma(mut self, trailing_comma: TrailingComma) -> Self {
self.trailing_comma = trailing_comma;
self
}
pub fn with_semicolons(mut self, semicolons: Semicolons) -> Self {
self.semicolons = semicolons;
self
}
pub fn arrow_parentheses(&self) -> ArrowParentheses {
self.arrow_parentheses
}
pub fn quote_style(&self) -> QuoteStyle {
self.quote_style
}
pub fn jsx_quote_style(&self) -> QuoteStyle {
self.jsx_quote_style
}
pub fn quote_properties(&self) -> QuoteProperties {
self.quote_properties
}
pub fn source_type(&self) -> JsFileSource {
self.source_type
}
pub fn trailing_comma(&self) -> TrailingComma {
self.trailing_comma
}
pub fn semicolons(&self) -> Semicolons {
self.semicolons
}
pub fn tab_width(&self) -> TabWidth {
match self.indent_style {
IndentStyle::Tab => 2.into(),
IndentStyle::Space(quantities) => quantities.into(),
}
}
}
impl FormatOptions for JsFormatOptions {
fn indent_style(&self) -> IndentStyle {
self.indent_style
}
fn line_width(&self) -> LineWidth {
self.line_width
}
fn as_print_options(&self) -> PrinterOptions {
PrinterOptions::from(self)
}
}
impl fmt::Display for JsFormatOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "Indent style: {}", self.indent_style)?;
writeln!(f, "Line width: {}", self.line_width.value())?;
writeln!(f, "Quote style: {}", self.quote_style)?;
writeln!(f, "JSX quote style: {}", self.jsx_quote_style)?;
writeln!(f, "Quote properties: {}", self.quote_properties)?;
writeln!(f, "Trailing comma: {}", self.trailing_comma)?;
writeln!(f, "Semicolons: {}", self.semicolons)?;
writeln!(f, "Arrow parentheses: {}", self.arrow_parentheses)
}
}
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema),
serde(rename_all = "camelCase")
)]
#[derive(Default)]
pub enum QuoteStyle {
#[default]
Double,
Single,
}
impl FromStr for QuoteStyle {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"double" | "Double" => Ok(Self::Double),
"single" | "Single" => Ok(Self::Single),
// TODO: replace this error with a diagnostic
_ => Err("Value not supported for QuoteStyle"),
}
}
}
impl fmt::Display for QuoteStyle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
QuoteStyle::Double => write!(f, "Double Quotes"),
QuoteStyle::Single => write!(f, "Single Quotes"),
}
}
}
impl QuoteStyle {
pub(crate) const KNOWN_VALUES: &'static [&'static str] = &["double", "single"];
pub fn as_char(&self) -> char {
match self {
QuoteStyle::Double => '"',
QuoteStyle::Single => '\'',
}
}
pub fn as_string(&self) -> &str {
match self {
QuoteStyle::Double => "\"",
QuoteStyle::Single => "'",
}
}
/// Returns the quote, prepended with a backslash (escaped)
pub fn as_escaped(&self) -> &str {
match self {
QuoteStyle::Double => "\\\"",
QuoteStyle::Single => "\\'",
}
}
pub fn as_bytes(&self) -> u8 {
self.as_char() as u8
}
/// Returns the quote in HTML entity
pub fn as_html_entity(&self) -> &str {
match self {
QuoteStyle::Double => """,
QuoteStyle::Single => "'",
}
}
/// Given the current quote, it returns the other one
pub fn other(&self) -> Self {
match self {
QuoteStyle::Double => QuoteStyle::Single,
QuoteStyle::Single => QuoteStyle::Double,
}
}
}
impl From<QuoteStyle> for Quote {
fn from(quote: QuoteStyle) -> Self {
match quote {
QuoteStyle::Double => Quote::Double,
QuoteStyle::Single => Quote::Single,
}
}
}
impl VisitNode<JsonLanguage> for QuoteStyle {
fn visit_member_value(
&mut self,
node: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let node = with_only_known_variants(node, QuoteStyle::KNOWN_VALUES, diagnostics)?;
if node.inner_string_text().ok()?.text() == "single" {
*self = QuoteStyle::Single;
} else {
*self = QuoteStyle::Double;
}
Some(())
}
}
#[derive(Debug, Eq, PartialEq, Clone, Copy, Default)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema),
serde(rename_all = "camelCase")
)]
pub enum QuoteProperties {
#[default]
AsNeeded,
Preserve,
}
impl FromStr for QuoteProperties {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"as-needed" | "AsNeeded" => Ok(Self::AsNeeded),
"preserve" | "Preserve" => Ok(Self::Preserve),
// TODO: replace this error with a diagnostic
_ => Err("Value not supported for QuoteProperties"),
}
}
}
impl fmt::Display for QuoteProperties {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
QuoteProperties::AsNeeded => write!(f, "As needed"),
QuoteProperties::Preserve => write!(f, "Preserve"),
}
}
}
impl QuoteProperties {
pub(crate) const KNOWN_VALUES: &'static [&'static str] = &["preserve", "asNeeded"];
}
impl VisitNode<JsonLanguage> for QuoteProperties {
fn visit_member_value(
&mut self,
node: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let node = with_only_known_variants(node, QuoteProperties::KNOWN_VALUES, diagnostics)?;
if node.inner_string_text().ok()?.text() == "asNeeded" {
*self = QuoteProperties::AsNeeded;
} else {
*self = QuoteProperties::Preserve;
}
Some(())
}
}
#[derive(Debug, Eq, PartialEq, Clone, Copy, Default)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema),
serde(rename_all = "camelCase")
)]
pub enum Semicolons {
#[default]
Always,
AsNeeded,
}
impl Semicolons {
pub(crate) const KNOWN_VALUES: &'static [&'static str] = &["always", "asNeeded"];
pub const fn is_as_needed(&self) -> bool {
matches!(self, Self::AsNeeded)
}
pub const fn is_always(&self) -> bool {
matches!(self, Self::Always)
}
}
impl FromStr for Semicolons {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"as-needed" | "AsNeeded" => Ok(Self::AsNeeded),
"always" | "Always" => Ok(Self::Always),
_ => Err("Value not supported for Semicolons. Supported values are 'as-needed' and 'always'."),
}
}
}
impl fmt::Display for Semicolons {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Semicolons::AsNeeded => write!(f, "As needed"),
Semicolons::Always => write!(f, "Always"),
}
}
}
impl VisitNode<JsonLanguage> for Semicolons {
fn visit_member_value(
&mut self,
node: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let node = with_only_known_variants(node, Semicolons::KNOWN_VALUES, diagnostics)?;
if node.inner_string_text().ok()?.text() == "asNeeded" {
*self = Semicolons::AsNeeded;
} else {
*self = Semicolons::Always;
}
Some(())
}
}
#[derive(Debug, Eq, PartialEq, Clone, Copy, Default)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema),
serde(rename_all = "camelCase")
)]
pub enum ArrowParentheses {
#[default]
Always,
AsNeeded,
}
impl ArrowParentheses {
pub(crate) const KNOWN_VALUES: &'static [&'static str] = &["always", "asNeeded"];
pub const fn is_as_needed(&self) -> bool {
matches!(self, Self::AsNeeded)
}
pub const fn is_always(&self) -> bool {
matches!(self, Self::Always)
}
}
impl FromStr for ArrowParentheses {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"as-needed" | "AsNeeded" => Ok(Self::AsNeeded),
"always" | "Always" => Ok(Self::Always),
_ => Err("Value not supported for Arrow parentheses. Supported values are 'as-needed' and 'always'."),
}
}
}
impl fmt::Display for ArrowParentheses {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ArrowParentheses::AsNeeded => write!(f, "As needed"),
ArrowParentheses::Always => write!(f, "Always"),
}
}
}
impl VisitNode<JsonLanguage> for ArrowParentheses {
fn visit_member_value(
&mut self,
node: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let node = with_only_known_variants(node, ArrowParentheses::KNOWN_VALUES, diagnostics)?;
if node.inner_string_text().ok()?.text() == "asNeeded" {
*self = ArrowParentheses::AsNeeded;
} else {
*self = ArrowParentheses::Always;
}
Some(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/separated.rs | crates/rome_js_formatter/src/separated.rs | use crate::prelude::*;
use crate::{AsFormat, FormatJsSyntaxToken};
use rome_formatter::separated::{FormatSeparatedElementRule, FormatSeparatedIter};
use rome_formatter::FormatRefWithRule;
use rome_js_syntax::{JsLanguage, JsSyntaxToken};
use rome_rowan::{AstNode, AstSeparatedList, AstSeparatedListElementsIterator};
use std::marker::PhantomData;
#[derive(Clone)]
pub(crate) struct JsFormatSeparatedElementRule<N>
where
N: AstNode<Language = JsLanguage>,
{
node: PhantomData<N>,
}
impl<N> FormatSeparatedElementRule<N> for JsFormatSeparatedElementRule<N>
where
N: AstNode<Language = JsLanguage> + AsFormat<JsFormatContext> + 'static,
{
type Context = JsFormatContext;
type FormatNode<'a> = N::Format<'a>;
type FormatSeparator<'a> = FormatRefWithRule<'a, JsSyntaxToken, FormatJsSyntaxToken>;
fn format_node<'a>(&self, node: &'a N) -> Self::FormatNode<'a> {
node.format()
}
fn format_separator<'a>(&self, separator: &'a JsSyntaxToken) -> Self::FormatSeparator<'a> {
separator.format()
}
}
type JsFormatSeparatedIter<Node> = FormatSeparatedIter<
AstSeparatedListElementsIterator<JsLanguage, Node>,
Node,
JsFormatSeparatedElementRule<Node>,
>;
/// AST Separated list formatting extension methods
pub(crate) trait FormatAstSeparatedListExtension:
AstSeparatedList<Language = JsLanguage>
{
/// Prints a separated list of nodes
///
/// Trailing separators will be reused from the original list or
/// created by calling the `separator_factory` function.
/// The last trailing separator in the list will only be printed
/// if the outer group breaks.
fn format_separated(&self, separator: &'static str) -> JsFormatSeparatedIter<Self::Node> {
JsFormatSeparatedIter::new(
self.elements(),
separator,
JsFormatSeparatedElementRule { node: PhantomData },
)
}
}
impl<T> FormatAstSeparatedListExtension for T where T: AstSeparatedList<Language = JsLanguage> {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/generated.rs | crates/rome_js_formatter/src/generated.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
use crate::{
AsFormat, FormatBogusNodeRule, FormatNodeRule, IntoFormat, JsFormatContext, JsFormatter,
};
use rome_formatter::{FormatOwnedWithRule, FormatRefWithRule, FormatResult, FormatRule};
impl FormatRule<rome_js_syntax::JsScript> for crate::js::auxiliary::script::FormatJsScript {
type Context = JsFormatContext;
#[inline(always)]
fn fmt(&self, node: &rome_js_syntax::JsScript, f: &mut JsFormatter) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsScript>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsScript {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsScript,
crate::js::auxiliary::script::FormatJsScript,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::auxiliary::script::FormatJsScript::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsScript {
type Format =
FormatOwnedWithRule<rome_js_syntax::JsScript, crate::js::auxiliary::script::FormatJsScript>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::auxiliary::script::FormatJsScript::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsModule> for crate::js::auxiliary::module::FormatJsModule {
type Context = JsFormatContext;
#[inline(always)]
fn fmt(&self, node: &rome_js_syntax::JsModule, f: &mut JsFormatter) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsModule>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsModule {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsModule,
crate::js::auxiliary::module::FormatJsModule,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::auxiliary::module::FormatJsModule::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsModule {
type Format =
FormatOwnedWithRule<rome_js_syntax::JsModule, crate::js::auxiliary::module::FormatJsModule>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::auxiliary::module::FormatJsModule::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsExpressionSnipped>
for crate::js::auxiliary::expression_snipped::FormatJsExpressionSnipped
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsExpressionSnipped,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsExpressionSnipped>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsExpressionSnipped {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsExpressionSnipped,
crate::js::auxiliary::expression_snipped::FormatJsExpressionSnipped,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::auxiliary::expression_snipped::FormatJsExpressionSnipped::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsExpressionSnipped {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsExpressionSnipped,
crate::js::auxiliary::expression_snipped::FormatJsExpressionSnipped,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::auxiliary::expression_snipped::FormatJsExpressionSnipped::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsDirective>
for crate::js::auxiliary::directive::FormatJsDirective
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(&self, node: &rome_js_syntax::JsDirective, f: &mut JsFormatter) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsDirective>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsDirective {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsDirective,
crate::js::auxiliary::directive::FormatJsDirective,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::auxiliary::directive::FormatJsDirective::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsDirective {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsDirective,
crate::js::auxiliary::directive::FormatJsDirective,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::auxiliary::directive::FormatJsDirective::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsBlockStatement>
for crate::js::statements::block_statement::FormatJsBlockStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsBlockStatement,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsBlockStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsBlockStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsBlockStatement,
crate::js::statements::block_statement::FormatJsBlockStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::block_statement::FormatJsBlockStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsBlockStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsBlockStatement,
crate::js::statements::block_statement::FormatJsBlockStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::block_statement::FormatJsBlockStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsBreakStatement>
for crate::js::statements::break_statement::FormatJsBreakStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsBreakStatement,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsBreakStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsBreakStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsBreakStatement,
crate::js::statements::break_statement::FormatJsBreakStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::break_statement::FormatJsBreakStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsBreakStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsBreakStatement,
crate::js::statements::break_statement::FormatJsBreakStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::break_statement::FormatJsBreakStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsClassDeclaration>
for crate::js::declarations::class_declaration::FormatJsClassDeclaration
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsClassDeclaration,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsClassDeclaration>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsClassDeclaration {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsClassDeclaration,
crate::js::declarations::class_declaration::FormatJsClassDeclaration,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::declarations::class_declaration::FormatJsClassDeclaration::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsClassDeclaration {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsClassDeclaration,
crate::js::declarations::class_declaration::FormatJsClassDeclaration,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::declarations::class_declaration::FormatJsClassDeclaration::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsContinueStatement>
for crate::js::statements::continue_statement::FormatJsContinueStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsContinueStatement,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsContinueStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsContinueStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsContinueStatement,
crate::js::statements::continue_statement::FormatJsContinueStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::continue_statement::FormatJsContinueStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsContinueStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsContinueStatement,
crate::js::statements::continue_statement::FormatJsContinueStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::continue_statement::FormatJsContinueStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsDebuggerStatement>
for crate::js::statements::debugger_statement::FormatJsDebuggerStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsDebuggerStatement,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsDebuggerStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsDebuggerStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsDebuggerStatement,
crate::js::statements::debugger_statement::FormatJsDebuggerStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::debugger_statement::FormatJsDebuggerStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsDebuggerStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsDebuggerStatement,
crate::js::statements::debugger_statement::FormatJsDebuggerStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::debugger_statement::FormatJsDebuggerStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsDoWhileStatement>
for crate::js::statements::do_while_statement::FormatJsDoWhileStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsDoWhileStatement,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsDoWhileStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsDoWhileStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsDoWhileStatement,
crate::js::statements::do_while_statement::FormatJsDoWhileStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::do_while_statement::FormatJsDoWhileStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsDoWhileStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsDoWhileStatement,
crate::js::statements::do_while_statement::FormatJsDoWhileStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::do_while_statement::FormatJsDoWhileStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsEmptyStatement>
for crate::js::statements::empty_statement::FormatJsEmptyStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsEmptyStatement,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsEmptyStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsEmptyStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsEmptyStatement,
crate::js::statements::empty_statement::FormatJsEmptyStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::empty_statement::FormatJsEmptyStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsEmptyStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsEmptyStatement,
crate::js::statements::empty_statement::FormatJsEmptyStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::empty_statement::FormatJsEmptyStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsExpressionStatement>
for crate::js::statements::expression_statement::FormatJsExpressionStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsExpressionStatement,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsExpressionStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsExpressionStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsExpressionStatement,
crate::js::statements::expression_statement::FormatJsExpressionStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::expression_statement::FormatJsExpressionStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsExpressionStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsExpressionStatement,
crate::js::statements::expression_statement::FormatJsExpressionStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::expression_statement::FormatJsExpressionStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsForInStatement>
for crate::js::statements::for_in_statement::FormatJsForInStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsForInStatement,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsForInStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsForInStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsForInStatement,
crate::js::statements::for_in_statement::FormatJsForInStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::for_in_statement::FormatJsForInStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsForInStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsForInStatement,
crate::js::statements::for_in_statement::FormatJsForInStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::for_in_statement::FormatJsForInStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsForOfStatement>
for crate::js::statements::for_of_statement::FormatJsForOfStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsForOfStatement,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsForOfStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsForOfStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsForOfStatement,
crate::js::statements::for_of_statement::FormatJsForOfStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::for_of_statement::FormatJsForOfStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsForOfStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsForOfStatement,
crate::js::statements::for_of_statement::FormatJsForOfStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::for_of_statement::FormatJsForOfStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsForStatement>
for crate::js::statements::for_statement::FormatJsForStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(&self, node: &rome_js_syntax::JsForStatement, f: &mut JsFormatter) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsForStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsForStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsForStatement,
crate::js::statements::for_statement::FormatJsForStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::for_statement::FormatJsForStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsForStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsForStatement,
crate::js::statements::for_statement::FormatJsForStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::for_statement::FormatJsForStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsIfStatement>
for crate::js::statements::if_statement::FormatJsIfStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(&self, node: &rome_js_syntax::JsIfStatement, f: &mut JsFormatter) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsIfStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsIfStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsIfStatement,
crate::js::statements::if_statement::FormatJsIfStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::if_statement::FormatJsIfStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsIfStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsIfStatement,
crate::js::statements::if_statement::FormatJsIfStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::if_statement::FormatJsIfStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsLabeledStatement>
for crate::js::statements::labeled_statement::FormatJsLabeledStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsLabeledStatement,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsLabeledStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsLabeledStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsLabeledStatement,
crate::js::statements::labeled_statement::FormatJsLabeledStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::labeled_statement::FormatJsLabeledStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsLabeledStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsLabeledStatement,
crate::js::statements::labeled_statement::FormatJsLabeledStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::labeled_statement::FormatJsLabeledStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsReturnStatement>
for crate::js::statements::return_statement::FormatJsReturnStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsReturnStatement,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsReturnStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsReturnStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsReturnStatement,
crate::js::statements::return_statement::FormatJsReturnStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::return_statement::FormatJsReturnStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsReturnStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsReturnStatement,
crate::js::statements::return_statement::FormatJsReturnStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::return_statement::FormatJsReturnStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsSwitchStatement>
for crate::js::statements::switch_statement::FormatJsSwitchStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsSwitchStatement,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsSwitchStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsSwitchStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsSwitchStatement,
crate::js::statements::switch_statement::FormatJsSwitchStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::switch_statement::FormatJsSwitchStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsSwitchStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsSwitchStatement,
crate::js::statements::switch_statement::FormatJsSwitchStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::switch_statement::FormatJsSwitchStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsThrowStatement>
for crate::js::statements::throw_statement::FormatJsThrowStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsThrowStatement,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsThrowStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsThrowStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsThrowStatement,
crate::js::statements::throw_statement::FormatJsThrowStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::throw_statement::FormatJsThrowStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsThrowStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsThrowStatement,
crate::js::statements::throw_statement::FormatJsThrowStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::throw_statement::FormatJsThrowStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsTryFinallyStatement>
for crate::js::statements::try_finally_statement::FormatJsTryFinallyStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsTryFinallyStatement,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsTryFinallyStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsTryFinallyStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsTryFinallyStatement,
crate::js::statements::try_finally_statement::FormatJsTryFinallyStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::try_finally_statement::FormatJsTryFinallyStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsTryFinallyStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsTryFinallyStatement,
crate::js::statements::try_finally_statement::FormatJsTryFinallyStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::try_finally_statement::FormatJsTryFinallyStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsTryStatement>
for crate::js::statements::try_statement::FormatJsTryStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(&self, node: &rome_js_syntax::JsTryStatement, f: &mut JsFormatter) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsTryStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsTryStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsTryStatement,
crate::js::statements::try_statement::FormatJsTryStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::try_statement::FormatJsTryStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsTryStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsTryStatement,
crate::js::statements::try_statement::FormatJsTryStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::try_statement::FormatJsTryStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsVariableStatement>
for crate::js::statements::variable_statement::FormatJsVariableStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsVariableStatement,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsVariableStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsVariableStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsVariableStatement,
crate::js::statements::variable_statement::FormatJsVariableStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::variable_statement::FormatJsVariableStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsVariableStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsVariableStatement,
crate::js::statements::variable_statement::FormatJsVariableStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::variable_statement::FormatJsVariableStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsWhileStatement>
for crate::js::statements::while_statement::FormatJsWhileStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsWhileStatement,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsWhileStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsWhileStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsWhileStatement,
crate::js::statements::while_statement::FormatJsWhileStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::while_statement::FormatJsWhileStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsWhileStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsWhileStatement,
crate::js::statements::while_statement::FormatJsWhileStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::while_statement::FormatJsWhileStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsWithStatement>
for crate::js::statements::with_statement::FormatJsWithStatement
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(&self, node: &rome_js_syntax::JsWithStatement, f: &mut JsFormatter) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsWithStatement>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsWithStatement {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsWithStatement,
crate::js::statements::with_statement::FormatJsWithStatement,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
crate::js::statements::with_statement::FormatJsWithStatement::default(),
)
}
}
impl IntoFormat<JsFormatContext> for rome_js_syntax::JsWithStatement {
type Format = FormatOwnedWithRule<
rome_js_syntax::JsWithStatement,
crate::js::statements::with_statement::FormatJsWithStatement,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
self,
crate::js::statements::with_statement::FormatJsWithStatement::default(),
)
}
}
impl FormatRule<rome_js_syntax::JsFunctionDeclaration>
for crate::js::declarations::function_declaration::FormatJsFunctionDeclaration
{
type Context = JsFormatContext;
#[inline(always)]
fn fmt(
&self,
node: &rome_js_syntax::JsFunctionDeclaration,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatNodeRule::<rome_js_syntax::JsFunctionDeclaration>::fmt(self, node, f)
}
}
impl AsFormat<JsFormatContext> for rome_js_syntax::JsFunctionDeclaration {
type Format<'a> = FormatRefWithRule<
'a,
rome_js_syntax::JsFunctionDeclaration,
crate::js::declarations::function_declaration::FormatJsFunctionDeclaration,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
self,
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/mod.rs | crates/rome_js_formatter/src/jsx/mod.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
pub(crate) mod any;
pub(crate) mod attribute;
pub(crate) mod auxiliary;
pub(crate) mod expressions;
pub(crate) mod lists;
pub(crate) mod objects;
pub(crate) mod tag;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/lists/child_list.rs | crates/rome_js_formatter/src/jsx/lists/child_list.rs | use crate::prelude::*;
use crate::utils::jsx::{
is_meaningful_jsx_text, is_whitespace_jsx_expression, jsx_split_children, JsxChild,
JsxChildrenIterator, JsxRawSpace, JsxSpace,
};
use crate::JsFormatter;
use rome_formatter::format_element::tag::{GroupMode, Tag};
use rome_formatter::{format_args, write, CstFormatContext, FormatRuleWithOptions, VecBuffer};
use rome_js_syntax::{AnyJsxChild, JsxChildList};
use std::cell::RefCell;
#[derive(Debug, Clone, Default)]
pub struct FormatJsxChildList {
layout: JsxChildListLayout,
}
impl FormatRuleWithOptions<JsxChildList> for FormatJsxChildList {
type Options = JsxChildListLayout;
fn with_options(mut self, options: Self::Options) -> Self {
self.layout = options;
self
}
}
impl FormatRule<JsxChildList> for FormatJsxChildList {
type Context = JsFormatContext;
fn fmt(&self, list: &JsxChildList, f: &mut JsFormatter) -> FormatResult<()> {
let result = self.fmt_children(list, f)?;
match result {
FormatChildrenResult::ForceMultiline(format_multiline) => {
write!(f, [format_multiline])
}
FormatChildrenResult::BestFitting {
flat_children,
expanded_children,
} => {
write!(f, [best_fitting![flat_children, expanded_children]])
}
}
}
}
#[derive(Debug)]
pub(crate) enum FormatChildrenResult {
ForceMultiline(FormatMultilineChildren),
BestFitting {
flat_children: FormatFlatChildren,
expanded_children: FormatMultilineChildren,
},
}
impl FormatJsxChildList {
pub(crate) fn fmt_children(
&self,
list: &JsxChildList,
f: &mut JsFormatter,
) -> FormatResult<FormatChildrenResult> {
self.disarm_debug_assertions(list, f);
let children_meta = self.children_meta(list, f.context().comments());
let layout = self.layout(children_meta);
let multiline_layout = if children_meta.meaningful_text {
MultilineLayout::Fill
} else {
MultilineLayout::NoFill
};
let mut flat = FlatBuilder::new();
let mut multiline = MultilineBuilder::new(multiline_layout);
let mut force_multiline = layout.is_multiline();
let mut children = jsx_split_children(list, f.context().comments())?;
// Trim trailing new lines
if let Some(JsxChild::EmptyLine | JsxChild::Newline) = children.last() {
children.pop();
}
let mut last: Option<&JsxChild> = None;
let mut children_iter = JsxChildrenIterator::new(children.iter());
// Trim leading new lines
if let Some(JsxChild::Newline | JsxChild::EmptyLine) = children_iter.peek() {
children_iter.next();
}
while let Some(child) = children_iter.next() {
let mut child_breaks = false;
match &child {
// A single word: Both `a` and `b` are a word in `a b` because they're separated by JSX Whitespace.
JsxChild::Word(word) => {
let separator = match children_iter.peek() {
Some(JsxChild::Word(_)) => {
// Separate words by a space or line break in extended mode
Some(WordSeparator::BetweenWords)
}
// Last word or last word before an element without any whitespace in between
Some(JsxChild::NonText(next_child)) => Some(WordSeparator::EndOfText {
is_soft_line_break: !matches!(
next_child,
AnyJsxChild::JsxSelfClosingElement(_)
) || word.is_ascii_punctuation(),
}),
Some(JsxChild::Newline | JsxChild::Whitespace | JsxChild::EmptyLine) => {
None
}
None => None,
};
child_breaks = separator.map_or(false, |separator| separator.will_break());
flat.write(&format_args![word, separator], f);
if let Some(separator) = separator {
multiline.write_with_separator(word, &separator, f);
} else {
// it's safe to write without a separator because None means that next element is a separator or end of the iterator
multiline.write_content(word, f);
}
}
// * Whitespace after the opening tag and before a meaningful text: `<div> a`
// * Whitespace before the closing tag: `a </div>`
// * Whitespace before an opening tag: `a <div>`
JsxChild::Whitespace => {
flat.write(&JsxSpace, f);
// ```javascript
// <div>a
// {' '}</div>
// ```
let is_after_line_break =
last.as_ref().map_or(false, |last| last.is_any_line());
// `<div>aaa </div>` or `<div> </div>`
let is_trailing_or_only_whitespace = children_iter.peek().is_none();
if is_trailing_or_only_whitespace || is_after_line_break {
multiline.write_separator(&JsxRawSpace, f);
}
// Leading whitespace. Only possible if used together with a expression child
//
// ```
// <div>
//
// {' '}
// <b />
// </div>
// ```
else if last.is_none() {
multiline.write_with_separator(&JsxRawSpace, &hard_line_break(), f);
} else {
multiline.write_separator(&JsxSpace, f);
}
}
// A new line between some JSX text and an element
JsxChild::Newline => {
let is_soft_break = {
// Here we handle the case when we have a newline between an ascii punctuation word and a jsx element
// We need to use the previous and the next element
// [JsxChild::Word, JsxChild::Newline, JsxChild::NonText]
// ```
// <div>
// <div>First</div>,
// <div>Second</div>
// </div>
// ```
if let Some(JsxChild::Word(word)) = last {
let is_next_element_self_closing = matches!(
children_iter.peek(),
Some(JsxChild::NonText(AnyJsxChild::JsxSelfClosingElement(_)))
);
!is_next_element_self_closing && word.is_ascii_punctuation()
}
// Here we handle the case when we have an ascii punctuation word between a new line and a jsx element
// Here we need to look ahead two elements
// [JsxChild::Newline, JsxChild::Word, JsxChild::NonText]
// ```
// <div>
// <div>First</div>
// ,<div>Second</div>
// </div>
// ```
else if let Some(JsxChild::Word(next_word)) = children_iter.peek() {
let is_next_next_element_self_closing = matches!(
children_iter.peek_next(),
Some(JsxChild::NonText(AnyJsxChild::JsxSelfClosingElement(_)))
);
!is_next_next_element_self_closing && next_word.is_ascii_punctuation()
} else {
false
}
};
if is_soft_break {
multiline.write_separator(&soft_line_break(), f);
} else {
child_breaks = true;
multiline.write_separator(&hard_line_break(), f);
}
}
// An empty line between some JSX text and an element
JsxChild::EmptyLine => {
child_breaks = true;
multiline.write_separator(&empty_line(), f);
}
// Any child that isn't text
JsxChild::NonText(non_text) => {
let line_mode = match children_iter.peek() {
Some(JsxChild::Word(word)) => {
// Break if the current or next element is a self closing element
// ```javascript
// <pre className="h-screen overflow-y-scroll" />adefg
// ```
// Becomes
// ```javascript
// <pre className="h-screen overflow-y-scroll" />
// adefg
// ```
if matches!(non_text, AnyJsxChild::JsxSelfClosingElement(_))
&& !word.is_ascii_punctuation()
{
Some(LineMode::Hard)
} else {
Some(LineMode::Soft)
}
}
// Add a hard line break if what comes after the element is not a text or is all whitespace
Some(JsxChild::NonText(_)) => Some(LineMode::Hard),
Some(JsxChild::Newline | JsxChild::Whitespace | JsxChild::EmptyLine) => {
None
}
// Don't insert trailing line breaks
None => None,
};
child_breaks = line_mode.map_or(false, |mode| mode.is_hard());
let format_separator = line_mode.map(|mode| {
format_with(move |f| f.write_element(FormatElement::Line(mode)))
});
if force_multiline {
if let Some(format_separator) = format_separator {
multiline.write_with_separator(
&non_text.format(),
&format_separator,
f,
);
} else {
// it's safe to write without a separator because None means that next element is a separator or end of the iterator
multiline.write_content(&non_text.format(), f);
}
} else {
let mut memoized = non_text.format().memoized();
force_multiline = memoized.inspect(f)?.will_break();
flat.write(&format_args![memoized, format_separator], f);
if let Some(format_separator) = format_separator {
multiline.write_with_separator(&memoized, &format_separator, f);
} else {
// it's safe to write without a separator because None means that next element is a separator or end of the iterator
multiline.write_content(&memoized, f);
}
}
}
}
if child_breaks {
flat.disable();
force_multiline = true;
}
last = Some(child);
}
if force_multiline {
Ok(FormatChildrenResult::ForceMultiline(multiline.finish()?))
} else {
Ok(FormatChildrenResult::BestFitting {
flat_children: flat.finish()?,
expanded_children: multiline.finish()?,
})
}
}
/// Tracks the tokens of [JsxText] and [JsxExpressionChild] nodes to be formatted and
/// asserts that the suppression comments are checked (they get ignored).
///
/// This is necessary because the formatting of [JsxChildList] bypasses the node formatting for
/// [JsxText] and [JsxExpressionChild] and instead, formats the nodes itself.
#[cfg(debug_assertions)]
fn disarm_debug_assertions(&self, node: &JsxChildList, f: &mut JsFormatter) {
use rome_js_syntax::{AnyJsExpression, AnyJsLiteralExpression};
use AnyJsxChild::*;
for child in node {
match child {
JsxExpressionChild(expression)
if is_whitespace_jsx_expression(&expression, f.context().comments()) =>
{
f.context()
.comments()
.mark_suppression_checked(expression.syntax());
match expression.expression().unwrap() {
AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsStringLiteralExpression(string_literal),
) => {
f.context()
.comments()
.mark_suppression_checked(string_literal.syntax());
f.state_mut()
.track_token(&string_literal.value_token().unwrap());
f.state_mut()
.track_token(&expression.l_curly_token().unwrap());
f.state_mut()
.track_token(&expression.r_curly_token().unwrap());
}
_ => unreachable!(),
}
}
JsxText(text) => {
f.state_mut().track_token(&text.value_token().unwrap());
// You can't suppress a text node
f.context()
.comments()
.mark_suppression_checked(text.syntax());
}
_ => {
continue;
}
}
}
}
#[cfg(not(debug_assertions))]
fn disarm_debug_assertions(&self, _: &JsxChildList, _: &mut JsFormatter) {}
fn layout(&self, meta: ChildrenMeta) -> JsxChildListLayout {
match self.layout {
JsxChildListLayout::BestFitting => {
if meta.any_tag || meta.multiple_expressions {
JsxChildListLayout::Multiline
} else {
JsxChildListLayout::BestFitting
}
}
JsxChildListLayout::Multiline => JsxChildListLayout::Multiline,
}
}
/// Computes additional meta data about the children by iterating once over all children.
fn children_meta(&self, list: &JsxChildList, comments: &JsComments) -> ChildrenMeta {
let mut has_expression = false;
let mut meta = ChildrenMeta::default();
for child in list {
use AnyJsxChild::*;
match child {
JsxElement(_) | JsxFragment(_) | JsxSelfClosingElement(_) => meta.any_tag = true,
JsxExpressionChild(expression) => {
if is_whitespace_jsx_expression(&expression, comments) {
meta.meaningful_text = true;
} else {
meta.multiple_expressions = has_expression;
has_expression = true;
}
}
JsxText(text) => {
meta.meaningful_text = meta.meaningful_text
|| text
.value_token()
.map_or(false, |token| is_meaningful_jsx_text(token.text()));
}
_ => {}
}
}
meta
}
}
#[derive(Debug, Default, Copy, Clone)]
pub enum JsxChildListLayout {
/// Prefers to format the children on a single line if possible.
#[default]
BestFitting,
/// Forces the children to be formatted over multiple lines
Multiline,
}
impl JsxChildListLayout {
const fn is_multiline(&self) -> bool {
matches!(self, JsxChildListLayout::Multiline)
}
}
#[derive(Copy, Clone, Debug, Default)]
struct ChildrenMeta {
/// `true` if children contains a [JsxElement] or [JsxFragment]
any_tag: bool,
/// `true` if children contains more than one [JsxExpressionChild]
multiple_expressions: bool,
/// `true` if any child contains meaningful a [JsxText] with meaningful text.
meaningful_text: bool,
}
#[derive(Copy, Clone, Debug)]
enum WordSeparator {
/// Separator between two words. Creates a soft line break or space.
///
/// `a b`
BetweenWords,
/// A separator of a word at the end of a [JsxText] element. Either because it is the last
/// child in its parent OR it is right before the start of another child (element, expression, ...).
///
/// ```javascript
/// <div>a</div>; // last element of parent
/// <div>a<other /></div> // last element before another element
/// <div>a{expression}</div> // last element before expression
/// ```
///
/// Creates a soft line break EXCEPT if the next element is a self closing element
/// or the previous word was an ascii punctuation, which results in a hard line break:
///
/// ```javascript
/// a = <div>ab<br/></div>;
///
/// // becomes
///
/// a = (
/// <div>
/// ab
/// <br />
/// </div>
/// );
/// ```
EndOfText { is_soft_line_break: bool },
}
impl WordSeparator {
/// Returns if formatting this separator will result in a child that expands
fn will_break(&self) -> bool {
matches!(
self,
WordSeparator::EndOfText {
is_soft_line_break: false,
}
)
}
}
impl Format<JsFormatContext> for WordSeparator {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
match self {
WordSeparator::BetweenWords => soft_line_break_or_space().fmt(f),
WordSeparator::EndOfText { is_soft_line_break } => {
if *is_soft_line_break {
soft_line_break().fmt(f)
}
// ```javascript
// <div>ab<br/></div>
// ```
// Becomes
//
// ```javascript
// <div>
// ab
// <br />
// </div>
// ```
else {
hard_line_break().fmt(f)
}
}
}
}
}
#[derive(Copy, Clone, Debug, Default)]
enum MultilineLayout {
Fill,
#[default]
NoFill,
}
/// Builder that helps to create the output for the multiline layout.
///
/// The multiline layout may use [FormatElement::Fill] element that requires that its children
/// are an alternating sequence of `[element, separator, element, separator, ...]`.
///
/// This requires that each element is wrapped inside of a list if it emits more than one element to uphold
/// the constraints of [FormatElement::Fill].
///
/// However, the wrapping is only necessary for [MultilineLayout::Fill] for when the [FormatElement::Fill] element is used.
///
/// This builder takes care of doing the least amount of work necessary for the chosen layout while also guaranteeing
/// that the written element is valid
#[derive(Debug, Clone)]
struct MultilineBuilder {
layout: MultilineLayout,
result: FormatResult<Vec<FormatElement>>,
}
impl MultilineBuilder {
fn new(layout: MultilineLayout) -> Self {
Self {
layout,
result: Ok(Vec::new()),
}
}
/// Formats an element that does not require a separator
/// It is safe to omit the separator because at the call side we must guarantee that we have reached the end of the iterator
/// or the next element is a space/newline that should be written into the separator "slot".
fn write_content(&mut self, content: &dyn Format<JsFormatContext>, f: &mut JsFormatter) {
self.write(content, None, f);
}
/// Formatting a separator does not require any element in the separator slot
fn write_separator(&mut self, separator: &dyn Format<JsFormatContext>, f: &mut JsFormatter) {
self.write(separator, None, f);
}
fn write_with_separator(
&mut self,
content: &dyn Format<JsFormatContext>,
separator: &dyn Format<JsFormatContext>,
f: &mut JsFormatter,
) {
self.write(content, Some(separator), f);
}
fn write(
&mut self,
content: &dyn Format<JsFormatContext>,
separator: Option<&dyn Format<JsFormatContext>>,
f: &mut JsFormatter,
) {
let result = std::mem::replace(&mut self.result, Ok(Vec::new()));
self.result = result.and_then(|elements| {
let elements = {
let mut buffer = VecBuffer::new_with_vec(f.state_mut(), elements);
match self.layout {
MultilineLayout::Fill => {
// Make sure that the separator and content only ever write a single element
buffer.write_element(FormatElement::Tag(Tag::StartEntry))?;
write!(buffer, [content])?;
buffer.write_element(FormatElement::Tag(Tag::EndEntry))?;
if let Some(separator) = separator {
buffer.write_element(FormatElement::Tag(Tag::StartEntry))?;
write!(buffer, [separator])?;
buffer.write_element(FormatElement::Tag(Tag::EndEntry))?;
}
}
MultilineLayout::NoFill => {
write!(buffer, [content, separator])?;
if let Some(separator) = separator {
write!(buffer, [separator])?;
}
}
};
buffer.into_vec()
};
Ok(elements)
})
}
fn finish(self) -> FormatResult<FormatMultilineChildren> {
Ok(FormatMultilineChildren {
layout: self.layout,
elements: RefCell::new(self.result?),
})
}
}
#[derive(Debug)]
pub(crate) struct FormatMultilineChildren {
layout: MultilineLayout,
elements: RefCell<Vec<FormatElement>>,
}
impl Format<JsFormatContext> for FormatMultilineChildren {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
let format_inner = format_once(|f| {
if let Some(elements) = f.intern_vec(self.elements.take()) {
match self.layout {
MultilineLayout::Fill => f.write_elements([
FormatElement::Tag(Tag::StartFill),
elements,
FormatElement::Tag(Tag::EndFill),
])?,
MultilineLayout::NoFill => f.write_elements([
FormatElement::Tag(Tag::StartGroup(
tag::Group::new().with_mode(GroupMode::Expand),
)),
elements,
FormatElement::Tag(Tag::EndGroup),
])?,
};
}
Ok(())
});
write!(f, [block_indent(&format_inner)])
}
}
#[derive(Debug)]
struct FlatBuilder {
result: FormatResult<Vec<FormatElement>>,
disabled: bool,
}
impl FlatBuilder {
fn new() -> Self {
Self {
result: Ok(Vec::new()),
disabled: false,
}
}
fn write(&mut self, content: &dyn Format<JsFormatContext>, f: &mut JsFormatter) {
if self.disabled {
return;
}
let result = std::mem::replace(&mut self.result, Ok(Vec::new()));
self.result = result.and_then(|elements| {
let mut buffer = VecBuffer::new_with_vec(f.state_mut(), elements);
write!(buffer, [content])?;
Ok(buffer.into_vec())
})
}
fn disable(&mut self) {
self.disabled = true;
}
fn finish(self) -> FormatResult<FormatFlatChildren> {
assert!(!self.disabled, "The flat builder has been disabled and thus, does no longer store any elements. Make sure you don't call disable if you later intend to format the flat content.");
Ok(FormatFlatChildren {
elements: RefCell::new(self.result?),
})
}
}
#[derive(Debug)]
pub(crate) struct FormatFlatChildren {
elements: RefCell<Vec<FormatElement>>,
}
impl Format<JsFormatContext> for FormatFlatChildren {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
if let Some(elements) = f.intern_vec(self.elements.take()) {
f.write_element(elements)?;
}
Ok(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/lists/attribute_list.rs | crates/rome_js_formatter/src/jsx/lists/attribute_list.rs | use crate::prelude::*;
use rome_js_syntax::JsxAttributeList;
#[derive(Debug, Clone, Default)]
pub struct FormatJsxAttributeList;
impl FormatRule<JsxAttributeList> for FormatJsxAttributeList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsxAttributeList, f: &mut JsFormatter) -> FormatResult<()> {
f.join_with(&soft_line_break_or_space())
.entries(node.iter().formatted())
.finish()
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/lists/mod.rs | crates/rome_js_formatter/src/jsx/lists/mod.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
pub(crate) mod attribute_list;
pub(crate) mod child_list;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/auxiliary/reference_identifier.rs | crates/rome_js_formatter/src/jsx/auxiliary/reference_identifier.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::JsxReferenceIdentifier;
#[derive(Debug, Clone, Default)]
pub struct FormatJsxReferenceIdentifier;
impl FormatNodeRule<JsxReferenceIdentifier> for FormatJsxReferenceIdentifier {
fn fmt_fields(&self, node: &JsxReferenceIdentifier, f: &mut JsFormatter) -> FormatResult<()> {
write![f, [node.value_token().format()]]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/auxiliary/string.rs | crates/rome_js_formatter/src/jsx/auxiliary/string.rs | use crate::prelude::*;
use crate::utils::{FormatLiteralStringToken, StringLiteralParentKind};
use rome_formatter::write;
use rome_js_syntax::JsxString;
#[derive(Debug, Clone, Default)]
pub struct FormatJsxString;
impl FormatNodeRule<JsxString> for FormatJsxString {
fn fmt_fields(&self, node: &JsxString, f: &mut JsFormatter) -> FormatResult<()> {
write![
f,
[FormatLiteralStringToken::new(
&node.value_token()?,
StringLiteralParentKind::Expression
)]
]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/auxiliary/expression_child.rs | crates/rome_js_formatter/src/jsx/auxiliary/expression_child.rs | use crate::jsx::attribute::expression_attribute_value::should_inline_jsx_expression;
use crate::prelude::*;
use crate::prelude::{format_args, write};
use crate::utils::AnyJsBinaryLikeExpression;
use rome_formatter::{CstFormatContext, FormatResult};
use rome_js_syntax::{AnyJsExpression, JsxExpressionChild, JsxExpressionChildFields};
#[derive(Debug, Clone, Default)]
pub struct FormatJsxExpressionChild;
impl FormatNodeRule<JsxExpressionChild> for FormatJsxExpressionChild {
fn fmt_fields(&self, node: &JsxExpressionChild, f: &mut JsFormatter) -> FormatResult<()> {
let JsxExpressionChildFields {
l_curly_token,
expression,
r_curly_token,
} = node.as_fields();
match expression {
Some(expression) => {
let comments = f.context().comments();
let is_conditional_or_binary =
matches!(expression, AnyJsExpression::JsConditionalExpression(_))
|| AnyJsBinaryLikeExpression::can_cast(expression.syntax().kind());
let should_inline = !comments.has_comments(expression.syntax())
&& (is_conditional_or_binary
|| should_inline_jsx_expression(&expression, comments));
if should_inline {
write!(
f,
[
l_curly_token.format(),
expression.format(),
line_suffix_boundary(),
r_curly_token.format()
]
)
} else {
write!(
f,
[group(&format_args![
l_curly_token.format(),
soft_block_indent(&expression.format()),
line_suffix_boundary(),
r_curly_token.format()
])]
)
}
}
None => {
let has_line_comment = f
.comments()
.leading_dangling_trailing_comments(node.syntax())
.any(|comment| comment.kind().is_line());
write!(f, [l_curly_token.format()])?;
if has_line_comment {
write!(
f,
[
format_dangling_comments(node.syntax()).with_block_indent(),
hard_line_break()
]
)?;
} else {
write!(f, [format_dangling_comments(node.syntax())])?;
}
write!(f, [r_curly_token.format()])
}
}
}
fn fmt_dangling_comments(
&self,
_: &JsxExpressionChild,
_: &mut JsFormatter,
) -> FormatResult<()> {
// Formatted inside of `fmt_fields`
Ok(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/auxiliary/text.rs | crates/rome_js_formatter/src/jsx/auxiliary/text.rs | use crate::prelude::*;
use rome_formatter::FormatResult;
use rome_js_syntax::JsxText;
#[derive(Debug, Clone, Default)]
pub struct FormatJsxText;
impl FormatNodeRule<JsxText> for FormatJsxText {
fn fmt_fields(&self, node: &JsxText, f: &mut JsFormatter) -> FormatResult<()> {
// Formatting a [JsxText] on its own isn't supported. Format as verbatim. A text should always be formatted
// through its [JsxChildList]
format_verbatim_node(node.syntax()).fmt(f)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/auxiliary/mod.rs | crates/rome_js_formatter/src/jsx/auxiliary/mod.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
pub(crate) mod expression_child;
pub(crate) mod name;
pub(crate) mod namespace_name;
pub(crate) mod reference_identifier;
pub(crate) mod spread_child;
pub(crate) mod string;
pub(crate) mod text;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/auxiliary/namespace_name.rs | crates/rome_js_formatter/src/jsx/auxiliary/namespace_name.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::{JsxNamespaceName, JsxNamespaceNameFields};
#[derive(Debug, Clone, Default)]
pub struct FormatJsxNamespaceName;
impl FormatNodeRule<JsxNamespaceName> for FormatJsxNamespaceName {
fn fmt_fields(&self, node: &JsxNamespaceName, f: &mut JsFormatter) -> FormatResult<()> {
let JsxNamespaceNameFields {
namespace,
colon_token,
name,
} = node.as_fields();
write![f, [namespace.format(), colon_token.format(), name.format()]]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/auxiliary/name.rs | crates/rome_js_formatter/src/jsx/auxiliary/name.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::{JsxName, JsxNameFields};
#[derive(Debug, Clone, Default)]
pub struct FormatJsxName;
impl FormatNodeRule<JsxName> for FormatJsxName {
fn fmt_fields(&self, node: &JsxName, f: &mut JsFormatter) -> FormatResult<()> {
let JsxNameFields { value_token } = node.as_fields();
write![f, [value_token.format()]]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/auxiliary/spread_child.rs | crates/rome_js_formatter/src/jsx/auxiliary/spread_child.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::{JsxSpreadChild, JsxSpreadChildFields};
#[derive(Debug, Clone, Default)]
pub struct FormatJsxSpreadChild;
impl FormatNodeRule<JsxSpreadChild> for FormatJsxSpreadChild {
fn fmt_fields(&self, node: &JsxSpreadChild, f: &mut JsFormatter) -> FormatResult<()> {
let JsxSpreadChildFields {
l_curly_token,
dotdotdot_token,
expression,
r_curly_token,
} = node.as_fields();
let expression = expression?;
let format_inner = format_with(|f| {
write!(
f,
[
dotdotdot_token.format(),
expression.format(),
line_suffix_boundary()
]
)
});
write!(f, [l_curly_token.format()])?;
if f.comments().has_comments(expression.syntax()) {
write!(f, [soft_block_indent(&format_inner)])?;
} else {
write!(f, [format_inner])?;
}
write!(f, [r_curly_token.format()])
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/expressions/tag_expression.rs | crates/rome_js_formatter/src/jsx/expressions/tag_expression.rs | use crate::parentheses::{is_callee, is_tag, NeedsParentheses};
use crate::prelude::*;
use crate::utils::jsx::{get_wrap_state, WrapState};
use rome_formatter::{format_args, write};
use rome_js_syntax::{
JsArrowFunctionExpression, JsBinaryExpression, JsBinaryOperator, JsCallArgumentList,
JsCallExpression, JsSyntaxKind, JsSyntaxNode, JsxExpressionChild, JsxTagExpression,
};
use rome_rowan::AstNode;
#[derive(Debug, Clone, Default)]
pub struct FormatJsxTagExpression;
impl FormatNodeRule<JsxTagExpression> for FormatJsxTagExpression {
fn fmt_fields(&self, node: &JsxTagExpression, f: &mut JsFormatter) -> FormatResult<()> {
let wrap = get_wrap_state(node);
match wrap {
WrapState::NoWrap => {
write![
f,
[
format_leading_comments(node.syntax()),
node.tag().format(),
format_trailing_comments(node.syntax())
]
]
}
WrapState::WrapOnBreak => {
let should_expand = should_expand(node);
let needs_parentheses = node.needs_parentheses();
let format_inner = format_with(|f| {
if !needs_parentheses {
write!(f, [if_group_breaks(&text("("))])?;
}
write!(
f,
[soft_block_indent(&format_args![
format_leading_comments(node.syntax()),
node.tag().format(),
format_trailing_comments(node.syntax())
])]
)?;
if !needs_parentheses {
write!(f, [if_group_breaks(&text(")"))])?;
}
Ok(())
});
write!(f, [group(&format_inner).should_expand(should_expand)])
}
}
}
fn needs_parentheses(&self, item: &JsxTagExpression) -> bool {
item.needs_parentheses()
}
fn fmt_leading_comments(&self, _: &JsxTagExpression, _: &mut JsFormatter) -> FormatResult<()> {
// Handled as part of `fmt_fields`
Ok(())
}
fn fmt_trailing_comments(&self, _: &JsxTagExpression, _: &mut JsFormatter) -> FormatResult<()> {
// handled as part of `fmt_fields`
Ok(())
}
}
/// This is a very special situation where we're returning a JsxElement
/// from an arrow function that's passed as an argument to a function,
/// which is itself inside a JSX expression child.
///
/// If you're wondering why this is the only other case, it's because
/// Prettier defines it to be that way.
///
/// ```jsx
/// let bar = <div>
/// {foo(() => <div> the quick brown fox jumps over the lazy dog </div>)}
/// </div>;
/// ```
pub fn should_expand(expression: &JsxTagExpression) -> bool {
let arrow = match expression.syntax().parent() {
Some(parent) if JsArrowFunctionExpression::can_cast(parent.kind()) => parent,
_ => return false,
};
let call = match arrow.parent() {
// Argument
Some(grand_parent) if JsCallArgumentList::can_cast(grand_parent.kind()) => {
let maybe_call_expression = grand_parent.grand_parent();
match maybe_call_expression {
Some(call) if JsCallExpression::can_cast(call.kind()) => call,
_ => return false,
}
}
// Callee
Some(grand_parent) if JsCallExpression::can_cast(grand_parent.kind()) => grand_parent,
_ => return false,
};
call.parent()
.map_or(false, |parent| JsxExpressionChild::can_cast(parent.kind()))
}
impl NeedsParentheses for JsxTagExpression {
fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool {
match parent.kind() {
JsSyntaxKind::JS_BINARY_EXPRESSION => {
let binary = JsBinaryExpression::unwrap_cast(parent.clone());
let is_left = binary.left().map(AstNode::into_syntax).as_ref() == Ok(self.syntax());
matches!(binary.operator(), Ok(JsBinaryOperator::LessThan)) && is_left
}
JsSyntaxKind::TS_AS_EXPRESSION
| JsSyntaxKind::TS_SATISFIES_EXPRESSION
| JsSyntaxKind::JS_AWAIT_EXPRESSION
| JsSyntaxKind::JS_EXTENDS_CLAUSE
| JsSyntaxKind::JS_STATIC_MEMBER_EXPRESSION
| JsSyntaxKind::JS_COMPUTED_MEMBER_EXPRESSION
| JsSyntaxKind::JS_SEQUENCE_EXPRESSION
| JsSyntaxKind::JS_UNARY_EXPRESSION
| JsSyntaxKind::TS_NON_NULL_ASSERTION_EXPRESSION
| JsSyntaxKind::JS_SPREAD
| JsSyntaxKind::JSX_SPREAD_ATTRIBUTE
| JsSyntaxKind::JSX_SPREAD_CHILD => true,
_ => is_callee(self.syntax(), parent) || is_tag(self.syntax(), parent),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/expressions/mod.rs | crates/rome_js_formatter/src/jsx/expressions/mod.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
pub(crate) mod tag_expression;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/tag/element.rs | crates/rome_js_formatter/src/jsx/tag/element.rs | use crate::prelude::*;
use crate::jsx::lists::child_list::{FormatChildrenResult, FormatJsxChildList, JsxChildListLayout};
use crate::utils::jsx::{is_jsx_suppressed, is_meaningful_jsx_text};
use rome_formatter::{format_args, write, CstFormatContext, FormatResult, FormatRuleWithOptions};
use rome_js_syntax::{
AnyJsExpression, AnyJsxChild, JsxChildList, JsxElement, JsxExpressionChild, JsxFragment,
};
use rome_rowan::{declare_node_union, SyntaxResult};
#[derive(Debug, Clone, Default)]
pub struct FormatJsxElement;
impl FormatNodeRule<JsxElement> for FormatJsxElement {
fn fmt_fields(&self, node: &JsxElement, f: &mut JsFormatter) -> FormatResult<()> {
AnyJsxTagWithChildren::from(node.clone()).fmt(f)
}
fn is_suppressed(&self, node: &JsxElement, f: &JsFormatter) -> bool {
is_jsx_suppressed(&node.clone().into(), f.comments())
}
fn fmt_leading_comments(&self, node: &JsxElement, f: &mut JsFormatter) -> FormatResult<()> {
debug_assert!(
!f.comments().has_leading_comments(node.syntax()),
"JsxElement can not have comments."
);
Ok(())
}
fn fmt_dangling_comments(&self, node: &JsxElement, f: &mut JsFormatter) -> FormatResult<()> {
debug_assert!(
!f.comments().has_dangling_comments(node.syntax()),
"JsxElement can not have comments."
);
Ok(())
}
fn fmt_trailing_comments(&self, node: &JsxElement, f: &mut JsFormatter) -> FormatResult<()> {
debug_assert!(
!f.comments().has_trailing_comments(node.syntax()),
"JsxElement can not have comments."
);
Ok(())
}
}
declare_node_union! {
pub(super) AnyJsxTagWithChildren = JsxElement | JsxFragment
}
impl Format<JsFormatContext> for AnyJsxTagWithChildren {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
let format_opening = format_with(|f| self.fmt_opening(f));
let format_closing = format_with(|f| self.fmt_closing(f));
let layout = self.layout(f)?;
match layout {
ElementLayout::NoChildren => {
write!(f, [format_opening, format_closing])
}
ElementLayout::Template(expression) => {
write!(f, [format_opening, expression.format(), format_closing])
}
ElementLayout::Default => {
let mut format_opening = format_opening.memoized();
let opening_breaks = format_opening.inspect(f)?.will_break();
let multiple_attributes = match self {
AnyJsxTagWithChildren::JsxElement(element) => {
element.opening_element()?.attributes().len() > 1
}
AnyJsxTagWithChildren::JsxFragment(_) => false,
};
let list_layout = if multiple_attributes || opening_breaks {
JsxChildListLayout::Multiline
} else {
JsxChildListLayout::BestFitting
};
let children = self.children();
let format_children = FormatJsxChildList::default()
.with_options(list_layout)
.fmt_children(&children, f)?;
match format_children {
FormatChildrenResult::ForceMultiline(multiline) => {
write!(f, [format_opening, multiline, format_closing])
}
FormatChildrenResult::BestFitting {
flat_children,
expanded_children,
} => {
let format_closing = format_closing.memoized();
write!(
f,
[best_fitting![
format_args![format_opening, flat_children, format_closing],
format_args![format_opening, expanded_children, format_closing]
]]
)
}
}
}
}
}
}
impl AnyJsxTagWithChildren {
fn fmt_opening(&self, f: &mut JsFormatter) -> FormatResult<()> {
match self {
AnyJsxTagWithChildren::JsxElement(element) => {
write!(f, [element.opening_element().format()])
}
AnyJsxTagWithChildren::JsxFragment(fragment) => {
write!(f, [fragment.opening_fragment().format()])
}
}
}
fn fmt_closing(&self, f: &mut JsFormatter) -> FormatResult<()> {
match self {
AnyJsxTagWithChildren::JsxElement(element) => {
write!(f, [element.closing_element().format()])
}
AnyJsxTagWithChildren::JsxFragment(fragment) => {
write!(f, [fragment.closing_fragment().format()])
}
}
}
fn children(&self) -> JsxChildList {
match self {
AnyJsxTagWithChildren::JsxElement(element) => element.children(),
AnyJsxTagWithChildren::JsxFragment(fragment) => fragment.children(),
}
}
fn layout(&self, f: &mut JsFormatter) -> SyntaxResult<ElementLayout> {
use AnyJsExpression::*;
use AnyJsxChild::*;
let children = self.children();
let layout = match children.len() {
0 => ElementLayout::NoChildren,
1 => {
// SAFETY: Safe because of length check above
let child = children.first().unwrap();
match child {
JsxText(text) => {
let value_token = text.value_token()?;
if !is_meaningful_jsx_text(value_token.text()) {
// Text nodes can't have suppressions
f.context_mut()
.comments()
.mark_suppression_checked(text.syntax());
// It's safe to ignore the tokens here because JSX text tokens can't have comments (nor whitespace) attached.
f.state_mut().track_token(&value_token);
ElementLayout::NoChildren
} else {
ElementLayout::Default
}
}
JsxExpressionChild(expression) => match expression.expression() {
Some(JsTemplateExpression(_)) => ElementLayout::Template(expression),
_ => ElementLayout::Default,
},
_ => ElementLayout::Default,
}
}
_ => ElementLayout::Default,
};
Ok(layout)
}
}
#[derive(Debug, Clone)]
enum ElementLayout {
/// Empty Tag with no children or contains no meaningful text.
NoChildren,
/// Prefer breaking the template if it is the only child of the element
/// ```javascript
/// <div>{`A Long Tempalte String That uses ${
/// 5 + 4
/// } that will eventually break across multiple lines ${(40 / 3) * 45}`}</div>;
/// ```
///
/// instead of
///
/// ```javascript
/// <div>
/// {`A Long Template String That uses ${
/// 5 + 4
/// } that will eventually break across multiple lines ${(40 / 3) * 45}`}
/// </div>;
/// ```
Template(JsxExpressionChild),
/// Default layout used for all elements that have children and [ElementLayout::Template] does not apply.
///
/// ```javascript
///<Element2>
/// Some more content
/// <Sub />
/// <Sub />
/// <Sub />
/// </Element2>;
/// ```
Default,
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/tag/closing_fragment.rs | crates/rome_js_formatter/src/jsx/tag/closing_fragment.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::{JsxClosingFragment, JsxClosingFragmentFields};
#[derive(Debug, Clone, Default)]
pub struct FormatJsxClosingFragment;
impl FormatNodeRule<JsxClosingFragment> for FormatJsxClosingFragment {
fn fmt_fields(&self, node: &JsxClosingFragment, f: &mut JsFormatter) -> FormatResult<()> {
let JsxClosingFragmentFields {
r_angle_token,
slash_token,
l_angle_token,
} = node.as_fields();
let mut has_own_line_comment = false;
let mut has_comment = false;
for comment in f
.comments()
.leading_dangling_trailing_comments(node.syntax())
{
has_comment = true;
has_own_line_comment = has_own_line_comment || comment.kind().is_line()
}
let format_comments = format_with(|f| {
if has_own_line_comment {
write!(f, [hard_line_break()])?;
} else if has_comment {
write!(f, [space()])?;
}
write!(f, [format_dangling_comments(node.syntax())])
});
write![
f,
[
l_angle_token.format(),
slash_token.format(),
indent(&format_comments),
has_own_line_comment.then_some(hard_line_break()),
r_angle_token.format(),
]
]
}
fn fmt_dangling_comments(
&self,
_: &JsxClosingFragment,
_: &mut JsFormatter,
) -> FormatResult<()> {
// Formatted as part of `fmt_fields`
Ok(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/tag/closing_element.rs | crates/rome_js_formatter/src/jsx/tag/closing_element.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::{JsxClosingElement, JsxClosingElementFields};
#[derive(Debug, Clone, Default)]
pub struct FormatJsxClosingElement;
impl FormatNodeRule<JsxClosingElement> for FormatJsxClosingElement {
fn fmt_fields(&self, node: &JsxClosingElement, f: &mut JsFormatter) -> FormatResult<()> {
let JsxClosingElementFields {
l_angle_token,
slash_token,
name,
r_angle_token,
} = node.as_fields();
let name = name?;
let mut name_has_leading_comment = false;
let mut name_has_own_line_leading_comment = false;
for leading_comment in f.comments().leading_comments(name.syntax()) {
name_has_leading_comment = true;
name_has_own_line_leading_comment =
name_has_own_line_leading_comment || leading_comment.kind().is_line()
}
let format_name = format_with(|f| {
if name_has_own_line_leading_comment {
write!(f, [hard_line_break()])?;
} else if name_has_leading_comment {
write!(f, [space()])?;
}
if name_has_own_line_leading_comment {
write!(f, [block_indent(&name.format()), hard_line_break()])
} else {
write!(f, [name.format()])
}
});
write![
f,
[
l_angle_token.format(),
slash_token.format(),
&format_name,
line_suffix_boundary(),
r_angle_token.format(),
]
]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/tag/fragment.rs | crates/rome_js_formatter/src/jsx/tag/fragment.rs | use crate::prelude::*;
use crate::jsx::tag::element::AnyJsxTagWithChildren;
use crate::utils::jsx::is_jsx_suppressed;
use rome_formatter::write;
use rome_js_syntax::JsxFragment;
#[derive(Debug, Clone, Default)]
pub struct FormatJsxFragment;
impl FormatNodeRule<JsxFragment> for FormatJsxFragment {
fn fmt_fields(&self, node: &JsxFragment, f: &mut JsFormatter) -> FormatResult<()> {
write!(f, [AnyJsxTagWithChildren::from(node.clone())])
}
fn is_suppressed(&self, node: &JsxFragment, f: &JsFormatter) -> bool {
is_jsx_suppressed(&node.clone().into(), f.comments())
}
fn fmt_leading_comments(&self, node: &JsxFragment, f: &mut JsFormatter) -> FormatResult<()> {
debug_assert!(
!f.comments().has_leading_comments(node.syntax()),
"JsxFragment can not have comments."
);
Ok(())
}
fn fmt_dangling_comments(&self, node: &JsxFragment, f: &mut JsFormatter) -> FormatResult<()> {
debug_assert!(
!f.comments().has_dangling_comments(node.syntax()),
"JsxFragment can not have comments."
);
Ok(())
}
fn fmt_trailing_comments(&self, node: &JsxFragment, f: &mut JsFormatter) -> FormatResult<()> {
debug_assert!(
!f.comments().has_trailing_comments(node.syntax()),
"JsxFragment can not have comments."
);
Ok(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/tag/opening_element.rs | crates/rome_js_formatter/src/jsx/tag/opening_element.rs | use crate::prelude::*;
use rome_formatter::{write, CstFormatContext};
use rome_js_syntax::{
AnyJsxAttribute, AnyJsxAttributeValue, AnyJsxElementName, JsSyntaxToken, JsxAttributeList,
JsxOpeningElement, JsxSelfClosingElement, JsxString, TsTypeArguments,
};
use rome_rowan::{declare_node_union, SyntaxResult};
#[derive(Debug, Clone, Default)]
pub struct FormatJsxOpeningElement;
impl FormatNodeRule<JsxOpeningElement> for FormatJsxOpeningElement {
fn fmt_fields(&self, node: &JsxOpeningElement, f: &mut JsFormatter) -> FormatResult<()> {
AnyJsxOpeningElement::from(node.clone()).fmt(f)
}
}
declare_node_union! {
pub(super) AnyJsxOpeningElement = JsxSelfClosingElement | JsxOpeningElement
}
impl Format<JsFormatContext> for AnyJsxOpeningElement {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
let layout = self.compute_layout(f.context().comments())?;
let l_angle_token = self.l_angle_token()?;
let name = self.name()?;
let type_arguments = self.type_arguments();
let attributes = self.attributes();
let format_close = format_with(|f| {
if let AnyJsxOpeningElement::JsxSelfClosingElement(element) = self {
write!(f, [element.slash_token().format()])?;
}
write!(f, [self.r_angle_token().format()])
});
match layout {
OpeningElementLayout::Inline => {
write!(
f,
[
l_angle_token.format(),
name.format(),
type_arguments.format(),
space(),
format_close
]
)
}
OpeningElementLayout::SingleStringAttribute => {
let attribute_spacing = if self.is_self_closing() {
Some(space())
} else {
None
};
write!(
f,
[
l_angle_token.format(),
name.format(),
type_arguments.format(),
space(),
attributes.format(),
attribute_spacing,
format_close
]
)
}
OpeningElementLayout::IndentAttributes { name_has_comments } => {
let format_inner = format_with(|f| {
write!(
f,
[
l_angle_token.format(),
name.format(),
type_arguments.format(),
soft_line_indent_or_space(&attributes.format()),
]
)?;
let bracket_same_line = attributes.is_empty() && !name_has_comments;
if self.is_self_closing() {
write!(f, [soft_line_break_or_space(), format_close])
} else if bracket_same_line {
write!(f, [format_close])
} else {
write!(f, [soft_line_break(), format_close])
}
});
let has_multiline_string_attribute = attributes
.iter()
.any(|attribute| is_multiline_string_literal_attribute(&attribute));
write![
f,
[group(&format_inner).should_expand(has_multiline_string_attribute)]
]
}
}
}
}
impl AnyJsxOpeningElement {
fn l_angle_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
AnyJsxOpeningElement::JsxSelfClosingElement(element) => element.l_angle_token(),
AnyJsxOpeningElement::JsxOpeningElement(element) => element.l_angle_token(),
}
}
fn name(&self) -> SyntaxResult<AnyJsxElementName> {
match self {
AnyJsxOpeningElement::JsxSelfClosingElement(element) => element.name(),
AnyJsxOpeningElement::JsxOpeningElement(element) => element.name(),
}
}
fn type_arguments(&self) -> Option<TsTypeArguments> {
match self {
AnyJsxOpeningElement::JsxSelfClosingElement(element) => element.type_arguments(),
AnyJsxOpeningElement::JsxOpeningElement(element) => element.type_arguments(),
}
}
fn attributes(&self) -> JsxAttributeList {
match self {
AnyJsxOpeningElement::JsxSelfClosingElement(element) => element.attributes(),
AnyJsxOpeningElement::JsxOpeningElement(element) => element.attributes(),
}
}
fn r_angle_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
AnyJsxOpeningElement::JsxSelfClosingElement(element) => element.r_angle_token(),
AnyJsxOpeningElement::JsxOpeningElement(element) => element.r_angle_token(),
}
}
fn is_self_closing(&self) -> bool {
matches!(self, AnyJsxOpeningElement::JsxSelfClosingElement(_))
}
fn compute_layout(&self, comments: &JsComments) -> SyntaxResult<OpeningElementLayout> {
let attributes = self.attributes();
let name = self.name()?;
let name_has_comments = comments.has_comments(name.syntax())
|| self
.type_arguments()
.map_or(false, |arguments| comments.has_comments(arguments.syntax()));
let layout = if self.is_self_closing() && attributes.is_empty() && !name_has_comments {
OpeningElementLayout::Inline
} else if attributes.len() == 1
&& attributes.iter().all(|attribute| {
is_single_line_string_literal_attribute(&attribute)
&& !comments.has_comments(attribute.syntax())
})
&& !name_has_comments
{
OpeningElementLayout::SingleStringAttribute
} else {
OpeningElementLayout::IndentAttributes { name_has_comments }
};
Ok(layout)
}
}
#[derive(Copy, Clone, Debug)]
enum OpeningElementLayout {
/// Don't create a group around the element to avoid it breaking ever.
///
/// Applied for elements that have no attributes nor any comment attached to their name.
///
/// ```javascript
/// <ASuperLongComponentNameThatWouldBreakButDoesntSinceTheComponent<DonTBreakThis>></ASuperLongComponentNameThatWouldBreakButDoesntSinceTheComponent>
/// ```
Inline,
/// Opening element with a single attribute that contains no line breaks, nor has comments.
///
/// ```javascript
/// <div tooltip="A very long tooltip text that would otherwise make the attribute break onto the same line but it is not because of the single string layout" more></div>;
/// ```
SingleStringAttribute,
/// Default layout that indents the attributes and formats each attribute on its own line.
///
/// ```javascript
/// <div
/// oneAttribute
/// another="with value"
/// moreAttributes={withSomeExpression}
/// ></div>;
/// ```
IndentAttributes { name_has_comments: bool },
}
/// Returns `true` if this is an attribute with a [JsxString] initializer that does not contain any new line characters.
fn is_single_line_string_literal_attribute(attribute: &AnyJsxAttribute) -> bool {
as_string_literal_attribute_value(attribute).map_or(false, |string| {
string
.value_token()
.map_or(false, |text| !text.text_trimmed().contains('\n'))
})
}
/// Returns `true` if this is an attribute with a [JsxString] initializer that contains at least one new line character.
fn is_multiline_string_literal_attribute(attribute: &AnyJsxAttribute) -> bool {
as_string_literal_attribute_value(attribute).map_or(false, |string| {
string
.value_token()
.map_or(false, |text| text.text_trimmed().contains('\n'))
})
}
/// Returns `Some` if the initializer value of this attribute is a [JsxString].
/// Returns [None] otherwise.
fn as_string_literal_attribute_value(attribute: &AnyJsxAttribute) -> Option<JsxString> {
use AnyJsxAttribute::*;
use AnyJsxAttributeValue::*;
match attribute {
JsxAttribute(attribute) => {
attribute
.initializer()
.and_then(|initializer| match initializer.value() {
Ok(JsxString(string)) => Some(string),
_ => None,
})
}
JsxSpreadAttribute(_) => None,
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/tag/mod.rs | crates/rome_js_formatter/src/jsx/tag/mod.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
pub(crate) mod closing_element;
pub(crate) mod closing_fragment;
pub(crate) mod element;
pub(crate) mod fragment;
pub(crate) mod opening_element;
pub(crate) mod opening_fragment;
pub(crate) mod self_closing_element;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/tag/opening_fragment.rs | crates/rome_js_formatter/src/jsx/tag/opening_fragment.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::{JsxOpeningFragment, JsxOpeningFragmentFields};
#[derive(Debug, Clone, Default)]
pub struct FormatJsxOpeningFragment;
impl FormatNodeRule<JsxOpeningFragment> for FormatJsxOpeningFragment {
fn fmt_fields(&self, node: &JsxOpeningFragment, f: &mut JsFormatter) -> FormatResult<()> {
let JsxOpeningFragmentFields {
r_angle_token,
l_angle_token,
} = node.as_fields();
let has_own_line_comment = f
.comments()
.leading_dangling_trailing_comments(node.syntax())
.any(|comment| comment.kind().is_line());
let format_comments = format_with(|f| {
if has_own_line_comment {
write!(f, [hard_line_break()])?;
}
write!(f, [format_dangling_comments(node.syntax())])
});
write![
f,
[
l_angle_token.format(),
indent(&format_comments),
has_own_line_comment.then_some(hard_line_break()),
r_angle_token.format()
]
]
}
fn fmt_dangling_comments(
&self,
_: &JsxOpeningFragment,
_: &mut JsFormatter,
) -> FormatResult<()> {
// Handled as part of `fmt_fields`
Ok(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/tag/self_closing_element.rs | crates/rome_js_formatter/src/jsx/tag/self_closing_element.rs | use crate::prelude::*;
use crate::jsx::tag::opening_element::AnyJsxOpeningElement;
use crate::utils::jsx::is_jsx_suppressed;
use rome_js_syntax::JsxSelfClosingElement;
#[derive(Debug, Clone, Default)]
pub struct FormatJsxSelfClosingElement;
impl FormatNodeRule<JsxSelfClosingElement> for FormatJsxSelfClosingElement {
fn fmt_fields(&self, node: &JsxSelfClosingElement, f: &mut JsFormatter) -> FormatResult<()> {
AnyJsxOpeningElement::from(node.clone()).fmt(f)
}
fn is_suppressed(&self, node: &JsxSelfClosingElement, f: &JsFormatter) -> bool {
is_jsx_suppressed(&node.clone().into(), f.comments())
}
fn fmt_leading_comments(
&self,
node: &JsxSelfClosingElement,
f: &mut JsFormatter,
) -> FormatResult<()> {
debug_assert!(
!f.comments().has_leading_comments(node.syntax()),
"JsxSelfClosingElement can not have comments."
);
Ok(())
}
fn fmt_dangling_comments(
&self,
node: &JsxSelfClosingElement,
f: &mut JsFormatter,
) -> FormatResult<()> {
debug_assert!(
!f.comments().has_dangling_comments(node.syntax()),
"JsxSelfClosingElement can not have comments."
);
Ok(())
}
fn fmt_trailing_comments(
&self,
node: &JsxSelfClosingElement,
f: &mut JsFormatter,
) -> FormatResult<()> {
debug_assert!(
!f.comments().has_trailing_comments(node.syntax()),
"JsxSelfClosingElement can not have comments."
);
Ok(())
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/any/attribute.rs | crates/rome_js_formatter/src/jsx/any/attribute.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
use crate::prelude::*;
use rome_js_syntax::AnyJsxAttribute;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyJsxAttribute;
impl FormatRule<AnyJsxAttribute> for FormatAnyJsxAttribute {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyJsxAttribute, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyJsxAttribute::JsxAttribute(node) => node.format().fmt(f),
AnyJsxAttribute::JsxSpreadAttribute(node) => node.format().fmt(f),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/any/mod.rs | crates/rome_js_formatter/src/jsx/any/mod.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
pub(crate) mod attribute;
pub(crate) mod attribute_name;
pub(crate) mod attribute_value;
pub(crate) mod child;
pub(crate) mod element_name;
pub(crate) mod name;
pub(crate) mod object_name;
pub(crate) mod tag;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/any/child.rs | crates/rome_js_formatter/src/jsx/any/child.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
use crate::prelude::*;
use rome_js_syntax::AnyJsxChild;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyJsxChild;
impl FormatRule<AnyJsxChild> for FormatAnyJsxChild {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyJsxChild, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyJsxChild::JsxElement(node) => node.format().fmt(f),
AnyJsxChild::JsxSelfClosingElement(node) => node.format().fmt(f),
AnyJsxChild::JsxText(node) => node.format().fmt(f),
AnyJsxChild::JsxExpressionChild(node) => node.format().fmt(f),
AnyJsxChild::JsxSpreadChild(node) => node.format().fmt(f),
AnyJsxChild::JsxFragment(node) => node.format().fmt(f),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/any/element_name.rs | crates/rome_js_formatter/src/jsx/any/element_name.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
use crate::prelude::*;
use rome_js_syntax::AnyJsxElementName;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyJsxElementName;
impl FormatRule<AnyJsxElementName> for FormatAnyJsxElementName {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyJsxElementName, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyJsxElementName::JsxName(node) => node.format().fmt(f),
AnyJsxElementName::JsxReferenceIdentifier(node) => node.format().fmt(f),
AnyJsxElementName::JsxMemberName(node) => node.format().fmt(f),
AnyJsxElementName::JsxNamespaceName(node) => node.format().fmt(f),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/any/attribute_name.rs | crates/rome_js_formatter/src/jsx/any/attribute_name.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
use crate::prelude::*;
use rome_js_syntax::AnyJsxAttributeName;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyJsxAttributeName;
impl FormatRule<AnyJsxAttributeName> for FormatAnyJsxAttributeName {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyJsxAttributeName, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyJsxAttributeName::JsxName(node) => node.format().fmt(f),
AnyJsxAttributeName::JsxNamespaceName(node) => node.format().fmt(f),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/any/attribute_value.rs | crates/rome_js_formatter/src/jsx/any/attribute_value.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
use crate::prelude::*;
use rome_js_syntax::AnyJsxAttributeValue;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyJsxAttributeValue;
impl FormatRule<AnyJsxAttributeValue> for FormatAnyJsxAttributeValue {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyJsxAttributeValue, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyJsxAttributeValue::AnyJsxTag(node) => node.format().fmt(f),
AnyJsxAttributeValue::JsxString(node) => node.format().fmt(f),
AnyJsxAttributeValue::JsxExpressionAttributeValue(node) => node.format().fmt(f),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/any/name.rs | crates/rome_js_formatter/src/jsx/any/name.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
use crate::prelude::*;
use rome_js_syntax::AnyJsxName;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyJsxName;
impl FormatRule<AnyJsxName> for FormatAnyJsxName {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyJsxName, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyJsxName::JsxName(node) => node.format().fmt(f),
AnyJsxName::JsxNamespaceName(node) => node.format().fmt(f),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/any/object_name.rs | crates/rome_js_formatter/src/jsx/any/object_name.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
use crate::prelude::*;
use rome_js_syntax::AnyJsxObjectName;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyJsxObjectName;
impl FormatRule<AnyJsxObjectName> for FormatAnyJsxObjectName {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyJsxObjectName, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyJsxObjectName::JsxReferenceIdentifier(node) => node.format().fmt(f),
AnyJsxObjectName::JsxMemberName(node) => node.format().fmt(f),
AnyJsxObjectName::JsxNamespaceName(node) => node.format().fmt(f),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/any/tag.rs | crates/rome_js_formatter/src/jsx/any/tag.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
use crate::prelude::*;
use rome_js_syntax::AnyJsxTag;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatAnyJsxTag;
impl FormatRule<AnyJsxTag> for FormatAnyJsxTag {
type Context = JsFormatContext;
fn fmt(&self, node: &AnyJsxTag, f: &mut JsFormatter) -> FormatResult<()> {
match node {
AnyJsxTag::JsxElement(node) => node.format().fmt(f),
AnyJsxTag::JsxSelfClosingElement(node) => node.format().fmt(f),
AnyJsxTag::JsxFragment(node) => node.format().fmt(f),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/objects/member_name.rs | crates/rome_js_formatter/src/jsx/objects/member_name.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::{JsxMemberName, JsxMemberNameFields};
#[derive(Debug, Clone, Default)]
pub struct FormatJsxMemberName;
impl FormatNodeRule<JsxMemberName> for FormatJsxMemberName {
fn fmt_fields(&self, node: &JsxMemberName, f: &mut JsFormatter) -> FormatResult<()> {
let JsxMemberNameFields {
object,
dot_token,
member,
} = node.as_fields();
write![f, [object.format(), dot_token.format(), member.format(),]]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/objects/mod.rs | crates/rome_js_formatter/src/jsx/objects/mod.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
pub(crate) mod member_name;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/attribute/attribute.rs | crates/rome_js_formatter/src/jsx/attribute/attribute.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::{JsxAttribute, JsxAttributeFields};
#[derive(Debug, Clone, Default)]
pub struct FormatJsxAttribute;
impl FormatNodeRule<JsxAttribute> for FormatJsxAttribute {
fn fmt_fields(&self, node: &JsxAttribute, f: &mut JsFormatter) -> FormatResult<()> {
let JsxAttributeFields { name, initializer } = node.as_fields();
write![f, [name.format(), initializer.format()]]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/attribute/expression_attribute_value.rs | crates/rome_js_formatter/src/jsx/attribute/expression_attribute_value.rs | use crate::prelude::*;
use rome_formatter::{format_args, write, CstFormatContext};
use rome_js_syntax::{
AnyJsExpression, AnyJsxTag, JsxExpressionAttributeValue, JsxExpressionAttributeValueFields,
};
#[derive(Debug, Clone, Default)]
pub struct FormatJsxExpressionAttributeValue;
impl FormatNodeRule<JsxExpressionAttributeValue> for FormatJsxExpressionAttributeValue {
fn fmt_fields(
&self,
node: &JsxExpressionAttributeValue,
f: &mut JsFormatter,
) -> FormatResult<()> {
let JsxExpressionAttributeValueFields {
l_curly_token,
expression,
r_curly_token,
} = node.as_fields();
let expression = expression?;
let should_inline = should_inline_jsx_expression(&expression, f.context().comments());
if should_inline {
write!(
f,
[
l_curly_token.format(),
expression.format(),
line_suffix_boundary(),
r_curly_token.format()
]
)
} else {
write!(
f,
[group(&format_args![
l_curly_token.format(),
soft_block_indent(&expression.format()),
line_suffix_boundary(),
r_curly_token.format()
])]
)
}
}
}
/// Tests if an expression inside of a [JsxExpressionChild] or [JsxExpressionAttributeValue] should be inlined.
/// Good:
/// ```jsx
/// <ColorPickerPage
/// colors={[
/// "blue",
/// "brown",
/// "green",
/// "orange",
/// "purple",
/// ]} />
/// ```
///
/// Bad:
/// ```jsx
/// <ColorPickerPage
/// colors={
/// [
/// "blue",
/// "brown",
/// "green",
/// "orange",
/// "purple",
/// ]
/// } />
/// ```
pub(crate) fn should_inline_jsx_expression(
expression: &AnyJsExpression,
comments: &JsComments,
) -> bool {
use AnyJsExpression::*;
if comments.has_comments(expression.syntax()) {
return false;
}
match expression {
JsArrayExpression(_)
| JsObjectExpression(_)
| JsArrowFunctionExpression(_)
| JsCallExpression(_)
| JsImportCallExpression(_)
| JsImportMetaExpression(_)
| JsFunctionExpression(_)
| JsTemplateExpression(_) => true,
JsAwaitExpression(await_expression) => match await_expression.argument() {
Ok(JsxTagExpression(argument)) => {
matches!(argument.tag(), Ok(AnyJsxTag::JsxElement(_)))
&& should_inline_jsx_expression(&argument.into(), comments)
}
_ => false,
},
_ => false,
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/attribute/mod.rs | crates/rome_js_formatter/src/jsx/attribute/mod.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
#[allow(clippy::module_inception)]
pub(crate) mod attribute;
pub(crate) mod attribute_initializer_clause;
pub(crate) mod expression_attribute_value;
pub(crate) mod spread_attribute;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/attribute/spread_attribute.rs | crates/rome_js_formatter/src/jsx/attribute/spread_attribute.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::{JsxSpreadAttribute, JsxSpreadAttributeFields};
#[derive(Debug, Clone, Default)]
pub struct FormatJsxSpreadAttribute;
impl FormatNodeRule<JsxSpreadAttribute> for FormatJsxSpreadAttribute {
fn fmt_fields(&self, node: &JsxSpreadAttribute, f: &mut JsFormatter) -> FormatResult<()> {
let JsxSpreadAttributeFields {
l_curly_token,
dotdotdot_token,
argument,
r_curly_token,
} = node.as_fields();
let argument = argument?;
let format_inner =
format_with(|f| write!(f, [dotdotdot_token.format(), argument.format(),]));
write!(f, [l_curly_token.format()])?;
if f.comments().has_comments(argument.syntax())
&& !f.comments().is_suppressed(argument.syntax())
{
write!(f, [soft_block_indent(&format_inner)])?;
} else {
write!(f, [format_inner])?;
}
write![f, [r_curly_token.format()]]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/jsx/attribute/attribute_initializer_clause.rs | crates/rome_js_formatter/src/jsx/attribute/attribute_initializer_clause.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::{JsxAttributeInitializerClause, JsxAttributeInitializerClauseFields};
#[derive(Debug, Clone, Default)]
pub struct FormatJsxAttributeInitializerClause;
impl FormatNodeRule<JsxAttributeInitializerClause> for FormatJsxAttributeInitializerClause {
fn fmt_fields(
&self,
node: &JsxAttributeInitializerClause,
f: &mut JsFormatter,
) -> FormatResult<()> {
let JsxAttributeInitializerClauseFields { eq_token, value } = node.as_fields();
write![f, [eq_token.format(), value.format()]]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/array.rs | crates/rome_js_formatter/src/utils/array.rs | use crate::prelude::*;
use crate::AsFormat;
use crate::context::trailing_comma::FormatTrailingComma;
use rome_formatter::write;
use rome_js_syntax::{
AnyJsArrayAssignmentPatternElement, AnyJsArrayBindingPatternElement, AnyJsArrayElement,
JsLanguage,
};
use rome_rowan::{AstNode, AstSeparatedList};
/// Utility function to print array-like nodes (array expressions, array bindings and assignment patterns)
pub(crate) fn write_array_node<N, I>(node: &N, f: &mut JsFormatter) -> FormatResult<()>
where
N: AstSeparatedList<Language = JsLanguage, Node = I>,
I: ArrayNodeElement + AsFormat<JsFormatContext>,
{
let trailing_separator = FormatTrailingComma::ES5.trailing_separator(f.options());
// Specifically do not use format_separated as arrays need separators
// inserted after holes regardless of the formatting since this makes a
// semantic difference
let mut join = f.join_nodes_with_soft_line();
let last_index = node.len().saturating_sub(1);
for (index, element) in node.elements().enumerate() {
let node = element.node()?;
let separator_mode = node.separator_mode();
let is_disallow = matches!(separator_mode, TrailingSeparatorMode::Disallow);
let is_force = matches!(separator_mode, TrailingSeparatorMode::Force);
join.entry(
node.syntax(),
&format_with(|f| {
write!(f, [group(&node.format())])?;
if is_disallow {
// Trailing separators are disallowed, replace it with an empty element
if let Some(separator) = element.trailing_separator()? {
write!(f, [format_removed(separator)])?;
}
} else if is_force || index != last_index {
// In forced separator mode or if this element is not the last in the list, print the separator
match element.trailing_separator()? {
Some(trailing) => write!(f, [trailing.format()])?,
None => text(",").fmt(f)?,
};
} else if let Some(separator) = element.trailing_separator()? {
match trailing_separator {
TrailingSeparator::Omit => {
write!(f, [format_removed(separator)])?;
}
_ => {
write!(f, [format_only_if_breaks(separator, &separator.format())])?;
}
}
} else {
write!(f, [FormatTrailingComma::ES5])?;
};
Ok(())
}),
);
}
join.finish()
}
/// Determines if a trailing separator should be inserted after an array element
pub(crate) enum TrailingSeparatorMode {
/// Trailing separators are not allowed after this element (eg. rest elements)
Disallow,
/// Trailing separators are inserted after this element except if its the
/// last element and the group is not breaking
Auto,
/// Trailing separators will always be inserted after this element (eg. hole elements)
Force,
}
pub(crate) trait ArrayNodeElement: AstNode<Language = JsLanguage> {
/// Determines how the trailing separator should be printer for this element
fn separator_mode(&self) -> TrailingSeparatorMode;
}
impl ArrayNodeElement for AnyJsArrayElement {
fn separator_mode(&self) -> TrailingSeparatorMode {
match self {
Self::JsArrayHole(_) => TrailingSeparatorMode::Force,
_ => TrailingSeparatorMode::Auto,
}
}
}
impl ArrayNodeElement for AnyJsArrayAssignmentPatternElement {
fn separator_mode(&self) -> TrailingSeparatorMode {
match self {
Self::JsArrayHole(_) => TrailingSeparatorMode::Force,
Self::JsArrayAssignmentPatternRestElement(_) => TrailingSeparatorMode::Disallow,
_ => TrailingSeparatorMode::Auto,
}
}
}
impl ArrayNodeElement for AnyJsArrayBindingPatternElement {
fn separator_mode(&self) -> TrailingSeparatorMode {
match self {
Self::JsArrayHole(_) => TrailingSeparatorMode::Force,
Self::JsArrayBindingPatternRestElement(_) => TrailingSeparatorMode::Disallow,
_ => TrailingSeparatorMode::Auto,
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/object.rs | crates/rome_js_formatter/src/utils/object.rs | use crate::prelude::*;
use crate::utils::FormatLiteralStringToken;
use crate::utils::StringLiteralParentKind;
use rome_formatter::write;
use rome_js_syntax::JsSyntaxKind::JS_STRING_LITERAL;
use rome_js_syntax::{AnyJsClassMemberName, AnyJsObjectMemberName};
use rome_rowan::{declare_node_union, AstNode};
use unicode_width::UnicodeWidthStr;
declare_node_union! {
pub(crate) AnyJsMemberName = AnyJsObjectMemberName | AnyJsClassMemberName
}
impl Format<JsFormatContext> for AnyJsMemberName {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
match self {
AnyJsMemberName::AnyJsObjectMemberName(node) => {
write!(f, [node.format()])
}
AnyJsMemberName::AnyJsClassMemberName(node) => {
write!(f, [node.format()])
}
}
}
}
pub(crate) fn write_member_name(
name: &AnyJsMemberName,
f: &mut JsFormatter,
) -> FormatResult<usize> {
match name {
name @ AnyJsMemberName::AnyJsClassMemberName(AnyJsClassMemberName::JsLiteralMemberName(
literal,
))
| name @ AnyJsMemberName::AnyJsObjectMemberName(
AnyJsObjectMemberName::JsLiteralMemberName(literal),
) => {
let value = literal.value()?;
if value.kind() == JS_STRING_LITERAL {
let format = FormatLiteralStringToken::new(&value, StringLiteralParentKind::Member);
let cleaned = format.clean_text(f.options());
write!(
f,
[
format_leading_comments(name.syntax()),
cleaned,
format_trailing_comments(name.syntax())
]
)?;
Ok(cleaned.width())
} else {
write!(f, [name])?;
Ok(value.text_trimmed().width())
}
}
name => {
write!(f, [&name])?;
Ok(name.text().width())
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/assignment_like.rs | crates/rome_js_formatter/src/utils/assignment_like.rs | use crate::js::auxiliary::initializer_clause::FormatJsInitializerClauseOptions;
use crate::js::expressions::arrow_function_expression::FormatJsArrowFunctionExpressionOptions;
use crate::prelude::*;
use crate::utils::member_chain::is_member_call_chain;
use crate::utils::object::write_member_name;
use crate::utils::AnyJsBinaryLikeExpression;
use rome_formatter::{format_args, write, CstFormatContext, FormatOptions, VecBuffer};
use rome_js_syntax::AnyJsLiteralExpression;
use rome_js_syntax::{
AnyJsAssignmentPattern, AnyJsBindingPattern, AnyJsCallArgument, AnyJsClassMemberName,
AnyJsExpression, AnyJsFunctionBody, AnyJsObjectAssignmentPatternMember,
AnyJsObjectBindingPatternMember, AnyJsObjectMemberName, AnyJsTemplateElement, AnyTsType,
AnyTsVariableAnnotation, JsAssignmentExpression, JsInitializerClause, JsLiteralMemberName,
JsObjectAssignmentPattern, JsObjectAssignmentPatternProperty, JsObjectBindingPattern,
JsPropertyClassMember, JsPropertyClassMemberFields, JsPropertyObjectMember, JsSyntaxKind,
JsVariableDeclarator, TsIdentifierBinding, TsInitializedPropertySignatureClassMember,
TsInitializedPropertySignatureClassMemberFields, TsPropertySignatureClassMember,
TsPropertySignatureClassMemberFields, TsTypeAliasDeclaration, TsTypeArguments,
};
use rome_rowan::{declare_node_union, AstNode, SyntaxNodeOptionExt, SyntaxResult};
use std::iter;
declare_node_union! {
pub(crate) AnyJsAssignmentLike =
JsPropertyObjectMember |
JsAssignmentExpression |
JsObjectAssignmentPatternProperty |
JsVariableDeclarator |
TsTypeAliasDeclaration |
JsPropertyClassMember |
TsPropertySignatureClassMember |
TsInitializedPropertySignatureClassMember
}
declare_node_union! {
pub(crate) LeftAssignmentLike =
AnyJsAssignmentPattern |
AnyJsObjectMemberName |
AnyJsBindingPattern |
TsIdentifierBinding |
JsLiteralMemberName |
AnyJsClassMemberName
}
declare_node_union! {
pub(crate) RightAssignmentLike = AnyJsExpression | AnyJsAssignmentPattern | JsInitializerClause | AnyTsType
}
declare_node_union! {
/// This is a convenient enum to map object patterns.
pub(crate) AnyObjectPattern = JsObjectAssignmentPattern | JsObjectBindingPattern
}
impl AnyObjectPattern {
/// Determines if this is a complex pattern. A pattern is considered complex if it has more than 2 properties
/// and any property:
///
/// * is a shorthand property with an initializer
/// * is a non-shorthand property
///
/// ## Examples
///
/// ```javascript
/// let { a, b, c = "test"} = ...
/// ```
///
/// Is considered a complex binding because it has three properties and a shorthand property with an initializer.
///
/// ```javascript
/// let { a, b, c: d } = ...
/// ```
///
/// Is considered a complex binding because it has three properties and a non-shorthand property
///
fn is_complex(&self) -> bool {
match self {
AnyObjectPattern::JsObjectAssignmentPattern(assignment_pattern) => {
use AnyJsObjectAssignmentPatternMember::*;
if assignment_pattern.properties().len() <= 2 {
return false;
}
assignment_pattern
.properties()
.iter()
.flatten()
.any(|property| match property {
JsObjectAssignmentPatternProperty(_) => true,
JsObjectAssignmentPatternShorthandProperty(short) => short.init().is_some(),
_ => false,
})
}
AnyObjectPattern::JsObjectBindingPattern(binding_pattern) => {
use AnyJsObjectBindingPatternMember::*;
if binding_pattern.properties().len() <= 2 {
return false;
}
binding_pattern
.properties()
.iter()
.flatten()
.any(|property| match property {
JsObjectBindingPatternProperty(_) => true,
JsObjectBindingPatternShorthandProperty(member) => member.init().is_some(),
_ => false,
})
}
}
}
}
impl LeftAssignmentLike {
fn into_object_pattern(self) -> Option<AnyObjectPattern> {
use AnyJsAssignmentPattern::*;
use AnyJsBindingPattern::*;
match self {
LeftAssignmentLike::AnyJsAssignmentPattern(JsObjectAssignmentPattern(node)) => {
Some(AnyObjectPattern::from(node))
}
LeftAssignmentLike::AnyJsBindingPattern(JsObjectBindingPattern(node)) => {
Some(AnyObjectPattern::from(node))
}
_ => None,
}
}
}
/// [Prettier applies]: https://github.com/prettier/prettier/blob/fde0b49d7866e203ca748c306808a87b7c15548f/src/language-js/print/assignment.js#L278
pub(crate) fn is_complex_type_annotation(
annotation: AnyTsVariableAnnotation,
) -> SyntaxResult<bool> {
let is_complex = annotation
.type_annotation()?
.and_then(|type_annotation| type_annotation.ty().ok())
.and_then(|ty| match ty {
AnyTsType::TsReferenceType(reference_type) => {
let type_arguments = reference_type.type_arguments()?;
let argument_list_len = type_arguments.ts_type_argument_list().len();
if argument_list_len <= 1 {
return Some(false);
}
let has_at_least_a_complex_type = type_arguments
.ts_type_argument_list()
.iter()
.flat_map(|p| p.ok())
.any(|argument| {
if matches!(argument, AnyTsType::TsConditionalType(_)) {
return true;
}
let is_complex_type = argument
.as_ts_reference_type()
.and_then(|reference_type| reference_type.type_arguments())
.map_or(false, |type_arguments| {
type_arguments.ts_type_argument_list().len() > 0
});
is_complex_type
});
Some(has_at_least_a_complex_type)
}
_ => Some(false),
})
.unwrap_or(false);
Ok(is_complex)
}
impl RightAssignmentLike {
fn as_expression(&self) -> Option<AnyJsExpression> {
match self {
RightAssignmentLike::AnyJsExpression(expression) => Some(expression.clone()),
RightAssignmentLike::JsInitializerClause(initializer) => initializer.expression().ok(),
RightAssignmentLike::AnyJsAssignmentPattern(_) => None,
RightAssignmentLike::AnyTsType(_) => None,
}
}
}
impl Format<JsFormatContext> for RightAssignmentLike {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
match self {
RightAssignmentLike::AnyJsExpression(expression) => {
write!(f, [expression.format()])
}
RightAssignmentLike::AnyJsAssignmentPattern(assignment) => {
write!(f, [assignment.format()])
}
RightAssignmentLike::JsInitializerClause(initializer) => {
write!(f, [space(), initializer.format()])
}
RightAssignmentLike::AnyTsType(ty) => {
write!(f, [space(), ty.format()])
}
}
}
}
/// Determines how a assignment like be formatted
///
/// Assignment like are:
/// - Assignment
/// - Object property member
/// - Variable declaration
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum AssignmentLikeLayout {
/// This is a special layout usually used for variable declarations.
/// This layout is hit, usually, when a [variable declarator](JsVariableDeclarator) doesn't have initializer:
/// ```js
/// let variable;
/// ```
/// ```ts
/// let variable: Map<string, number>;
/// ```
OnlyLeft,
/// First break right-hand side, then after operator.
/// ```js
/// {
/// "array-key": [
/// {
/// "nested-key-1": 1,
/// "nested-key-2": 2,
/// },
/// ]
/// }
/// ```
Fluid,
/// First break after operator, then the sides are broken independently on their own lines.
/// There is a soft line break after operator token.
/// ```js
/// {
/// "enough-long-key-to-break-line":
/// 1 + 2,
/// "not-long-enough-key":
/// "but long enough string to break line",
/// }
/// ```
BreakAfterOperator,
/// First break right-hand side, then left-hand side. There are not any soft line breaks
/// between left and right parts
/// ```js
/// {
/// key1: "123",
/// key2: 123,
/// key3: class MyClass {
/// constructor() {},
/// },
/// }
/// ```
NeverBreakAfterOperator,
/// This is a special layout usually used for long variable declarations or assignment expressions
/// This layout is hit, usually, when we are in the "middle" of the chain:
///
/// ```js
/// var a =
/// loreum =
/// ipsum =
/// "foo";
/// ```
///
/// Given the previous snippet, then `loreum` and `ipsum` will be formatted using the [Chain] layout.
Chain,
/// This is a special layout usually used for long variable declarations or assignment expressions
/// This layout is hit, usually, when we are in the end of a chain:
/// ```js
/// var a = loreum = ipsum = "foo";
/// ```
///
/// Given the previous snippet, then `"foo"` formatted using the [ChainTail] layout.
ChainTail,
/// This layout is used in cases where we want to "break" the left hand side
/// of assignment like expression, but only when the group decides to do it.
///
/// ```js
/// const a {
/// loreum: { ipsum },
/// something_else,
/// happy_days: { fonzy }
/// } = obj;
/// ```
///
/// The snippet triggers the layout because the left hand side contains a "complex destructuring"
/// which requires having the properties broke on different lines.
BreakLeftHandSide,
/// This is a special case of the "chain" layout collection. This is triggered when there's
/// a series of simple assignments (at least three) and in the middle we have an arrow function
/// and this function followed by two more arrow functions.
///
/// This layout will break the right hand side of the tail on a new line and add a new level
/// of indentation
///
/// ```js
/// lorem =
/// fff =
/// ee =
/// () => (fff) => () => (fefef) => () => fff;
/// ```
ChainTailArrowFunction,
/// Layout used when the operator and right hand side are part of a `JsInitializerClause<
/// that has a suppression comment.
SuppressedInitializer,
}
const MIN_OVERLAP_FOR_BREAK: u8 = 3;
impl AnyJsAssignmentLike {
fn right(&self) -> SyntaxResult<RightAssignmentLike> {
let right = match self {
AnyJsAssignmentLike::JsPropertyObjectMember(property) => property.value()?.into(),
AnyJsAssignmentLike::JsAssignmentExpression(assignment) => assignment.right()?.into(),
AnyJsAssignmentLike::JsObjectAssignmentPatternProperty(assignment_pattern) => {
assignment_pattern.pattern()?.into()
}
AnyJsAssignmentLike::JsVariableDeclarator(variable_declarator) => {
// SAFETY: Calling `unwrap` here is safe because we check `has_only_left_hand_side` variant at the beginning of the `layout` function
variable_declarator.initializer().unwrap().into()
}
AnyJsAssignmentLike::TsTypeAliasDeclaration(type_alias_declaration) => {
type_alias_declaration.ty()?.into()
}
AnyJsAssignmentLike::JsPropertyClassMember(n) => {
// SAFETY: Calling `unwrap` here is safe because we check `has_only_left_hand_side` variant at the beginning of the `layout` function
n.value().unwrap().into()
}
AnyJsAssignmentLike::TsPropertySignatureClassMember(_) => {
unreachable!("TsPropertySignatureClassMember doesn't have any right side. If you're here, `has_only_left_hand_side` hasn't been called")
}
AnyJsAssignmentLike::TsInitializedPropertySignatureClassMember(n) => {
// SAFETY: Calling `unwrap` here is safe because we check `has_only_left_hand_side` variant at the beginning of the `layout` function
n.value().unwrap().into()
}
};
Ok(right)
}
fn left(&self) -> SyntaxResult<LeftAssignmentLike> {
match self {
AnyJsAssignmentLike::JsPropertyObjectMember(property) => Ok(property.name()?.into()),
AnyJsAssignmentLike::JsAssignmentExpression(assignment) => {
Ok(assignment.left()?.into())
}
AnyJsAssignmentLike::JsObjectAssignmentPatternProperty(property) => {
Ok(property.pattern()?.into())
}
AnyJsAssignmentLike::JsVariableDeclarator(variable_declarator) => {
Ok(variable_declarator.id()?.into())
}
AnyJsAssignmentLike::TsTypeAliasDeclaration(type_alias_declaration) => {
Ok(type_alias_declaration.binding_identifier()?.into())
}
AnyJsAssignmentLike::JsPropertyClassMember(property_class_member) => {
Ok(property_class_member.name()?.into())
}
AnyJsAssignmentLike::TsPropertySignatureClassMember(
property_signature_class_member,
) => Ok(property_signature_class_member.name()?.into()),
AnyJsAssignmentLike::TsInitializedPropertySignatureClassMember(
property_signature_class_member,
) => Ok(property_signature_class_member.name()?.into()),
}
}
fn annotation(&self) -> Option<AnyTsVariableAnnotation> {
match self {
AnyJsAssignmentLike::JsVariableDeclarator(variable_declarator) => {
variable_declarator.variable_annotation()
}
_ => None,
}
}
fn write_left(&self, f: &mut JsFormatter) -> FormatResult<bool> {
match self {
AnyJsAssignmentLike::JsPropertyObjectMember(property) => {
let name = property.name()?;
// It's safe to mark the name as checked here because it is at the beginning of the property
// and any suppression comment that would apply to the name applies to the property too and is,
// thus, handled on the property level.
f.context()
.comments()
.mark_suppression_checked(name.syntax());
let width = write_member_name(&name.into(), f)?;
let text_width_for_break =
(u8::from(f.options().tab_width()) + MIN_OVERLAP_FOR_BREAK) as usize;
Ok(width < text_width_for_break)
}
AnyJsAssignmentLike::JsAssignmentExpression(assignment) => {
let left = assignment.left()?;
write!(f, [&left.format()])?;
Ok(false)
}
AnyJsAssignmentLike::JsObjectAssignmentPatternProperty(property) => {
let member_name = property.member()?;
// It's safe to mark the name as checked here because it is at the beginning of the property
// and any suppression comment that would apply to the name applies to the property too and is,
// thus, handled on the property level.
f.context()
.comments()
.mark_suppression_checked(member_name.syntax());
let width = write_member_name(&member_name.into(), f)?;
let text_width_for_break =
(u8::from(f.options().tab_width()) + MIN_OVERLAP_FOR_BREAK) as usize;
Ok(width < text_width_for_break)
}
AnyJsAssignmentLike::JsVariableDeclarator(variable_declarator) => {
let id = variable_declarator.id()?;
let variable_annotation = variable_declarator.variable_annotation();
write!(f, [id.format(), variable_annotation.format()])?;
Ok(false)
}
AnyJsAssignmentLike::TsTypeAliasDeclaration(type_alias_declaration) => {
let binding_identifier = type_alias_declaration.binding_identifier()?;
let type_parameters = type_alias_declaration.type_parameters();
write!(f, [binding_identifier.format()])?;
if let Some(type_parameters) = type_parameters {
write!(f, [type_parameters.format(),])?;
}
Ok(false)
}
AnyJsAssignmentLike::JsPropertyClassMember(property_class_member) => {
let JsPropertyClassMemberFields {
modifiers,
name,
property_annotation,
value: _,
semicolon_token: _,
} = property_class_member.as_fields();
write!(f, [modifiers.format(), space()])?;
let name = name?;
if f.context().comments().is_suppressed(name.syntax()) {
write!(f, [format_suppressed_node(name.syntax())])?;
} else {
write_member_name(&name.into(), f)?;
};
write!(f, [property_annotation.format()])?;
Ok(false)
}
AnyJsAssignmentLike::TsPropertySignatureClassMember(
property_signature_class_member,
) => {
let TsPropertySignatureClassMemberFields {
modifiers,
name,
property_annotation,
semicolon_token: _,
} = property_signature_class_member.as_fields();
write!(f, [modifiers.format(), space(),])?;
let width = write_member_name(&name?.into(), f)?;
write!(f, [property_annotation.format()])?;
let text_width_for_break =
(u8::from(f.options().tab_width()) + MIN_OVERLAP_FOR_BREAK) as usize;
Ok(width < text_width_for_break)
}
AnyJsAssignmentLike::TsInitializedPropertySignatureClassMember(
property_signature_class_member,
) => {
let TsInitializedPropertySignatureClassMemberFields {
modifiers,
name,
question_mark_token,
value: _,
semicolon_token: _,
} = property_signature_class_member.as_fields();
write!(f, [modifiers.format(), space(),])?;
let width = write_member_name(&name?.into(), f)?;
write!(f, [question_mark_token.format()])?;
let text_width_for_break =
(u8::from(f.options().tab_width()) + MIN_OVERLAP_FOR_BREAK) as usize;
Ok(width < text_width_for_break)
}
}
}
fn write_operator(&self, f: &mut JsFormatter) -> FormatResult<()> {
match self {
AnyJsAssignmentLike::JsPropertyObjectMember(property) => {
let colon_token = property.colon_token()?;
write!(f, [colon_token.format()])
}
AnyJsAssignmentLike::JsAssignmentExpression(assignment) => {
let operator_token = assignment.operator_token()?;
write!(f, [space(), operator_token.format()])
}
AnyJsAssignmentLike::JsObjectAssignmentPatternProperty(property) => {
let colon_token = property.colon_token()?;
write!(f, [colon_token.format()])
}
AnyJsAssignmentLike::JsVariableDeclarator(variable_declarator) => {
if let Some(initializer) = variable_declarator.initializer() {
let eq_token = initializer.eq_token()?;
write!(f, [space(), eq_token.format()])?
}
Ok(())
}
AnyJsAssignmentLike::TsTypeAliasDeclaration(type_alias_declaration) => {
let eq_token = type_alias_declaration.eq_token()?;
write!(f, [space(), eq_token.format()])
}
AnyJsAssignmentLike::JsPropertyClassMember(property_class_member) => {
if let Some(initializer) = property_class_member.value() {
let eq_token = initializer.eq_token()?;
write!(f, [space(), eq_token.format()])?
}
Ok(())
}
// this variant doesn't have any operator
AnyJsAssignmentLike::TsPropertySignatureClassMember(_) => Ok(()),
AnyJsAssignmentLike::TsInitializedPropertySignatureClassMember(
property_class_member,
) => {
let initializer = property_class_member.value()?;
let eq_token = initializer.eq_token()?;
write!(f, [space(), eq_token.format()])
}
}
}
fn write_right(&self, f: &mut JsFormatter, layout: AssignmentLikeLayout) -> FormatResult<()> {
match self {
AnyJsAssignmentLike::JsPropertyObjectMember(property) => {
let value = property.value()?;
write!(f, [with_assignment_layout(&value, Some(layout))])
}
AnyJsAssignmentLike::JsAssignmentExpression(assignment) => {
let right = assignment.right()?;
write!(f, [space(), with_assignment_layout(&right, Some(layout))])
}
AnyJsAssignmentLike::JsObjectAssignmentPatternProperty(property) => {
let pattern = property.pattern()?;
let init = property.init();
write!(f, [pattern.format()])?;
if let Some(init) = init {
write!(
f,
[
space(),
init.format()
.with_options(FormatJsInitializerClauseOptions {
assignment_layout: Some(layout)
})
]
)?;
}
Ok(())
}
AnyJsAssignmentLike::JsVariableDeclarator(variable_declarator) => {
if let Some(initializer) = variable_declarator.initializer() {
let expression = initializer.expression()?;
write!(
f,
[
space(),
format_leading_comments(initializer.syntax()),
with_assignment_layout(&expression, Some(layout)),
format_trailing_comments(initializer.syntax())
]
)?;
}
Ok(())
}
AnyJsAssignmentLike::TsTypeAliasDeclaration(type_alias_declaration) => {
let ty = type_alias_declaration.ty()?;
write!(f, [space(), ty.format()])
}
AnyJsAssignmentLike::JsPropertyClassMember(property_class_member) => {
if let Some(initializer) = property_class_member.value() {
let expression = initializer.expression()?;
write!(
f,
[
space(),
format_leading_comments(initializer.syntax()),
with_assignment_layout(&expression, Some(layout)),
format_trailing_comments(initializer.syntax())
]
)?;
}
Ok(())
}
// this variant doesn't have any right part
AnyJsAssignmentLike::TsPropertySignatureClassMember(_) => Ok(()),
AnyJsAssignmentLike::TsInitializedPropertySignatureClassMember(
property_class_member,
) => {
let initializer = property_class_member.value()?;
let expression = initializer.expression()?;
write!(
f,
[
space(),
format_leading_comments(initializer.syntax()),
with_assignment_layout(&expression, Some(layout)),
format_trailing_comments(initializer.syntax())
]
)
}
}
}
fn write_suppressed_initializer(&self, f: &mut JsFormatter) -> FormatResult<()> {
let initializer = match self {
AnyJsAssignmentLike::JsPropertyClassMember(class_member) => class_member.value(),
AnyJsAssignmentLike::TsInitializedPropertySignatureClassMember(class_member) => {
Some(class_member.value()?)
}
AnyJsAssignmentLike::JsVariableDeclarator(variable_declarator) => {
variable_declarator.initializer()
}
AnyJsAssignmentLike::JsPropertyObjectMember(_)
| AnyJsAssignmentLike::JsAssignmentExpression(_)
| AnyJsAssignmentLike::JsObjectAssignmentPatternProperty(_)
| AnyJsAssignmentLike::TsTypeAliasDeclaration(_)
| AnyJsAssignmentLike::TsPropertySignatureClassMember(_) => {
unreachable!("These variants have no initializer")
}
};
let initializer =
initializer.expect("Expected an initializer because it has a suppression comment");
write!(f, [soft_line_indent_or_space(&initializer.format())])
}
/// Returns the layout variant for an assignment like depending on right expression and left part length
/// [Prettier applies]: https://github.com/prettier/prettier/blob/main/src/language-js/print/assignment.js
fn layout(
&self,
is_left_short: bool,
f: &mut Formatter<JsFormatContext>,
) -> FormatResult<AssignmentLikeLayout> {
if self.has_only_left_hand_side() {
return Ok(AssignmentLikeLayout::OnlyLeft);
}
let right = self.right()?;
if let RightAssignmentLike::JsInitializerClause(initializer) = &right {
if f.context().comments().is_suppressed(initializer.syntax()) {
return Ok(AssignmentLikeLayout::SuppressedInitializer);
}
}
let right_expression = right.as_expression();
if let Some(layout) = self.chain_formatting_layout(right_expression.as_ref())? {
return Ok(layout);
}
if let Some(AnyJsExpression::JsCallExpression(call_expression)) = &right_expression {
if call_expression.callee()?.syntax().text() == "require" {
return Ok(AssignmentLikeLayout::NeverBreakAfterOperator);
}
}
if self.should_break_left_hand_side()? {
return Ok(AssignmentLikeLayout::BreakLeftHandSide);
}
if self.should_break_after_operator(&right, f.context().comments())? {
return Ok(AssignmentLikeLayout::BreakAfterOperator);
}
if is_left_short {
return Ok(AssignmentLikeLayout::NeverBreakAfterOperator);
}
// Before checking `BreakAfterOperator` layout, we need to unwrap the right expression from `JsUnaryExpression` or `TsNonNullAssertionExpression`
// [Prettier applies]: https://github.com/prettier/prettier/blob/a043ac0d733c4d53f980aa73807a63fc914f23bd/src/language-js/print/assignment.js#L199-L211
// Example:
// !"123" -> "123"
// void "123" -> "123"
// !!"string"! -> "string"
let right_expression = iter::successors(right_expression, |expression| match expression {
AnyJsExpression::JsUnaryExpression(unary) => unary.argument().ok(),
AnyJsExpression::TsNonNullAssertionExpression(assertion) => assertion.expression().ok(),
_ => None,
})
.last();
if matches!(
right_expression,
Some(AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsStringLiteralExpression(_)
)),
) {
return Ok(AssignmentLikeLayout::BreakAfterOperator);
}
let is_poorly_breakable = match &right_expression {
Some(expression) => is_poorly_breakable_member_or_call_chain(expression, f)?,
None => false,
};
if is_poorly_breakable {
return Ok(AssignmentLikeLayout::BreakAfterOperator);
}
if matches!(
right_expression,
Some(
AnyJsExpression::JsClassExpression(_)
| AnyJsExpression::JsTemplateExpression(_)
| AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsBooleanLiteralExpression(_),
)
| AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsNumberLiteralExpression(_)
)
)
) {
return Ok(AssignmentLikeLayout::NeverBreakAfterOperator);
}
Ok(AssignmentLikeLayout::Fluid)
}
/// Checks that a [JsAnyAssignmentLike] consists only of the left part
/// usually, when a [variable declarator](JsVariableDeclarator) doesn't have initializer
fn has_only_left_hand_side(&self) -> bool {
if let AnyJsAssignmentLike::JsVariableDeclarator(declarator) = self {
declarator.initializer().is_none()
} else if let AnyJsAssignmentLike::JsPropertyClassMember(class_member) = self {
class_member.value().is_none()
} else {
matches!(self, AnyJsAssignmentLike::TsPropertySignatureClassMember(_))
}
}
/// Checks if the right node is entitled of the chain formatting,
/// and if so, it return the layout type
fn chain_formatting_layout(
&self,
right_expression: Option<&AnyJsExpression>,
) -> SyntaxResult<Option<AssignmentLikeLayout>> {
let right_is_tail = !matches!(
right_expression,
Some(AnyJsExpression::JsAssignmentExpression(_))
);
// The chain goes up two levels, by checking up to the great parent if all the conditions
// are correctly met.
let upper_chain_is_eligible =
// First, we check if the current node is an assignment expression
if let AnyJsAssignmentLike::JsAssignmentExpression(assignment) = self {
assignment.syntax().parent().map_or(false, |parent| {
// Then we check if the parent is assignment expression or variable declarator
if matches!(
parent.kind(),
JsSyntaxKind::JS_ASSIGNMENT_EXPRESSION
| JsSyntaxKind::JS_INITIALIZER_CLAUSE
) {
let great_parent_kind = parent.parent().kind();
// Finally, we check the great parent.
// The great parent triggers the eligibility when
// - the current node that we were inspecting is not a "tail"
// - or the great parent is not an expression statement or a variable declarator
!right_is_tail
|| !matches!(
great_parent_kind,
Some(
JsSyntaxKind::JS_EXPRESSION_STATEMENT
| JsSyntaxKind::JS_VARIABLE_DECLARATOR
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/object_like.rs | crates/rome_js_formatter/src/utils/object_like.rs | use crate::prelude::*;
use crate::JsFormatContext;
use rome_formatter::write;
use rome_formatter::{Format, FormatResult};
use rome_js_syntax::{JsObjectExpression, JsSyntaxToken, TsObjectType};
use rome_rowan::{declare_node_union, AstNode, AstNodeList, AstSeparatedList, SyntaxResult};
declare_node_union! {
pub (crate) JsObjectLike = JsObjectExpression | TsObjectType
}
impl JsObjectLike {
fn l_curly_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
JsObjectLike::JsObjectExpression(oe) => oe.l_curly_token(),
JsObjectLike::TsObjectType(ot) => ot.l_curly_token(),
}
}
fn r_curly_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
JsObjectLike::JsObjectExpression(oe) => oe.r_curly_token(),
JsObjectLike::TsObjectType(ot) => ot.r_curly_token(),
}
}
fn members_have_leading_newline(&self) -> bool {
match self {
JsObjectLike::JsObjectExpression(oe) => oe.members().syntax().has_leading_newline(),
JsObjectLike::TsObjectType(ot) => ot.members().syntax().has_leading_newline(),
}
}
fn members_are_empty(&self) -> bool {
match self {
JsObjectLike::JsObjectExpression(oe) => oe.members().is_empty(),
JsObjectLike::TsObjectType(ot) => ot.members().is_empty(),
}
}
fn write_members(&self, f: &mut JsFormatter) -> FormatResult<()> {
match self {
JsObjectLike::JsObjectExpression(oe) => {
write!(f, [oe.members().format()])
}
JsObjectLike::TsObjectType(ot) => {
write!(f, [ot.members().format()])
}
}
}
}
impl Format<JsFormatContext> for JsObjectLike {
fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> {
let members = format_with(|f| self.write_members(f));
write!(f, [self.l_curly_token().format(),])?;
if self.members_are_empty() {
write!(
f,
[format_dangling_comments(self.syntax()).with_block_indent(),]
)?;
} else {
let should_expand = self.members_have_leading_newline();
write!(
f,
[group(&soft_space_or_block_indent(&members)).should_expand(should_expand)]
)?;
}
write!(f, [self.r_curly_token().format()])
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/test_each_template.rs | crates/rome_js_formatter/src/utils/test_each_template.rs | use crate::js::auxiliary::template_element::TemplateElementOptions;
use crate::js::lists::template_element_list::{TemplateElementIndention, TemplateElementLayout};
use crate::prelude::*;
use rome_formatter::printer::Printer;
use rome_formatter::{
format_args, write, CstFormatContext, FormatOptions, RemoveSoftLinesBuffer, VecBuffer,
};
use rome_js_syntax::{AnyJsTemplateElement, JsTemplateElementList};
use rome_text_size::{TextRange, TextSize};
use std::cmp;
use unicode_width::UnicodeWidthStr;
#[derive(Debug)]
enum EachTemplateElement {
/// A significant value in the test each table. It's a row element.
Column(EachTemplateColumn),
/// Indicates the end of the current row.
LineBreak,
}
/// Row element containing the column information.
#[derive(Debug)]
struct EachTemplateColumn {
/// Formatted text of the column.
text: String,
/// Formatted text width.
width: TextSize,
/// Corresponding range for the text to replace it.
range: TextRange,
/// Indicates the line break in the text.
will_break: bool,
}
impl EachTemplateColumn {
fn new(text: String, range: TextRange, will_break: bool) -> Self {
let width = TextSize::try_from(text.width())
.expect("integer overflow while converting a text width to `TextSize`");
EachTemplateColumn {
text,
width,
range,
will_break,
}
}
}
struct EachTemplateTableBuilder {
/// Holds information about the current row.
current_row: EachTemplateCurrentRow,
/// Information about all rows.
rows: Vec<EachTemplateRow>,
/// Contains the maximum length of each column of all rows.
columns_width: Vec<TextSize>,
/// Elements for formatting.
elements: Vec<EachTemplateElement>,
}
impl EachTemplateTableBuilder {
fn new() -> Self {
EachTemplateTableBuilder {
current_row: EachTemplateCurrentRow::new(),
rows: Vec::new(),
columns_width: Vec::new(),
elements: Vec::new(),
}
}
/// Adds a new item to the buffer.
fn entry(&mut self, element: EachTemplateElement) {
match &element {
EachTemplateElement::Column(column) => {
if column.will_break {
self.current_row.has_line_break_column = true;
}
// if there was no column with a line break, then add width of the current column to the buffer
if !self.current_row.has_line_break_column {
self.current_row.column_widths.push(column.width);
}
}
EachTemplateElement::LineBreak => {
self.next_row();
}
}
self.elements.push(element);
}
/// Advance the table state to a new row.
/// Merge the current row columns width with the table ones if row doesn't contain a line break column.
fn next_row(&mut self) {
if !self.current_row.has_line_break_column {
let table_column_width_iter = self.columns_width.iter_mut();
let mut row_column_width_iter = self.current_row.column_widths.iter();
// find the maximum length between the table and the current row
for table_column_width in table_column_width_iter {
let row_column_width = match row_column_width_iter.next() {
Some(width) => width,
_ => break,
};
*table_column_width = cmp::max(*table_column_width, *row_column_width);
}
// add the remaining items to the buffer
self.columns_width.extend(row_column_width_iter);
}
// save information about the row to buffer
self.rows.push(EachTemplateRow {
has_line_break_column: self.current_row.has_line_break_column,
});
self.current_row.reset();
}
fn finish(mut self) -> EachTemplateTable {
self.next_row();
EachTemplateTable {
rows: self.rows,
columns_width: self.columns_width,
elements: self.elements,
}
}
}
#[derive(Debug)]
pub(crate) struct EachTemplateTable {
/// Information about all rows.
rows: Vec<EachTemplateRow>,
/// Contains the maximum length of each column of all rows.
columns_width: Vec<TextSize>,
/// Elements for formatting.
elements: Vec<EachTemplateElement>,
}
#[derive(Debug)]
struct EachTemplateCurrentRow {
/// Contains the maximum length of the current column.
column_widths: Vec<TextSize>,
/// Whether the current row contains a column with a line break.
has_line_break_column: bool,
}
impl EachTemplateCurrentRow {
fn new() -> Self {
EachTemplateCurrentRow {
column_widths: Vec::new(),
has_line_break_column: false,
}
}
/// Reset the state of the current row when moving to the next line.
fn reset(&mut self) {
self.column_widths.clear();
self.has_line_break_column = false;
}
}
#[derive(Debug)]
struct EachTemplateRow {
/// Whether the current row contains a column with a line break.
has_line_break_column: bool,
}
/// Separator between columns in a row.
struct EachTemplateSeparator;
impl Format<JsFormatContext> for EachTemplateSeparator {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
write!(f, [text("|")])
}
}
impl EachTemplateTable {
pub(crate) fn from(list: &JsTemplateElementList, f: &mut JsFormatter) -> FormatResult<Self> {
let mut iter = list.into_iter().peekable();
let mut builder = EachTemplateTableBuilder::new();
// the table must have a header
// e.g. a | b | expected
let header = match iter.next() {
Some(AnyJsTemplateElement::JsTemplateChunkElement(header)) => header,
// we check this case in `is_test_each_pattern` and `is_test_each_pattern_elements` functions
_ => return Err(FormatError::SyntaxError),
};
// It's safe to mark the header as checked here because we check that node doesn't have any trivia
// when we call `is_test_each_pattern`
f.context()
.comments()
.mark_suppression_checked(header.syntax());
write!(f, [format_removed(&header.template_chunk_token()?)])?;
let header = header.template_chunk_token()?;
// split the header to get columns
for column in header.text_trimmed().split_terminator('|') {
let text = column.trim().to_string();
let range = header.text_range();
let column = EachTemplateColumn::new(text, range, false);
builder.entry(EachTemplateElement::Column(column));
}
builder.entry(EachTemplateElement::LineBreak);
while let Some(element) = iter.next() {
match element {
AnyJsTemplateElement::JsTemplateChunkElement(element) => {
// It's safe to mark the element as checked here because we check that node doesn't have any trivia
// when we call `is_test_each_pattern`
f.context()
.comments()
.mark_suppression_checked(element.syntax());
write!(f, [format_removed(&element.template_chunk_token()?)])?;
let has_line_break = element
.template_chunk_token()?
.text_trimmed()
.contains('\n');
let is_last = iter.peek().is_none();
// go to the next line if the current element contains a line break
if has_line_break && !is_last {
builder.entry(EachTemplateElement::LineBreak);
}
}
AnyJsTemplateElement::JsTemplateElement(element) => {
let mut vec_buffer = VecBuffer::new(f.state_mut());
// The softline buffer replaces all softline breaks with a space or removes it entirely
// to "mimic" an infinite print width
let mut buffer = RemoveSoftLinesBuffer::new(&mut vec_buffer);
let mut recording = buffer.start_recording();
let options = TemplateElementOptions {
after_new_line: false,
indention: TemplateElementIndention::default(),
layout: TemplateElementLayout::Fit,
};
// print the current column with infinite print width
write!(recording, [element.format().with_options(options)])?;
let recorded = recording.stop();
// whether there was a line break when formatting the column
let will_break = recorded.will_break();
let root = Document::from(vec_buffer.into_vec());
let range = element.range();
let print_options = f.options().as_print_options();
let printed = Printer::new(print_options).print(&root)?;
let text = printed.into_code();
let column = EachTemplateColumn::new(text, range, will_break);
builder.entry(EachTemplateElement::Column(column));
}
}
}
let each_table = builder.finish();
Ok(each_table)
}
}
impl Format<JsFormatContext> for EachTemplateTable {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
let table_content = format_with(|f| {
let mut current_column: usize = 0;
let mut current_row: usize = 0;
let mut iter = self.elements.iter().peekable();
write!(f, [hard_line_break()])?;
while let Some(element) = iter.next() {
let next_item = iter.peek();
let is_last = next_item.is_none();
let is_last_in_row =
matches!(next_item, Some(EachTemplateElement::LineBreak)) || is_last;
match element {
EachTemplateElement::Column(column) => {
let mut text = column.text.to_string();
if current_column != 0 && (!is_last_in_row || !text.is_empty()) {
text = std::format!(" {text}");
}
// align the column based on the maximum column width in the table
if !is_last_in_row {
if !self.rows[current_row].has_line_break_column {
let column_width = self
.columns_width
.get(current_column)
.copied()
.unwrap_or_default();
let padding = " ".repeat(
column_width
.checked_sub(column.width)
.unwrap_or_default()
.into(),
);
text.push_str(&padding);
}
text.push(' ');
}
write!(f, [dynamic_text(&text, column.range.start())])?;
if !is_last_in_row {
write!(f, [EachTemplateSeparator])?;
}
current_column += 1;
}
EachTemplateElement::LineBreak => {
current_column = 0;
current_row += 1;
if !is_last {
write!(f, [hard_line_break()])?;
}
}
}
}
Ok(())
});
write!(f, [indent(&format_args!(table_content)), hard_line_break()])
}
}
| 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.