-
-
Notifications
You must be signed in to change notification settings - Fork 475
/
lib.rs
2014 lines (1761 loc) · 62.4 KB
/
lib.rs
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
//! 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;
use std::fmt::{Debug, Display};
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_console::markup;
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, Default, Clone, Copy, Deserializable, Eq, Hash, Merge, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema),
serde(rename_all = "camelCase")
)]
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" => Ok(Self::Tab),
"space" => Ok(Self::Space),
// TODO: replace this error with a diagnostic
_ => Err("Unsupported value for this option"),
}
}
}
impl 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, Eq, Merge, Hash, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, schemars::JsonSchema),
serde(rename_all = "camelCase")
)]
pub struct IndentWidth(u8);
impl IndentWidth {
pub const MIN: u8 = 0;
pub const MAX: u8 = 24;
/// Return the numeric value for this [IndentWidth]
pub fn value(&self) -> u8 {
self.0
}
}
impl Default for IndentWidth {
fn default() -> Self {
Self(2)
}
}
impl Deserializable for IndentWidth {
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
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for IndentWidth {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value: u8 = serde::Deserialize::deserialize(deserializer)?;
let indent_width = IndentWidth::try_from(value).map_err(serde::de::Error::custom)?;
Ok(indent_width)
}
}
impl FromStr for IndentWidth {
type Err = ParseFormatNumberError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let value = u8::from_str(s).map_err(ParseFormatNumberError::ParseError)?;
let value = Self::try_from(value).map_err(ParseFormatNumberError::TryFromU8Error)?;
Ok(value)
}
}
impl TryFrom<u8> for IndentWidth {
type Error = IndentWidthFromIntError;
fn try_from(value: u8) -> Result<Self, Self::Error> {
if (Self::MIN..=Self::MAX).contains(&value) {
Ok(Self(value))
} else {
Err(IndentWidthFromIntError(value))
}
}
}
impl biome_console::fmt::Display for IndentWidth {
fn fmt(&self, fmt: &mut biome_console::fmt::Formatter) -> std::io::Result<()> {
fmt.write_markup(markup! {{self.value()}})
}
}
impl Display for IndentWidth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let value = self.value();
f.write_str(&std::format!("{value}"))
}
}
impl Debug for IndentWidth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self, f)
}
}
/// Validated value for the `line_width` formatter options
///
/// The allowed range of values is 1..=320
#[derive(Clone, Copy, Eq, Merge, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, 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 value(&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
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for LineWidth {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value: u16 = serde::Deserialize::deserialize(deserializer)?;
let line_width = LineWidth::try_from(value).map_err(serde::de::Error::custom)?;
Ok(line_width)
}
}
impl biome_console::fmt::Display for LineWidth {
fn fmt(&self, fmt: &mut biome_console::fmt::Formatter) -> std::io::Result<()> {
fmt.write_markup(markup! {{self.0}})
}
}
impl Display for LineWidth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let value = self.value();
f.write_str(&std::format!("{value}"))
}
}
impl Debug for LineWidth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self, f)
}
}
/// Error type returned when parsing a [LineWidth] or [IndentWidth] from a string fails
pub enum ParseFormatNumberError {
/// The string could not be parsed to a number
ParseError(ParseIntError),
/// The `u16` value of the string is not a valid [LineWidth]
TryFromU16Error(LineWidthFromIntError),
/// The `u8 value of the string is not a valid [IndentWidth]
TryFromU8Error(IndentWidthFromIntError),
}
impl From<IndentWidthFromIntError> for ParseFormatNumberError {
fn from(value: IndentWidthFromIntError) -> Self {
Self::TryFromU8Error(value)
}
}
impl From<LineWidthFromIntError> for ParseFormatNumberError {
fn from(value: LineWidthFromIntError) -> Self {
Self::TryFromU16Error(value)
}
}
impl From<ParseIntError> for ParseFormatNumberError {
fn from(value: ParseIntError) -> Self {
Self::ParseError(value)
}
}
impl Debug for ParseFormatNumberError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self, f)
}
}
impl std::fmt::Display for ParseFormatNumberError {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ParseFormatNumberError::ParseError(err) => std::fmt::Display::fmt(err, fmt),
ParseFormatNumberError::TryFromU16Error(err) => std::fmt::Display::fmt(err, fmt),
ParseFormatNumberError::TryFromU8Error(err) => std::fmt::Display::fmt(err, fmt),
}
}
}
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 FromStr for LineWidth {
type Err = ParseFormatNumberError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let value = u16::from_str(s).map_err(ParseFormatNumberError::ParseError)?;
let value = Self::try_from(value).map_err(ParseFormatNumberError::TryFromU16Error)?;
Ok(value)
}
}
/// Error type returned when converting a u16 to a [LineWidth] fails
#[derive(Clone, Copy, Debug)]
pub struct IndentWidthFromIntError(pub u8);
impl std::fmt::Display for IndentWidthFromIntError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(
f,
"The indent width should be between {} and {}",
LineWidth::MIN,
LineWidth::MAX,
)
}
}
/// Error type returned when converting a u16 to a [LineWidth] fails
#[derive(Clone, Copy, Debug)]
pub struct LineWidthFromIntError(pub u16);
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_byte(&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, Deserializable, Eq, Hash, Merge, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema),
serde(rename_all = "camelCase")
)]
pub struct BracketSpacing(bool);
impl BracketSpacing {
/// Return the boolean value for this [BracketSpacing]
pub fn value(&self) -> bool {
self.0
}
}
impl Default for BracketSpacing {
fn default() -> Self {
Self(true)
}
}
impl From<bool> for BracketSpacing {
fn from(value: bool) -> Self {
Self(value)
}
}
impl std::fmt::Display for BracketSpacing {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::write!(f, "{}", self.value())
}
}
impl FromStr for BracketSpacing {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let value = bool::from_str(s);
match value {
Ok(value) => Ok(Self(value)),
Err(_) => Err(
"Value not supported for BracketSpacing. Supported values are 'true' and 'false'.",
),
}
}
}
#[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;
/// Whether to insert spaces around brackets in object literals. Defaults to true.
fn bracket_spacing(&self) -> BracketSpacing;
/// 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, Copy, Clone)]
pub struct SimpleFormatOptions {
pub indent_style: IndentStyle,
pub indent_width: IndentWidth,
pub line_width: LineWidth,
pub line_ending: LineEnding,
pub attribute_position: AttributePosition,
pub bracket_spacing: BracketSpacing,
}
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 bracket_spacing(&self) -> BracketSpacing {
self.bracket_spacing
}
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)
.with_bracket_spacing(self.bracket_spacing)
}
}
impl Display for SimpleFormatOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt::Debug::fmt(self, f)
}
}
/// 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>,
{