ruff_python_formatter 0.0.5

This is an internal component crate of Ruff
Documentation
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
use ruff_db::diagnostic::{Diagnostic, DiagnosticId, Severity};
use ruff_db::files::File;
use ruff_db::parsed::parsed_module;
use ruff_db::source::source_text;
use thiserror::Error;
use tracing::Level;

pub use range::format_range;
use ruff_formatter::prelude::*;
use ruff_formatter::{FormatError, Formatted, PrintError, Printed, SourceCode, format, write};
use ruff_python_ast::{AnyNodeRef, Mod};
use ruff_python_parser::{ParseError, ParseOptions, Parsed, parse};
use ruff_python_trivia::TriviaRanges;
use ruff_text_size::{Ranged, TextRange};

use crate::comments::{
    Comments, SourceComment, has_skip_comment, leading_comments, trailing_comments,
};
pub use crate::context::PyFormatContext;
pub use crate::db::Db;
pub use crate::options::{
    DocstringCode, DocstringCodeLineWidth, MagicTrailingComma, NestedStringQuoteStyle, PreviewMode,
    PyFormatOptions, QuoteStyle,
};
use crate::range::is_logical_line;
pub use crate::shared_traits::{AsFormat, FormattedIter, FormattedIterExt, IntoFormat};

pub(crate) mod builders;
pub mod cli;
mod comments;
pub(crate) mod context;
mod db;
pub(crate) mod expression;
mod generated;
pub(crate) mod module;
mod options;
pub(crate) mod other;
pub(crate) mod pattern;
mod prelude;
mod preview;
mod range;
mod shared_traits;
pub(crate) mod statement;
pub(crate) mod string;
pub(crate) mod type_param;
mod verbatim;

/// 'ast is the lifetime of the source code (input), 'buf is the lifetime of the buffer (output)
pub(crate) type PyFormatter<'ast, 'buf> = Formatter<'buf, PyFormatContext<'ast>>;

/// Rule for formatting a Python AST node.
pub(crate) trait FormatNodeRule<N>
where
    N: Ranged,
    for<'a> AnyNodeRef<'a>: From<&'a N>,
{
    fn fmt(&self, node: &N, f: &mut PyFormatter) -> FormatResult<()> {
        let comments = f.context().comments().clone();

        let node_ref = AnyNodeRef::from(node);
        let node_comments = comments.leading_dangling_trailing(node_ref);

        leading_comments(node_comments.leading).fmt(f)?;

        // Emit source map information for nodes that are valid "narrowing" targets
        // in range formatting. Never emit source map information if they're disabled
        // for performance reasons.
        let emit_source_position = (is_logical_line(node_ref) || node_ref.is_mod_module())
            && f.options().source_map_generation().is_enabled();

        emit_source_position
            .then_some(source_position(node.start()))
            .fmt(f)?;

        self.fmt_fields(node, f)?;

        debug_assert!(
            node_comments
                .dangling
                .iter()
                .all(SourceComment::is_formatted),
            "The node has dangling comments that need to be formatted manually. Add the special dangling comments handling to `fmt_fields`."
        );

        write!(
            f,
            [
                emit_source_position.then_some(source_position(node.end())),
                trailing_comments(node_comments.trailing)
            ]
        )
    }

    /// Formats the node's fields.
    fn fmt_fields(&self, item: &N, f: &mut PyFormatter) -> FormatResult<()>;
}

#[derive(Error, Debug, PartialEq, Eq)]
pub enum FormatModuleError {
    #[error(transparent)]
    ParseError(#[from] ParseError),
    #[error(transparent)]
    FormatError(#[from] FormatError),
    #[error(transparent)]
    PrintError(#[from] PrintError),
}

impl FormatModuleError {
    pub fn range(&self) -> Option<TextRange> {
        match self {
            FormatModuleError::ParseError(parse_error) => Some(parse_error.range()),
            FormatModuleError::FormatError(_) | FormatModuleError::PrintError(_) => None,
        }
    }
}

impl From<&FormatModuleError> for Diagnostic {
    fn from(error: &FormatModuleError) -> Self {
        match error {
            FormatModuleError::ParseError(parse_error) => Diagnostic::new(
                DiagnosticId::InternalError,
                Severity::Error,
                &parse_error.error,
            ),
            FormatModuleError::FormatError(format_error) => {
                Diagnostic::new(DiagnosticId::InternalError, Severity::Error, format_error)
            }
            FormatModuleError::PrintError(print_error) => {
                Diagnostic::new(DiagnosticId::InternalError, Severity::Error, print_error)
            }
        }
    }
}

#[tracing::instrument(name = "format", level = Level::TRACE, skip_all)]
pub fn format_module_source(
    source: &str,
    options: PyFormatOptions,
) -> Result<Printed, FormatModuleError> {
    let source_type = options.source_type();
    let parsed = parse(source, ParseOptions::from(source_type))?;
    let trivia = TriviaRanges::from(parsed.tokens());
    let formatted = format_module_ast(&parsed, &trivia, source, options)?;
    Ok(formatted.print()?)
}

pub fn format_module_ast<'a>(
    parsed: &'a Parsed<Mod>,
    trivia: &'a TriviaRanges,
    source: &'a str,
    options: PyFormatOptions,
) -> FormatResult<Formatted<PyFormatContext<'a>>> {
    format_node(parsed, trivia, source, options)
}

fn format_node<'a, N>(
    parsed: &'a Parsed<N>,
    trivia: &'a TriviaRanges,
    source: &'a str,
    options: PyFormatOptions,
) -> FormatResult<Formatted<PyFormatContext<'a>>>
where
    N: AsFormat<PyFormatContext<'a>>,
    &'a N: Into<AnyNodeRef<'a>>,
{
    let source_code = SourceCode::new(source);
    let comments = Comments::from_ast(parsed.syntax(), source_code, trivia);

    let formatted = format!(
        PyFormatContext::new(options, source, comments, trivia, parsed.tokens()),
        [parsed.syntax().format()]
    )?;
    formatted
        .context()
        .comments()
        .assert_all_formatted(source_code);
    Ok(formatted)
}

pub fn formatted_file(db: &dyn Db, file: File) -> Result<Option<String>, FormatModuleError> {
    let options = db.format_options(file);

    let parsed = parsed_module(db, file).load(db);

    if let Some(first) = parsed.errors().first() {
        return Err(FormatModuleError::ParseError(first.clone()));
    }

    let trivia = TriviaRanges::from(parsed.tokens());
    let source = source_text(db, file);

    let formatted = format_node(&parsed, &trivia, &source, options)?;
    let printed = formatted.print()?;

    if printed.as_code() == &*source {
        Ok(None)
    } else {
        Ok(Some(printed.into_code()))
    }
}

/// Public function for generating a printable string of the debug comments.
pub fn pretty_comments(module: &Mod, trivia: &TriviaRanges, source: &str) -> String {
    let source_code = SourceCode::new(source);
    let comments = Comments::from_ast(module, source_code, trivia);

    std::format!("{comments:#?}", comments = comments.debug(source_code))
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use anyhow::Result;
    use insta::assert_snapshot;

    use ruff_python_ast::PySourceType;
    use ruff_python_parser::{ParseOptions, parse};
    use ruff_python_trivia::TriviaRanges;
    use ruff_text_size::{TextRange, TextSize};

    use crate::{PyFormatOptions, format_module_ast, format_module_source, format_range};

    /// Very basic test intentionally kept very similar to the CLI
    #[test]
    fn basic() -> Result<()> {
        let input = r"
# preceding
if    True:
    pass
# trailing
";
        let expected = r"# preceding
if True:
    pass
# trailing
";
        let actual = format_module_source(input, PyFormatOptions::default())?
            .as_code()
            .to_string();
        assert_eq!(expected, actual);
        Ok(())
    }

    /// Use this test to debug the formatting of some snipped
    #[ignore]
    #[test]
    fn quick_test() {
        let source = r#"
def hello(): ...

@lambda _, /: _
class A: ...
"#;
        let source_type = PySourceType::Python;

        // Parse the AST.
        let source_path = "code_inline.py";
        let parsed = parse(source, ParseOptions::from(source_type)).unwrap();
        let trivia = TriviaRanges::from(parsed.tokens());
        let options = PyFormatOptions::from_extension(Path::new(source_path));
        let formatted = format_module_ast(&parsed, &trivia, source, options).unwrap();

        // Uncomment the `dbg` to print the IR.
        // Use `dbg_write!(f, []) instead of `write!(f, [])` in your formatting code to print some IR
        // inside of a `Format` implementation
        // use ruff_formatter::FormatContext;
        // dbg!(formatted
        //     .document()
        //     .display(formatted.context().source_code()));
        //
        // dbg!(formatted
        //     .context()
        //     .comments()
        //     .debug(formatted.context().source_code()));

        let printed = formatted.print().unwrap();

        assert_eq!(
            printed.as_code(),
            r"for converter in connection.ops.get_db_converters(
    expression
) + expression.get_db_converters(connection):
    ...
"
        );
    }

    /// Use this test to quickly debug some formatting issue.
    #[ignore]
    #[test]
    fn range_formatting_quick_test() {
        let source = r#"def convert_str(value: str) -> str:  # Trailing comment
    """Return a string as-is."""

<RANGE_START>

    return value  # Trailing comment
<RANGE_END>"#;

        let mut source = source.to_string();

        let start = TextSize::try_from(
            source
                .find("<RANGE_START>")
                .expect("Start marker not found"),
        )
        .unwrap();

        source.replace_range(
            start.to_usize()..start.to_usize() + "<RANGE_START>".len(),
            "",
        );

        let end =
            TextSize::try_from(source.find("<RANGE_END>").expect("End marker not found")).unwrap();

        source.replace_range(end.to_usize()..end.to_usize() + "<RANGE_END>".len(), "");

        let source_type = PySourceType::Python;
        let options = PyFormatOptions::from_source_type(source_type);
        let printed = format_range(&source, TextRange::new(start, end), options).unwrap();

        let mut formatted = source.clone();
        formatted.replace_range(
            std::ops::Range::<usize>::from(printed.source_range()),
            printed.as_code(),
        );

        assert_eq!(
            formatted,
            r#"print ( "format me" )
print("format me")
print("format me")
print ( "format me" )
print ( "format me" )"#
        );
    }

    #[test]
    fn string_processing() {
        use crate::prelude::*;
        use ruff_formatter::{format, format_args, write};

        struct FormatString<'a>(&'a str);

        impl Format<SimpleFormatContext> for FormatString<'_> {
            fn fmt(&self, f: &mut Formatter<SimpleFormatContext>) -> FormatResult<()> {
                let format_str = format_with(|f| {
                    write!(f, [token("\"")])?;

                    let mut words = self.0.split_whitespace().peekable();
                    let mut fill = f.fill();

                    let separator = format_with(|f| {
                        group(&format_args![
                            if_group_breaks(&token("\"")),
                            soft_line_break_or_space(),
                            if_group_breaks(&token("\" "))
                        ])
                        .fmt(f)
                    });

                    while let Some(word) = words.next() {
                        let is_last = words.peek().is_none();
                        let format_word = format_with(|f| {
                            write!(f, [text(word)])?;

                            if is_last {
                                write!(f, [token("\"")])?;
                            }

                            Ok(())
                        });

                        fill.entry(&separator, &format_word);
                    }

                    fill.finish()
                });

                write!(
                    f,
                    [group(&format_args![
                        if_group_breaks(&token("(")),
                        soft_block_indent(&format_str),
                        if_group_breaks(&token(")"))
                    ])]
                )
            }
        }

        // 77 after g group (leading quote)
        let fits =
            r"aaaaaaaaaa bbbbbbbbbb cccccccccc dddddddddd eeeeeeeeee ffffffffff gggggggggg h";
        let breaks =
            r"aaaaaaaaaa bbbbbbbbbb cccccccccc dddddddddd eeeeeeeeee ffffffffff gggggggggg hh";

        let output = format!(
            SimpleFormatContext::default(),
            [FormatString(fits), hard_line_break(), FormatString(breaks)]
        )
        .expect("Formatting to succeed");

        assert_snapshot!(output.print().expect("Printing to succeed").as_code());
    }
}