1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
//! Infrastructure for code formatting
//!
//! This module defines [FormatElement], an IR to format code documents and provides a mean to print
//! such a document to a string. Objects that know how to format themselves implement the [Format] trait.
//!
//! ## Formatting Traits
//!
//! * [Format]: Implemented by objects that can be formatted.
//! * [FormatRule]: Rule that knows how to format an object of another type. Necessary in the situation where
//! it's necessary to implement [Format] on an object from another crate. This module defines the
//! [FormatRefWithRule] and [FormatOwnedWithRule] structs to pass an item with its corresponding rule.
//! * [FormatWithRule] implemented by objects that know how to format another type. Useful for implementing
//! some reusable formatting logic inside of this module if the type itself doesn't implement [Format]
//!
//! ## Formatting Macros
//!
//! This crate defines two macros to construct the IR. These are inspired by Rust's `fmt` macros
//! * [`format!`]: Formats a formatable object
//! * [`format_args!`]: Concatenates a sequence of Format objects.
//! * [`write!`]: Writes a sequence of formatable objects into an output buffer.
#![deny(rustdoc::broken_intra_doc_links)]
mod arguments;
mod buffer;
mod builders;
pub mod comments;
pub mod diagnostics;
pub mod format_element;
mod format_extensions;
pub mod formatter;
pub mod group_id;
pub mod macros;
pub mod prelude;
#[cfg(debug_assertions)]
pub mod printed_tokens;
pub mod printer;
pub mod separated;
mod source_map;
pub mod token;
pub mod trivia;
mod verbatim;
use crate::formatter::Formatter;
use crate::group_id::UniqueGroupIdBuilder;
use crate::prelude::TagKind;
use std::fmt::Debug;
use crate::builders::syntax_token_cow_slice;
use crate::comments::{CommentStyle, Comments, SourceComment};
pub use crate::diagnostics::{ActualStart, FormatError, InvalidDocumentError, PrintError};
use crate::format_element::document::Document;
#[cfg(debug_assertions)]
use crate::printed_tokens::PrintedTokens;
use crate::printer::{Printer, PrinterOptions};
use crate::trivia::{format_skipped_token_trivia, format_trimmed_token};
pub use arguments::{Argument, Arguments};
use biome_deserialize::{
Deserializable, DeserializableValue, DeserializationDiagnostic, TextNumber,
};
use biome_deserialize_macros::Deserializable;
use biome_deserialize_macros::Merge;
use biome_rowan::{
Language, NodeOrToken, SyntaxElement, SyntaxNode, SyntaxResult, SyntaxToken, SyntaxTriviaPiece,
TextLen, TextRange, TextSize, TokenAtOffset,
};
pub use buffer::{
Buffer, BufferExtensions, BufferSnapshot, Inspect, PreambleBuffer, RemoveSoftLinesBuffer,
VecBuffer,
};
pub use builders::BestFitting;
pub use format_element::{normalize_newlines, FormatElement, LINE_TERMINATORS};
pub use group_id::GroupId;
pub use source_map::{TransformSourceMap, TransformSourceMapBuilder};
use std::marker::PhantomData;
use std::num::ParseIntError;
use std::str::FromStr;
use token::string::Quote;
#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)
)]
#[derive(Default)]
pub enum IndentStyle {
/// Tab
#[default]
Tab,
/// Space
Space,
}
impl IndentStyle {
pub const DEFAULT_SPACES: u8 = 2;
/// Returns `true` if this is an [IndentStyle::Tab].
pub const fn is_tab(&self) -> bool {
matches!(self, IndentStyle::Tab)
}
/// Returns `true` if this is an [IndentStyle::Space].
pub const fn is_space(&self) -> bool {
matches!(self, IndentStyle::Space)
}
}
impl FromStr for IndentStyle {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"tab" | "Tabs" => Ok(Self::Tab),
"space" | "Spaces" => Ok(Self::Space),
// TODO: replace this error with a diagnostic
_ => Err("Value not supported for IndentStyle"),
}
}
}
impl std::fmt::Display for IndentStyle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
IndentStyle::Tab => std::write!(f, "Tab"),
IndentStyle::Space => std::write!(f, "Space"),
}
}
}
#[derive(Clone, Copy, Debug, Deserializable, Eq, Hash, Merge, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema),
serde(rename_all = "camelCase")
)]
#[derive(Default)]
pub enum LineEnding {
/// Line Feed only (\n), common on Linux and macOS as well as inside git repos
#[default]
Lf,
/// Carriage Return + Line Feed characters (\r\n), common on Windows
Crlf,
/// Carriage Return character only (\r), used very rarely
Cr,
}
impl LineEnding {
#[inline]
pub const fn as_str(&self) -> &'static str {
match self {
LineEnding::Lf => "\n",
LineEnding::Crlf => "\r\n",
LineEnding::Cr => "\r",
}
}
/// Returns `true` if this is a [LineEnding::Lf].
pub const fn is_line_feed(&self) -> bool {
matches!(self, LineEnding::Lf)
}
/// Returns `true` if this is a [LineEnding::Crlf].
pub const fn is_carriage_return_line_feed(&self) -> bool {
matches!(self, LineEnding::Crlf)
}
/// Returns `true` if this is a [LineEnding::Cr].
pub const fn is_carriage_return(&self) -> bool {
matches!(self, LineEnding::Cr)
}
}
impl FromStr for LineEnding {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"lf" => Ok(Self::Lf),
"crlf" => Ok(Self::Crlf),
"cr" => Ok(Self::Cr),
// TODO: replace this error with a diagnostic
_ => Err("Value not supported for LineEnding"),
}
}
}
impl std::fmt::Display for LineEnding {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
LineEnding::Lf => std::write!(f, "LF"),
LineEnding::Crlf => std::write!(f, "CRLF"),
LineEnding::Cr => std::write!(f, "CR"),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema),
serde(rename_all = "camelCase")
)]
pub struct IndentWidth(u8);
impl IndentWidth {
/// Return the numeric value for this [IndentWidth]
pub fn value(&self) -> u8 {
self.0
}
}
impl Default for IndentWidth {
fn default() -> Self {
Self(2)
}
}
impl From<u8> for IndentWidth {
fn from(value: u8) -> Self {
Self(value)
}
}
/// Validated value for the `line_width` formatter options
///
/// The allowed range of values is 1..=320
#[derive(Clone, Copy, Debug, Eq, Merge, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema),
serde(rename_all = "camelCase")
)]
pub struct LineWidth(u16);
impl LineWidth {
/// Minimum allowed value for a valid [LineWidth]
pub const MIN: u16 = 1;
/// Maximum allowed value for a valid [LineWidth]
pub const MAX: u16 = 320;
/// Return the numeric value for this [LineWidth]
pub fn get(&self) -> u16 {
self.0
}
}
impl Default for LineWidth {
fn default() -> Self {
Self(80)
}
}
impl Deserializable for LineWidth {
fn deserialize(
value: &impl DeserializableValue,
name: &str,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<Self> {
let value_text = TextNumber::deserialize(value, name, diagnostics)?;
if let Ok(value) = value_text.parse::<Self>() {
return Some(value);
}
diagnostics.push(DeserializationDiagnostic::new_out_of_bound_integer(
Self::MIN,
Self::MAX,
value.range(),
));
None
}
}
/// Error type returned when parsing a [LineWidth] from a string fails
pub enum ParseLineWidthError {
/// The string could not be parsed as a valid [u16]
ParseError(ParseIntError),
/// The [u16] value of the string is not a valid [LineWidth]
TryFromIntError(LineWidthFromIntError),
}
impl Debug for ParseLineWidthError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self, f)
}
}
impl std::fmt::Display for ParseLineWidthError {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ParseLineWidthError::ParseError(err) => std::fmt::Display::fmt(err, fmt),
ParseLineWidthError::TryFromIntError(err) => std::fmt::Display::fmt(err, fmt),
}
}
}
impl FromStr for LineWidth {
type Err = ParseLineWidthError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let value = u16::from_str(s).map_err(ParseLineWidthError::ParseError)?;
let value = Self::try_from(value).map_err(ParseLineWidthError::TryFromIntError)?;
Ok(value)
}
}
/// Error type returned when converting a u16 to a [LineWidth] fails
#[derive(Clone, Copy, Debug)]
pub struct LineWidthFromIntError(pub u16);
impl TryFrom<u16> for LineWidth {
type Error = LineWidthFromIntError;
fn try_from(value: u16) -> Result<Self, Self::Error> {
if (Self::MIN..=Self::MAX).contains(&value) {
Ok(Self(value))
} else {
Err(LineWidthFromIntError(value))
}
}
}
impl std::fmt::Display for LineWidthFromIntError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(
f,
"The line width should be between {} and {}",
LineWidth::MIN,
LineWidth::MAX,
)
}
}
impl From<LineWidth> for u16 {
fn from(value: LineWidth) -> Self {
value.0
}
}
#[derive(Clone, Copy, Debug, Default, Deserializable, Eq, Hash, Merge, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema),
serde(rename_all = "camelCase")
)]
pub enum QuoteStyle {
#[default]
Double,
Single,
}
impl QuoteStyle {
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,
}
}
pub const fn is_double(&self) -> bool {
matches!(self, Self::Double)
}
}
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 std::fmt::Display for QuoteStyle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
QuoteStyle::Double => std::write!(f, "Double Quotes"),
QuoteStyle::Single => std::write!(f, "Single Quotes"),
}
}
}
impl From<QuoteStyle> for Quote {
fn from(quote: QuoteStyle) -> Self {
match quote {
QuoteStyle::Double => Self::Double,
QuoteStyle::Single => Self::Single,
}
}
}
#[derive(Clone, Copy, Debug, Default, Deserializable, Eq, Hash, Merge, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema),
serde(rename_all = "camelCase")
)]
pub enum AttributePosition {
#[default]
Auto,
Multiline,
}
impl std::fmt::Display for AttributePosition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AttributePosition::Auto => std::write!(f, "Auto"),
AttributePosition::Multiline => std::write!(f, "Multiline"),
}
}
}
impl FromStr for AttributePosition {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"multiline" | "Multiline" => Ok(Self::Multiline),
"auto" | "Auto" => Ok(Self::Auto),
_ => Err("Value not supported for attribute_position. Supported values are 'auto' and 'multiline'."),
}
}
}
/// Context object storing data relevant when formatting an object.
pub trait FormatContext {
type Options: FormatOptions;
/// Returns the formatting options
fn options(&self) -> &Self::Options;
/// Returns [None] if the CST has not been pre-processed.
///
/// Returns [Some] if the CST has been pre-processed to simplify formatting.
/// The source map can be used to map positions of the formatted nodes back to their original
/// source locations or to resolve the source text.
fn source_map(&self) -> Option<&TransformSourceMap>;
}
/// Options customizing how the source code should be formatted.
pub trait FormatOptions {
/// The indent style.
fn indent_style(&self) -> IndentStyle;
/// The indent width.
fn indent_width(&self) -> IndentWidth;
/// What's the max width of a line. Defaults to 80.
fn line_width(&self) -> LineWidth;
/// The type of line ending.
fn line_ending(&self) -> LineEnding;
/// The attribute position.
fn attribute_position(&self) -> AttributePosition;
/// Derives the print options from the these format options
fn as_print_options(&self) -> PrinterOptions;
}
/// The [CstFormatContext] is an extension of the CST unaware [FormatContext] and must be implemented
/// by every language.
///
/// The context customizes the comments formatting and stores the comments of the CST.
pub trait CstFormatContext: FormatContext {
type Language: Language;
type Style: CommentStyle<Language = Self::Language>;
/// Rule for formatting comments.
type CommentRule: FormatRule<SourceComment<Self::Language>, Context = Self> + Default;
/// Returns a reference to the program's comments.
fn comments(&self) -> &Comments<Self::Language>;
}
#[derive(Debug, Default, Eq, PartialEq)]
pub struct SimpleFormatContext {
options: SimpleFormatOptions,
}
impl SimpleFormatContext {
pub fn new(options: SimpleFormatOptions) -> Self {
Self { options }
}
}
impl FormatContext for SimpleFormatContext {
type Options = SimpleFormatOptions;
fn options(&self) -> &Self::Options {
&self.options
}
fn source_map(&self) -> Option<&TransformSourceMap> {
None
}
}
#[derive(Debug, Default, Eq, PartialEq)]
pub struct SimpleFormatOptions {
pub indent_style: IndentStyle,
pub indent_width: IndentWidth,
pub line_width: LineWidth,
pub line_ending: LineEnding,
pub attribute_position: AttributePosition,
}
impl FormatOptions for SimpleFormatOptions {
fn indent_style(&self) -> IndentStyle {
self.indent_style
}
fn indent_width(&self) -> IndentWidth {
self.indent_width
}
fn line_width(&self) -> LineWidth {
self.line_width
}
fn line_ending(&self) -> LineEnding {
self.line_ending
}
fn attribute_position(&self) -> AttributePosition {
self.attribute_position
}
fn as_print_options(&self) -> PrinterOptions {
PrinterOptions::default()
.with_indent_style(self.indent_style)
.with_indent_width(self.indent_width)
.with_print_width(self.line_width.into())
.with_line_ending(self.line_ending)
.with_attribute_position(self.attribute_position)
}
}
/// Lightweight sourcemap marker between source and output tokens
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)
)]
pub struct SourceMarker {
/// Position of the marker in the original source
pub source: TextSize,
/// Position of the marker in the output code
pub dest: TextSize,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Formatted<Context> {
document: Document,
context: Context,
}
impl<Context> Formatted<Context> {
pub fn new(document: Document, context: Context) -> Self {
Self { document, context }
}
/// Returns the context used during formatting.
pub fn context(&self) -> &Context {
&self.context
}
/// Returns the formatted document.
pub fn document(&self) -> &Document {
&self.document
}
/// Consumes `self` and returns the formatted document.
pub fn into_document(self) -> Document {
self.document
}
}
impl<Context> Formatted<Context>
where
Context: FormatContext,
{
pub fn print(&self) -> PrintResult<Printed> {
let print_options = self.context.options().as_print_options();
let printed = Printer::new(print_options).print(&self.document)?;
let printed = match self.context.source_map() {
Some(source_map) => source_map.map_printed(printed),
None => printed,
};
Ok(printed)
}
pub fn print_with_indent(&self, indent: u16) -> PrintResult<Printed> {
let print_options = self.context.options().as_print_options();
let printed = Printer::new(print_options).print_with_indent(&self.document, indent)?;
let printed = match self.context.source_map() {
Some(source_map) => source_map.map_printed(printed),
None => printed,
};
Ok(printed)
}
}
pub type PrintResult<T> = Result<T, PrintError>;
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)
)]
pub struct Printed {
code: String,
range: Option<TextRange>,
sourcemap: Vec<SourceMarker>,
verbatim_ranges: Vec<TextRange>,
}
impl Printed {
pub fn new(
code: String,
range: Option<TextRange>,
sourcemap: Vec<SourceMarker>,
verbatim_source: Vec<TextRange>,
) -> Self {
Self {
code,
range,
sourcemap,
verbatim_ranges: verbatim_source,
}
}
/// Construct an empty formatter result
pub fn new_empty() -> Self {
Self {
code: String::new(),
range: None,
sourcemap: Vec::new(),
verbatim_ranges: Vec::new(),
}
}
/// Range of the input source file covered by this formatted code,
/// or None if the entire file is covered in this instance
pub fn range(&self) -> Option<TextRange> {
self.range
}
/// Returns a list of [SourceMarker] mapping byte positions
/// in the output string to the input source code.
/// It's not guaranteed that the markers are sorted by source position.
pub fn sourcemap(&self) -> &[SourceMarker] {
&self.sourcemap
}
/// Returns a list of [SourceMarker] mapping byte positions
/// in the output string to the input source code, consuming the result
pub fn into_sourcemap(self) -> Vec<SourceMarker> {
self.sourcemap
}
/// Takes the list of [SourceMarker] mapping byte positions in the output string
/// to the input source code.
pub fn take_sourcemap(&mut self) -> Vec<SourceMarker> {
std::mem::take(&mut self.sourcemap)
}
/// Access the resulting code, borrowing the result
pub fn as_code(&self) -> &str {
&self.code
}
/// Access the resulting code, consuming the result
pub fn into_code(self) -> String {
self.code
}
/// The text in the formatted code that has been formatted as verbatim.
pub fn verbatim(&self) -> impl Iterator<Item = (TextRange, &str)> {
self.verbatim_ranges
.iter()
.map(|range| (*range, &self.code[*range]))
}
/// Ranges of the formatted code that have been formatted as verbatim.
pub fn verbatim_ranges(&self) -> &[TextRange] {
&self.verbatim_ranges
}
/// Takes the ranges of nodes that have been formatted as verbatim, replacing them with an empty list.
pub fn take_verbatim_ranges(&mut self) -> Vec<TextRange> {
std::mem::take(&mut self.verbatim_ranges)
}
}
/// Public return type of the formatter
pub type FormatResult<F> = Result<F, FormatError>;
/// Formatting trait for types that can create a formatted representation. The `biome_formatter` equivalent
/// to [std::fmt::Display].
///
/// ## Example
/// Implementing `Format` for a custom struct
///
/// ```
/// use biome_formatter::{format, write, IndentStyle, LineWidth};
/// use biome_formatter::prelude::*;
/// use biome_rowan::TextSize;
///
/// struct Paragraph(String);
///
/// impl Format<SimpleFormatContext> for Paragraph {
/// fn fmt(&self, f: &mut Formatter<SimpleFormatContext>) -> FormatResult<()> {
/// write!(f, [
/// hard_line_break(),
/// dynamic_text(&self.0, TextSize::from(0)),
/// hard_line_break(),
/// ])
/// }
/// }
///
/// # fn main() -> FormatResult<()> {
/// let paragraph = Paragraph(String::from("test"));
/// let formatted = format!(SimpleFormatContext::default(), [paragraph])?;
///
/// assert_eq!("test\n", formatted.print()?.as_code());
/// # Ok(())
/// # }
/// ```
pub trait Format<Context> {
/// Formats the object using the given formatter.
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()>;
}
impl<T, Context> Format<Context> for &T
where
T: ?Sized + Format<Context>,
{
#[inline(always)]
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
Format::fmt(&**self, f)
}
}
impl<T, Context> Format<Context> for &mut T
where
T: ?Sized + Format<Context>,
{
#[inline(always)]
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
Format::fmt(&**self, f)
}
}
impl<T, Context> Format<Context> for Option<T>
where
T: Format<Context>,
{
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
match self {
Some(value) => value.fmt(f),
None => Ok(()),
}
}
}
impl<T, Context> Format<Context> for SyntaxResult<T>
where
T: Format<Context>,
{
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
match self {
Ok(value) => value.fmt(f),
Err(err) => Err(err.into()),
}
}
}
impl<Context> Format<Context> for () {
#[inline]
fn fmt(&self, _: &mut Formatter<Context>) -> FormatResult<()> {
// Intentionally left empty
Ok(())
}
}
/// Rule that knows how to format an object of type `T`.
///
/// Implementing [Format] on the object itself is preferred over implementing [FormatRule] but
/// this isn't possible inside of a dependent crate for external type.
///
/// For example, the `biome_js_formatter` crate isn't able to implement [Format] on `JsIfStatement`
/// because both the [Format] trait and `JsIfStatement` are external types (Rust's orphan rule).
///
/// That's why the `biome_js_formatter` crate must define a new-type that implements the formatting
/// of `JsIfStatement`.
pub trait FormatRule<T> {
type Context;
fn fmt(&self, item: &T, f: &mut Formatter<Self::Context>) -> FormatResult<()>;
}
/// Default implementation for formatting a token
pub struct FormatToken<C> {
context: PhantomData<C>,
}
impl<C> Default for FormatToken<C> {
fn default() -> Self {
Self {
context: PhantomData,
}
}
}
impl<C> FormatRule<SyntaxToken<C::Language>> for FormatToken<C>
where
C: CstFormatContext,
C::Language: 'static,
{
type Context = C;
fn fmt(
&self,
token: &SyntaxToken<C::Language>,
f: &mut Formatter<Self::Context>,
) -> FormatResult<()> {
f.state_mut().track_token(token);
crate::write!(
f,
[
format_skipped_token_trivia(token),
format_trimmed_token(token),
]
)
}
}
/// Rule that supports customizing how it formats an object of type `T`.
pub trait FormatRuleWithOptions<T>: FormatRule<T> {
type Options;
/// Returns a new rule that uses the given options to format an object.
fn with_options(self, options: Self::Options) -> Self;
}
/// Trait for an object that formats an object with a specified rule.
///
/// Gives access to the underlying item.
///
/// Useful in situation where a type itself doesn't implement [Format] (e.g. because of Rust's orphan rule)
/// but you want to implement some common formatting logic.
///
/// ## Examples
///
/// This can be useful if you want to format a `SyntaxNode` inside biome_formatter.. `SyntaxNode` doesn't implement [Format]
/// itself but the language specific crate implements `AsFormat` and `IntoFormat` for it and the returned [Format]
/// implement [FormatWithRule].
///
/// ```ignore
/// use biome_formatter::prelude::*;
/// use biome_formatter::{format, Formatted, FormatWithRule};
/// use biome_rowan::{Language, SyntaxNode};
/// fn format_node<L: Language, F: FormatWithRule<SimpleFormatContext, Item=SyntaxNode<L>>>(node: F) -> FormatResult<Formatted<SimpleFormatContext>> {
/// let formatted = format!(SimpleFormatContext::default(), [node]);
/// let syntax = node.item();
/// // Do something with syntax
/// formatted;
/// }
/// ```
pub trait FormatWithRule<Context>: Format<Context> {
type Item;
/// Returns the associated item
fn item(&self) -> &Self::Item;
}
/// Formats the referenced `item` with the specified rule.
#[derive(Debug, Copy, Clone)]
pub struct FormatRefWithRule<'a, T, R>
where
R: FormatRule<T>,
{
item: &'a T,
rule: R,
}
impl<'a, T, R> FormatRefWithRule<'a, T, R>
where
R: FormatRule<T>,
{
pub fn new(item: &'a T, rule: R) -> Self {
Self { item, rule }
}
}
impl<T, R, O> FormatRefWithRule<'_, T, R>
where
R: FormatRuleWithOptions<T, Options = O>,
{
pub fn with_options(mut self, options: O) -> Self {
self.rule = self.rule.with_options(options);
self
}
}
impl<T, R> FormatWithRule<R::Context> for FormatRefWithRule<'_, T, R>
where
R: FormatRule<T>,
{
type Item = T;
fn item(&self) -> &Self::Item {
self.item
}
}
impl<T, R> Format<R::Context> for FormatRefWithRule<'_, T, R>
where
R: FormatRule<T>,
{
#[inline(always)]
fn fmt(&self, f: &mut Formatter<R::Context>) -> FormatResult<()> {
self.rule.fmt(self.item, f)
}
}
/// Formats the `item` with the specified rule.
#[derive(Debug, Clone)]
pub struct FormatOwnedWithRule<T, R>
where
R: FormatRule<T>,
{
item: T,
rule: R,
}
impl<T, R> FormatOwnedWithRule<T, R>
where
R: FormatRule<T>,
{
pub fn new(item: T, rule: R) -> Self {
Self { item, rule }
}
pub fn with_item(mut self, item: T) -> Self {
self.item = item;
self
}
pub fn into_item(self) -> T {
self.item
}
}
impl<T, R> Format<R::Context> for FormatOwnedWithRule<T, R>
where
R: FormatRule<T>,
{
#[inline(always)]
fn fmt(&self, f: &mut Formatter<R::Context>) -> FormatResult<()> {
self.rule.fmt(&self.item, f)
}
}
impl<T, R, O> FormatOwnedWithRule<T, R>
where
R: FormatRuleWithOptions<T, Options = O>,
{
pub fn with_options(mut self, options: O) -> Self {
self.rule = self.rule.with_options(options);
self
}
}
impl<T, R> FormatWithRule<R::Context> for FormatOwnedWithRule<T, R>
where
R: FormatRule<T>,
{
type Item = T;
fn item(&self) -> &Self::Item {
&self.item
}
}
/// The `write` function takes a target buffer and an `Arguments` struct that can be precompiled with the `format_args!` macro.
///
/// The arguments will be formatted in-order into the output buffer provided.
///
/// # Examples
///
/// ```
/// use biome_formatter::prelude::*;
/// use biome_formatter::{VecBuffer, format_args, FormatState, write, Formatted};
///
/// # fn main() -> FormatResult<()> {
/// let mut state = FormatState::new(SimpleFormatContext::default());
/// let mut buffer = VecBuffer::new(&mut state);
///
/// write!(&mut buffer, [format_args!(text("Hello World"))])?;
///
/// let formatted = Formatted::new(Document::from(buffer.into_vec()), SimpleFormatContext::default());
///
/// assert_eq!("Hello World", formatted.print()?.as_code());
/// # Ok(())
/// # }
/// ```
///
/// Please note that using [`write!`] might be preferable. Example:
///
/// ```
/// use biome_formatter::prelude::*;
/// use biome_formatter::{VecBuffer, format_args, FormatState, write, Formatted};
///
/// # fn main() -> FormatResult<()> {
/// let mut state = FormatState::new(SimpleFormatContext::default());
/// let mut buffer = VecBuffer::new(&mut state);
///
/// write!(&mut buffer, [text("Hello World")])?;
///
/// let formatted = Formatted::new(Document::from(buffer.into_vec()), SimpleFormatContext::default());
///
/// assert_eq!("Hello World", formatted.print()?.as_code());
/// # Ok(())
/// # }
/// ```
///
#[inline(always)]
pub fn write<Context>(
output: &mut dyn Buffer<Context = Context>,
args: Arguments<Context>,
) -> FormatResult<()> {
let mut f = Formatter::new(output);
f.write_fmt(args)
}
/// The `format` function takes an [`Arguments`] struct and returns the resulting formatting IR.
///
/// The [`Arguments`] instance can be created with the [`format_args!`].
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use biome_formatter::prelude::*;
/// use biome_formatter::{format, format_args};
///
/// # fn main() -> FormatResult<()> {
/// let formatted = format!(SimpleFormatContext::default(), [&format_args!(text("test"))])?;
/// assert_eq!("test", formatted.print()?.as_code());
/// # Ok(())
/// # }
/// ```
///
/// Please note that using [`format!`] might be preferable. Example:
///
/// ```
/// use biome_formatter::prelude::*;
/// use biome_formatter::{format};
///
/// # fn main() -> FormatResult<()> {
/// let formatted = format!(SimpleFormatContext::default(), [text("test")])?;
/// assert_eq!("test", formatted.print()?.as_code());
/// # Ok(())
/// # }
/// ```
pub fn format<Context>(
context: Context,
arguments: Arguments<Context>,
) -> FormatResult<Formatted<Context>>
where
Context: FormatContext,
{
let mut state = FormatState::new(context);
let mut buffer = VecBuffer::with_capacity(arguments.items().len(), &mut state);
buffer.write_fmt(arguments)?;
let mut document = Document::from(buffer.into_vec());
document.propagate_expand();
Ok(Formatted::new(document, state.into_context()))
}
/// Entry point for formatting a [SyntaxNode] for a specific language.
pub trait FormatLanguage {
type SyntaxLanguage: Language;
/// The type of the formatting context
type Context: CstFormatContext<Language = Self::SyntaxLanguage>;
/// The rule type that can format a [SyntaxNode] of this language
type FormatRule: FormatRule<SyntaxNode<Self::SyntaxLanguage>, Context = Self::Context> + Default;
/// Performs an optional pre-processing of the tree. This can be useful to remove nodes
/// that otherwise complicate formatting.
///
/// Return [None] if the tree shouldn't be processed. Return [Some] with the transformed
/// tree and the source map otherwise.
fn transform(
&self,
_root: &SyntaxNode<Self::SyntaxLanguage>,
) -> Option<(SyntaxNode<Self::SyntaxLanguage>, TransformSourceMap)> {
None
}
/// This is used to select appropriate "root nodes" for the
/// range formatting process: for instance in JavaScript the function returns
/// true for statement and declaration nodes, to ensure the entire statement
/// gets formatted instead of the smallest sub-expression that fits the range
fn is_range_formatting_node(&self, _node: &SyntaxNode<Self::SyntaxLanguage>) -> bool {
true
}
/// Returns the formatting options
fn options(&self) -> &<Self::Context as FormatContext>::Options;
/// Creates the [FormatContext] with the given `source map` and `comments`
fn create_context(
self,
root: &SyntaxNode<Self::SyntaxLanguage>,
source_map: Option<TransformSourceMap>,
) -> Self::Context;
}
/// Formats a syntax node file based on its features.
///
/// It returns a [Formatted] result, which the user can use to override a file.
pub fn format_node<L: FormatLanguage>(
root: &SyntaxNode<L::SyntaxLanguage>,
language: L,
) -> FormatResult<Formatted<L::Context>> {
tracing::trace_span!("format_node").in_scope(move || {
let (root, source_map) = match language.transform(&root.clone()) {
Some((transformed, source_map)) => {
// we don't need to insert the node back if it has the same offset
if &transformed == root {
(transformed, Some(source_map))
} else {
match root
.ancestors()
// ancestors() always returns self as the first element of the iterator.
.skip(1)
.last()
{
// current root node is the topmost node we don't need to insert the transformed node back
None => (transformed, Some(source_map)),
Some(top_root) => {
// we have to return transformed node back into subtree
let transformed_range = transformed.text_range();
let root_range = root.text_range();
let transformed_root = top_root
.replace_child(root.clone().into(), transformed.into())
// SAFETY: Calling `unwrap` is safe because we know that `root` is part of the `top_root` subtree.
.unwrap();
let transformed = transformed_root.covering_element(TextRange::new(
root_range.start(),
root_range.start() + transformed_range.len(),
));
let node = match transformed {
NodeOrToken::Node(node) => node,
NodeOrToken::Token(token) => {
// if we get a token we need to get the parent node
token.parent().unwrap_or(transformed_root)
}
};
(node, Some(source_map))
}
}
}
}
None => (root.clone(), None),
};
let context = language.create_context(&root, source_map);
let format_node = FormatRefWithRule::new(&root, L::FormatRule::default());
let mut state = FormatState::new(context);
let mut buffer = VecBuffer::new(&mut state);
write!(buffer, [format_node])?;
let mut document = Document::from(buffer.into_vec());
document.propagate_expand();
state.assert_formatted_all_tokens(&root);
let context = state.into_context();
let comments = context.comments();
comments.assert_checked_all_suppressions(&root);
comments.assert_formatted_all_comments();
Ok(Formatted::new(document, context))
})
}
/// Returns the [TextRange] for this [SyntaxElement] with the leading and
/// trailing whitespace trimmed (but keeping comments or skipped trivias)
fn text_non_whitespace_range<E, L>(elem: &E) -> TextRange
where
E: Into<SyntaxElement<L>> + Clone,
L: Language,
{
let elem: SyntaxElement<L> = elem.clone().into();
let start = elem
.leading_trivia()
.into_iter()
.flat_map(|trivia| trivia.pieces())
.find_map(|piece| {
if piece.is_whitespace() || piece.is_newline() {
None
} else {
Some(piece.text_range().start())
}
})
.unwrap_or_else(|| elem.text_trimmed_range().start());
let end = elem
.trailing_trivia()
.into_iter()
.flat_map(|trivia| trivia.pieces().rev())
.find_map(|piece| {
if piece.is_whitespace() || piece.is_newline() {
None
} else {
Some(piece.text_range().end())
}
})
.unwrap_or_else(|| elem.text_trimmed_range().end());
TextRange::new(start, end)
}
/// Formats a range within a file, supported by Biome
///
/// This runs a simple heuristic to determine the initial indentation
/// level of the node based on the provided [FormatContext], which
/// must match currently the current initial of the file. Additionally,
/// because the reformatting happens only locally the resulting code
/// will be indented with the same level as the original selection,
/// even if it's a mismatch from the rest of the block the selection is in
///
/// It returns a [Formatted] result with a range corresponding to the
/// range of the input that was effectively overwritten by the formatter
pub fn format_range<Language: FormatLanguage>(
root: &SyntaxNode<Language::SyntaxLanguage>,
mut range: TextRange,
language: Language,
) -> FormatResult<Printed> {
if range.is_empty() {
return Ok(Printed::new(
String::new(),
Some(range),
Vec::new(),
Vec::new(),
));
}
let root_range = root.text_range();
if range.start() < root_range.start() || range.end() > root_range.end() {
return Err(FormatError::RangeError {
input: range,
tree: root_range,
});
}
// Find the tokens corresponding to the start and end of the range
let start_token = root.token_at_offset(range.start());
let end_token = root.token_at_offset(range.end());
// If these tokens were not found this means either:
// 1. The input [SyntaxNode] was empty
// 2. The input node was not the root [SyntaxNode] of the file
// In the first case we can return an empty result immediately,
// otherwise default to the first and last tokens in the root node
let mut start_token = match start_token {
// If the start of the range lies between two tokens,
// start at the rightmost one
TokenAtOffset::Between(_, token) => token,
TokenAtOffset::Single(token) => token,
TokenAtOffset::None => match root.first_token() {
Some(token) => token,
// root node is empty
None => return Ok(Printed::new_empty()),
},
};
let mut end_token = match end_token {
// If the end of the range lies between two tokens,
// end at the leftmost one
TokenAtOffset::Between(token, _) => token,
TokenAtOffset::Single(token) => token,
TokenAtOffset::None => match root.last_token() {
Some(token) => token,
// root node is empty
None => return Ok(Printed::new_empty()),
},
};
// Trim leading and trailing whitespace off from the formatting range
let mut trimmed_start = range.start();
let start_token_range = text_non_whitespace_range(&start_token);
let start_token_trimmed_start = start_token_range.start();
let start_token_trimmed_end = start_token_range.end();
if start_token_trimmed_start >= range.start() && start_token_trimmed_start <= range.end() {
// If the range starts before the trimmed start of the token, move the
// start towards that position
trimmed_start = start_token_trimmed_start;
} else if start_token_trimmed_end <= range.start() {
// If the range starts after the trimmed end of the token, move the
// start to the trimmed start of the next token if it exists
if let Some(next_token) = start_token.next_token() {
let next_token_start = text_non_whitespace_range(&next_token).start();
if next_token_start <= range.end() {
trimmed_start = next_token_start;
start_token = next_token;
}
}
}
let end_token_range = text_non_whitespace_range(&end_token);
let end_token_trimmed_start = end_token_range.start();
// If the range ends before the trimmed start of the token, move the
// end to the trimmed end of the previous token if it exists
if end_token_trimmed_start >= range.end() {
if let Some(next_token) = end_token.prev_token() {
let next_token_end = text_non_whitespace_range(&next_token).end();
if next_token_end >= trimmed_start {
end_token = next_token;
}
}
}
// Find suitable formatting-root nodes (matching the predicate provided by
// the language implementation) in the ancestors of the start and end tokens
let start_node = start_token
.ancestors()
.find(|node| language.is_range_formatting_node(node))
.unwrap_or_else(|| root.clone());
let end_node = end_token
.ancestors()
.find(|node| language.is_range_formatting_node(node))
.unwrap_or_else(|| root.clone());
let common_root = if start_node == end_node {
range = text_non_whitespace_range(&start_node);
Some(start_node)
} else {
// Find the two highest sibling nodes that satisfy the formatting range
// from the ancestors of the start and end nodes (this is roughly the
// same algorithm as the findSiblingAncestors function in Prettier, see
// https://github.com/prettier/prettier/blob/cae195187f524dd74e60849e0a4392654423415b/src/main/range-util.js#L36)
let start_node_start = start_node.text_range().start();
let end_node_end = end_node.text_range().end();
let result_end_node = end_node
.ancestors()
.take_while(|end_parent| end_parent.text_range().start() >= start_node_start)
.last()
.unwrap_or(end_node);
let result_start_node = start_node
.ancestors()
.take_while(|start_parent| start_parent.text_range().end() <= end_node_end)
.last()
.unwrap_or(start_node);
range = text_non_whitespace_range(&result_start_node)
.cover(text_non_whitespace_range(&result_end_node));
// Find the lowest common ancestor node for the previously selected
// sibling nodes by building the path to the root node from both
// nodes and iterating along the two paths at once to find the first
// divergence (the ancestors have to be collected into vectors first
// since the ancestor iterator isn't double ended)
#[allow(clippy::needless_collect)]
let start_to_root: Vec<_> = result_start_node.ancestors().collect();
#[allow(clippy::needless_collect)]
let end_to_root: Vec<_> = result_end_node.ancestors().collect();
start_to_root
.into_iter()
.rev()
.zip(end_to_root.into_iter().rev())
.map_while(|(lhs, rhs)| if lhs == rhs { Some(lhs) } else { None })
.last()
};
// Logically this should always return at least the root node,
// fallback to said node just in case
let common_root = common_root.as_ref().unwrap_or(root);
// Perform the actual formatting of the root node with
// an appropriate indentation level
let mut printed = format_sub_tree(common_root, language)?;
// This finds the closest marker to the beginning of the source
// starting before or at said starting point, and the closest
// marker to the end of the source range starting after or at
// said ending point respectively
let mut range_start: Option<&SourceMarker> = None;
let mut range_end: Option<&SourceMarker> = None;
let sourcemap = printed.sourcemap();
for marker in sourcemap {
if marker.source <= range.start() {
range_start = match range_start {
Some(prev_marker) => {
if marker.source > prev_marker.source {
if prev_marker.dest == marker.dest {
// we found a marker that is closer to the start range than we have
// but we need to check if the marker has the same dest, otherwise we can get an incorrect substring in the source text
// e.g
// ...
// SourceMarker {
// source: 94, <----- but we need to use this source position to get correct substring in the source
// dest: 99,
// },
// SourceMarker {
// source: 96,
// dest: 99, <----- both markers have the same dest.
// },
// ...
Some(prev_marker)
} else {
Some(marker)
}
} else {
Some(prev_marker)
}
}
None => Some(marker),
}
}
if marker.source >= range.end() {
range_end = match range_end {
Some(prev_marker) => {
if marker.source <= prev_marker.source || marker.dest == prev_marker.dest {
// 1. if we found a marker that is closer to the end we take it.
// 2. if we found a marker that is farther to the end range than we have
// but we need to check if the marker has the same dest, otherwise we can get an incorrect substring in the source text
// e.g
// ...
// SourceMarker {
// source: 94,
// dest: 99, <----- both markers have the same dest.
// },
// SourceMarker {
// source: 96, <----- but we need to use this source position to get correct substring in the source
// dest: 99,
// },
// ...
Some(marker)
} else {
Some(prev_marker)
}
}
None => Some(marker),
}
}
}
// If no start or end were found, this means that the edge of the formatting
// range was near the edge of the input, and no marker were emitted before
// the start (or after the end) of the formatting range: in this case
// the start/end marker default to the start/end of the input
let (start_source, start_dest) = match range_start {
Some(start_marker) => (start_marker.source, start_marker.dest),
None => (common_root.text_range().start(), TextSize::from(0)),
};
let (end_source, end_dest) = match range_end {
Some(end_marker) => (end_marker.source, end_marker.dest),
None => (
common_root.text_range().end(),
TextSize::try_from(printed.as_code().len()).expect("code length out of bounds"),
),
};
let input_range = TextRange::new(start_source, end_source);
let output_range = TextRange::new(start_dest, end_dest);
let sourcemap = printed.take_sourcemap();
let verbatim_ranges = printed.take_verbatim_ranges();
let code = &printed.into_code()[output_range];
Ok(Printed::new(
code.into(),
Some(input_range),
sourcemap,
verbatim_ranges,
))
}
/// Formats a single node within a file, supported by Biome.
///
/// This runs a simple heuristic to determine the initial indentation
/// level of the node based on the provided [FormatContext], which
/// must match currently the current initial of the file. Additionally,
/// because the reformatting happens only locally the resulting code
/// will be indented with the same level as the original selection,
/// even if it's a mismatch from the rest of the block the selection is in
///
/// It returns a [Formatted] result
pub fn format_sub_tree<L: FormatLanguage>(
root: &SyntaxNode<L::SyntaxLanguage>,
language: L,
) -> FormatResult<Printed> {
// Determine the initial indentation level for the printer by inspecting the trivia pieces
// of each token from the first token of the common root towards the start of the file
let mut tokens = std::iter::successors(root.first_token(), |token| token.prev_token());
// From the iterator of tokens, build an iterator of trivia pieces (once again the iterator is
// reversed, starting from the last trailing trivia towards the first leading trivia).
// The first token is handled specially as we only wan to consider its leading trivia pieces
let first_token = tokens.next();
let first_token_trivias = first_token
.into_iter()
.flat_map(|token| token.leading_trivia().pieces().rev());
let next_tokens_trivias = tokens.flat_map(|token| {
token
.trailing_trivia()
.pieces()
.rev()
.chain(token.leading_trivia().pieces().rev())
});
let trivias = first_token_trivias
.chain(next_tokens_trivias)
.filter(|piece| {
// We're only interested in newline and whitespace trivias, skip over comments
let is_newline = piece.is_newline();
let is_whitespace = piece.is_whitespace();
is_newline || is_whitespace
});
// Finally run the iterator until a newline trivia is found, and get the last whitespace trivia before it
let last_whitespace = trivias.map_while(|piece| piece.as_whitespace()).last();
let initial_indent = match last_whitespace {
Some(trivia) => {
// This logic is based on the formatting options passed in
// the be user (or the editor) as we do not have any kind
// of indentation type detection yet. Unfortunately this
// may not actually match the current content of the file
let length = trivia.text().len() as u16;
let width = language.options().indent_width().value();
match language.options().indent_style() {
IndentStyle::Tab => length,
IndentStyle::Space => length / u16::from(width),
}
}
// No whitespace was found between the start of the range
// and the start of the file
None => 0,
};
let formatted = format_node(root, language)?;
let mut printed = formatted.print_with_indent(initial_indent)?;
let sourcemap = printed.take_sourcemap();
let verbatim_ranges = printed.take_verbatim_ranges();
Ok(Printed::new(
printed.into_code(),
Some(root.text_range()),
sourcemap,
verbatim_ranges,
))
}
impl<L: Language, Context> Format<Context> for SyntaxTriviaPiece<L> {
fn fmt(&self, f: &mut Formatter<Context>) -> FormatResult<()> {
let range = self.text_range();
// Trim start/end and update the range
let trimmed = self.text().trim_start();
let trimmed_start = range.start() + (range.len() - trimmed.text_len());
let trimmed = trimmed.trim_end();
write!(
f,
[syntax_token_cow_slice(
normalize_newlines(trimmed, LINE_TERMINATORS),
&self.token(),
trimmed_start
)]
)
}
}
/// This structure stores the state that is relevant for the formatting of the whole document.
///
/// This structure is different from [crate::Formatter] in that the formatting infrastructure
/// creates a new [crate::Formatter] for every [crate::write!] call, whereas this structure stays alive
/// for the whole process of formatting a root with [crate::format!].
pub struct FormatState<Context> {
context: Context,
group_id_builder: UniqueGroupIdBuilder,
// This is using a RefCell as it only exists in debug mode,
// the Formatter is still completely immutable in release builds
#[cfg(debug_assertions)]
pub printed_tokens: PrintedTokens,
}
impl<Context> std::fmt::Debug for FormatState<Context>
where
Context: std::fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("FormatState")
.field("context", &self.context)
.finish()
}
}
impl<Context> FormatState<Context> {
/// Creates a new state with the given language specific context
pub fn new(context: Context) -> Self {
Self {
context,
group_id_builder: Default::default(),
#[cfg(debug_assertions)]
printed_tokens: Default::default(),
}
}
pub fn into_context(self) -> Context {
self.context
}
/// Returns the context specifying how to format the current CST
pub fn context(&self) -> &Context {
&self.context
}
/// Returns a mutable reference to the context
pub fn context_mut(&mut self) -> &mut Context {
&mut self.context
}
/// Creates a new group id that is unique to this document. The passed debug name is used in the
/// [std::fmt::Debug] of the document if this is a debug build.
/// The name is unused for production builds and has no meaning on the equality of two group ids.
pub fn group_id(&self, debug_name: &'static str) -> GroupId {
self.group_id_builder.group_id(debug_name)
}
/// Tracks the given token as formatted
#[inline]
pub fn track_token<L: Language>(&mut self, #[allow(unused_variables)] token: &SyntaxToken<L>) {
cfg_if::cfg_if! {
if #[cfg(debug_assertions)] {
self.printed_tokens.track_token(token);
}
}
}
#[cfg(not(debug_assertions))]
#[inline]
pub fn set_token_tracking_disabled(&mut self, _: bool) {}
/// Disables or enables token tracking for a portion of the code.
///
/// It can be useful to disable the token tracking when it is necessary to re-format a node with different parameters.
#[cfg(debug_assertions)]
pub fn set_token_tracking_disabled(&mut self, enabled: bool) {
self.printed_tokens.set_disabled(enabled)
}
#[cfg(not(debug_assertions))]
#[inline]
pub fn is_token_tracking_disabled(&self) -> bool {
false
}
/// Returns `true` if token tracking is currently disabled.
#[cfg(debug_assertions)]
pub fn is_token_tracking_disabled(&self) -> bool {
self.printed_tokens.is_disabled()
}
/// Asserts in debug builds that all tokens have been printed.
#[inline]
pub fn assert_formatted_all_tokens<L: Language>(
&self,
#[allow(unused_variables)] root: &SyntaxNode<L>,
) {
cfg_if::cfg_if! {
if #[cfg(debug_assertions)] {
self.printed_tokens.assert_all_tracked(root);
}
}
}
}
impl<Context> FormatState<Context>
where
Context: FormatContext,
{
pub fn snapshot(&self) -> FormatStateSnapshot {
FormatStateSnapshot {
#[cfg(debug_assertions)]
printed_tokens: self.printed_tokens.snapshot(),
}
}
pub fn restore_snapshot(&mut self, snapshot: FormatStateSnapshot) {
let FormatStateSnapshot {
#[cfg(debug_assertions)]
printed_tokens,
} = snapshot;
cfg_if::cfg_if! {
if #[cfg(debug_assertions)] {
self.printed_tokens.restore(printed_tokens);
}
}
}
}
pub struct FormatStateSnapshot {
#[cfg(debug_assertions)]
printed_tokens: printed_tokens::PrintedTokensSnapshot,
}
#[cfg(test)]
mod tests {
use super::LineWidth;
use biome_deserialize::json::deserialize_from_json_str;
use biome_deserialize_macros::Deserializable;
use biome_diagnostics::Error;
#[test]
fn test_out_of_range_line_width() {
#[derive(Debug, Default, Deserializable, Eq, PartialEq)]
struct TestConfig {
line_width: LineWidth,
}
struct DiagnosticPrinter<'a> {
diagnostics: &'a [Error],
}
impl<'a> DiagnosticPrinter<'a> {
fn new(diagnostics: &'a [Error]) -> Self {
Self { diagnostics }
}
}
impl<'a> std::fmt::Display for DiagnosticPrinter<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for diagnostic in self.diagnostics {
diagnostic.description(f)?;
}
Ok(())
}
}
let source = r#"{ "lineWidth": 500 }"#;
let deserialized = deserialize_from_json_str::<TestConfig>(source, Default::default(), "");
assert_eq!(
format!("{}", DiagnosticPrinter::new(deserialized.diagnostics())),
"The number should be an integer between 1 and 320."
);
assert_eq!(
deserialized.into_deserialized().unwrap(),
TestConfig {
line_width: LineWidth(80)
}
);
}
}