[red-knot] Add 'Format document' to playground (#17217)
Some checks are pending
CI / cargo build (msrv) (push) Blocked by required conditions
CI / cargo fuzz build (push) Blocked by required conditions
CI / Determine changes (push) Waiting to run
CI / cargo fmt (push) Waiting to run
CI / cargo clippy (push) Blocked by required conditions
CI / cargo test (linux) (push) Blocked by required conditions
CI / cargo test (linux, release) (push) Blocked by required conditions
CI / cargo test (windows) (push) Blocked by required conditions
CI / cargo test (wasm) (push) Blocked by required conditions
CI / cargo build (release) (push) Waiting to run
CI / fuzz parser (push) Blocked by required conditions
CI / test scripts (push) Blocked by required conditions
CI / ecosystem (push) Blocked by required conditions
CI / cargo shear (push) Blocked by required conditions
CI / python package (push) Waiting to run
CI / pre-commit (push) Waiting to run
CI / mkdocs (push) Waiting to run
CI / formatter instabilities and black similarity (push) Blocked by required conditions
CI / test ruff-lsp (push) Blocked by required conditions
CI / check playground (push) Blocked by required conditions
CI / benchmarks (push) Blocked by required conditions
[Knot Playground] Release / publish (push) Waiting to run

## Summary
This is more "because we can" than something we need. 

But since we're already building an "almost IDE" 

## Test Plan



https://github.com/user-attachments/assets/3a4bdad1-ba32-455a-9909-cfeb8caa1b28
This commit is contained in:
Micha Reiser 2025-04-07 09:26:03 +02:00 committed by GitHub
parent 12d7fad4ef
commit 3150812ac4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 162 additions and 27 deletions

View file

@ -15,6 +15,7 @@ doctest = false
[dependencies]
ruff_cache = { workspace = true }
ruff_db = { workspace = true }
ruff_formatter = { workspace = true }
ruff_macros = { workspace = true }
ruff_python_trivia = { workspace = true }
@ -30,6 +31,7 @@ itertools = { workspace = true }
memchr = { workspace = true }
regex = { workspace = true }
rustc-hash = { workspace = true }
salsa = { workspace = true }
serde = { workspace = true, optional = true }
schemars = { workspace = true, optional = true }
smallvec = { workspace = true }
@ -58,7 +60,12 @@ required-features = ["serde"]
[features]
default = ["serde"]
serde = ["dep:serde", "ruff_formatter/serde", "ruff_source_file/serde", "ruff_python_ast/serde"]
serde = [
"dep:serde",
"ruff_formatter/serde",
"ruff_source_file/serde",
"ruff_python_ast/serde",
]
schemars = ["dep:schemars", "ruff_formatter/schemars"]
[lints]

View file

@ -0,0 +1,9 @@
use ruff_db::{files::File, Db as SourceDb, Upcast};
use crate::PyFormatOptions;
#[salsa::db]
pub trait Db: SourceDb + Upcast<dyn SourceDb> {
/// Returns the formatting options
fn format_options(&self, file: File) -> PyFormatOptions;
}

View file

@ -1,3 +1,6 @@
use ruff_db::files::File;
use ruff_db::parsed::parsed_module;
use ruff_db::source::source_text;
use thiserror::Error;
use tracing::Level;
@ -13,6 +16,7 @@ use crate::comments::{
has_skip_comment, leading_comments, trailing_comments, Comments, SourceComment,
};
pub use crate::context::PyFormatContext;
pub use crate::db::Db;
pub use crate::options::{
DocstringCode, DocstringCodeLineWidth, MagicTrailingComma, PreviewMode, PyFormatOptions,
QuoteStyle,
@ -25,6 +29,7 @@ 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;
@ -96,7 +101,7 @@ where
}
}
#[derive(Error, Debug)]
#[derive(Error, Debug, salsa::Update, PartialEq, Eq)]
pub enum FormatModuleError {
#[error(transparent)]
ParseError(#[from] ParseError),
@ -124,6 +129,19 @@ pub fn format_module_ast<'a>(
source: &'a str,
options: PyFormatOptions,
) -> FormatResult<Formatted<PyFormatContext<'a>>> {
format_node(parsed, comment_ranges, source, options)
}
fn format_node<'a, N>(
parsed: &'a Parsed<N>,
comment_ranges: &'a CommentRanges,
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, comment_ranges);
@ -138,6 +156,28 @@ pub fn format_module_ast<'a>(
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.upcast(), file);
if let Some(first) = parsed.errors().first() {
return Err(FormatModuleError::ParseError(first.clone()));
}
let comment_ranges = CommentRanges::from(parsed.tokens());
let source = source_text(db.upcast(), file);
let formatted = format_node(parsed, &comment_ranges, &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, comment_ranges: &CommentRanges, source: &str) -> String {
let source_code = SourceCode::new(source);