mirror of
https://github.com/astral-sh/ruff.git
synced 2026-12-04 00:22:00 +08:00
[ty] Separate module token access from syntax access
This commit is contained in:
@@ -34,7 +34,7 @@
|
||||
//! reveal_type(x)
|
||||
//! ```
|
||||
|
||||
use ruff_db::parsed::ParsedModuleRef;
|
||||
use ruff_python_ast::token::Tokens;
|
||||
use ruff_python_trivia::{CommentRanges, Cursor};
|
||||
use ruff_source_file::{LineIndex, OneIndexed};
|
||||
use ruff_text_size::{Ranged, TextRange, TextSize};
|
||||
@@ -46,7 +46,7 @@ use crate::RunOptions;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum AssertionSource<'a> {
|
||||
Python(&'a ParsedModuleRef),
|
||||
Python(&'a Tokens),
|
||||
Toml,
|
||||
}
|
||||
|
||||
@@ -63,10 +63,9 @@ impl<'s> InlineFileAssertions<'s> {
|
||||
file_index: &LineIndex,
|
||||
) -> Self {
|
||||
match assertion_source {
|
||||
AssertionSource::Python(parsed) => Self::from_comment_ranges(
|
||||
AssertionSource::Python(tokens) => Self::from_comment_ranges(
|
||||
source,
|
||||
parsed
|
||||
.tokens()
|
||||
tokens
|
||||
.iter()
|
||||
.filter(|token| token.kind().is_comment())
|
||||
.map(Ranged::range),
|
||||
@@ -537,7 +536,7 @@ mod tests {
|
||||
use crate::tests::TestDb;
|
||||
use ruff_db::PythonFile;
|
||||
use ruff_db::files::system_path_to_file;
|
||||
use ruff_db::parsed::parsed_module;
|
||||
use ruff_db::parsed::module_tokens;
|
||||
use ruff_db::source::line_index;
|
||||
use ruff_db::system::DbWithWritableSystem as _;
|
||||
use ruff_python_ast::PythonVersion;
|
||||
@@ -548,11 +547,11 @@ mod tests {
|
||||
let mut db = TestDb::setup();
|
||||
db.write_file("/src/test.py", source).unwrap();
|
||||
let file = system_path_to_file(&db, "/src/test.py").unwrap();
|
||||
let parsed =
|
||||
parsed_module(&db, PythonFile::new(&db, file, PythonVersion::latest_ty())).load(&db);
|
||||
let tokens =
|
||||
module_tokens(&db, PythonFile::new(&db, file, PythonVersion::latest_ty())).load(&db);
|
||||
InlineFileAssertions::from_file(
|
||||
source,
|
||||
AssertionSource::Python(&parsed),
|
||||
AssertionSource::Python(&tokens),
|
||||
&line_index(&db, file),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ use ruff_db::Db;
|
||||
use ruff_db::PythonFile;
|
||||
use ruff_db::diagnostic::{Diagnostic, DiagnosticId};
|
||||
use ruff_db::files::File;
|
||||
use ruff_db::parsed::parsed_module;
|
||||
use ruff_db::parsed::module_tokens;
|
||||
use ruff_db::source::{SourceText, line_index, source_text};
|
||||
use ruff_python_ast::PythonVersion;
|
||||
use ruff_source_file::{LineIndex, OneIndexed};
|
||||
@@ -111,10 +111,10 @@ pub fn match_file(
|
||||
});
|
||||
(assertions, diagnostics)
|
||||
} else {
|
||||
let parsed = parsed_module(db, PythonFile::new(db, file, python_version)).load(db);
|
||||
let tokens = module_tokens(db, PythonFile::new(db, file, python_version)).load(db);
|
||||
let assertions = InlineFileAssertions::from_file(
|
||||
source.as_str(),
|
||||
AssertionSource::Python(&parsed),
|
||||
AssertionSource::Python(&tokens),
|
||||
&line_index,
|
||||
);
|
||||
|
||||
@@ -122,10 +122,7 @@ pub fn match_file(
|
||||
// which the diagnostic appears. This can differ from the line containing the start of the
|
||||
// diagnostic range, for example for syntax errors inside stringized annotations.
|
||||
let diagnostics = SortedDiagnostics::new(diagnostics, &|diagnostic_range| {
|
||||
let token_start = parsed
|
||||
.tokens()
|
||||
.token_range(diagnostic_range.start())
|
||||
.start();
|
||||
let token_start = tokens.token_range(diagnostic_range.start()).start();
|
||||
line_index.line_index(token_start)
|
||||
});
|
||||
(assertions, diagnostics)
|
||||
|
||||
@@ -3,12 +3,13 @@ use std::sync::Arc;
|
||||
|
||||
use arc_swap::ArcSwapOption;
|
||||
use get_size2::{GetSize, GetSizeTracker};
|
||||
use ruff_python_ast::token::Tokens;
|
||||
use ruff_python_ast::{
|
||||
AnyRootNodeRef, HasNodeIndex, ModExpression, ModModule, NodeIndex, NodeIndexError,
|
||||
PythonVersion, StringLiteral,
|
||||
};
|
||||
use ruff_python_parser::{
|
||||
ParseError, ParseErrorType, ParseOptions, Parsed, parse_cells_unchecked,
|
||||
ParseError, ParseErrorType, ParseOptions, Parsed, ParsedSyntax, parse_cells_unchecked,
|
||||
parse_string_annotation, parse_unchecked,
|
||||
};
|
||||
|
||||
@@ -16,11 +17,12 @@ use crate::files::File;
|
||||
use crate::source::{read_source_text, source_text};
|
||||
use crate::{Db, PythonFile};
|
||||
|
||||
/// Returns the parsed AST of `file`, including its token stream.
|
||||
/// Returns the syntax tree and parse errors for `file`.
|
||||
/// Use [`module_tokens()`] to access the tokens from the same parse.
|
||||
///
|
||||
/// The query uses Ruff's error-resilient parser. That means that the parser always succeeds to produce an
|
||||
/// AST even if the file contains syntax errors. The parse errors
|
||||
/// are then accessible through [`Parsed::errors`].
|
||||
/// are then accessible through [`ParsedSyntax::errors`].
|
||||
///
|
||||
/// The query is only cached when the [`source_text()`] hasn't changed. This is because
|
||||
/// comparing two ASTs is a non-trivial operation and every offset change is directly
|
||||
@@ -42,6 +44,41 @@ pub fn parsed_module(db: &dyn Db, file: PythonFile<'_>) -> ParsedModule {
|
||||
ParsedModule::new(source_file, python_version, parsed)
|
||||
}
|
||||
|
||||
/// Returns the token stream for `file`. This shares the [`parsed_module()`] memo
|
||||
/// so callers can request both syntax and tokens without parsing twice.
|
||||
pub fn module_tokens<'db>(db: &'db dyn Db, file: PythonFile<'db>) -> ModuleTokens<'db> {
|
||||
ModuleTokens {
|
||||
module: parsed_module(db, file),
|
||||
}
|
||||
}
|
||||
|
||||
/// A handle to the tokens stored alongside a parsed module.
|
||||
pub struct ModuleTokens<'db> {
|
||||
module: &'db ParsedModule,
|
||||
}
|
||||
|
||||
impl ModuleTokens<'_> {
|
||||
/// Loads the tokens, keeping their indexed module alive until the guard is dropped.
|
||||
pub fn load(&self, db: &dyn Db) -> ModuleTokensRef {
|
||||
ModuleTokensRef {
|
||||
indexed: self.module.load(db).indexed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pins the indexed module while its tokens are in use.
|
||||
pub struct ModuleTokensRef {
|
||||
indexed: Arc<indexed::IndexedModule>,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for ModuleTokensRef {
|
||||
type Target = Tokens;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.indexed.tokens
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn disable_eviction(db: &mut dyn Db) {
|
||||
parsed_module::set_eviction_capacity(db, 0);
|
||||
}
|
||||
@@ -249,7 +286,7 @@ impl ParsedModuleRef {
|
||||
}
|
||||
|
||||
impl std::ops::Deref for ParsedModuleRef {
|
||||
type Target = Parsed<ModModule>;
|
||||
type Target = ParsedSyntax<ModModule>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.indexed.parsed
|
||||
@@ -281,15 +318,17 @@ impl Drop for ParsedModuleGuard {
|
||||
mod indexed {
|
||||
use std::sync::Arc;
|
||||
|
||||
use ruff_python_ast::token::Tokens;
|
||||
use ruff_python_ast::visitor::source_order::*;
|
||||
use ruff_python_ast::*;
|
||||
use ruff_python_parser::Parsed;
|
||||
use ruff_python_parser::{Parsed, ParsedSyntax};
|
||||
|
||||
/// A wrapper around the AST that allows access to AST nodes by index.
|
||||
#[derive(Debug, get_size2::GetSize)]
|
||||
pub struct IndexedModule {
|
||||
index: IndexedNodes,
|
||||
pub parsed: Parsed<ModModule>,
|
||||
pub parsed: ParsedSyntax<ModModule>,
|
||||
pub(super) tokens: Tokens,
|
||||
}
|
||||
|
||||
/// Compact storage for the address and [`RootNodeKind`] of every indexed AST node.
|
||||
@@ -630,8 +669,10 @@ mod indexed {
|
||||
overflowed: false,
|
||||
};
|
||||
|
||||
let (parsed, tokens) = parsed.into_parts();
|
||||
let mut inner = Arc::new(IndexedModule {
|
||||
parsed,
|
||||
tokens,
|
||||
index: IndexedNodes::default(),
|
||||
});
|
||||
|
||||
@@ -994,7 +1035,7 @@ mod tests {
|
||||
use crate::Db;
|
||||
use crate::PythonFile;
|
||||
use crate::files::{system_path_to_file, vendored_path_to_file};
|
||||
use crate::parsed::parsed_module;
|
||||
use crate::parsed::{module_tokens, parsed_module};
|
||||
use crate::source::source_text;
|
||||
use crate::system::{
|
||||
DbWithTestSystem, DbWithWritableSystem as _, SystemPath, SystemVirtualPath,
|
||||
@@ -1022,6 +1063,25 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syntax_and_tokens_share_the_indexed_module() -> crate::system::Result<()> {
|
||||
let mut db = TestDb::new();
|
||||
db.write_file("test.py", "x = 10")?;
|
||||
let file = system_path_to_file(&db, "test.py").unwrap();
|
||||
let file = PythonFile::new(&db, file, PythonVersion::latest_ty());
|
||||
|
||||
let module = parsed_module(&db, file);
|
||||
let syntax = module.load(&db);
|
||||
let tokens = module_tokens(&db, file).load(&db);
|
||||
assert!(std::sync::Arc::ptr_eq(&syntax.indexed, &tokens.indexed));
|
||||
|
||||
module.clear();
|
||||
let reloaded = module_tokens(&db, file).load(&db);
|
||||
assert!(!std::sync::Arc::ptr_eq(&tokens.indexed, &reloaded.indexed));
|
||||
assert_eq!(*tokens, *reloaded);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_ipynb_file() -> crate::system::Result<()> {
|
||||
let mut db = TestDb::new();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use ruff_db::PythonFile;
|
||||
use ruff_db::diagnostic::{Diagnostic, DiagnosticId, Severity};
|
||||
use ruff_db::files::File;
|
||||
use ruff_db::parsed::parsed_module;
|
||||
use ruff_db::parsed::{module_tokens, parsed_module};
|
||||
use ruff_db::source::source_text;
|
||||
use thiserror::Error;
|
||||
use tracing::Level;
|
||||
@@ -9,6 +9,7 @@ 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::token::Tokens;
|
||||
use ruff_python_ast::{AnyNodeRef, Mod};
|
||||
use ruff_python_parser::{ParseError, ParseOptions, Parsed, parse};
|
||||
use ruff_python_trivia::TriviaRanges;
|
||||
@@ -156,11 +157,12 @@ pub fn format_module_ast<'a>(
|
||||
source: &'a str,
|
||||
options: PyFormatOptions,
|
||||
) -> FormatResult<Formatted<PyFormatContext<'a>>> {
|
||||
format_node(parsed, trivia, source, options)
|
||||
format_node(parsed.syntax(), parsed.tokens(), trivia, source, options)
|
||||
}
|
||||
|
||||
fn format_node<'a, N>(
|
||||
parsed: &'a Parsed<N>,
|
||||
syntax: &'a N,
|
||||
tokens: &'a Tokens,
|
||||
trivia: &'a TriviaRanges,
|
||||
source: &'a str,
|
||||
options: PyFormatOptions,
|
||||
@@ -170,11 +172,11 @@ where
|
||||
&'a N: Into<AnyNodeRef<'a>>,
|
||||
{
|
||||
let source_code = SourceCode::new(source);
|
||||
let comments = Comments::from_ast(parsed.syntax(), source_code, trivia);
|
||||
let comments = Comments::from_ast(syntax, source_code, trivia);
|
||||
|
||||
let formatted = format!(
|
||||
PyFormatContext::new(options, source, comments, trivia, parsed.tokens()),
|
||||
[parsed.syntax().format()]
|
||||
PyFormatContext::new(options, source, comments, trivia, tokens),
|
||||
[syntax.format()]
|
||||
)?;
|
||||
formatted
|
||||
.context()
|
||||
@@ -186,16 +188,18 @@ where
|
||||
pub fn formatted_file(db: &dyn Db, file: File) -> Result<Option<String>, FormatModuleError> {
|
||||
let options = db.format_options(file);
|
||||
|
||||
let parsed = parsed_module(db, PythonFile::new(db, file, options.target_version())).load(db);
|
||||
let python_file = PythonFile::new(db, file, options.target_version());
|
||||
let parsed = parsed_module(db, python_file).load(db);
|
||||
|
||||
if let Some(first) = parsed.errors().first() {
|
||||
return Err(FormatModuleError::ParseError(first.clone()));
|
||||
}
|
||||
|
||||
let trivia = TriviaRanges::from(parsed.tokens());
|
||||
let tokens = module_tokens(db, python_file).load(db);
|
||||
let trivia = TriviaRanges::from(&*tokens);
|
||||
let source = source_text(db, file);
|
||||
|
||||
let formatted = format_node(&parsed, &trivia, &source, options)?;
|
||||
let formatted = format_node(parsed.syntax(), &tokens, &trivia, &source, options)?;
|
||||
let printed = formatted.print()?;
|
||||
|
||||
if printed.as_code() == &*source {
|
||||
|
||||
@@ -390,26 +390,42 @@ pub fn parse_cells_unchecked(
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the parsed source code.
|
||||
/// The parsed syntax tree and diagnostics without the token stream.
|
||||
pub type ParsedSyntax<T> = Parsed<T, ()>;
|
||||
|
||||
/// Represents the parsed source code, including its tokens by default.
|
||||
#[derive(Debug, PartialEq, Clone, get_size2::GetSize)]
|
||||
pub struct Parsed<T> {
|
||||
pub struct Parsed<T, TokenStream = Tokens> {
|
||||
syntax: T,
|
||||
tokens: Tokens,
|
||||
tokens: TokenStream,
|
||||
errors: Vec<ParseError>,
|
||||
unsupported_syntax_errors: Vec<UnsupportedSyntaxError>,
|
||||
}
|
||||
|
||||
impl<T> Parsed<T> {
|
||||
/// Returns the syntax node represented by this parsed output.
|
||||
pub fn syntax(&self) -> &T {
|
||||
&self.syntax
|
||||
}
|
||||
|
||||
/// Returns all the tokens for the parsed output.
|
||||
pub fn tokens(&self) -> &Tokens {
|
||||
&self.tokens
|
||||
}
|
||||
|
||||
/// Separates the tokens from the syntax tree and diagnostics.
|
||||
pub fn into_parts(self) -> (ParsedSyntax<T>, Tokens) {
|
||||
let parsed = Parsed {
|
||||
syntax: self.syntax,
|
||||
errors: self.errors,
|
||||
unsupported_syntax_errors: self.unsupported_syntax_errors,
|
||||
tokens: (),
|
||||
};
|
||||
(parsed, self.tokens)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S> Parsed<T, S> {
|
||||
/// Returns the syntax node represented by this parsed output.
|
||||
pub fn syntax(&self) -> &T {
|
||||
&self.syntax
|
||||
}
|
||||
|
||||
/// Returns a list of syntax errors found during parsing.
|
||||
pub fn errors(&self) -> &[ParseError] {
|
||||
&self.errors
|
||||
@@ -469,7 +485,7 @@ impl<T> Parsed<T> {
|
||||
///
|
||||
/// Note that any [`unsupported_syntax_errors`](Parsed::unsupported_syntax_errors) will not
|
||||
/// cause [`Err`] to be returned.
|
||||
pub fn as_result(&self) -> Result<&Parsed<T>, &[ParseError]> {
|
||||
pub fn as_result(&self) -> Result<&Self, &[ParseError]> {
|
||||
if self.has_valid_syntax() {
|
||||
Ok(self)
|
||||
} else {
|
||||
@@ -482,7 +498,7 @@ impl<T> Parsed<T> {
|
||||
///
|
||||
/// Note that any [`unsupported_syntax_errors`](Parsed::unsupported_syntax_errors) will not
|
||||
/// cause [`Err`] to be returned.
|
||||
fn into_result(self) -> Result<Parsed<T>, ParseError> {
|
||||
fn into_result(self) -> Result<Self, ParseError> {
|
||||
if self.has_valid_syntax() {
|
||||
Ok(self)
|
||||
} else {
|
||||
@@ -491,15 +507,10 @@ impl<T> Parsed<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl Parsed<Mod> {
|
||||
/// Attempts to convert the [`Parsed<Mod>`] into a [`Parsed<ModModule>`].
|
||||
///
|
||||
/// This method checks if the `syntax` field of the output is a [`Mod::Module`]. If it is, the
|
||||
/// method returns [`Some(Parsed<ModModule>)`] with the contained module. Otherwise, it
|
||||
/// returns [`None`].
|
||||
///
|
||||
/// [`Some(Parsed<ModModule>)`]: Some
|
||||
pub fn try_into_module(self) -> Option<Parsed<ModModule>> {
|
||||
impl<S> Parsed<Mod, S> {
|
||||
/// Returns the parsed module if the root is a [`Mod::Module`], preserving
|
||||
/// the diagnostics and any retained tokens.
|
||||
pub fn try_into_module(self) -> Option<Parsed<ModModule, S>> {
|
||||
match self.syntax {
|
||||
Mod::Module(module) => Some(Parsed {
|
||||
syntax: module,
|
||||
@@ -511,14 +522,9 @@ impl Parsed<Mod> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempts to convert the [`Parsed<Mod>`] into a [`Parsed<ModExpression>`].
|
||||
///
|
||||
/// This method checks if the `syntax` field of the output is a [`Mod::Expression`]. If it is,
|
||||
/// the method returns [`Some(Parsed<ModExpression>)`] with the contained expression.
|
||||
/// Otherwise, it returns [`None`].
|
||||
///
|
||||
/// [`Some(Parsed<ModExpression>)`]: Some
|
||||
fn try_into_expression(self) -> Option<Parsed<ModExpression>> {
|
||||
/// Returns the parsed expression if the root is a [`Mod::Expression`],
|
||||
/// preserving the diagnostics and any retained tokens.
|
||||
fn try_into_expression(self) -> Option<Parsed<ModExpression, S>> {
|
||||
match self.syntax {
|
||||
Mod::Module(_) => None,
|
||||
Mod::Expression(expression) => Some(Parsed {
|
||||
@@ -531,7 +537,7 @@ impl Parsed<Mod> {
|
||||
}
|
||||
}
|
||||
|
||||
impl Parsed<ModModule> {
|
||||
impl<S> Parsed<ModModule, S> {
|
||||
/// Returns the module body contained in this parsed output as a [`Suite`].
|
||||
pub fn suite(&self) -> &Suite {
|
||||
&self.syntax.body
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::references::has_any_external_visible_definitions;
|
||||
use crate::{CallHierarchyItem, Db, SymbolKind};
|
||||
use rayon::prelude::*;
|
||||
use ruff_db::files::File;
|
||||
use ruff_db::parsed::{ParsedModuleRef, parsed_module};
|
||||
use ruff_db::parsed::{ParsedModuleRef, module_tokens, parsed_module};
|
||||
use ruff_python_ast::helpers::is_dunder;
|
||||
use ruff_python_ast::name::Name;
|
||||
use ruff_python_ast::token::Tokens;
|
||||
@@ -172,9 +172,11 @@ fn call_sites_for_file(
|
||||
target_role: Option<PropertyAccessorRole>,
|
||||
needle: Option<&str>,
|
||||
) -> Vec<RawCallSite> {
|
||||
let parsed = parsed_module(db, file.python_file(db));
|
||||
let python_file = file.python_file(db);
|
||||
let parsed = parsed_module(db, python_file);
|
||||
// Incoming call searches can scan the whole project, so release closed files' ASTs as we go.
|
||||
let module = parsed.load_then_clear_on_drop(db);
|
||||
let tokens = module_tokens(db, python_file).load(db);
|
||||
let model = SemanticModel::new(db, file);
|
||||
let mut sites = Vec::new();
|
||||
|
||||
@@ -182,7 +184,7 @@ fn call_sites_for_file(
|
||||
db,
|
||||
model: &model,
|
||||
module: &module,
|
||||
tokens: module.tokens(),
|
||||
tokens: &tokens,
|
||||
target_definitions,
|
||||
target_role,
|
||||
needle,
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use std::collections::hash_map::Entry;
|
||||
|
||||
use crate::call_hierarchy::CalleeLeaf;
|
||||
use crate::goto::find_goto_target;
|
||||
use crate::goto::find_goto_target_impl;
|
||||
use crate::{CallHierarchyItem, Db};
|
||||
use ruff_db::files::File;
|
||||
use ruff_db::parsed::parsed_module;
|
||||
use ruff_db::parsed::{module_tokens, parsed_module};
|
||||
use ruff_python_ast::token::Tokens;
|
||||
use ruff_python_ast::visitor::source_order::{
|
||||
walk_arguments, walk_decorator, walk_expr, walk_parameters, walk_type_params,
|
||||
@@ -31,9 +31,12 @@ use ty_python_semantic::{ImportAliasResolution, SemanticModel};
|
||||
/// expressions attached to a nested callable are still included while
|
||||
/// traversing the containing item's body.
|
||||
pub fn outgoing_calls(db: &dyn Db, file: ProgramFile<'_>, offset: TextSize) -> Vec<OutgoingCall> {
|
||||
let module = parsed_module(db, file.python_file(db)).load(db);
|
||||
let python_file = file.python_file(db);
|
||||
let module = parsed_module(db, python_file).load(db);
|
||||
let tokens = module_tokens(db, python_file).load(db);
|
||||
let model = SemanticModel::new(db, file);
|
||||
let Some(goto_target) = find_goto_target(&model, &module, offset) else {
|
||||
let Some(goto_target) = find_goto_target_impl(&model, &tokens, module.syntax().into(), offset)
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(definitions) = goto_target
|
||||
@@ -60,7 +63,7 @@ pub fn outgoing_calls(db: &dyn Db, file: ProgramFile<'_>, offset: TextSize) -> V
|
||||
let mut finder = OutgoingCallsFinder {
|
||||
db,
|
||||
model: &model,
|
||||
tokens: module.tokens(),
|
||||
tokens: &tokens,
|
||||
by_callee: &mut groups,
|
||||
ancestors: Vec::new(),
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::collections::{BinaryHeap, binary_heap};
|
||||
use ty_python_semantic::ProgramEnvironment;
|
||||
|
||||
use compact_str::{CompactString, CompactStringExt};
|
||||
use ruff_db::parsed::{ParsedModuleRef, parsed_module};
|
||||
use ruff_db::parsed::{ParsedModuleRef, module_tokens, parsed_module};
|
||||
use ruff_db::source::{SourceText, source_text};
|
||||
use ruff_diagnostics::Edit;
|
||||
use ruff_python_ast::find_node::{CoveringNode, covering_node};
|
||||
@@ -41,11 +41,13 @@ pub fn completion<'db>(
|
||||
offset: TextSize,
|
||||
) -> Vec<Completion<'db>> {
|
||||
let program_file = file;
|
||||
let parsed = parsed_module(db, file.python_file(db)).load(db);
|
||||
let python_file = file.python_file(db);
|
||||
let parsed = parsed_module(db, python_file).load(db);
|
||||
let tokens = module_tokens(db, python_file).load(db);
|
||||
let file = file.file(db);
|
||||
let source = source_text(db, file);
|
||||
|
||||
let Some(context) = Context::new(db, program_file, &parsed, &source, offset) else {
|
||||
let Some(context) = Context::new(db, program_file, &parsed, &tokens, &source, offset) else {
|
||||
return vec![];
|
||||
};
|
||||
let model = SemanticModel::new(db, program_file);
|
||||
@@ -804,10 +806,11 @@ impl<'m> Context<'m> {
|
||||
db: &'_ dyn Db,
|
||||
file: ProgramFile<'_>,
|
||||
parsed: &'m ParsedModuleRef,
|
||||
tokens: &'m Tokens,
|
||||
source: &'m SourceText,
|
||||
offset: TextSize,
|
||||
) -> Option<Context<'m>> {
|
||||
let cursor = ContextCursor::new(parsed, source, offset);
|
||||
let cursor = ContextCursor::new(parsed, tokens, source, offset);
|
||||
if cursor.is_in_comment() {
|
||||
return None;
|
||||
}
|
||||
@@ -884,9 +887,7 @@ impl<'m> Context<'m> {
|
||||
/// This includes text that was typed and the cursor's
|
||||
/// byte offset in the source code.
|
||||
///
|
||||
/// The lifetime parameter `'m` refers to the shorter of the following
|
||||
/// lifetimes: the parsed module the cursor is in and the actual bytes
|
||||
/// making up the source file containing the cursor.
|
||||
/// The cursor borrows the parsed module, its tokens, and its source for `'m`.
|
||||
struct ContextCursor<'m> {
|
||||
/// The parsed module containing the cursor.
|
||||
parsed: &'m ParsedModuleRef,
|
||||
@@ -902,6 +903,8 @@ struct ContextCursor<'m> {
|
||||
/// When empty, this is just an empty range at the
|
||||
/// position of the cursor.
|
||||
range: TextRange,
|
||||
/// All tokens in the module.
|
||||
tokens: &'m Tokens,
|
||||
/// The tokens that appear before the cursor.
|
||||
tokens_before: &'m [Token],
|
||||
/// The covering node based on `parsed` and `range`.
|
||||
@@ -942,10 +945,11 @@ impl<'m> ContextCursor<'m> {
|
||||
/// Returns information about the context of the cursor.
|
||||
fn new(
|
||||
parsed: &'m ParsedModuleRef,
|
||||
tokens: &'m Tokens,
|
||||
source: &'m SourceText,
|
||||
offset: TextSize,
|
||||
) -> ContextCursor<'m> {
|
||||
let tokens_before = tokens_start_before(parsed.tokens(), offset);
|
||||
let tokens_before = tokens_start_before(tokens, offset);
|
||||
let Some(range) = ContextCursor::find_typed_text_range(tokens_before, offset) else {
|
||||
let range = TextRange::empty(offset);
|
||||
let covering_node = covering_node(parsed.syntax().into(), range);
|
||||
@@ -955,6 +959,7 @@ impl<'m> ContextCursor<'m> {
|
||||
typed: None,
|
||||
offset,
|
||||
range,
|
||||
tokens,
|
||||
tokens_before,
|
||||
covering_node,
|
||||
};
|
||||
@@ -973,6 +978,7 @@ impl<'m> ContextCursor<'m> {
|
||||
typed: Some(text),
|
||||
offset,
|
||||
range,
|
||||
tokens,
|
||||
tokens_before,
|
||||
covering_node,
|
||||
}
|
||||
@@ -1090,8 +1096,7 @@ impl<'m> ContextCursor<'m> {
|
||||
}
|
||||
|
||||
fn next_token_is_open_parenthesis(&self) -> bool {
|
||||
self.parsed
|
||||
.tokens()
|
||||
self.tokens
|
||||
.at_offset(self.offset)
|
||||
.last()
|
||||
.is_some_and(|token| token.kind() == TokenKind::Lpar)
|
||||
@@ -1198,15 +1203,13 @@ impl<'m> ContextCursor<'m> {
|
||||
parent: AnyNodeRef,
|
||||
) -> impl Iterator<Item = &Token> {
|
||||
let right_parentheses = self
|
||||
.parsed
|
||||
.tokens()
|
||||
.tokens
|
||||
.in_range(TextRange::new(range.end(), parent.end()))
|
||||
.iter()
|
||||
.filter(|token| !token.kind().is_trivia())
|
||||
.take_while(|token| token.kind() == TokenKind::Rpar);
|
||||
let left_parentheses = self
|
||||
.parsed
|
||||
.tokens()
|
||||
.tokens
|
||||
.before(range.start())
|
||||
.iter()
|
||||
.rev()
|
||||
@@ -1264,8 +1267,7 @@ impl<'m> ContextCursor<'m> {
|
||||
}
|
||||
|
||||
let Some(next) = self
|
||||
.parsed
|
||||
.tokens()
|
||||
.tokens
|
||||
.after(self.offset)
|
||||
.iter()
|
||||
.find(|token| !token.kind().is_trivia())
|
||||
@@ -1320,8 +1322,7 @@ impl<'m> ContextCursor<'m> {
|
||||
if token.kind() == TokenKind::Newline
|
||||
|| token.end() >= start
|
||||
|| self
|
||||
.parsed
|
||||
.tokens()
|
||||
.tokens
|
||||
.in_range(TextRange::new(token.end(), start))
|
||||
.iter()
|
||||
.any(|token| !token.kind().is_trivia())
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use crate::goto::find_goto_target;
|
||||
use crate::goto::find_goto_target_impl;
|
||||
use crate::references::{FixtureReferenceTarget, ReferencesMode, references};
|
||||
use crate::{Db, ReferenceTarget};
|
||||
use ruff_db::parsed::ParsedModuleRef;
|
||||
use ruff_db::parsed::{ParsedModuleRef, module_tokens, parsed_module};
|
||||
use ruff_python_ast::AnyNodeRef;
|
||||
use ruff_python_ast::find_node::covering_node;
|
||||
use ruff_python_ast::token::TokenKind;
|
||||
use ruff_python_ast::token::{TokenKind, Tokens};
|
||||
use ruff_text_size::{Ranged, TextSize};
|
||||
use ty_python_core::ProgramFile;
|
||||
use ty_python_semantic::{FixtureNameSource, SemanticModel, fixture_exposures_for_definition};
|
||||
@@ -17,8 +17,9 @@ pub fn find_references(
|
||||
offset: TextSize,
|
||||
include_declaration: bool,
|
||||
) -> Option<Vec<ReferenceTarget>> {
|
||||
let parsed = ruff_db::parsed::parsed_module(db, file.python_file(db));
|
||||
let module = parsed.load(db);
|
||||
let python_file = file.python_file(db);
|
||||
let module = parsed_module(db, python_file).load(db);
|
||||
let tokens = module_tokens(db, python_file).load(db);
|
||||
let model = SemanticModel::new(db, file);
|
||||
|
||||
let mode = if include_declaration {
|
||||
@@ -29,12 +30,12 @@ pub fn find_references(
|
||||
|
||||
// A decorator's `name="..."` literal names a fixture without defining a Python symbol.
|
||||
// Start a fixture-only search before the ordinary symbol lookup below.
|
||||
if let Some(target) = explicit_fixture_name_at_offset(&model, &module, offset) {
|
||||
if let Some(target) = explicit_fixture_name_at_offset(&model, &module, &tokens, offset) {
|
||||
return target.references(db, file, mode);
|
||||
}
|
||||
|
||||
// Get the definitions for the symbol at the cursor position
|
||||
let goto_target = find_goto_target(&model, &module, offset)?;
|
||||
let goto_target = find_goto_target_impl(&model, &tokens, module.syntax().into(), offset)?;
|
||||
references(db, file, &goto_target, mode)
|
||||
}
|
||||
|
||||
@@ -55,10 +56,10 @@ pub fn find_references(
|
||||
fn explicit_fixture_name_at_offset<'db>(
|
||||
model: &SemanticModel<'db>,
|
||||
module: &ParsedModuleRef,
|
||||
tokens: &Tokens,
|
||||
offset: TextSize,
|
||||
) -> Option<FixtureReferenceTarget<'db>> {
|
||||
let token = module
|
||||
.tokens()
|
||||
let token = tokens
|
||||
.at_offset(offset)
|
||||
.find(|token| token.kind() == TokenKind::String)?;
|
||||
let covering = covering_node(module.syntax().into(), token.range());
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use ruff_db::PythonFile;
|
||||
use ruff_db::parsed::parsed_module;
|
||||
use ruff_db::parsed::{module_tokens, parsed_module};
|
||||
use ruff_db::source::source_text;
|
||||
use ruff_python_ast::token::{TokenKind, Tokens, parenthesized_range};
|
||||
use ruff_python_ast::visitor::source_order::{
|
||||
@@ -60,6 +60,7 @@ pub fn folding_ranges(
|
||||
range_filter: Option<TextRange>,
|
||||
) -> Vec<FoldingRange> {
|
||||
let parsed = parsed_module(db, file).load(db);
|
||||
let tokens = module_tokens(db, file).load(db);
|
||||
let file = file.file(db);
|
||||
let source = source_text(db, file);
|
||||
|
||||
@@ -67,7 +68,7 @@ pub fn folding_ranges(
|
||||
source: source.as_str(),
|
||||
ranges: vec![],
|
||||
active_block_fold_start_lines: vec![],
|
||||
tokens: parsed.tokens(),
|
||||
tokens: &tokens,
|
||||
range_filter,
|
||||
};
|
||||
walk_node(&mut visitor, AnyNodeRef::from(parsed.syntax()));
|
||||
@@ -77,8 +78,7 @@ pub fn folding_ranges(
|
||||
);
|
||||
|
||||
// Add remaining ranges not covered by the AST visitor.
|
||||
let own_line_comment_ranges: Vec<_> = parsed
|
||||
.tokens()
|
||||
let own_line_comment_ranges: Vec<_> = tokens
|
||||
.iter()
|
||||
.filter_map(|token| {
|
||||
if token.kind() == TokenKind::Comment
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::borrow::Cow;
|
||||
|
||||
use crate::NavigationTarget;
|
||||
use crate::stub_mapping::StubMapper;
|
||||
use ruff_db::parsed::ParsedModuleRef;
|
||||
use ruff_db::parsed::{ParsedModuleRef, module_tokens};
|
||||
use ruff_python_ast::find_node::{CoveringNode, covering_node};
|
||||
use ruff_python_ast::token::{Token, TokenAt, TokenKind, Tokens};
|
||||
use ruff_python_ast::{self as ast, AnyNodeRef, ExprRef};
|
||||
@@ -1435,12 +1435,13 @@ pub(crate) fn find_goto_target<'a>(
|
||||
parsed: &'a ParsedModuleRef,
|
||||
offset: TextSize,
|
||||
) -> Option<GotoTarget<'a>> {
|
||||
find_goto_target_impl(model, parsed.tokens(), parsed.syntax().into(), offset)
|
||||
let tokens = module_tokens(model.db(), model.python_file()).load(model.db());
|
||||
find_goto_target_impl(model, &tokens, parsed.syntax().into(), offset)
|
||||
}
|
||||
|
||||
pub(crate) fn find_goto_target_impl<'a>(
|
||||
model: &'a SemanticModel,
|
||||
tokens: &'a Tokens,
|
||||
tokens: &Tokens,
|
||||
syntax: AnyNodeRef<'a>,
|
||||
offset: TextSize,
|
||||
) -> Option<GotoTarget<'a>> {
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::{fmt, vec};
|
||||
use ty_python_semantic::ProgramEnvironment;
|
||||
|
||||
use crate::{Db, FxIndexMap, HasNavigationTargets, NavigationTarget};
|
||||
use ruff_db::parsed::{ParsedModuleRef, parsed_module};
|
||||
use ruff_db::parsed::{ParsedModuleRef, module_tokens, parsed_module};
|
||||
use ruff_python_ast::token::{Tokens, parenthesized_range};
|
||||
use ruff_python_ast::visitor::source_order::{self, SourceOrderVisitor, TraversalSignal};
|
||||
use ruff_python_ast::{
|
||||
@@ -366,8 +366,10 @@ pub fn inlay_hints(
|
||||
range: TextRange,
|
||||
settings: &InlayHintSettings,
|
||||
) -> Vec<InlayHint> {
|
||||
let ast = parsed_module(db, file.python_file(db)).load(db);
|
||||
let mut visitor = InlayHintVisitor::new(db, file, &ast, range, settings);
|
||||
let python_file = file.python_file(db);
|
||||
let ast = parsed_module(db, python_file).load(db);
|
||||
let tokens = module_tokens(db, python_file).load(db);
|
||||
let mut visitor = InlayHintVisitor::new(db, file, &ast, &tokens, range, settings);
|
||||
|
||||
visitor.visit_body(ast.suite());
|
||||
|
||||
@@ -440,6 +442,7 @@ impl<'a, 'db> InlayHintVisitor<'a, 'db> {
|
||||
db: &'db dyn Db,
|
||||
file: ProgramFile<'db>,
|
||||
ast: &'db ParsedModuleRef,
|
||||
tokens: &'db Tokens,
|
||||
range: TextRange,
|
||||
settings: &'a InlayHintSettings,
|
||||
) -> Self {
|
||||
@@ -447,7 +450,7 @@ impl<'a, 'db> InlayHintVisitor<'a, 'db> {
|
||||
db,
|
||||
model: SemanticModel::new(db, file),
|
||||
importer: Importer::new(db, file, ast),
|
||||
tokens: ast.tokens(),
|
||||
tokens,
|
||||
hints: Vec::new(),
|
||||
pending_return_hint: None,
|
||||
assignment: None,
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::goto::{Definitions, GotoTarget};
|
||||
use crate::{Db, ReferenceKind, ReferenceTarget};
|
||||
use rayon::prelude::*;
|
||||
use ruff_db::files::File;
|
||||
use ruff_db::parsed::parsed_module;
|
||||
use ruff_db::parsed::{module_tokens, parsed_module};
|
||||
use ruff_python_ast::find_node::CoveringNode;
|
||||
use ruff_python_ast::token::Tokens;
|
||||
use ruff_python_ast::{
|
||||
@@ -258,16 +258,18 @@ fn references_for_keyword_arguments_in_file(
|
||||
"keyword-label cross-file scan should not run in DocumentHighlights mode"
|
||||
);
|
||||
|
||||
let parsed = parsed_module(db, file.python_file(db));
|
||||
let python_file = file.python_file(db);
|
||||
let parsed = parsed_module(db, python_file);
|
||||
// Reference and rename searches can scan the whole project, so release closed files' ASTs
|
||||
// as we go.
|
||||
let module = parsed.load_then_clear_on_drop(db);
|
||||
let tokens = module_tokens(db, python_file).load(db);
|
||||
let model = SemanticModel::new(db, file);
|
||||
let mut references = Vec::new();
|
||||
|
||||
let mut finder = KeywordArgumentReferencesFinder(LocalReferencesFinder {
|
||||
model: &model,
|
||||
tokens: module.tokens(),
|
||||
tokens: &tokens,
|
||||
search,
|
||||
references: &mut references,
|
||||
mode,
|
||||
@@ -313,10 +315,12 @@ fn references_for_file(
|
||||
search: &LocalReferenceSearch<'_>,
|
||||
mode: ReferencesMode,
|
||||
) -> Vec<ReferenceTarget> {
|
||||
let parsed = parsed_module(db, file.python_file(db));
|
||||
let python_file = file.python_file(db);
|
||||
let parsed = parsed_module(db, python_file);
|
||||
// Reference and rename searches can scan the whole project, so release closed files' ASTs
|
||||
// as we go.
|
||||
let module = parsed.load_then_clear_on_drop(db);
|
||||
let tokens = module_tokens(db, python_file).load(db);
|
||||
let model = SemanticModel::new(db, file);
|
||||
let mut references = Vec::new();
|
||||
|
||||
@@ -325,7 +329,7 @@ fn references_for_file(
|
||||
search,
|
||||
references: &mut references,
|
||||
mode,
|
||||
tokens: module.tokens(),
|
||||
tokens: &tokens,
|
||||
fixture_match_cache: FxHashMap::default(),
|
||||
ancestors: Vec::new(),
|
||||
};
|
||||
|
||||
@@ -9,10 +9,10 @@
|
||||
use crate::docstring::Docstring;
|
||||
use crate::goto::{docstring_for_call_definition, docstring_for_parameter_field};
|
||||
use crate::{Db, FxIndexMap, MarkupKind};
|
||||
use ruff_db::parsed::parsed_module;
|
||||
use ruff_db::parsed::{module_tokens, parsed_module};
|
||||
use ruff_db::source::source_text;
|
||||
use ruff_python_ast::find_node::covering_node;
|
||||
use ruff_python_ast::token::TokenKind;
|
||||
use ruff_python_ast::token::{TokenKind, Tokens};
|
||||
use ruff_python_ast::{self as ast, AnyNodeRef};
|
||||
use ruff_python_trivia::PythonWhitespace;
|
||||
use ruff_source_file::LineRanges;
|
||||
@@ -83,10 +83,11 @@ pub fn signature_help<'db>(
|
||||
) -> Option<SignatureHelpInfo<'db>> {
|
||||
let python_file = file.python_file(db);
|
||||
let parsed = parsed_module(db, python_file).load(db);
|
||||
let tokens = module_tokens(db, python_file).load(db);
|
||||
let source = source_text(db, python_file.file(db));
|
||||
|
||||
// Get the call expression at the given position.
|
||||
let (call_expr, current_arg_index) = get_call_expr(&parsed, &source, offset)?;
|
||||
let (call_expr, current_arg_index) = get_call_expr(&parsed, &tokens, &source, offset)?;
|
||||
|
||||
let model = SemanticModel::new(db, file);
|
||||
|
||||
@@ -119,6 +120,7 @@ pub fn signature_help<'db>(
|
||||
/// and the index of the argument that the offset maps to.
|
||||
fn get_call_expr<'ast>(
|
||||
parsed: &'ast ruff_db::parsed::ParsedModuleRef,
|
||||
tokens: &Tokens,
|
||||
source: &str,
|
||||
offset: TextSize,
|
||||
) -> Option<(&'ast ast::ExprCall, usize)> {
|
||||
@@ -129,8 +131,7 @@ fn get_call_expr<'ast>(
|
||||
let token_offset = offset.min(line_end);
|
||||
|
||||
// Find the token under the cursor and use its offset to find the node
|
||||
let token = parsed
|
||||
.tokens()
|
||||
let token = tokens
|
||||
.at_offset(token_offset)
|
||||
.max_by_key(|token| match token.kind() {
|
||||
TokenKind::Identifier
|
||||
|
||||
@@ -13,7 +13,7 @@ The main differences here are:
|
||||
use rustc_hash::FxHashMap;
|
||||
|
||||
use ruff_db::PythonFile;
|
||||
use ruff_db::parsed::{ParsedModuleRef, parsed_module};
|
||||
use ruff_db::parsed::{ModuleTokensRef, ParsedModuleRef, module_tokens, parsed_module};
|
||||
|
||||
use crate::types::Type;
|
||||
use crate::{Db, SemanticModel};
|
||||
@@ -21,7 +21,6 @@ use ruff_db::source::{SourceText, source_text};
|
||||
use ruff_diagnostics::Edit;
|
||||
use ruff_python_ast as ast;
|
||||
use ruff_python_ast::name::Name;
|
||||
use ruff_python_ast::token::Tokens;
|
||||
use ruff_python_codegen::Stylist;
|
||||
use ruff_python_importer::Insertion;
|
||||
use ruff_text_size::{Ranged, TextRange, TextSize};
|
||||
@@ -40,7 +39,7 @@ pub struct Importer<'a> {
|
||||
/// The parsed module ref.
|
||||
parsed: &'a ParsedModuleRef,
|
||||
/// The tokens representing the Python AST.
|
||||
tokens: &'a Tokens,
|
||||
tokens: ModuleTokensRef,
|
||||
/// The source code for `file`.
|
||||
source: SourceText,
|
||||
/// The cached source style for formatting inserted code.
|
||||
@@ -58,15 +57,16 @@ impl<'a> Importer<'a> {
|
||||
/// Source style and top-level imports are cached per file, so callers
|
||||
/// can construct an importer without rescanning the source or AST.
|
||||
pub fn new(db: &'a dyn Db, file: ProgramFile<'a>, parsed: &'a ParsedModuleRef) -> Self {
|
||||
let imports = top_level_imports(db, file.python_file(db));
|
||||
let python_file = file.python_file(db);
|
||||
let imports = top_level_imports(db, python_file);
|
||||
|
||||
Self {
|
||||
db,
|
||||
file,
|
||||
parsed,
|
||||
tokens: parsed.tokens(),
|
||||
tokens: module_tokens(db, python_file).load(db),
|
||||
source: source_text(db, file.file(db)),
|
||||
stylist: stylist(db, file.python_file(db)),
|
||||
stylist: stylist(db, python_file),
|
||||
imports,
|
||||
}
|
||||
}
|
||||
@@ -192,7 +192,7 @@ impl<'a> Importer<'a> {
|
||||
}
|
||||
ImportResponseKind::Partial => {
|
||||
let import = if let Some(insertion) =
|
||||
Insertion::existing_import(response.import.stmt, self.tokens)
|
||||
Insertion::existing_import(response.import.stmt, &self.tokens)
|
||||
{
|
||||
insertion.into_edit(member)
|
||||
} else {
|
||||
@@ -506,9 +506,9 @@ impl<'a> Importer<'a> {
|
||||
/// Detects source style once per file revision, shared by diagnostics and IDE features.
|
||||
#[salsa::tracked(returns(ref), no_eq)]
|
||||
fn stylist(db: &dyn Db, file: PythonFile<'_>) -> Stylist<'static> {
|
||||
let parsed = parsed_module(db, file).load(db);
|
||||
let tokens = module_tokens(db, file).load(db);
|
||||
let source = source_text(db, file.file(db));
|
||||
Stylist::from_tokens(parsed.tokens(), &source).into_owned()
|
||||
Stylist::from_tokens(&tokens, &source).into_owned()
|
||||
}
|
||||
|
||||
#[salsa::tracked(returns(ref), no_eq, heap_size=ruff_memory_usage::heap_size)]
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::hash::{Hash, Hasher};
|
||||
use ruff_db::diagnostic::{
|
||||
Annotation, Diagnostic, DiagnosticId, IntoDiagnosticMessage, LintName, Severity, Span,
|
||||
};
|
||||
use ruff_db::{PythonFile, files::File, parsed::parsed_module, source::source_text};
|
||||
use ruff_db::{PythonFile, files::File, parsed::module_tokens, source::source_text};
|
||||
use ruff_diagnostics::{Edit, Fix};
|
||||
use ruff_python_ast::token::{TokenKind, Tokens};
|
||||
use ruff_python_trivia::indentation_at_offset;
|
||||
@@ -88,7 +88,7 @@ pub(crate) fn is_unused_ignore_comment_lint(name: LintName) -> bool {
|
||||
#[salsa::tracked(returns(ref), heap_size=ruff_memory_usage::heap_size)]
|
||||
pub(crate) fn suppressions(db: &dyn Db, file: PythonFile<'_>) -> Suppressions {
|
||||
let source_file = file.file(db);
|
||||
let parsed = parsed_module(db, file).load(db);
|
||||
let tokens = module_tokens(db, file).load(db);
|
||||
let source = source_text(db, source_file);
|
||||
|
||||
let respect_type_ignore = db
|
||||
@@ -98,7 +98,7 @@ pub(crate) fn suppressions(db: &dyn Db, file: PythonFile<'_>) -> Suppressions {
|
||||
let mut builder = SuppressionsBuilder::new(&source, db.lint_registry());
|
||||
let mut line_start = TextSize::default();
|
||||
|
||||
for token in parsed.tokens() {
|
||||
for token in tokens.iter() {
|
||||
if !token.kind().is_trivia() {
|
||||
builder.set_seen_non_trivia_token();
|
||||
}
|
||||
@@ -116,7 +116,7 @@ pub(crate) fn suppressions(db: &dyn Db, file: PythonFile<'_>) -> Suppressions {
|
||||
builder.add_comment(
|
||||
comment,
|
||||
TextRange::new(line_start, token.end()),
|
||||
parsed.tokens(),
|
||||
&tokens,
|
||||
);
|
||||
}
|
||||
Err(error) => match error.kind {
|
||||
|
||||
@@ -12,10 +12,10 @@ use std::fmt::Formatter;
|
||||
use ruff_db::PythonFile;
|
||||
use ruff_db::diagnostic::LintName;
|
||||
use ruff_db::display::FormatterJoinExtension;
|
||||
use ruff_db::parsed::parsed_module;
|
||||
use ruff_db::parsed::module_tokens;
|
||||
use ruff_db::source::source_text;
|
||||
use ruff_diagnostics::{Edit, Fix};
|
||||
use ruff_python_ast::token::TokenKind;
|
||||
use ruff_python_ast::token::{TokenKind, Tokens};
|
||||
use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};
|
||||
use smallvec::SmallVec;
|
||||
|
||||
@@ -38,8 +38,7 @@ pub(crate) fn suppress_all(
|
||||
) -> Vec<SuppressFix> {
|
||||
let suppressions = suppressions(db, file);
|
||||
let source = source_text(db, file.file(db));
|
||||
let parsed = parsed_module(db, file).load(db);
|
||||
let tokens = parsed.tokens();
|
||||
let tokens = module_tokens(db, file).load(db);
|
||||
|
||||
// Compute the full suppression ranges for each diagnostic, while retaining the original
|
||||
// diagnostic ranges for matching existing suppressions.
|
||||
@@ -49,7 +48,7 @@ pub(crate) fn suppress_all(
|
||||
(
|
||||
id,
|
||||
diagnostic_range,
|
||||
suppression_range(db, file, diagnostic_range),
|
||||
suppression_range(&tokens, diagnostic_range),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
@@ -109,7 +108,7 @@ pub(crate) fn suppress_all(
|
||||
*suppressed_diagnostics += 1;
|
||||
|
||||
by_line
|
||||
.entry(line_start(tokens, range.end()))
|
||||
.entry(line_start(&tokens, range.end()))
|
||||
.or_default()
|
||||
.entry(id)
|
||||
.or_insert(range.end());
|
||||
@@ -167,7 +166,8 @@ pub(crate) struct SuppressFix {
|
||||
|
||||
/// Creates a fix to suppress a single lint.
|
||||
pub fn suppress_single(db: &dyn Db, file: PythonFile<'_>, id: LintId, range: TextRange) -> Fix {
|
||||
let suppression_range = suppression_range(db, file, range);
|
||||
let tokens = module_tokens(db, file).load(db);
|
||||
let suppression_range = suppression_range(&tokens, range);
|
||||
|
||||
let suppressions = suppressions(db, file);
|
||||
let source = source_text(db, file.file(db));
|
||||
@@ -193,18 +193,17 @@ pub fn suppress_single(db: &dyn Db, file: PythonFile<'_>, id: LintId, range: Tex
|
||||
/// * If `range` is within a single-line interpolated expression, then the start and end are extended to the start and end of the enclosing interpolated string.
|
||||
/// * If there's a line continuation, then the suppression range is extended to include the following line too.
|
||||
/// * If there's a multiline string, then the suppression range is extended to cover the starting and ending line of the multiline string.
|
||||
fn suppression_range(db: &dyn Db, file: PythonFile<'_>, range: TextRange) -> TextRange {
|
||||
fn suppression_range(tokens: &Tokens, range: TextRange) -> TextRange {
|
||||
// Always insert a new suppression at the end of the range to avoid having to deal with multiline strings
|
||||
// etc. Also make sure to not pass a sub-token range to `Tokens::after`.
|
||||
let parsed = parsed_module(db, file).load(db);
|
||||
let line_start = line_start(parsed.tokens(), range.start());
|
||||
let line_start = line_start(tokens, range.start());
|
||||
|
||||
let after_token_range = match parsed.tokens().at_offset(range.end()) {
|
||||
let after_token_range = match tokens.at_offset(range.end()) {
|
||||
ruff_python_ast::token::TokenAt::None => range,
|
||||
ruff_python_ast::token::TokenAt::Single(token) => token.range(),
|
||||
ruff_python_ast::token::TokenAt::Between(..) => range,
|
||||
};
|
||||
let after_tokens = parsed.tokens().after(after_token_range.end());
|
||||
let after_tokens = tokens.after(after_token_range.end());
|
||||
let line_end = after_tokens
|
||||
.iter()
|
||||
.find(|token| {
|
||||
@@ -219,7 +218,7 @@ fn suppression_range(db: &dyn Db, file: PythonFile<'_>, range: TextRange) -> Tex
|
||||
TextRange::new(line_start, line_end)
|
||||
}
|
||||
|
||||
fn line_start(tokens: &ruff_python_ast::token::Tokens, offset: TextSize) -> TextSize {
|
||||
fn line_start(tokens: &Tokens, offset: TextSize) -> TextSize {
|
||||
tokens
|
||||
.before(tokens.token_range(offset).start())
|
||||
.iter()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use ruff_db::parsed::parsed_module;
|
||||
use ruff_db::parsed::module_tokens;
|
||||
use ruff_db::source::source_text;
|
||||
use ruff_diagnostics::{Edit, Fix};
|
||||
use ruff_python_ast::token::Tokens;
|
||||
@@ -76,7 +76,7 @@ pub(super) fn check_unused_suppressions(context: &mut CheckSuppressionsContext)
|
||||
}
|
||||
|
||||
let source = source_text(context.db, context.file());
|
||||
let parsed = parsed_module(context.db, context.python_file).load(context.db);
|
||||
let tokens = module_tokens(context.db, context.python_file).load(context.db);
|
||||
|
||||
while let Some(suppression) = unused_iter.next() {
|
||||
let unused_lint = match suppression.kind {
|
||||
@@ -208,7 +208,7 @@ pub(super) fn check_unused_suppressions(context: &mut CheckSuppressionsContext)
|
||||
diag.primary_annotation_mut()
|
||||
.unwrap()
|
||||
.push_tag(ruff_db::diagnostic::DiagnosticTag::Unnecessary);
|
||||
diag.set_fix(remove_comment_fix(suppression, &source, parsed.tokens()));
|
||||
diag.set_fix(remove_comment_fix(suppression, &source, &tokens));
|
||||
diag.help("Remove the unused suppression comment");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::{
|
||||
use drop_bomb::DebugDropBomb;
|
||||
use ruff_db::PythonFile;
|
||||
use ruff_db::diagnostic::DiagnosticTag;
|
||||
use ruff_db::parsed::ParsedModuleRef;
|
||||
use ruff_db::parsed::{ModuleTokensRef, ParsedModuleRef, module_tokens};
|
||||
use ruff_db::{
|
||||
diagnostic::{Annotation, Diagnostic, DiagnosticId, IntoDiagnosticMessage, Severity, Span},
|
||||
files::File,
|
||||
@@ -225,6 +225,10 @@ impl<'db, 'ast> InferContext<'db, 'ast> {
|
||||
self.module
|
||||
}
|
||||
|
||||
pub(super) fn module_tokens(&self) -> ModuleTokensRef {
|
||||
module_tokens(self.db, self.python_file()).load(self.db)
|
||||
}
|
||||
|
||||
/// Constructs an importer using the file's cached imports and source style.
|
||||
pub(crate) fn importer(&self) -> Importer<'_> {
|
||||
Importer::new(self.db, self.program_file, self.module)
|
||||
|
||||
@@ -2272,7 +2272,7 @@ fn assignment_diagnostic_range(
|
||||
// 1 + 2 + 3
|
||||
// ) # ty: ignore <- or here
|
||||
// ```
|
||||
parentheses_iterator(value_node.into(), None, context.module().tokens())
|
||||
parentheses_iterator(value_node.into(), None, &context.module_tokens())
|
||||
.last()
|
||||
.unwrap_or(value_node.range())
|
||||
})
|
||||
|
||||
@@ -1785,7 +1785,7 @@ impl KnownFunction {
|
||||
call_expression,
|
||||
value,
|
||||
covering.parent(),
|
||||
builder.module().tokens(),
|
||||
&builder.context.module_tokens(),
|
||||
&source,
|
||||
);
|
||||
diagnostic.help("Remove the redundant `cast`");
|
||||
|
||||
+4
-4
@@ -1447,7 +1447,7 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
|
||||
.map_or_default(|(_, ending)| ending)
|
||||
.as_str();
|
||||
|
||||
let mut end = logical_line_end(&source, self.module().tokens(), clause.end());
|
||||
let mut end = logical_line_end(&source, &self.context.module_tokens(), clause.end());
|
||||
|
||||
// Keep trailing body comments with the `elif`, including those after a nested statement.
|
||||
for line in UniversalNewlineIterator::with_offset(&source[usize::from(end)..], end) {
|
||||
@@ -1576,10 +1576,10 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
|
||||
) -> Option<Fix> {
|
||||
let first_statement = clause.body.first()?;
|
||||
let source = source_text(self.db(), self.file());
|
||||
let tokens = self.module().tokens();
|
||||
let tokens = self.context.module_tokens();
|
||||
let first_statement_line_start = source.line_start(first_statement.start());
|
||||
|
||||
if first_statement_line_start < logical_line_end(&source, tokens, clause.start()) {
|
||||
if first_statement_line_start < logical_line_end(&source, &tokens, clause.start()) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -1593,7 +1593,7 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
|
||||
}
|
||||
|
||||
let indentation = indentation_at_offset(first_statement.start(), &source)?;
|
||||
let parenthesized_test_range = parenthesized_range(test.into(), clause.into(), tokens);
|
||||
let parenthesized_test_range = parenthesized_range(test.into(), clause.into(), &tokens);
|
||||
let test_range = parenthesized_test_range.unwrap_or(test.range());
|
||||
let header_prefix_range = TextRange::new(clause.start(), test_range.start());
|
||||
|
||||
|
||||
@@ -798,18 +798,13 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
|
||||
if let (Some(first_elt), Some(last_elt)) =
|
||||
(tuple.elts.first(), tuple.elts.last())
|
||||
{
|
||||
let first_range = parenthesized_range(
|
||||
first_elt.into(),
|
||||
tuple.into(),
|
||||
self.module().tokens(),
|
||||
)
|
||||
.unwrap_or(first_elt.range());
|
||||
let last_range = parenthesized_range(
|
||||
last_elt.into(),
|
||||
tuple.into(),
|
||||
self.module().tokens(),
|
||||
)
|
||||
.unwrap_or(last_elt.range());
|
||||
let tokens = self.context.module_tokens();
|
||||
let first_range =
|
||||
parenthesized_range(first_elt.into(), tuple.into(), &tokens)
|
||||
.unwrap_or(first_elt.range());
|
||||
let last_range =
|
||||
parenthesized_range(last_elt.into(), tuple.into(), &tokens)
|
||||
.unwrap_or(last_elt.range());
|
||||
diagnostic.set_fix(Fix::unsafe_edits(
|
||||
Edit::range_replacement(
|
||||
"tuple[".to_string(),
|
||||
@@ -981,12 +976,11 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
|
||||
&& SemanticModel::new(db, self.program_file())
|
||||
.definitely_has_builtin_binding("dict", dict.into())
|
||||
{
|
||||
let key_range =
|
||||
parenthesized_range(key.into(), dict.into(), self.module().tokens())
|
||||
.unwrap_or(key.range());
|
||||
let value_range =
|
||||
parenthesized_range(value.into(), dict.into(), self.module().tokens())
|
||||
.unwrap_or(value.range());
|
||||
let tokens = self.context.module_tokens();
|
||||
let key_range = parenthesized_range(key.into(), dict.into(), &tokens)
|
||||
.unwrap_or(key.range());
|
||||
let value_range = parenthesized_range(value.into(), dict.into(), &tokens)
|
||||
.unwrap_or(value.range());
|
||||
diagnostic.help("Replace with `dict[...]`");
|
||||
diagnostic.set_fix(Fix::unsafe_edits(
|
||||
Edit::range_replacement(
|
||||
@@ -1044,7 +1038,7 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
|
||||
let element_range = parenthesized_range(
|
||||
single_element.into(),
|
||||
set.into(),
|
||||
self.module().tokens(),
|
||||
&self.context.module_tokens(),
|
||||
)
|
||||
.unwrap_or(single_element.range());
|
||||
diagnostic.help("Replace with `set[...]`");
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::types::{
|
||||
};
|
||||
use compact_str::ToCompactString;
|
||||
use ruff_db::diagnostic::{Annotation, Span};
|
||||
use ruff_db::parsed::parsed_module;
|
||||
use ruff_db::parsed::{module_tokens, parsed_module};
|
||||
use ruff_python_ast as ast;
|
||||
use ruff_python_ast::name::Name;
|
||||
use ruff_python_ast::token::TokenKind;
|
||||
@@ -65,14 +65,15 @@ fn async_generator_stub_declaration<'db>(
|
||||
let DefinitionKind::Function(function) = definition.kind(db) else {
|
||||
return None;
|
||||
};
|
||||
let module = parsed_module(db, definition.program_file(db).python_file(db)).load(db);
|
||||
let file = definition.python_file(db);
|
||||
let module = parsed_module(db, file).load(db);
|
||||
let node = function.node(&module);
|
||||
if !node.is_async || !function_has_stub_body(node) {
|
||||
return None;
|
||||
}
|
||||
// Start at `async`, excluding any decorators from the declaration's range.
|
||||
let start = module
|
||||
.tokens()
|
||||
let start = module_tokens(db, file)
|
||||
.load(db)
|
||||
.in_range(TextRange::new(node.start(), node.name.start()))
|
||||
.iter()
|
||||
.rfind(|token| token.kind() == TokenKind::Async)?
|
||||
|
||||
@@ -301,13 +301,13 @@ impl Workspace {
|
||||
|
||||
/// Returns the token stream for `path` serialized as a string.
|
||||
pub fn tokens(&self, file_id: &FileHandle) -> Result<String, Error> {
|
||||
let parsed = ruff_db::parsed::parsed_module(
|
||||
let tokens = ruff_db::parsed::module_tokens(
|
||||
&self.db,
|
||||
self.db.program_file(file_id.file).python_file(&self.db),
|
||||
)
|
||||
.load(&self.db);
|
||||
|
||||
Ok(format!("{:#?}", parsed.tokens()))
|
||||
Ok(format!("{:#?}", *tokens))
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = "sourceText")]
|
||||
|
||||
@@ -129,7 +129,7 @@ reason = "preserves the public parser and linter target-version accessor pair"
|
||||
[[override]]
|
||||
lint = "hawk::unnecessary_public"
|
||||
crate = "ruff_python_parser"
|
||||
item = "Parsed::<T>::has_no_syntax_errors"
|
||||
item = "Parsed::<T, S>::has_no_syntax_errors"
|
||||
kind = "inherent_method"
|
||||
level = "expect"
|
||||
reason = "preserves the public syntax-validity predicate API"
|
||||
@@ -417,7 +417,7 @@ reason = "downstream parser clients can consume a parse error into its error kin
|
||||
[[override]]
|
||||
lint = "hawk::dead_public"
|
||||
crate = "ruff_python_parser"
|
||||
item = "Parsed::<T>::as_result"
|
||||
item = "Parsed::<T, S>::as_result"
|
||||
kind = "inherent_method"
|
||||
level = "expect"
|
||||
reason = "downstream parser clients retain borrowed result conversion"
|
||||
|
||||
Reference in New Issue
Block a user