repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_macros/src/newtype_index.rs
crates/ruff_macros/src/newtype_index.rs
use quote::quote; use syn::spanned::Spanned; use syn::{Error, ItemStruct}; pub(super) fn generate_newtype_index(item: ItemStruct) -> syn::Result<proc_macro2::TokenStream> { if !item.fields.is_empty() { return Err(Error::new( item.span(), "A new type index cannot have any fields.", )); } if !item.generics.params.is_empty() { return Err(Error::new( item.span(), "A new type index cannot be generic.", )); } let ItemStruct { attrs, vis, struct_token, ident, generics: _, fields: _, semi_token, } = item; let debug_name = ident.to_string(); let semi_token = semi_token.unwrap_or_default(); let output = quote! { #(#attrs)* #[derive(Copy, Clone, Eq, PartialEq, Hash)] #vis #struct_token #ident(std::num::NonZeroU32)#semi_token impl #ident { const MAX_VALUE: u32 = u32::MAX - 1; const MAX: Self = Self::from_u32(Self::MAX_VALUE); #vis const fn from_usize(value: usize) -> Self { assert!(value <= Self::MAX_VALUE as usize); // SAFETY: // * The `value < u32::MAX` guarantees that the add doesn't overflow. // * The `+ 1` guarantees that the index is not zero Self(std::num::NonZeroU32::new((value as u32) + 1).unwrap()) } #vis const fn from_u32(value: u32) -> Self { assert!(value <= Self::MAX_VALUE); // SAFETY: // * The `value < u32::MAX` guarantees that the add doesn't overflow. // * The `+ 1` guarantees that the index is larger than zero. Self(std::num::NonZeroU32::new(value + 1).unwrap()) } /// Returns the index as a `u32` value #[inline] #vis const fn as_u32(self) -> u32 { self.0.get() - 1 } /// Returns the index as a `usize` value #[inline] #vis const fn as_usize(self) -> usize { self.as_u32() as usize } #[inline] #vis const fn index(self) -> usize { self.as_usize() } } impl std::ops::Add<usize> for #ident { type Output = #ident; fn add(self, rhs: usize) -> Self::Output { #ident::from_usize(self.index() + rhs) } } impl std::ops::Add for #ident { type Output = #ident; fn add(self, rhs: Self) -> Self::Output { #ident::from_usize(self.index() + rhs.index()) } } impl std::fmt::Debug for #ident { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple(#debug_name).field(&self.index()).finish() } } impl ruff_index::Idx for #ident { #[inline] fn new(value: usize) -> Self { #ident::from_usize(value) } #[inline] fn index(self) -> usize { self.index() } } impl From<usize> for #ident { fn from(value: usize) -> Self { #ident::from_usize(value) } } impl From<u32> for #ident { fn from(value: u32) -> Self { #ident::from_u32(value) } } impl From<#ident> for usize { fn from(value: #ident) -> Self { value.as_usize() } } impl From<#ident> for u32 { fn from(value: #ident) -> Self { value.as_u32() } } }; Ok(output) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_macros/src/kebab_case.rs
crates/ruff_macros/src/kebab_case.rs
use heck::ToKebabCase; use proc_macro2::TokenStream; pub(crate) fn kebab_case(input: &syn::Ident) -> TokenStream { let s = input.to_string(); let kebab_case_lit = syn::LitStr::new(&s.to_kebab_case(), input.span()); quote::quote!(#kebab_case_lit) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_macros/src/lib.rs
crates/ruff_macros/src/lib.rs
//! This crate implements internal macros for the `ruff` and `ty` libraries. use crate::cache_key::derive_cache_key; use crate::newtype_index::generate_newtype_index; use crate::violation_metadata::violation_metadata; use proc_macro::TokenStream; use syn::{DeriveInput, Error, ItemFn, ItemStruct, parse_macro_input}; mod cache_key; mod combine; mod combine_options; mod config; mod derive_message_formats; mod env_vars; mod kebab_case; mod map_codes; mod newtype_index; mod rule_code_prefix; mod rule_namespace; mod rust_doc; mod violation_metadata; #[proc_macro_derive(OptionsMetadata, attributes(option, doc, option_group))] pub fn derive_options_metadata(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); config::derive_impl(input) .unwrap_or_else(syn::Error::into_compile_error) .into() } #[proc_macro_derive(RustDoc)] pub fn derive_rust_doc(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); rust_doc::derive_impl(input) .unwrap_or_else(syn::Error::into_compile_error) .into() } #[proc_macro_derive(CombineOptions)] pub fn derive_combine_options(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); combine_options::derive_impl(input) .unwrap_or_else(syn::Error::into_compile_error) .into() } /// Automatically derives a `ty_combine::Combine` implementation for the attributed type /// that calls `ty_combine::Combine::combine` for each field. /// /// The derive macro can only be used on structs. Enums aren't yet supported. #[proc_macro_derive(Combine)] pub fn derive_combine(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); combine::derive_impl(input) .unwrap_or_else(syn::Error::into_compile_error) .into() } /// Converts an identifier to a kebab case string. #[proc_macro] pub fn kebab_case(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as syn::Ident); kebab_case::kebab_case(&input).into() } /// Generates a [`CacheKey`] implementation for the attributed type. /// /// Struct fields can be attributed with the `cache_key` field-attribute that supports: /// * `ignore`: Ignore the attributed field in the cache key #[proc_macro_derive(CacheKey, attributes(cache_key))] pub fn cache_key(input: TokenStream) -> TokenStream { let item = parse_macro_input!(input as DeriveInput); let result = derive_cache_key(&item); let stream = result.unwrap_or_else(|err| err.to_compile_error()); TokenStream::from(stream) } #[proc_macro_derive(ViolationMetadata, attributes(violation_metadata))] pub fn derive_violation_metadata(item: TokenStream) -> TokenStream { let input: DeriveInput = parse_macro_input!(item); violation_metadata(input) .unwrap_or_else(Error::into_compile_error) .into() } #[proc_macro_derive(RuleNamespace, attributes(prefix))] pub fn derive_rule_namespace(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); rule_namespace::derive_impl(input) .unwrap_or_else(syn::Error::into_compile_error) .into() } #[proc_macro_attribute] pub fn map_codes(_attr: TokenStream, item: TokenStream) -> TokenStream { let func = parse_macro_input!(item as ItemFn); map_codes::map_codes(&func) .unwrap_or_else(syn::Error::into_compile_error) .into() } #[proc_macro_attribute] pub fn derive_message_formats(_attr: TokenStream, item: TokenStream) -> TokenStream { let func = parse_macro_input!(item as ItemFn); derive_message_formats::derive_message_formats(&func).into() } /// Derives a newtype wrapper that can be used as an index. /// The wrapper can represent indices up to `u32::MAX - 1`. /// /// The `u32::MAX - 1` is an optimization so that `Option<Index>` has the same size as `Index`. /// /// Can store at most `u32::MAX - 1` values /// /// ## Warning /// /// Additional `derive` attributes must come AFTER this attribute: /// /// Good: /// /// ```ignore /// use ruff_macros::newtype_index; /// /// #[newtype_index] /// #[derive(Ord, PartialOrd)] /// struct MyIndex; /// ``` #[proc_macro_attribute] pub fn newtype_index(_metadata: TokenStream, input: TokenStream) -> TokenStream { let item = parse_macro_input!(input as ItemStruct); let output = match generate_newtype_index(item) { Ok(output) => output, Err(err) => err.to_compile_error(), }; TokenStream::from(output) } /// Generates metadata for environment variables declared in the impl block. /// /// This attribute macro should be applied to an `impl EnvVars` block. /// It will generate a `metadata()` method that returns all non-hidden /// environment variables with their documentation. #[proc_macro_attribute] pub fn attribute_env_vars_metadata(_attr: TokenStream, item: TokenStream) -> TokenStream { let input = parse_macro_input!(item as syn::ItemImpl); env_vars::attribute_env_vars_metadata(input).into() }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_macros/src/rust_doc.rs
crates/ruff_macros/src/rust_doc.rs
use proc_macro2::TokenStream; use quote::quote; use syn::{Attribute, DeriveInput, Error, Lit, LitStr, Meta}; pub(crate) fn derive_impl(input: DeriveInput) -> syn::Result<TokenStream> { let docs = get_docs(&input.attrs)?; let name = input.ident; let (impl_generics, ty_generics, where_clause) = &input.generics.split_for_impl(); Ok(quote! { #[automatically_derived] impl #impl_generics ruff_db::RustDoc for #name #ty_generics #where_clause { fn rust_doc() -> &'static str { #docs } } }) } /// Collect all doc comment attributes into a string fn get_docs(attrs: &[Attribute]) -> syn::Result<String> { let mut explanation = String::new(); for attr in attrs { if attr.path().is_ident("doc") { if let Some(lit) = parse_attr(["doc"], attr) { let value = lit.value(); // `/// ` adds let line = value.strip_prefix(' ').unwrap_or(&value); explanation.push_str(line); explanation.push('\n'); } else { return Err(Error::new_spanned(attr, "unimplemented doc comment style")); } } } Ok(explanation) } fn parse_attr<'a, const LEN: usize>( path: [&'static str; LEN], attr: &'a Attribute, ) -> Option<&'a LitStr> { if let Meta::NameValue(name_value) = &attr.meta { let path_idents = name_value .path .segments .iter() .map(|segment| &segment.ident); if path_idents.eq(path) { if let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(lit), .. }) = &name_value.value { return Some(lit); } } } None }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_macros/src/derive_message_formats.rs
crates/ruff_macros/src/derive_message_formats.rs
use proc_macro2::TokenStream; use quote::{ToTokens, quote, quote_spanned}; use syn::spanned::Spanned; use syn::token::{Dot, Paren}; use syn::{Block, Expr, ExprLit, ExprMethodCall, ItemFn, Lit, Stmt}; pub(crate) fn derive_message_formats(func: &ItemFn) -> TokenStream { let mut strings = quote!(); if let Err(err) = parse_block(&func.block, &mut strings) { return err; } quote! { #func fn message_formats() -> &'static [&'static str] { &[#strings] } } } fn parse_block(block: &Block, strings: &mut TokenStream) -> Result<(), TokenStream> { let Some(Stmt::Expr(last, _)) = block.stmts.last() else { panic!("expected last statement in block to be an expression") }; parse_expr(last, strings)?; Ok(()) } fn parse_expr(expr: &Expr, strings: &mut TokenStream) -> Result<(), TokenStream> { match expr { Expr::Macro(mac) if mac.mac.path.is_ident("format") => { let mut tokens = mac.mac.tokens.to_token_stream().into_iter(); let Some(first_token) = tokens.next() else { return Err( quote_spanned!(expr.span() => compile_error!("expected `format!` to have an argument")), ); }; // do not throw an error if the `format!` argument contains a formatting argument if !first_token.to_string().contains('{') { // comma and string if tokens.next().is_none() || tokens.next().is_none() { return Err( quote_spanned!(expr.span() => compile_error!("prefer `String::to_string` over `format!` without arguments")), ); } } strings.extend(quote! {#first_token,}); Ok(()) } Expr::Block(block) => parse_block(&block.block, strings), Expr::If(expr) => { parse_block(&expr.then_branch, strings)?; if let Some((_, then)) = &expr.else_branch { parse_expr(then, strings)?; } Ok(()) } Expr::MethodCall(method_call) => match method_call { ExprMethodCall { method, receiver, attrs, dot_token, turbofish: None, paren_token, args, } if *method == *"to_string" && attrs.is_empty() && args.is_empty() && *paren_token == Paren::default() && *dot_token == Dot::default() => { let Expr::Lit(ExprLit { lit: Lit::Str(ref literal_string), .. }) = **receiver else { return Err( quote_spanned!(expr.span() => compile_error!("expected `String::to_string` method on str literal")), ); }; let str_token = literal_string.token(); strings.extend(quote! {#str_token,}); Ok(()) } _ => Err( quote_spanned!(expr.span() => compile_error!("expected `String::to_string` method on str literal")), ), }, Expr::Match(block) => { for arm in &block.arms { parse_expr(&arm.body, strings)?; } Ok(()) } _ => Err(quote_spanned!( expr.span() => compile_error!("expected last expression to be a `format!` macro, a static String or a match block") )), } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_macros/src/cache_key.rs
crates/ruff_macros/src/cache_key.rs
use proc_macro2::{Ident, TokenStream}; use quote::{format_ident, quote}; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; use syn::{Data, DeriveInput, Error, Field, Fields, Token}; pub(crate) fn derive_cache_key(item: &DeriveInput) -> syn::Result<TokenStream> { let fields = match &item.data { Data::Enum(item_enum) => { let arms = item_enum.variants.iter().enumerate().map(|(i, variant)| { let variant_name = &variant.ident; match &variant.fields { Fields::Named(fields) => { let field_names: Vec<_> = fields .named .iter() .map(|field| field.ident.clone().unwrap()) .collect(); let fields_code = field_names .iter() .map(|field| quote!(#field.cache_key(key);)); quote! { Self::#variant_name{#(#field_names),*} => { key.write_usize(#i); #(#fields_code)* } } } Fields::Unnamed(fields) => { let field_names: Vec<_> = fields .unnamed .iter() .enumerate() .map(|(i, _)| format_ident!("field_{i}")) .collect(); let fields_code = field_names .iter() .map(|field| quote!(#field.cache_key(key);)); quote! { Self::#variant_name(#(#field_names),*) => { key.write_usize(#i); #(#fields_code)* } } } Fields::Unit => { quote! { Self::#variant_name => { key.write_usize(#i); } } } } }); quote! { match self { #(#arms)* } } } Data::Struct(item_struct) => { let mut fields = Vec::with_capacity(item_struct.fields.len()); for (i, field) in item_struct.fields.iter().enumerate() { if let Some(cache_field_attribute) = cache_key_field_attribute(field)? { if cache_field_attribute.ignore { continue; } } let field_attr = if let Some(ident) = &field.ident { quote!(self.#ident) } else { let index = syn::Index::from(i); quote!(self.#index) }; fields.push(quote!(#field_attr.cache_key(key);)); } quote! {#(#fields)*} } Data::Union(_) => { return Err(Error::new( item.span(), "CacheKey does not support unions. Only structs and enums are supported", )); } }; let name = &item.ident; let (impl_generics, ty_generics, where_clause) = &item.generics.split_for_impl(); Ok(quote!( #[automatically_derived] impl #impl_generics ruff_cache::CacheKey for #name #ty_generics #where_clause { fn cache_key(&self, key: &mut ruff_cache::CacheKeyHasher) { use std::hash::Hasher; use ruff_cache::CacheKey; #fields } } )) } fn cache_key_field_attribute(field: &Field) -> syn::Result<Option<CacheKeyFieldAttributes>> { if let Some(attribute) = field .attrs .iter() .find(|attribute| attribute.path().is_ident("cache_key")) { attribute.parse_args::<CacheKeyFieldAttributes>().map(Some) } else { Ok(None) } } #[derive(Debug, Default)] struct CacheKeyFieldAttributes { ignore: bool, } impl Parse for CacheKeyFieldAttributes { fn parse(input: ParseStream) -> syn::Result<Self> { let mut attributes = CacheKeyFieldAttributes::default(); let args = input.parse_terminated(Ident::parse, Token![,])?; for arg in args { match arg.to_string().as_str() { "ignore" => { attributes.ignore = true; } name => { return Err(Error::new( arg.span(), format!("Unknown `cache_field` argument {name}"), )); } } } Ok(attributes) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_macros/src/rule_namespace.rs
crates/ruff_macros/src/rule_namespace.rs
use std::cmp::Reverse; use std::collections::HashSet; use quote::quote; use syn::spanned::Spanned; use syn::{Attribute, Data, DataEnum, DeriveInput, Error, ExprLit, Lit, Meta, MetaNameValue}; pub(crate) fn derive_impl(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> { let DeriveInput { ident, data: Data::Enum(DataEnum { variants, .. }), .. } = input else { return Err(Error::new( input.ident.span(), "only named fields are supported", )); }; let mut parsed = Vec::new(); let mut common_prefix_match_arms = quote!(); let mut name_match_arms = quote!(Self::Ruff => "Ruff-specific rules", Self::Numpy => "NumPy-specific rules", ); let mut url_match_arms = quote!(Self::Ruff => None, Self::Numpy => None, ); let mut all_prefixes = HashSet::new(); for variant in variants { let mut first_chars = HashSet::new(); let prefixes: Result<Vec<_>, _> = variant .attrs .iter() .filter(|attr| attr.path().is_ident("prefix")) .map(|attr| { let Meta::NameValue(MetaNameValue{value: syn::Expr::Lit (ExprLit { lit: Lit::Str(lit), ..}), ..}) = &attr.meta else { return Err(Error::new(attr.span(), r#"expected attribute to be in the form of [#prefix = "..."]"#)); }; let str = lit.value(); match str.chars().next() { None => return Err(Error::new(lit.span(), "expected prefix string to be non-empty")), Some(c) => if !first_chars.insert(c) { return Err(Error::new(lit.span(), format!("this variant already has another prefix starting with the character '{c}'"))) } } if !all_prefixes.insert(str.clone()) { return Err(Error::new(lit.span(), "prefix has already been defined before")); } Ok(str) }) .collect(); let prefixes = prefixes?; if prefixes.is_empty() { return Err(Error::new( variant.span(), r#"Missing #[prefix = "..."] attribute"#, )); } let Some(doc_attr) = variant .attrs .iter() .find(|attr| attr.path().is_ident("doc")) else { return Err(Error::new(variant.span(), "expected a doc comment")); }; let variant_ident = variant.ident; if variant_ident != "Ruff" && variant_ident != "Numpy" { let (name, url) = parse_doc_attr(doc_attr)?; name_match_arms.extend(quote! {Self::#variant_ident => #name,}); url_match_arms.extend(quote! {Self::#variant_ident => Some(#url),}); } for lit in &prefixes { parsed.push(( lit.clone(), variant_ident.clone(), match prefixes.len() { 1 => ParseStrategy::SinglePrefix, _ => ParseStrategy::MultiplePrefixes, }, )); } if let [prefix] = &prefixes[..] { common_prefix_match_arms.extend(quote! { Self::#variant_ident => #prefix, }); } else { // There is more than one prefix. We already previously asserted // that prefixes of the same variant don't start with the same character // so the common prefix for this variant is the empty string. common_prefix_match_arms.extend(quote! { Self::#variant_ident => "", }); } } parsed.sort_by_key(|(prefix, ..)| Reverse(prefix.len())); let mut if_statements = quote!(); for (prefix, field, strategy) in parsed { let ret_str = match strategy { ParseStrategy::SinglePrefix => quote!(rest), ParseStrategy::MultiplePrefixes => quote!(code), }; if_statements.extend(quote! {if let Some(rest) = code.strip_prefix(#prefix) { return Some((#ident::#field, #ret_str)); }}); } Ok(quote! { #[automatically_derived] impl crate::registry::RuleNamespace for #ident { fn parse_code(code: &str) -> Option<(Self, &str)> { #if_statements None } fn common_prefix(&self) -> &'static str { match self { #common_prefix_match_arms } } fn name(&self) -> &'static str { match self { #name_match_arms } } fn url(&self) -> Option<&'static str> { match self { #url_match_arms } } } }) } /// Parses an attribute in the form of `#[doc = " [name](https://example.com/)"]` /// into a tuple of link label and URL. fn parse_doc_attr(doc_attr: &Attribute) -> syn::Result<(String, String)> { let Meta::NameValue(MetaNameValue { value: syn::Expr::Lit(ExprLit { lit: Lit::Str(doc_lit), .. }), .. }) = &doc_attr.meta else { return Err(Error::new( doc_attr.span(), r#"expected doc attribute to be in the form of #[doc = "..."]"#, )); }; parse_markdown_link(doc_lit.value().trim()) .map(|(name, url)| (name.to_string(), url.to_string())) .ok_or_else(|| { Error::new( doc_lit.span(), "expected doc comment to be in the form of `/// [name](https://example.com/)`", ) }) } fn parse_markdown_link(link: &str) -> Option<(&str, &str)> { link.strip_prefix('[')?.strip_suffix(')')?.split_once("](") } enum ParseStrategy { SinglePrefix, MultiplePrefixes, }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_macros/src/combine.rs
crates/ruff_macros/src/combine.rs
use quote::{quote, quote_spanned}; use syn::spanned::Spanned; use syn::{Data, DataStruct, DeriveInput}; pub(crate) fn derive_impl(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> { let DeriveInput { ident, data, .. } = input; match data { Data::Struct(DataStruct { fields, .. }) => { let output: Vec<_> = fields .members() .map(|member| { quote_spanned!( member.span() => ty_combine::Combine::combine_with(&mut self.#member, other.#member) ) }) .collect(); Ok(quote! { #[automatically_derived] impl ty_combine::Combine for #ident { #[allow(deprecated)] fn combine_with(&mut self, other: Self) { #( #output );* } } }) } _ => Err(syn::Error::new( ident.span(), "Can only derive Combine from structs.", )), } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_macros/src/rule_code_prefix.rs
crates/ruff_macros/src/rule_code_prefix.rs
use std::collections::{BTreeMap, BTreeSet}; use proc_macro2::Span; use quote::quote; use syn::{Attribute, Ident}; pub(crate) fn expand<'a>( prefix_ident: &Ident, variants: impl Iterator<Item = (&'a str, &'a Vec<Attribute>)>, ) -> proc_macro2::TokenStream { // Build up a map from prefix to matching RuleCodes. let mut prefix_to_codes: BTreeMap<String, BTreeSet<String>> = BTreeMap::default(); let mut code_to_attributes: BTreeMap<String, &[Attribute]> = BTreeMap::default(); for (variant, .., attr) in variants { let code_str = variant.to_string(); for i in 1..=code_str.len() { let prefix = code_str[..i].to_string(); prefix_to_codes .entry(prefix) .or_default() .insert(code_str.clone()); } code_to_attributes.insert(code_str, attr); } let variant_strs: Vec<_> = prefix_to_codes.keys().collect(); let variant_idents: Vec<_> = prefix_to_codes .keys() .map(|prefix| { let ident = get_prefix_ident(prefix); quote! { #ident } }) .collect(); let attributes: Vec<_> = prefix_to_codes .values() .map(|codes| attributes_for_prefix(codes, &code_to_attributes)) .collect(); quote! { #[derive( ::strum_macros::EnumIter, Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash, )] pub enum #prefix_ident { #(#attributes #variant_idents,)* } impl std::str::FromStr for #prefix_ident { type Err = crate::registry::FromCodeError; fn from_str(code: &str) -> Result<Self, Self::Err> { match code { #(#attributes #variant_strs => Ok(Self::#variant_idents),)* _ => Err(crate::registry::FromCodeError::Unknown) } } } impl From<&#prefix_ident> for &'static str { fn from(code: &#prefix_ident) -> Self { match code { #(#attributes #prefix_ident::#variant_idents => #variant_strs,)* } } } impl AsRef<str> for #prefix_ident { fn as_ref(&self) -> &str { match self { #(#attributes Self::#variant_idents => #variant_strs,)* } } } } } fn attributes_for_prefix( codes: &BTreeSet<String>, attributes: &BTreeMap<String, &[Attribute]>, ) -> proc_macro2::TokenStream { let attrs = intersection_all(codes.iter().map(|code| attributes[code])); if attrs.is_empty() { quote!() } else { quote!(#(#attrs)*) } } /// Collect all the items from an iterable of slices that are present in all slices. pub(crate) fn intersection_all<'a, T: PartialEq>( mut slices: impl Iterator<Item = &'a [T]>, ) -> Vec<&'a T> { if let Some(slice) = slices.next() { // Collect all the items in the first slice let mut intersection = Vec::with_capacity(slice.len()); for item in slice { intersection.push(item); } // Then only keep items that are present in each of the remaining slices for slice in slices { intersection.retain(|item| slice.contains(item)); } intersection } else { Vec::new() } } /// Returns an identifier for the given prefix. pub(crate) fn get_prefix_ident(prefix: &str) -> Ident { let prefix = if prefix.as_bytes()[0].is_ascii_digit() { // Identifiers in Rust may not start with a number. format!("_{prefix}") } else { prefix.to_string() }; Ident::new(&prefix, Span::call_site()) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_macros/src/env_vars.rs
crates/ruff_macros/src/env_vars.rs
use proc_macro2::TokenStream; use quote::quote; use syn::{ImplItem, ItemImpl}; pub(crate) fn attribute_env_vars_metadata(mut input: ItemImpl) -> TokenStream { // Verify that this is an impl for EnvVars let impl_type = &input.self_ty; let mut env_var_entries = Vec::new(); let mut hidden_vars = Vec::new(); // Process each item in the impl block for item in &mut input.items { if let ImplItem::Const(const_item) = item { // Extract the const name and value let const_name = &const_item.ident; let const_expr = &const_item.expr; // Check if the const has the #[attr_hidden] attribute let is_hidden = const_item .attrs .iter() .any(|attr| attr.path().is_ident("attr_hidden")); // Remove our custom attributes const_item.attrs.retain(|attr| { !attr.path().is_ident("attr_hidden") && !attr.path().is_ident("attr_env_var_pattern") }); if is_hidden { hidden_vars.push(const_name.clone()); } else { // Extract documentation from doc comments let doc_attrs: Vec<_> = const_item .attrs .iter() .filter(|attr| attr.path().is_ident("doc")) .collect(); if !doc_attrs.is_empty() { // Convert doc attributes to a single string let doc_string = extract_doc_string(&doc_attrs); env_var_entries.push((const_name.clone(), const_expr.clone(), doc_string)); } } } } // Generate the metadata method. let metadata_entries: Vec<_> = env_var_entries .iter() .map(|(_name, expr, doc)| { quote! { (#expr, #doc) } }) .collect(); let metadata_impl = quote! { impl #impl_type { /// Returns metadata for all non-hidden environment variables. pub fn metadata() -> Vec<(&'static str, &'static str)> { vec![ #(#metadata_entries),* ] } } }; quote! { #input #metadata_impl } } /// Extract documentation from doc attributes into a single string fn extract_doc_string(attrs: &[&syn::Attribute]) -> String { attrs .iter() .filter_map(|attr| { if let syn::Meta::NameValue(meta) = &attr.meta { if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit_str), .. }) = &meta.value { return Some(lit_str.value().trim().to_string()); } } None }) .collect::<Vec<_>>() .join("\n") }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_macros/src/map_codes.rs
crates/ruff_macros/src/map_codes.rs
use std::collections::{BTreeMap, HashMap}; use itertools::Itertools; use proc_macro2::TokenStream; use quote::{ToTokens, quote}; use syn::{ Attribute, Error, Expr, ExprCall, ExprMatch, Ident, ItemFn, LitStr, Pat, Path, Stmt, Token, parenthesized, parse::Parse, spanned::Spanned, }; use crate::rule_code_prefix::{get_prefix_ident, intersection_all}; /// A rule entry in the big match statement such a /// `(Pycodestyle, "E112") => (RuleGroup::Preview, rules::pycodestyle::rules::logical_lines::NoIndentedBlock),` #[derive(Clone)] struct Rule { /// The actual name of the rule, e.g., `NoIndentedBlock`. name: Ident, /// The linter associated with the rule, e.g., `Pycodestyle`. linter: Ident, /// The code associated with the rule, e.g., `"E112"`. code: LitStr, /// The path to the struct implementing the rule, e.g. /// `rules::pycodestyle::rules::logical_lines::NoIndentedBlock` path: Path, /// The rule attributes, e.g. for feature gates attrs: Vec<Attribute>, } pub(crate) fn map_codes(func: &ItemFn) -> syn::Result<TokenStream> { let Some(last_stmt) = func.block.stmts.last() else { return Err(Error::new( func.block.span(), "expected body to end in an expression", )); }; let Stmt::Expr( Expr::Call(ExprCall { args: some_args, .. }), _, ) = last_stmt else { return Err(Error::new( last_stmt.span(), "expected last expression to be `Some(match (..) { .. })`", )); }; let mut some_args = some_args.into_iter(); let (Some(Expr::Match(ExprMatch { arms, .. })), None) = (some_args.next(), some_args.next()) else { return Err(Error::new( last_stmt.span(), "expected last expression to be `Some(match (..) { .. })`", )); }; // Map from: linter (e.g., `Flake8Bugbear`) to rule code (e.g.,`"002"`) to rule data (e.g., // `(Rule::UnaryPrefixIncrement, RuleGroup::Stable, vec![])`). let mut linter_to_rules: BTreeMap<Ident, BTreeMap<String, Rule>> = BTreeMap::new(); for arm in arms { if matches!(arm.pat, Pat::Wild(..)) { break; } let rule = syn::parse::<Rule>(arm.into_token_stream().into())?; linter_to_rules .entry(rule.linter.clone()) .or_default() .insert(rule.code.value(), rule); } let linter_idents: Vec<_> = linter_to_rules.keys().collect(); let all_rules = linter_to_rules.values().flat_map(BTreeMap::values); let mut output = register_rules(all_rules); output.extend(quote! { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum RuleCodePrefix { #(#linter_idents(#linter_idents),)* } impl RuleCodePrefix { pub fn linter(&self) -> &'static Linter { match self { #(Self::#linter_idents(..) => &Linter::#linter_idents,)* } } pub fn short_code(&self) -> &'static str { match self { #(Self::#linter_idents(code) => code.into(),)* } } } }); for (linter, rules) in &linter_to_rules { output.extend(super::rule_code_prefix::expand( linter, rules .iter() .map(|(code, Rule { attrs, .. })| (code.as_str(), attrs)), )); output.extend(quote! { impl From<#linter> for RuleCodePrefix { fn from(linter: #linter) -> Self { Self::#linter(linter) } } // Rust doesn't yet support `impl const From<RuleCodePrefix> for RuleSelector` // See https://github.com/rust-lang/rust/issues/67792 impl From<#linter> for crate::rule_selector::RuleSelector { fn from(linter: #linter) -> Self { let prefix = RuleCodePrefix::#linter(linter); if is_single_rule_selector(&prefix) { Self::Rule { prefix, redirected_from: None, } } else { Self::Prefix { prefix, redirected_from: None, } } } } }); } let mut all_codes = Vec::new(); for (linter, rules) in &linter_to_rules { let rules_by_prefix = rules_by_prefix(rules); for (prefix, rules) in &rules_by_prefix { let prefix_ident = get_prefix_ident(prefix); let attrs = intersection_all(rules.iter().map(|(.., attrs)| attrs.as_slice())); let attrs = if attrs.is_empty() { quote!() } else { quote!(#(#attrs)*) }; all_codes.push(quote! { #attrs Self::#linter(#linter::#prefix_ident) }); } let mut prefix_into_iter_match_arms = quote!(); for (prefix, rules) in rules_by_prefix { let rule_paths = rules.iter().map(|(path, .., attrs)| { let rule_name = path.segments.last().unwrap(); quote!(#(#attrs)* Rule::#rule_name) }); let prefix_ident = get_prefix_ident(&prefix); let attrs = intersection_all(rules.iter().map(|(.., attrs)| attrs.as_slice())); let attrs = if attrs.is_empty() { quote!() } else { quote!(#(#attrs)*) }; prefix_into_iter_match_arms.extend(quote! { #attrs #linter::#prefix_ident => vec![#(#rule_paths,)*].into_iter(), }); } output.extend(quote! { impl #linter { pub(crate) fn rules(&self) -> ::std::vec::IntoIter<Rule> { match self { #prefix_into_iter_match_arms } } } }); } output.extend(quote! { impl RuleCodePrefix { pub(crate) fn parse(linter: &Linter, code: &str) -> Result<Self, crate::registry::FromCodeError> { use std::str::FromStr; Ok(match linter { #(Linter::#linter_idents => RuleCodePrefix::#linter_idents(#linter_idents::from_str(code).map_err(|_| crate::registry::FromCodeError::Unknown)?),)* }) } pub(crate) fn rules(&self) -> ::std::vec::IntoIter<Rule> { match self { #(RuleCodePrefix::#linter_idents(prefix) => prefix.clone().rules(),)* } } } }); let rule_to_code = generate_rule_to_code(&linter_to_rules); output.extend(rule_to_code); output.extend(generate_iter_impl(&linter_to_rules, &linter_idents)); Ok(output) } /// Group the rules by their common prefixes. fn rules_by_prefix( rules: &BTreeMap<String, Rule>, ) -> BTreeMap<String, Vec<(Path, Vec<Attribute>)>> { // TODO(charlie): Why do we do this here _and_ in `rule_code_prefix::expand`? let mut rules_by_prefix = BTreeMap::new(); for code in rules.keys() { for i in 1..=code.len() { let prefix = code[..i].to_string(); let rules: Vec<_> = rules .iter() .filter_map(|(code, rule)| { if code.starts_with(&prefix) { Some((rule.path.clone(), rule.attrs.clone())) } else { None } }) .collect(); rules_by_prefix.insert(prefix, rules); } } rules_by_prefix } /// Map from rule to codes that can be used to select it. /// This abstraction exists to support a one-to-many mapping, whereby a single rule could map /// to multiple codes (e.g., if it existed in multiple linters, like Pylint and Flake8, under /// different codes). We haven't actually activated this functionality yet, but some work was /// done to support it, so the logic exists here. fn generate_rule_to_code(linter_to_rules: &BTreeMap<Ident, BTreeMap<String, Rule>>) -> TokenStream { let mut rule_to_codes: HashMap<&Path, Vec<&Rule>> = HashMap::new(); let mut linter_code_for_rule_match_arms = quote!(); for (linter, map) in linter_to_rules { for (code, rule) in map { let Rule { path, attrs, name, .. } = rule; rule_to_codes.entry(path).or_default().push(rule); linter_code_for_rule_match_arms.extend(quote! { #(#attrs)* (Self::#linter, Rule::#name) => Some(#code), }); } } let mut rule_noqa_code_match_arms = quote!(); for (rule, codes) in rule_to_codes { let rule_name = rule.segments.last().unwrap(); assert_eq!( codes.len(), 1, " {} is mapped to multiple codes. The mapping of multiple codes to one rule has been disabled due to UX concerns (it would be confusing if violations were reported under a different code than the code you selected). We firstly want to allow rules to be selected by their names (and report them by name), and before we can do that we have to rename all our rules to match our naming convention (see CONTRIBUTING.md) because after that change every rule rename will be a breaking change. See also https://github.com/astral-sh/ruff/issues/2186. ", rule_name.ident ); let Rule { linter, code, attrs, .. } = codes .iter() .sorted_by_key(|data| data.linter == "Pylint") .next() .unwrap(); rule_noqa_code_match_arms.extend(quote! { #(#attrs)* Rule::#rule_name => NoqaCode(crate::registry::Linter::#linter.common_prefix(), #code), }); } let rule_to_code = quote! { impl Rule { pub fn noqa_code(&self) -> NoqaCode { use crate::registry::RuleNamespace; match self { #rule_noqa_code_match_arms } } pub fn is_preview(&self) -> bool { matches!(self.group(), RuleGroup::Preview { .. }) } pub(crate) fn is_stable(&self) -> bool { matches!(self.group(), RuleGroup::Stable { .. }) } pub fn is_deprecated(&self) -> bool { matches!(self.group(), RuleGroup::Deprecated { .. }) } pub fn is_removed(&self) -> bool { matches!(self.group(), RuleGroup::Removed { .. }) } } impl Linter { pub fn code_for_rule(&self, rule: Rule) -> Option<&'static str> { match (self, rule) { #linter_code_for_rule_match_arms _ => None, } } } }; rule_to_code } /// Implement `impl IntoIterator for &Linter` and `RuleCodePrefix::iter()` fn generate_iter_impl( linter_to_rules: &BTreeMap<Ident, BTreeMap<String, Rule>>, linter_idents: &[&Ident], ) -> TokenStream { let mut linter_rules_match_arms = quote!(); let mut linter_all_rules_match_arms = quote!(); for (linter, map) in linter_to_rules { let rule_paths = map.values().map(|Rule { attrs, path, .. }| { let rule_name = path.segments.last().unwrap(); quote!(#(#attrs)* Rule::#rule_name) }); linter_rules_match_arms.extend(quote! { Linter::#linter => vec![#(#rule_paths,)*].into_iter(), }); let rule_paths = map.values().map(|Rule { attrs, path, .. }| { let rule_name = path.segments.last().unwrap(); quote!(#(#attrs)* Rule::#rule_name) }); linter_all_rules_match_arms.extend(quote! { Linter::#linter => vec![#(#rule_paths,)*].into_iter(), }); } quote! { impl Linter { /// Rules not in the preview. pub(crate) fn rules(self: &Linter) -> ::std::vec::IntoIter<Rule> { match self { #linter_rules_match_arms } } /// All rules, including those in the preview. pub fn all_rules(self: &Linter) -> ::std::vec::IntoIter<Rule> { match self { #linter_all_rules_match_arms } } } impl RuleCodePrefix { pub(crate) fn iter() -> impl Iterator<Item = RuleCodePrefix> { use strum::IntoEnumIterator; let mut prefixes = Vec::new(); #(prefixes.extend(#linter_idents::iter().map(|x| Self::#linter_idents(x)));)* prefixes.into_iter() } } } } /// Generate the `Rule` enum fn register_rules<'a>(input: impl Iterator<Item = &'a Rule>) -> TokenStream { let mut rule_variants = quote!(); let mut rule_message_formats_match_arms = quote!(); let mut rule_fixable_match_arms = quote!(); let mut rule_explanation_match_arms = quote!(); let mut rule_group_match_arms = quote!(); let mut rule_file_match_arms = quote!(); let mut rule_line_match_arms = quote!(); for Rule { name, attrs, path, .. } in input { rule_variants.extend(quote! { #(#attrs)* #name, }); // Apply the `attrs` to each arm, like `[cfg(feature = "foo")]`. rule_message_formats_match_arms.extend( quote! {#(#attrs)* Self::#name => <#path as crate::Violation>::message_formats(),}, ); rule_fixable_match_arms.extend( quote! {#(#attrs)* Self::#name => <#path as crate::Violation>::FIX_AVAILABILITY,}, ); rule_explanation_match_arms.extend(quote! {#(#attrs)* Self::#name => #path::explain(),}); rule_group_match_arms.extend( quote! {#(#attrs)* Self::#name => <#path as crate::ViolationMetadata>::group(),}, ); rule_file_match_arms.extend( quote! {#(#attrs)* Self::#name => <#path as crate::ViolationMetadata>::file(),}, ); rule_line_match_arms.extend( quote! {#(#attrs)* Self::#name => <#path as crate::ViolationMetadata>::line(),}, ); } quote! { use crate::Violation; #[derive( EnumIter, Debug, PartialEq, Eq, Copy, Clone, Hash, ::strum_macros::IntoStaticStr, )] #[repr(u16)] #[strum(serialize_all = "kebab-case")] pub enum Rule { #rule_variants } impl Rule { /// Returns the format strings used to report violations of this rule. pub fn message_formats(&self) -> &'static [&'static str] { match self { #rule_message_formats_match_arms } } /// Returns the documentation for this rule. pub fn explanation(&self) -> Option<&'static str> { use crate::ViolationMetadata; match self { #rule_explanation_match_arms } } /// Returns the fix status of this rule. pub const fn fixable(&self) -> crate::FixAvailability { match self { #rule_fixable_match_arms } } pub fn group(&self) -> crate::codes::RuleGroup { match self { #rule_group_match_arms } } pub fn file(&self) -> &'static str { match self { #rule_file_match_arms } } pub fn line(&self) -> u32 { match self { #rule_line_match_arms } } } } } impl Parse for Rule { /// Parses a match arm such as `(Pycodestyle, "E112") => rules::pycodestyle::rules::logical_lines::NoIndentedBlock,` fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { let attrs = Attribute::parse_outer(input)?; let pat_tuple; parenthesized!(pat_tuple in input); let linter: Ident = pat_tuple.parse()?; let _: Token!(,) = pat_tuple.parse()?; let code: LitStr = pat_tuple.parse()?; let _: Token!(=>) = input.parse()?; let rule_path: Path = input.parse()?; let _: Token!(,) = input.parse()?; let rule_name = rule_path.segments.last().unwrap().ident.clone(); Ok(Rule { name: rule_name, linter, code, path: rule_path, attrs, }) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_macros/src/violation_metadata.rs
crates/ruff_macros/src/violation_metadata.rs
use proc_macro2::TokenStream; use quote::quote; use syn::{Attribute, DeriveInput, Error, Lit, LitStr, Meta}; pub(crate) fn violation_metadata(input: DeriveInput) -> syn::Result<TokenStream> { let docs = get_docs(&input.attrs)?; let Some(group) = get_rule_status(&input.attrs)? else { return Err(Error::new_spanned( input, "Missing required rule group metadata", )); }; let name = input.ident; let (impl_generics, ty_generics, where_clause) = &input.generics.split_for_impl(); Ok(quote! { #[automatically_derived] #[expect(deprecated)] impl #impl_generics crate::ViolationMetadata for #name #ty_generics #where_clause { fn rule() -> crate::registry::Rule { crate::registry::Rule::#name } fn explain() -> Option<&'static str> { Some(#docs) } fn group() -> crate::codes::RuleGroup { crate::codes::#group } fn file() -> &'static str { file!() } fn line() -> u32 { line!() } } }) } /// Collect all doc comment attributes into a string fn get_docs(attrs: &[Attribute]) -> syn::Result<String> { let mut explanation = String::new(); for attr in attrs { if attr.path().is_ident("doc") { if let Some(lit) = parse_attr(["doc"], attr) { let value = lit.value(); // `/// ` adds let line = value.strip_prefix(' ').unwrap_or(&value); explanation.push_str(line); explanation.push('\n'); } else { return Err(Error::new_spanned(attr, "unimplemented doc comment style")); } } } Ok(explanation) } /// Extract the rule status attribute. /// /// These attributes look like: /// /// ```ignore /// #[violation_metadata(stable_since = "1.2.3")] /// struct MyRule; /// ``` /// /// The result is returned as a `TokenStream` so that the version string literal can be combined /// with the proper `RuleGroup` variant, e.g. `RuleGroup::Stable` for `stable_since` above. fn get_rule_status(attrs: &[Attribute]) -> syn::Result<Option<TokenStream>> { let mut group = None; for attr in attrs { if attr.path().is_ident("violation_metadata") { attr.parse_nested_meta(|meta| { if meta.path.is_ident("stable_since") { let lit: LitStr = meta.value()?.parse()?; group = Some(quote!(RuleGroup::Stable { since: #lit })); return Ok(()); } else if meta.path.is_ident("preview_since") { let lit: LitStr = meta.value()?.parse()?; group = Some(quote!(RuleGroup::Preview { since: #lit })); return Ok(()); } else if meta.path.is_ident("deprecated_since") { let lit: LitStr = meta.value()?.parse()?; group = Some(quote!(RuleGroup::Deprecated { since: #lit })); return Ok(()); } else if meta.path.is_ident("removed_since") { let lit: LitStr = meta.value()?.parse()?; group = Some(quote!(RuleGroup::Removed { since: #lit })); return Ok(()); } Err(Error::new_spanned( attr, "unimplemented violation metadata option", )) })?; } } Ok(group) } fn parse_attr<'a, const LEN: usize>( path: [&'static str; LEN], attr: &'a Attribute, ) -> Option<&'a LitStr> { if let Meta::NameValue(name_value) = &attr.meta { let path_idents = name_value .path .segments .iter() .map(|segment| &segment.ident); if itertools::equal(path_idents, path) { if let syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(lit), .. }) = &name_value.value { return Some(lit); } } } None }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_wasm/build.rs
crates/ty_wasm/build.rs
use std::{ fs, path::{Path, PathBuf}, process::Command, }; fn main() { // The workspace root directory is not available without walking up the tree // https://github.com/rust-lang/cargo/issues/3946 let workspace_root = Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap()) .join("..") .join(".."); commit_info(&workspace_root); } /// Retrieve commit information from the Git repository. fn commit_info(workspace_root: &Path) { // If not in a git repository, do not attempt to retrieve commit information let git_dir = workspace_root.join(".git"); if !git_dir.exists() { return; } if let Some(git_head_path) = git_head(&git_dir) { println!("cargo:rerun-if-changed={}", git_head_path.display()); let git_head_contents = fs::read_to_string(git_head_path); if let Ok(git_head_contents) = git_head_contents { // The contents are either a commit or a reference in the following formats // - "<commit>" when the head is detached // - "ref <ref>" when working on a branch // If a commit, checking if the HEAD file has changed is sufficient // If a ref, we need to add the head file for that ref to rebuild on commit let mut git_ref_parts = git_head_contents.split_whitespace(); git_ref_parts.next(); if let Some(git_ref) = git_ref_parts.next() { let git_ref_path = git_dir.join(git_ref); println!("cargo:rerun-if-changed={}", git_ref_path.display()); } } } let output = match Command::new("git") .arg("log") .arg("-1") .arg("--date=short") .arg("--abbrev=9") .arg("--format=%H %h %cd %(describe:tags)") .current_dir(workspace_root) .output() { Ok(output) if output.status.success() => output, _ => return, }; let stdout = String::from_utf8(output.stdout).unwrap(); let mut parts = stdout.split_whitespace(); let mut next = || parts.next().unwrap(); let _commit_hash = next(); println!("cargo::rustc-env=TY_WASM_COMMIT_SHORT_HASH={}", next()); } fn git_head(git_dir: &Path) -> Option<PathBuf> { // The typical case is a standard git repository. let git_head_path = git_dir.join("HEAD"); if git_head_path.exists() { return Some(git_head_path); } if !git_dir.is_file() { return None; } // If `.git/HEAD` doesn't exist and `.git` is actually a file, // then let's try to attempt to read it as a worktree. If it's // a worktree, then its contents will look like this, e.g.: // // gitdir: /home/andrew/astral/uv/main/.git/worktrees/pr2 // // And the HEAD file we want to watch will be at: // // /home/andrew/astral/uv/main/.git/worktrees/pr2/HEAD let contents = fs::read_to_string(git_dir).ok()?; let (label, worktree_path) = contents.split_once(':')?; if label != "gitdir" { return None; } let worktree_path = worktree_path.trim(); Some(PathBuf::from(worktree_path)) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_wasm/src/lib.rs
crates/ty_wasm/src/lib.rs
use std::any::Any; use js_sys::{Error, JsString}; use ruff_db::Db as _; use ruff_db::diagnostic::{self, DisplayDiagnosticConfig}; use ruff_db::files::{File, FilePath, FileRange, system_path_to_file, vendored_path_to_file}; use ruff_db::source::{SourceText, line_index, source_text}; use ruff_db::system::walk_directory::WalkDirectoryBuilder; use ruff_db::system::{ CaseSensitivity, DirectoryEntry, GlobError, MemoryFileSystem, Metadata, PatternError, System, SystemPath, SystemPathBuf, SystemVirtualPath, WritableSystem, }; use ruff_db::vendored::VendoredPath; use ruff_diagnostics::{Applicability, Edit}; use ruff_notebook::Notebook; use ruff_python_formatter::formatted_file; use ruff_source_file::{LineIndex, OneIndexed, SourceLocation}; use ruff_text_size::{Ranged, TextSize}; use ty_ide::{ InlayHintSettings, MarkupKind, RangedValue, document_highlights, find_references, goto_declaration, goto_definition, goto_type_definition, hover, inlay_hints, }; use ty_ide::{NavigationTarget, NavigationTargets, signature_help}; use ty_project::metadata::options::Options; use ty_project::metadata::value::ValueSource; use ty_project::watch::{ChangeEvent, ChangedKind, CreatedKind, DeletedKind}; use ty_project::{CheckMode, ProjectMetadata}; use ty_project::{Db, ProjectDatabase}; use ty_python_semantic::{MisconfigurationMode, Program}; use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn version() -> String { option_env!("TY_WASM_COMMIT_SHORT_HASH") .or_else(|| option_env!("CARGO_PKG_VERSION")) .unwrap_or("unknown") .to_string() } /// Perform global constructor initialization. #[cfg(target_family = "wasm")] #[expect(unsafe_code)] pub fn before_main() { unsafe extern "C" { fn __wasm_call_ctors(); } // Salsa uses the `inventory` crate, which registers global constructors that may need to be // called explicitly on WASM. See <https://github.com/dtolnay/inventory/blob/master/src/lib.rs#L105> // for details. unsafe { __wasm_call_ctors(); } } #[cfg(not(target_family = "wasm"))] pub fn before_main() {} #[wasm_bindgen(start)] pub fn run() { use log::Level; before_main(); ruff_db::set_program_version(version()).unwrap(); // When the `console_error_panic_hook` feature is enabled, we can call the // `set_panic_hook` function at least once during initialization, and then // we will get better error messages if our code ever panics. // // For more details see // https://github.com/rustwasm/console_error_panic_hook#readme #[cfg(feature = "console_error_panic_hook")] console_error_panic_hook::set_once(); console_log::init_with_level(Level::Debug).expect("Initializing logger went wrong."); } #[wasm_bindgen] pub struct Workspace { db: ProjectDatabase, position_encoding: PositionEncoding, system: WasmSystem, } #[wasm_bindgen] impl Workspace { #[wasm_bindgen(constructor)] pub fn new( root: &str, position_encoding: PositionEncoding, options: JsValue, ) -> Result<Workspace, Error> { let options = Options::deserialize_with( ValueSource::Cli, serde_wasm_bindgen::Deserializer::from(options), ) .map_err(into_error)?; let system = WasmSystem::new(SystemPath::new(root)); let project = ProjectMetadata::from_options( options, SystemPathBuf::from(root), None, MisconfigurationMode::Fail, ) .map_err(into_error)?; let mut db = ProjectDatabase::new(project, system.clone()).map_err(into_error)?; // By default, it will check all files in the project but we only want to check the open // files in the playground. db.set_check_mode(CheckMode::OpenFiles); Ok(Self { db, position_encoding, system, }) } #[wasm_bindgen(js_name = "updateOptions")] pub fn update_options(&mut self, options: JsValue) -> Result<(), Error> { let options = Options::deserialize_with( ValueSource::Cli, serde_wasm_bindgen::Deserializer::from(options), ) .map_err(into_error)?; let project = ProjectMetadata::from_options( options, self.db.project().root(&self.db).to_path_buf(), None, MisconfigurationMode::Fail, ) .map_err(into_error)?; let program_settings = project .to_program_settings(&self.system, self.db.vendored()) .map_err(into_error)?; Program::get(&self.db).update_from_settings(&mut self.db, program_settings); self.db.project().reload(&mut self.db, project); Ok(()) } #[wasm_bindgen(js_name = "openFile")] pub fn open_file(&mut self, path: &str, contents: &str) -> Result<FileHandle, Error> { let path = SystemPath::absolute(path, self.db.project().root(&self.db)); self.system .fs .write_file_all(&path, contents) .map_err(into_error)?; self.db.apply_changes( vec![ChangeEvent::Created { path: path.clone(), kind: CreatedKind::File, }], None, ); let file = system_path_to_file(&self.db, &path).expect("File to exist"); self.db.project().open_file(&mut self.db, file); Ok(FileHandle { path: path.into(), file, }) } #[wasm_bindgen(js_name = "updateFile")] pub fn update_file(&mut self, file_id: &FileHandle, contents: &str) -> Result<(), Error> { let system_path = file_id.path.as_system_path().ok_or_else(|| { Error::new("Cannot update non-system files (vendored files are read-only)") })?; if !self.system.fs.exists(system_path) { return Err(Error::new("File does not exist")); } self.system .fs .write_file(system_path, contents) .map_err(into_error)?; self.db.apply_changes( vec![ ChangeEvent::Changed { path: system_path.to_path_buf(), kind: ChangedKind::FileContent, }, ChangeEvent::Changed { path: system_path.to_path_buf(), kind: ChangedKind::FileMetadata, }, ], None, ); Ok(()) } #[wasm_bindgen(js_name = "closeFile")] #[allow( clippy::needless_pass_by_value, reason = "It's intentional that the file handle is consumed because it is no longer valid after closing" )] pub fn close_file(&mut self, file_id: FileHandle) -> Result<(), Error> { let file = file_id.file; self.db.project().close_file(&mut self.db, file); // Only close system files (vendored files can't be closed/deleted) if let Some(system_path) = file_id.path.as_system_path() { self.system .fs .remove_file(system_path) .map_err(into_error)?; self.db.apply_changes( vec![ChangeEvent::Deleted { path: system_path.to_path_buf(), kind: DeletedKind::File, }], None, ); } Ok(()) } /// Checks a single file. #[wasm_bindgen(js_name = "checkFile")] pub fn check_file(&self, file_id: &FileHandle) -> Result<Vec<Diagnostic>, Error> { let result = self.db.check_file(file_id.file); Ok(result.into_iter().map(Diagnostic::wrap).collect()) } /// Checks all open files pub fn check(&self) -> Result<Vec<Diagnostic>, Error> { let result = self.db.check(); Ok(result.into_iter().map(Diagnostic::wrap).collect()) } /// Returns the parsed AST for `path` pub fn parsed(&self, file_id: &FileHandle) -> Result<String, Error> { let parsed = ruff_db::parsed::parsed_module(&self.db, file_id.file).load(&self.db); Ok(format!("{:#?}", parsed.syntax())) } pub fn format(&self, file_id: &FileHandle) -> Result<Option<String>, Error> { formatted_file(&self.db, file_id.file).map_err(into_error) } /// 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(&self.db, file_id.file).load(&self.db); Ok(format!("{:#?}", parsed.tokens())) } #[wasm_bindgen(js_name = "sourceText")] pub fn source_text(&self, file_id: &FileHandle) -> Result<String, Error> { let source_text = ruff_db::source::source_text(&self.db, file_id.file); Ok(source_text.to_string()) } #[wasm_bindgen(js_name = "gotoTypeDefinition")] pub fn goto_type_definition( &self, file_id: &FileHandle, position: Position, ) -> Result<Vec<LocationLink>, Error> { let source = source_text(&self.db, file_id.file); let index = line_index(&self.db, file_id.file); let offset = position.to_text_size(&source, &index, self.position_encoding)?; let Some(targets) = goto_type_definition(&self.db, file_id.file, offset) else { return Ok(Vec::new()); }; Ok(map_targets_to_links( &self.db, targets, &source, &index, self.position_encoding, )) } #[wasm_bindgen(js_name = "gotoDeclaration")] pub fn goto_declaration( &self, file_id: &FileHandle, position: Position, ) -> Result<Vec<LocationLink>, Error> { let source = source_text(&self.db, file_id.file); let index = line_index(&self.db, file_id.file); let offset = position.to_text_size(&source, &index, self.position_encoding)?; let Some(targets) = goto_declaration(&self.db, file_id.file, offset) else { return Ok(Vec::new()); }; Ok(map_targets_to_links( &self.db, targets, &source, &index, self.position_encoding, )) } #[wasm_bindgen(js_name = "gotoDefinition")] pub fn goto_definition( &self, file_id: &FileHandle, position: Position, ) -> Result<Vec<LocationLink>, Error> { let source = source_text(&self.db, file_id.file); let index = line_index(&self.db, file_id.file); let offset = position.to_text_size(&source, &index, self.position_encoding)?; let Some(targets) = goto_definition(&self.db, file_id.file, offset) else { return Ok(Vec::new()); }; Ok(map_targets_to_links( &self.db, targets, &source, &index, self.position_encoding, )) } #[wasm_bindgen(js_name = "gotoReferences")] pub fn goto_references( &self, file_id: &FileHandle, position: Position, ) -> Result<Vec<LocationLink>, Error> { let source = source_text(&self.db, file_id.file); let index = line_index(&self.db, file_id.file); let offset = position.to_text_size(&source, &index, self.position_encoding)?; let Some(targets) = find_references(&self.db, file_id.file, offset, true) else { return Ok(Vec::new()); }; Ok(targets .into_iter() .map(|target| LocationLink { path: target.file().path(&self.db).to_string(), full_range: Range::from_file_range( &self.db, target.file_range(), self.position_encoding, ), selection_range: Some(Range::from_file_range( &self.db, target.file_range(), self.position_encoding, )), origin_selection_range: Some(Range::from_text_range( ruff_text_size::TextRange::new(offset, offset), &index, &source, self.position_encoding, )), }) .collect()) } #[wasm_bindgen] pub fn hover(&self, file_id: &FileHandle, position: Position) -> Result<Option<Hover>, Error> { let source = source_text(&self.db, file_id.file); let index = line_index(&self.db, file_id.file); let offset = position.to_text_size(&source, &index, self.position_encoding)?; let Some(range_info) = hover(&self.db, file_id.file, offset) else { return Ok(None); }; let source_range = Range::from_text_range( range_info.file_range().range(), &index, &source, self.position_encoding, ); Ok(Some(Hover { markdown: range_info .display(&self.db, MarkupKind::Markdown) .to_string(), range: source_range, })) } #[wasm_bindgen] pub fn completions( &self, file_id: &FileHandle, position: Position, ) -> Result<Vec<Completion>, Error> { let source = source_text(&self.db, file_id.file); let index = line_index(&self.db, file_id.file); let offset = position.to_text_size(&source, &index, self.position_encoding)?; let settings = ty_ide::CompletionSettings { auto_import: true }; let completions = ty_ide::completion(&self.db, &settings, file_id.file, offset); Ok(completions .into_iter() .map(|comp| { let kind = comp.kind(&self.db).map(CompletionKind::from); let type_display = comp.ty.map(|ty| ty.display(&self.db).to_string()); let import_edit = comp.import.as_ref().map(|edit| { let range = Range::from_text_range( edit.range(), &index, &source, self.position_encoding, ); TextEdit { range, new_text: edit.content().map(ToString::to_string).unwrap_or_default(), } }); Completion { name: comp.name.into(), kind, detail: type_display, module_name: comp.module_name.map(ToString::to_string), insert_text: comp.insert.map(String::from), additional_text_edits: import_edit.map(|edit| vec![edit]), documentation: comp .documentation .map(|docstring| docstring.render_plaintext()), } }) .collect()) } #[wasm_bindgen(js_name = "inlayHints")] pub fn inlay_hints(&self, file_id: &FileHandle, range: Range) -> Result<Vec<InlayHint>, Error> { let index = line_index(&self.db, file_id.file); let source = source_text(&self.db, file_id.file); let result = inlay_hints( &self.db, file_id.file, range.to_text_range(&index, &source, self.position_encoding)?, // TODO: Provide a way to configure this &InlayHintSettings { variable_types: true, call_argument_names: true, }, ); Ok(result .into_iter() .map(|hint| InlayHint { label: hint .label .into_parts() .into_iter() .map(|part| InlayHintLabelPart { location: part.target().map(|target| { location_link_from_navigation_target( target, &self.db, self.position_encoding, None, ) }), label: part.into_text(), }) .collect(), position: Position::from_text_size( hint.position, &index, &source, self.position_encoding, ), kind: hint.kind.into(), text_edits: hint .text_edits .into_iter() .map(|edit| TextEdit { range: Range::from_text_range( edit.range, &index, &source, self.position_encoding, ), new_text: edit.new_text, }) .collect(), }) .collect()) } #[wasm_bindgen(js_name = "semanticTokens")] pub fn semantic_tokens(&self, file_id: &FileHandle) -> Result<Vec<SemanticToken>, Error> { let index = line_index(&self.db, file_id.file); let source = source_text(&self.db, file_id.file); let semantic_token = ty_ide::semantic_tokens(&self.db, file_id.file, None); let result = semantic_token .iter() .map(|token| SemanticToken { kind: token.token_type.into(), modifiers: token.modifiers.bits(), range: Range::from_text_range(token.range, &index, &source, self.position_encoding), }) .collect::<Vec<_>>(); Ok(result) } #[wasm_bindgen(js_name = "semanticTokensInRange")] pub fn semantic_tokens_in_range( &self, file_id: &FileHandle, range: Range, ) -> Result<Vec<SemanticToken>, Error> { let index = line_index(&self.db, file_id.file); let source = source_text(&self.db, file_id.file); let semantic_token = ty_ide::semantic_tokens( &self.db, file_id.file, Some(range.to_text_range(&index, &source, self.position_encoding)?), ); let result = semantic_token .iter() .map(|token| SemanticToken { kind: token.token_type.into(), modifiers: token.modifiers.bits(), range: Range::from_text_range(token.range, &index, &source, self.position_encoding), }) .collect::<Vec<_>>(); Ok(result) } #[wasm_bindgen(js_name = "codeActions")] pub fn code_actions( &self, file_id: &FileHandle, diagnostic: &Diagnostic, ) -> Option<Vec<CodeAction>> { // If the diagnostic includes fixes, offer those up as options. let mut actions = Vec::new(); if let Some(action) = diagnostic.code_action(self) { actions.push(action); } // Try to find other applicable actions. // // This is only for actions that are messy to compute at the time of the diagnostic. // For instance, suggesting imports requires finding symbols for the entire project, // which is dubious when you're in the middle of resolving symbols. if let Some(range) = diagnostic.inner.range() { actions.extend( ty_ide::code_actions( &self.db, file_id.file, range, diagnostic.inner.id().as_str(), ) .into_iter() .map(|action| CodeAction { title: action.title, preferred: action.preferred, edits: action .edits .into_iter() .map(|edit| edit_to_text_edit(self, file_id.file, &edit)) .collect(), }), ); } if actions.is_empty() { None } else { Some(actions) } } #[wasm_bindgen(js_name = "signatureHelp")] pub fn signature_help( &self, file_id: &FileHandle, position: Position, ) -> Result<Option<SignatureHelp>, Error> { let source = source_text(&self.db, file_id.file); let index = line_index(&self.db, file_id.file); let offset = position.to_text_size(&source, &index, self.position_encoding)?; let Some(signature_help_info) = signature_help(&self.db, file_id.file, offset) else { return Ok(None); }; let signatures = signature_help_info .signatures .into_iter() .map(|sig| { let parameters = sig .parameters .into_iter() .map(|param| ParameterInformation { label: param.label, documentation: param.documentation, }) .collect(); SignatureInformation { label: sig.label, documentation: sig .documentation .map(|docstring| docstring.render_plaintext()), parameters, active_parameter: sig.active_parameter.and_then(|p| u32::try_from(p).ok()), } }) .collect(); Ok(Some(SignatureHelp { signatures, active_signature: signature_help_info .active_signature .and_then(|s| u32::try_from(s).ok()), })) } #[wasm_bindgen(js_name = "documentHighlights")] pub fn document_highlights( &self, file_id: &FileHandle, position: Position, ) -> Result<Vec<DocumentHighlight>, Error> { let source = source_text(&self.db, file_id.file); let index = line_index(&self.db, file_id.file); let offset = position.to_text_size(&source, &index, self.position_encoding)?; let Some(targets) = document_highlights(&self.db, file_id.file, offset) else { return Ok(Vec::new()); }; Ok(targets .into_iter() .map(|target| DocumentHighlight { range: Range::from_file_range( &self.db, target.file_range(), self.position_encoding, ), kind: target.kind().into(), }) .collect()) } /// Gets a file handle for a vendored file by its path. /// This allows vendored files to participate in LSP features like hover, completions, etc. #[wasm_bindgen(js_name = "getVendoredFile")] pub fn get_vendored_file(&self, path: &str) -> Result<FileHandle, Error> { let vendored_path = VendoredPath::new(path); // Try to get the vendored file as a File let file = vendored_path_to_file(&self.db, vendored_path) .map_err(|err| Error::new(&format!("Vendored file not found: {path}: {err}")))?; Ok(FileHandle { file, path: vendored_path.to_path_buf().into(), }) } } pub(crate) fn into_error<E: std::fmt::Display>(err: E) -> Error { Error::new(&err.to_string()) } fn map_targets_to_links( db: &dyn Db, targets: RangedValue<NavigationTargets>, source: &SourceText, index: &LineIndex, position_encoding: PositionEncoding, ) -> Vec<LocationLink> { let source_range = Range::from_text_range( targets.file_range().range(), index, source, position_encoding, ); targets .into_iter() .map(|target| { location_link_from_navigation_target(&target, db, position_encoding, Some(source_range)) }) .collect() } #[derive(Debug, Eq, PartialEq)] #[wasm_bindgen(inspectable)] pub struct FileHandle { path: FilePath, file: File, } #[wasm_bindgen] impl FileHandle { #[wasm_bindgen(js_name = toString)] pub fn js_to_string(&self) -> String { format!("file(id: {:?}, path: {})", self.file, self.path) } pub fn path(&self) -> String { self.path.to_string() } } #[wasm_bindgen] pub struct Diagnostic { #[wasm_bindgen(readonly)] inner: diagnostic::Diagnostic, } #[wasm_bindgen] impl Diagnostic { fn wrap(diagnostic: diagnostic::Diagnostic) -> Self { Self { inner: diagnostic } } #[wasm_bindgen] pub fn message(&self) -> JsString { JsString::from(self.inner.concise_message().to_string()) } #[wasm_bindgen] pub fn id(&self) -> JsString { JsString::from(self.inner.id().to_string()) } #[wasm_bindgen] pub fn severity(&self) -> Severity { Severity::from(self.inner.severity()) } #[wasm_bindgen(js_name = "textRange")] pub fn text_range(&self) -> Option<TextRange> { self.inner .primary_span() .and_then(|span| Some(TextRange::from(span.range()?))) } #[wasm_bindgen(js_name = "toRange")] pub fn to_range(&self, workspace: &Workspace) -> Option<Range> { self.inner.primary_span().and_then(|span| { Some(Range::from_file_range( &workspace.db, FileRange::new(span.expect_ty_file(), span.range()?), workspace.position_encoding, )) }) } #[wasm_bindgen] pub fn display(&self, workspace: &Workspace) -> JsString { let config = DisplayDiagnosticConfig::default().color(false); self.inner .display(&workspace.db, &config) .to_string() .into() } /// Returns the code action for this diagnostic, if it has a fix. #[wasm_bindgen(js_name = "codeAction")] pub fn code_action(&self, workspace: &Workspace) -> Option<CodeAction> { let fix = self .inner .fix() .filter(|fix| fix.applies(Applicability::Unsafe))?; let primary_span = self.inner.primary_span()?; let file = primary_span.expect_ty_file(); let edits: Vec<TextEdit> = fix .edits() .iter() .map(|edit| edit_to_text_edit(workspace, file, edit)) .collect(); let title = self .inner .first_help_text() .map(ToString::to_string) .unwrap_or_else(|| format!("Fix {}", self.inner.id())); Some(CodeAction { title, edits, preferred: true, }) } } fn edit_to_text_edit(workspace: &Workspace, file: File, edit: &Edit) -> TextEdit { let source = source_text(&workspace.db, file); let index = line_index(&workspace.db, file); TextEdit { range: Range::from_text_range(edit.range(), &index, &source, workspace.position_encoding), new_text: edit.content().unwrap_or_default().to_string(), } } /// A code action that can be applied to fix a diagnostic. #[wasm_bindgen] #[derive(Debug, Clone, PartialEq, Eq)] pub struct CodeAction { #[wasm_bindgen(getter_with_clone)] pub title: String, #[wasm_bindgen(getter_with_clone)] pub edits: Vec<TextEdit>, pub preferred: bool, } #[wasm_bindgen] #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub struct Range { pub start: Position, pub end: Position, } #[wasm_bindgen] impl Range { #[wasm_bindgen(constructor)] pub fn new(start: Position, end: Position) -> Self { Self { start, end } } } impl Range { fn from_file_range( db: &dyn Db, file_range: FileRange, position_encoding: PositionEncoding, ) -> Self { let index = line_index(db, file_range.file()); let source = source_text(db, file_range.file()); Self::from_text_range(file_range.range(), &index, &source, position_encoding) } fn from_text_range( text_range: ruff_text_size::TextRange, line_index: &LineIndex, source: &str, position_encoding: PositionEncoding, ) -> Self { Self { start: Position::from_text_size( text_range.start(), line_index, source, position_encoding, ), end: Position::from_text_size(text_range.end(), line_index, source, position_encoding), } } fn to_text_range( self, line_index: &LineIndex, source: &str, position_encoding: PositionEncoding, ) -> Result<ruff_text_size::TextRange, Error> { let start = self .start .to_text_size(source, line_index, position_encoding)?; let end = self .end .to_text_size(source, line_index, position_encoding)?; Ok(ruff_text_size::TextRange::new(start, end)) } } #[wasm_bindgen] #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub struct Position { /// One indexed line number pub line: usize, /// One indexed column number (the nth character on the line) pub column: usize, } #[wasm_bindgen] impl Position { #[wasm_bindgen(constructor)] pub fn new(line: usize, column: usize) -> Self { Self { line, column } } } impl Position { fn to_text_size( self, text: &str, index: &LineIndex, position_encoding: PositionEncoding, ) -> Result<TextSize, Error> { let text_size = index.offset( SourceLocation { line: OneIndexed::new(self.line).ok_or_else(|| { Error::new( "Invalid value `0` for `position.line`. The line index is 1-indexed.", ) })?, character_offset: OneIndexed::new(self.column).ok_or_else(|| { Error::new( "Invalid value `0` for `position.column`. The column index is 1-indexed.", ) })?, }, text, position_encoding.into(), ); Ok(text_size) } fn from_text_size( offset: TextSize, line_index: &LineIndex, source: &str, position_encoding: PositionEncoding, ) -> Self { let location = line_index.source_location(offset, source, position_encoding.into()); Self { line: location.line.get(), column: location.character_offset.get(), } } } #[wasm_bindgen] #[derive(Copy, Clone, Hash, PartialEq, Eq)] pub enum Severity { Info, Warning, Error, Fatal, } impl From<diagnostic::Severity> for Severity { fn from(value: diagnostic::Severity) -> Self { match value { diagnostic::Severity::Info => Self::Info, diagnostic::Severity::Warning => Self::Warning, diagnostic::Severity::Error => Self::Error, diagnostic::Severity::Fatal => Self::Fatal, } } } #[wasm_bindgen] pub struct TextRange { pub start: u32, pub end: u32, } impl From<ruff_text_size::TextRange> for TextRange { fn from(value: ruff_text_size::TextRange) -> Self { Self { start: value.start().into(), end: value.end().into(), } } } #[derive(Default, Copy, Clone)] #[wasm_bindgen] pub enum PositionEncoding { #[default] Utf8, Utf16, Utf32, } impl From<PositionEncoding> for ruff_source_file::PositionEncoding { fn from(value: PositionEncoding) -> Self { match value { PositionEncoding::Utf8 => Self::Utf8, PositionEncoding::Utf16 => Self::Utf16, PositionEncoding::Utf32 => Self::Utf32, } } } #[wasm_bindgen] #[derive(Clone)] pub struct LocationLink { /// The target file path #[wasm_bindgen(getter_with_clone)] pub path: String, /// The full range of the target pub full_range: Range, /// The target's range that should be selected/highlighted pub selection_range: Option<Range>, /// The range of the origin. pub origin_selection_range: Option<Range>, } fn location_link_from_navigation_target( target: &NavigationTarget, db: &dyn Db, position_encoding: PositionEncoding, source_range: Option<Range>, ) -> LocationLink { LocationLink { path: target.file().path(db).to_string(), full_range: Range::from_file_range(db, target.full_file_range(), position_encoding), selection_range: Some(Range::from_file_range( db,
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ty_wasm/tests/api.rs
crates/ty_wasm/tests/api.rs
#![cfg(target_arch = "wasm32")] use ty_wasm::{Position, PositionEncoding, Workspace}; use wasm_bindgen_test::wasm_bindgen_test; #[wasm_bindgen_test] fn check() { ty_wasm::before_main(); let mut workspace = Workspace::new( "/", PositionEncoding::Utf32, js_sys::JSON::parse("{}").unwrap(), ) .expect("Workspace to be created"); workspace .open_file("test.py", "import random22\n") .expect("File to be opened"); let result = workspace.check().expect("Check to succeed"); assert_eq!(result.len(), 1); let diagnostic = &result[0]; assert_eq!(diagnostic.id(), "unresolved-import"); assert_eq!( diagnostic.to_range(&workspace).unwrap().start, Position { line: 1, column: 8 } ); assert_eq!( diagnostic.message(), "Cannot resolve imported module `random22`" ); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_trivia_integration_tests/src/lib.rs
crates/ruff_python_trivia_integration_tests/src/lib.rs
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_trivia_integration_tests/tests/whitespace.rs
crates/ruff_python_trivia_integration_tests/tests/whitespace.rs
use ruff_python_parser::{ParseError, parse_module}; use ruff_python_trivia::has_trailing_content; use ruff_text_size::Ranged; #[test] fn trailing_content() -> Result<(), ParseError> { let contents = "x = 1"; let suite = parse_module(contents)?.into_suite(); let stmt = suite.first().unwrap(); assert!(!has_trailing_content(stmt.end(), contents)); let contents = "x = 1; y = 2"; let suite = parse_module(contents)?.into_suite(); let stmt = suite.first().unwrap(); assert!(has_trailing_content(stmt.end(), contents)); let contents = "x = 1 "; let suite = parse_module(contents)?.into_suite(); let stmt = suite.first().unwrap(); assert!(!has_trailing_content(stmt.end(), contents)); let contents = "x = 1 # Comment"; let suite = parse_module(contents)?.into_suite(); let stmt = suite.first().unwrap(); assert!(!has_trailing_content(stmt.end(), contents)); let contents = r" x = 1 y = 2 " .trim(); let suite = parse_module(contents)?.into_suite(); let stmt = suite.first().unwrap(); assert!(!has_trailing_content(stmt.end(), contents)); Ok(()) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_trivia_integration_tests/tests/block_comments.rs
crates/ruff_python_trivia_integration_tests/tests/block_comments.rs
use ruff_python_parser::{Mode, ParseOptions, parse_unchecked}; use ruff_python_trivia::CommentRanges; use ruff_text_size::TextSize; #[test] fn block_comments_two_line_block_at_start() { // arrange let source = "# line 1\n# line 2\n"; let parsed = parse_unchecked(source, ParseOptions::from(Mode::Module)); let comment_ranges = CommentRanges::from(parsed.tokens()); // act let block_comments = comment_ranges.block_comments(source); // assert assert_eq!(block_comments, vec![TextSize::new(0), TextSize::new(9)]); } #[test] fn block_comments_indented_block() { // arrange let source = " # line 1\n # line 2\n"; let parsed = parse_unchecked(source, ParseOptions::from(Mode::Module)); let comment_ranges = CommentRanges::from(parsed.tokens()); // act let block_comments = comment_ranges.block_comments(source); // assert assert_eq!(block_comments, vec![TextSize::new(4), TextSize::new(17)]); } #[test] fn block_comments_single_line_is_not_a_block() { // arrange let source = "\n"; let parsed = parse_unchecked(source, ParseOptions::from(Mode::Module)); let comment_ranges = CommentRanges::from(parsed.tokens()); // act let block_comments = comment_ranges.block_comments(source); // assert assert_eq!(block_comments, Vec::<TextSize>::new()); } #[test] fn block_comments_lines_with_code_not_a_block() { // arrange let source = "x = 1 # line 1\ny = 2 # line 2\n"; let parsed = parse_unchecked(source, ParseOptions::from(Mode::Module)); let comment_ranges = CommentRanges::from(parsed.tokens()); // act let block_comments = comment_ranges.block_comments(source); // assert assert_eq!(block_comments, Vec::<TextSize>::new()); } #[test] fn block_comments_sequential_lines_not_in_block() { // arrange let source = " # line 1\n # line 2\n"; let parsed = parse_unchecked(source, ParseOptions::from(Mode::Module)); let comment_ranges = CommentRanges::from(parsed.tokens()); // act let block_comments = comment_ranges.block_comments(source); // assert assert_eq!(block_comments, Vec::<TextSize>::new()); } #[test] fn block_comments_lines_in_triple_quotes_not_a_block() { // arrange let source = r#" """ # line 1 # line 2 """ "#; let parsed = parse_unchecked(source, ParseOptions::from(Mode::Module)); let comment_ranges = CommentRanges::from(parsed.tokens()); // act let block_comments = comment_ranges.block_comments(source); // assert assert_eq!(block_comments, Vec::<TextSize>::new()); } #[test] fn block_comments_stress_test() { // arrange let source = r#" # block comment 1 line 1 # block comment 2 line 2 # these lines # do not form # a block comment x = 1 # these lines also do not y = 2 # do not form a block comment # these lines do form a block comment # # # and so do these # """ # these lines are in triple quotes and # therefore do not form a block comment """ "#; let parsed = parse_unchecked(source, ParseOptions::from(Mode::Module)); let comment_ranges = CommentRanges::from(parsed.tokens()); // act let block_comments = comment_ranges.block_comments(source); // assert assert_eq!( block_comments, vec![ // Block #1 TextSize::new(1), TextSize::new(26), // Block #2 TextSize::new(174), TextSize::new(212), // Block #3 TextSize::new(219), TextSize::new(225), TextSize::new(247) ] ); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_trivia_integration_tests/tests/simple_tokenizer.rs
crates/ruff_python_trivia_integration_tests/tests/simple_tokenizer.rs
use insta::assert_debug_snapshot; use ruff_python_parser::{Mode, ParseOptions, parse_unchecked}; use ruff_python_trivia::{BackwardsTokenizer, SimpleTokenKind}; use ruff_python_trivia::{CommentRanges, SimpleToken, SimpleTokenizer, lines_after, lines_before}; use ruff_text_size::{TextLen, TextRange, TextSize}; struct TokenizationTestCase { source: &'static str, range: TextRange, tokens: Vec<SimpleToken>, } impl TokenizationTestCase { fn assert_reverse_tokenization(&self) { let mut backwards = self.tokenize_reverse(); // Re-reverse to get the tokens in forward order. backwards.reverse(); assert_eq!(&backwards, &self.tokens); } fn tokenize_reverse(&self) -> Vec<SimpleToken> { let parsed = parse_unchecked(self.source, ParseOptions::from(Mode::Module)); let comment_ranges = CommentRanges::from(parsed.tokens()); BackwardsTokenizer::new(self.source, self.range, &comment_ranges).collect() } fn tokens(&self) -> &[SimpleToken] { &self.tokens } } fn tokenize_range(source: &'static str, range: TextRange) -> TokenizationTestCase { let tokens: Vec<_> = SimpleTokenizer::new(source, range).collect(); TokenizationTestCase { source, range, tokens, } } fn tokenize(source: &'static str) -> TokenizationTestCase { tokenize_range(source, TextRange::new(TextSize::new(0), source.text_len())) } #[test] fn tokenize_trivia() { let source = "# comment\n # comment"; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); test_case.assert_reverse_tokenization(); } #[test] fn tokenize_parentheses() { let source = "([{}])"; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); test_case.assert_reverse_tokenization(); } #[test] fn tokenize_comma() { let source = ",,,,"; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); test_case.assert_reverse_tokenization(); } #[test] fn tokenize_eq() { // Should tokenize as `==`, then `=`, regardless of whether we're lexing forwards or // backwards. let source = "==="; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); test_case.assert_reverse_tokenization(); } #[test] fn tokenize_not_eq() { // Should tokenize as `!=`, then `=`, regardless of whether we're lexing forwards or // backwards. let source = "!=="; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); test_case.assert_reverse_tokenization(); } #[test] fn tokenize_continuation() { let source = "( \\\n )"; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); test_case.assert_reverse_tokenization(); } #[test] fn tokenize_operators() { let source = "-> *= ( -= ) ~ // ** **= ^ ^= | |="; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); test_case.assert_reverse_tokenization(); } #[test] fn tokenize_invalid_operators() { let source = "-> $="; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); // note: not reversible: [other, bogus, bogus] vs [bogus, bogus, other] } #[test] fn tricky_unicode() { let source = "មុ"; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); test_case.assert_reverse_tokenization(); } #[test] fn identifier_ending_in_non_start_char() { let source = "i5"; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); test_case.assert_reverse_tokenization(); } #[test] fn string_with_kind() { let source = "f'foo'"; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); // note: not reversible: [other, bogus] vs [bogus, other] } #[test] fn string_with_byte_kind() { let source = "BR'foo'"; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); // note: not reversible: [other, bogus] vs [bogus, other] } #[test] fn fstring() { let source = "f'foo'"; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); } #[test] fn tstring() { let source = "t'foo'"; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); } #[test] fn string_with_invalid_kind() { let source = "abc'foo'"; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); // note: not reversible: [other, bogus] vs [bogus, other] } #[test] fn identifier_starting_with_string_kind() { let source = "foo bar"; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); test_case.assert_reverse_tokenization(); } #[test] fn ignore_word_with_only_id_continuing_chars() { let source = "555"; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); // note: not reversible: [other, bogus, bogus] vs [bogus, bogus, other] } #[test] fn tokenize_multichar() { let source = "if in else match"; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); test_case.assert_reverse_tokenization(); } #[test] fn tokenize_substring() { let source = "('some string') # comment"; let test_case = tokenize_range(source, TextRange::new(TextSize::new(14), source.text_len())); assert_debug_snapshot!(test_case.tokens()); test_case.assert_reverse_tokenization(); } #[test] fn tokenize_slash() { let source = r" # trailing positional comment # Positional arguments only after here ,/"; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); test_case.assert_reverse_tokenization(); } #[test] fn tokenize_bogus() { let source = r#"# leading comment "a string" a = (10)"#; let test_case = tokenize(source); assert_debug_snapshot!(test_case.tokens()); assert_debug_snapshot!("Reverse", test_case.tokenize_reverse()); } #[test] fn single_quoted_multiline_string_containing_comment() { let test_case = tokenize( r"'This string contains a hash looking like a comment\ # This is not a comment'", ); assert_debug_snapshot!(test_case.tokenize_reverse()); } #[test] fn single_quoted_multiline_string_implicit_concatenation() { let test_case = tokenize( r#"'This string contains a hash looking like a comment\ # This is' "not_a_comment""#, ); assert_debug_snapshot!(test_case.tokenize_reverse()); } #[test] fn triple_quoted_multiline_string_containing_comment() { let test_case = tokenize( r"'''This string contains a hash looking like a comment # This is not a comment'''", ); assert_debug_snapshot!(test_case.tokenize_reverse()); } #[test] fn comment_containing_triple_quoted_string() { let test_case = tokenize("'''leading string''' # a comment '''not a string'''"); assert_debug_snapshot!(test_case.tokenize_reverse()); } #[test] fn comment_containing_single_quoted_string() { let test_case = tokenize("'leading string' # a comment 'not a string'"); assert_debug_snapshot!(test_case.tokenize_reverse()); } #[test] fn string_followed_by_multiple_comments() { let test_case = tokenize(r#"'a string # containing a hash " # and another hash ' # finally a comment"#); assert_debug_snapshot!(test_case.tokenize_reverse()); } #[test] fn string_with_escaped_quote() { let test_case = tokenize(r"'a string \' # containing a hash ' # finally a comment"); assert_debug_snapshot!(test_case.tokenize_reverse()); } #[test] fn string_with_double_escaped_backslash() { let test_case = tokenize(r"'a string \\' # a comment '"); assert_debug_snapshot!(test_case.tokenize_reverse()); } #[test] fn empty_string_literal() { let test_case = tokenize(r"'' # a comment '"); assert_debug_snapshot!(test_case.tokenize_reverse()); } #[test] fn lines_before_empty_string() { assert_eq!(lines_before(TextSize::new(0), ""), 0); } #[test] fn lines_before_in_the_middle_of_a_line() { assert_eq!(lines_before(TextSize::new(4), "a = 20"), 0); } #[test] fn lines_before_on_a_new_line() { assert_eq!(lines_before(TextSize::new(7), "a = 20\nb = 10"), 1); } #[test] fn lines_before_multiple_leading_newlines() { assert_eq!(lines_before(TextSize::new(9), "a = 20\n\r\nb = 10"), 2); } #[test] fn lines_before_with_comment_offset() { assert_eq!(lines_before(TextSize::new(8), "a = 20\n# a comment"), 0); } #[test] fn lines_before_with_trailing_comment() { assert_eq!( lines_before(TextSize::new(22), "a = 20 # some comment\nb = 10"), 1 ); } #[test] fn lines_before_with_comment_only_line() { assert_eq!( lines_before(TextSize::new(22), "a = 20\n# some comment\nb = 10"), 1 ); } #[test] fn lines_after_empty_string() { assert_eq!(lines_after(TextSize::new(0), ""), 0); } #[test] fn lines_after_in_the_middle_of_a_line() { assert_eq!(lines_after(TextSize::new(4), "a = 20"), 0); } #[test] fn lines_after_before_a_new_line() { assert_eq!(lines_after(TextSize::new(6), "a = 20\nb = 10"), 1); } #[test] fn lines_after_multiple_newlines() { assert_eq!(lines_after(TextSize::new(6), "a = 20\n\r\nb = 10"), 2); } #[test] fn lines_after_before_comment_offset() { assert_eq!(lines_after(TextSize::new(7), "a = 20 # a comment\n"), 0); } #[test] fn lines_after_with_comment_only_line() { assert_eq!( lines_after(TextSize::new(6), "a = 20\n# some comment\nb = 10"), 1 ); } #[test] fn test_previous_token_simple() { let cases = &["x = (", "x = ( ", "x = (\n"]; for source in cases { let token = BackwardsTokenizer::up_to(source.text_len(), source, &[]) .skip_trivia() .next() .unwrap(); assert_eq!( token, SimpleToken { kind: SimpleTokenKind::LParen, range: TextRange::new(TextSize::new(4), TextSize::new(5)), } ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_notebook/src/notebook.rs
crates/ruff_notebook/src/notebook.rs
use itertools::Itertools; use rand::{Rng, SeedableRng}; use serde::Serialize; use serde_json::error::Category; use std::cmp::Ordering; use std::collections::HashSet; use std::fs::File; use std::io; use std::io::{BufReader, Cursor, Read, Seek, SeekFrom, Write}; use std::path::Path; use std::sync::OnceLock; use thiserror::Error; use ruff_diagnostics::{SourceMap, SourceMarker}; use ruff_source_file::{NewlineWithTrailingNewline, OneIndexed, UniversalNewlineIterator}; use ruff_text_size::{TextRange, TextSize}; use crate::cell::CellOffsets; use crate::index::NotebookIndex; use crate::schema::{Cell, RawNotebook, SortAlphabetically, SourceValue}; use crate::{CellMetadata, CellStart, RawNotebookMetadata, schema}; /// Run round-trip source code generation on a given Jupyter notebook file path. pub fn round_trip(path: &Path) -> anyhow::Result<String> { let mut notebook = Notebook::from_path(path).map_err(|err| { anyhow::anyhow!( "Failed to read notebook file `{}`: {:?}", path.display(), err ) })?; let code = notebook.source_code().to_string(); notebook.update_cell_content(&code); let mut writer = Vec::new(); notebook.write(&mut writer)?; Ok(String::from_utf8(writer)?) } /// An error that can occur while deserializing a Jupyter Notebook. #[derive(Error, Debug)] pub enum NotebookError { #[error(transparent)] Io(#[from] io::Error), #[error(transparent)] Json(serde_json::Error), #[error( "Expected a Jupyter Notebook, which must be internally stored as JSON, but this file isn't valid JSON: {0}" )] InvalidJson(serde_json::Error), #[error("This file does not match the schema expected of Jupyter Notebooks: {0}")] InvalidSchema(serde_json::Error), #[error("Expected Jupyter Notebook format 4, found: {0}")] InvalidFormat(i64), } #[derive(Clone, Debug)] pub struct Notebook { /// Python source code of the notebook. /// /// This is the concatenation of all valid code cells in the notebook /// separated by a newline and a trailing newline. The trailing newline /// is added to make sure that each cell ends with a newline which will /// be removed when updating the cell content. source_code: String, /// The index of the notebook. This is used to map between the concatenated /// source code and the original notebook. index: OnceLock<NotebookIndex>, /// The raw notebook i.e., the deserialized version of JSON string. raw: RawNotebook, /// The offsets of each cell in the concatenated source code. This includes /// the first and last character offsets as well. cell_offsets: CellOffsets, /// The cell index of all valid code cells in the notebook. valid_code_cells: Vec<u32>, /// Flag to indicate if the JSON string of the notebook has a trailing newline. trailing_newline: bool, } impl Notebook { /// Read the Jupyter Notebook from the given [`Path`]. pub fn from_path(path: &Path) -> Result<Self, NotebookError> { Self::from_reader(BufReader::new(File::open(path)?)) } /// Read the Jupyter Notebook from its JSON string. pub fn from_source_code(source_code: &str) -> Result<Self, NotebookError> { Self::from_reader(Cursor::new(source_code)) } /// Read a Jupyter Notebook from a [`Read`] implementer. /// /// See also the black implementation /// <https://github.com/psf/black/blob/69ca0a4c7a365c5f5eea519a90980bab72cab764/src/black/__init__.py#L1017-L1046> fn from_reader<R>(mut reader: R) -> Result<Self, NotebookError> where R: Read + Seek, { let trailing_newline = reader.seek(SeekFrom::End(-1)).is_ok_and(|_| { let mut buf = [0; 1]; reader.read_exact(&mut buf).is_ok_and(|()| buf[0] == b'\n') }); reader.rewind()?; let raw_notebook: RawNotebook = match serde_json::from_reader(reader.by_ref()) { Ok(notebook) => notebook, Err(err) => { // Translate the error into a diagnostic return Err(match err.classify() { Category::Io => NotebookError::Json(err), Category::Syntax | Category::Eof => NotebookError::InvalidJson(err), Category::Data => { // We could try to read the schema version here but if this fails it's // a bug anyway. NotebookError::InvalidSchema(err) } }); } }; Self::from_raw_notebook(raw_notebook, trailing_newline) } pub fn from_raw_notebook( mut raw_notebook: RawNotebook, trailing_newline: bool, ) -> Result<Self, NotebookError> { // v4 is what everybody uses if raw_notebook.nbformat != 4 { // bail because we should have already failed at the json schema stage return Err(NotebookError::InvalidFormat(raw_notebook.nbformat)); } let valid_code_cells = raw_notebook .cells .iter() .enumerate() .filter(|(_, cell)| cell.is_valid_python_code_cell()) .map(|(cell_index, _)| u32::try_from(cell_index).unwrap()) .collect::<Vec<_>>(); let mut contents = Vec::with_capacity(valid_code_cells.len()); let mut current_offset = TextSize::from(0); let mut cell_offsets = CellOffsets::with_capacity(valid_code_cells.len()); cell_offsets.push(TextSize::from(0)); for &idx in &valid_code_cells { let cell_contents = match &raw_notebook.cells[idx as usize].source() { SourceValue::String(string) => string.clone(), SourceValue::StringArray(string_array) => string_array.join(""), }; current_offset += TextSize::of(&cell_contents) + TextSize::new(1); contents.push(cell_contents); cell_offsets.push(current_offset); } // Add cell ids to 4.5+ notebooks if they are missing // https://github.com/astral-sh/ruff/issues/6834 // https://github.com/jupyter/enhancement-proposals/blob/master/62-cell-id/cell-id.md#required-field // https://github.com/jupyter/enhancement-proposals/blob/master/62-cell-id/cell-id.md#questions if raw_notebook.nbformat == 4 && raw_notebook.nbformat_minor >= 5 { // We use a insecure random number generator to generate deterministic uuids let mut rng = rand::rngs::StdRng::seed_from_u64(0); let mut existing_ids = HashSet::new(); for cell in &raw_notebook.cells { let id = match cell { Cell::Code(cell) => &cell.id, Cell::Markdown(cell) => &cell.id, Cell::Raw(cell) => &cell.id, }; if let Some(id) = id { existing_ids.insert(id.clone()); } } for cell in &mut raw_notebook.cells { let id = match cell { Cell::Code(cell) => &mut cell.id, Cell::Markdown(cell) => &mut cell.id, Cell::Raw(cell) => &mut cell.id, }; if id.is_none() { loop { let new_id = uuid::Builder::from_random_bytes(rng.random()) .into_uuid() .as_simple() .to_string(); if existing_ids.insert(new_id.clone()) { *id = Some(new_id); break; } } } } } Ok(Self { raw: raw_notebook, index: OnceLock::new(), // The additional newline at the end is to maintain consistency for // all cells. These newlines will be removed before updating the // source code with the transformed content. Refer `update_cell_content`. source_code: contents.join("\n") + "\n", cell_offsets, valid_code_cells, trailing_newline, }) } /// Creates an empty notebook with a single code cell. pub fn empty() -> Self { Self::from_raw_notebook( RawNotebook { cells: vec![schema::Cell::Code(schema::CodeCell { execution_count: None, id: None, metadata: CellMetadata::default(), outputs: vec![], source: schema::SourceValue::String(String::default()), })], metadata: RawNotebookMetadata::default(), nbformat: 4, nbformat_minor: 5, }, false, ) .unwrap() } /// Update the cell offsets as per the given [`SourceMap`]. fn update_cell_offsets(&mut self, source_map: &SourceMap) { // When there are multiple cells without any edits, the offsets of those // cells will be updated using the same marker. So, we can keep track of // the last marker used to update the offsets and check if it's still // the closest marker to the current offset. let mut last_marker: Option<&SourceMarker> = None; // The first offset is always going to be at 0, so skip it. for offset in self.cell_offsets.iter_mut().skip(1).rev() { let closest_marker = match last_marker { Some(marker) if marker.source() <= *offset => marker, _ => { let Some(marker) = source_map .markers() .iter() .rev() .find(|marker| marker.source() <= *offset) else { // There are no markers above the current offset, so we can // stop here. break; }; last_marker = Some(marker); marker } }; match closest_marker.source().cmp(&closest_marker.dest()) { Ordering::Less => *offset += closest_marker.dest() - closest_marker.source(), Ordering::Greater => *offset -= closest_marker.source() - closest_marker.dest(), Ordering::Equal => (), } } } /// Update the cell contents with the transformed content. /// /// ## Panics /// /// Panics if the transformed content is out of bounds for any cell. This /// can happen only if the cell offsets were not updated before calling /// this method or the offsets were updated incorrectly. fn update_cell_content(&mut self, transformed: &str) { for (&idx, (start, end)) in self .valid_code_cells .iter() .zip(self.cell_offsets.iter().tuple_windows::<(_, _)>()) { let cell_content = transformed .get(start.to_usize()..end.to_usize()) .unwrap_or_else(|| { panic!( "Transformed content out of bounds ({start:?}..{end:?}) for cell at {idx:?}" ); }); self.raw.cells[idx as usize].set_source(SourceValue::StringArray( UniversalNewlineIterator::from( // We only need to strip the trailing newline which we added // while concatenating the cell contents. cell_content.strip_suffix('\n').unwrap_or(cell_content), ) .map(|line| line.as_full_str().to_string()) .collect::<Vec<_>>(), )); } } /// Build and return the [`NotebookIndex`]. /// /// ## Notes /// /// Empty cells don't have any newlines, but there's a single visible line /// in the UI. That single line needs to be accounted for. /// /// In case of [`SourceValue::StringArray`], newlines are part of the strings. /// So, to get the actual count of lines, we need to check for any trailing /// newline for the last line. /// /// For example, consider the following cell: /// ```python /// [ /// "import os\n", /// "import sys\n", /// ] /// ``` /// /// Here, the array suggests that there are two lines, but the actual number /// of lines visible in the UI is three. The same goes for [`SourceValue::String`] /// where we need to check for the trailing newline. /// /// The index building is expensive as it needs to go through the content of /// every valid code cell. fn build_index(&self) -> NotebookIndex { let mut cell_starts = Vec::with_capacity(self.valid_code_cells.len()); let mut current_row = OneIndexed::MIN; for &cell_index in &self.valid_code_cells { let raw_cell_index = cell_index as usize; // Record the starting row of this cell cell_starts.push(CellStart { start_row: current_row, raw_cell_index: OneIndexed::from_zero_indexed(raw_cell_index), }); let line_count = match &self.raw.cells[raw_cell_index].source() { SourceValue::String(string) => { if string.is_empty() { 1 } else { NewlineWithTrailingNewline::from(string).count() } } SourceValue::StringArray(string_array) => { if string_array.is_empty() { 1 } else { let trailing_newline = usize::from(string_array.last().is_some_and(|s| s.ends_with('\n'))); string_array.len() + trailing_newline } } }; current_row = current_row.saturating_add(line_count); } NotebookIndex { cell_starts } } /// Return the notebook content. /// /// This is the concatenation of all Python code cells. pub fn source_code(&self) -> &str { &self.source_code } /// Return the Jupyter notebook index. /// /// The index is built only once when required. This is only used to /// report diagnostics, so by that time all of the fixes must have /// been applied if `--fix` was passed. pub fn index(&self) -> &NotebookIndex { self.index.get_or_init(|| self.build_index()) } /// Return the Jupyter notebook index, consuming the notebook. /// /// The index is built only once when required. This is only used to /// report diagnostics, so by that time all of the fixes must have /// been applied if `--fix` was passed. pub fn into_index(mut self) -> NotebookIndex { self.index.take().unwrap_or_else(|| self.build_index()) } /// Return the [`CellOffsets`] for the concatenated source code corresponding /// the Jupyter notebook. pub fn cell_offsets(&self) -> &CellOffsets { &self.cell_offsets } /// Returns the start offset of the cell at index `cell` in the concatenated /// text document. pub fn cell_offset(&self, cell: OneIndexed) -> Option<TextSize> { self.cell_offsets.get(cell.to_zero_indexed()).copied() } /// Returns the text range in the concatenated document of the cell /// with index `cell`. pub fn cell_range(&self, cell: OneIndexed) -> Option<TextRange> { let start = self.cell_offsets.get(cell.to_zero_indexed()).copied()?; let end = self.cell_offsets.get(cell.to_zero_indexed() + 1).copied()?; Some(TextRange::new(start, end)) } /// Return `true` if the notebook has a trailing newline, `false` otherwise. pub fn trailing_newline(&self) -> bool { self.trailing_newline } /// Update the notebook with the given sourcemap and transformed content. pub fn update(&mut self, source_map: &SourceMap, transformed: String) { // Cell offsets must be updated before updating the cell content as // it depends on the offsets to extract the cell content. self.index.take(); self.update_cell_offsets(source_map); self.update_cell_content(&transformed); self.source_code = transformed; } /// Return a slice of [`Cell`] in the Jupyter notebook. pub fn cells(&self) -> &[Cell] { &self.raw.cells } pub fn metadata(&self) -> &RawNotebookMetadata { &self.raw.metadata } /// Check if it's a Python notebook. /// /// This is determined by checking the `language_info` or `kernelspec` in the notebook /// metadata. If neither is present, it's assumed to be a Python notebook. pub fn is_python_notebook(&self) -> bool { if let Some(language_info) = self.raw.metadata.language_info.as_ref() { return language_info.name == "python"; } if let Some(kernel_spec) = self.raw.metadata.kernelspec.as_ref() { return kernel_spec.language.as_deref() == Some("python"); } true } /// Write the notebook back to the given [`Write`] implementer. pub fn write(&self, writer: &mut dyn Write) -> Result<(), NotebookError> { // https://github.com/psf/black/blob/69ca0a4c7a365c5f5eea519a90980bab72cab764/src/black/__init__.py#LL1041 let formatter = serde_json::ser::PrettyFormatter::with_indent(b" "); let mut serializer = serde_json::Serializer::with_formatter(writer, formatter); SortAlphabetically(&self.raw) .serialize(&mut serializer) .map_err(NotebookError::Json)?; if self.trailing_newline { writeln!(serializer.into_inner())?; } Ok(()) } } impl PartialEq for Notebook { fn eq(&self, other: &Self) -> bool { self.trailing_newline == other.trailing_newline && self.raw == other.raw } } impl Eq for Notebook {} #[cfg(test)] mod tests { use std::path::Path; use anyhow::Result; use test_case::test_case; use ruff_source_file::OneIndexed; use crate::{Cell, CellStart, Notebook, NotebookError, NotebookIndex}; /// Construct a path to a Jupyter notebook in the `resources/test/fixtures/jupyter` directory. fn notebook_path(path: impl AsRef<Path>) -> std::path::PathBuf { Path::new("./resources/test/fixtures/jupyter").join(path) } #[test_case("valid.ipynb", true)] #[test_case("R.ipynb", false)] #[test_case("kernelspec_language.ipynb", true)] fn is_python_notebook(filename: &str, expected: bool) { let notebook = Notebook::from_path(&notebook_path(filename)).unwrap(); assert_eq!(notebook.is_python_notebook(), expected); } #[test] fn test_invalid() { assert!(matches!( Notebook::from_path(&notebook_path("invalid_extension.ipynb")), Err(NotebookError::InvalidJson(_)) )); assert!(matches!( Notebook::from_path(&notebook_path("not_json.ipynb")), Err(NotebookError::InvalidJson(_)) )); assert!(matches!( Notebook::from_path(&notebook_path("wrong_schema.ipynb")), Err(NotebookError::InvalidSchema(_)) )); } #[test] fn empty_notebook() { let notebook = Notebook::empty(); assert_eq!(notebook.source_code(), "\n"); } #[test_case("markdown", false)] #[test_case("only_magic", true)] #[test_case("code_and_magic", true)] #[test_case("only_code", true)] #[test_case("cell_magic", false)] #[test_case("valid_cell_magic", true)] #[test_case("automagic", false)] #[test_case("automagic_assignment", true)] #[test_case("automagics", false)] #[test_case("automagic_before_code", false)] #[test_case("automagic_after_code", true)] #[test_case("unicode_magic_gh9145", true)] #[test_case("vscode_language_id_python", true)] #[test_case("vscode_language_id_javascript", false)] fn test_is_valid_python_code_cell(cell: &str, expected: bool) -> Result<()> { /// Read a Jupyter cell from the `resources/test/fixtures/jupyter/cell` directory. fn read_jupyter_cell(path: impl AsRef<Path>) -> Result<Cell> { let path = notebook_path("cell").join(path); let source_code = std::fs::read_to_string(path)?; Ok(serde_json::from_str(&source_code)?) } assert_eq!( read_jupyter_cell(format!("{cell}.json"))?.is_valid_python_code_cell(), expected ); Ok(()) } #[test] fn test_concat_notebook() -> Result<(), NotebookError> { let notebook = Notebook::from_path(&notebook_path("valid.ipynb"))?; assert_eq!( notebook.source_code, r#"def unused_variable(): x = 1 y = 2 print(f"cell one: {y}") unused_variable() def mutable_argument(z=set()): print(f"cell two: {z}") mutable_argument() print("after empty cells") "# ); assert_eq!( notebook.index(), &NotebookIndex { cell_starts: vec![ CellStart { start_row: OneIndexed::MIN, raw_cell_index: OneIndexed::MIN }, CellStart { start_row: OneIndexed::from_zero_indexed(6), raw_cell_index: OneIndexed::from_zero_indexed(2) }, CellStart { start_row: OneIndexed::from_zero_indexed(11), raw_cell_index: OneIndexed::from_zero_indexed(4) }, CellStart { start_row: OneIndexed::from_zero_indexed(12), raw_cell_index: OneIndexed::from_zero_indexed(6) }, CellStart { start_row: OneIndexed::from_zero_indexed(14), raw_cell_index: OneIndexed::from_zero_indexed(7) } ], } ); assert_eq!( notebook.cell_offsets().as_ref(), &[ 0.into(), 90.into(), 168.into(), 169.into(), 171.into(), 198.into() ] ); Ok(()) } #[test_case("vscode_language_id.ipynb")] #[test_case("kernelspec_language.ipynb")] fn round_trip(filename: &str) { let path = notebook_path(filename); let expected = std::fs::read_to_string(&path).unwrap(); let actual = super::round_trip(&path).unwrap(); assert_eq!(actual, expected); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_notebook/src/lib.rs
crates/ruff_notebook/src/lib.rs
//! Utils for reading and writing jupyter notebooks pub use cell::*; pub use index::*; pub use notebook::*; pub use schema::*; mod cell; mod index; mod notebook; mod schema;
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_notebook/src/index.rs
crates/ruff_notebook/src/index.rs
use serde::{Deserialize, Serialize}; use ruff_source_file::{LineColumn, OneIndexed, SourceLocation}; /// Jupyter Notebook indexing table /// /// When we lint a jupyter notebook, we have to translate the row/column based on /// [`ruff_text_size::TextSize`] to jupyter notebook cell/row/column. #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct NotebookIndex { /// Stores the starting row and the absolute cell index for every Python (valid) cell. /// /// The index in this vector corresponds to the Python cell index (valid cell index). pub(super) cell_starts: Vec<CellStart>, } impl NotebookIndex { fn find_cell(&self, row: OneIndexed) -> Option<CellStart> { match self .cell_starts .binary_search_by_key(&row, |start| start.start_row) { Ok(cell_index) => Some(self.cell_starts[cell_index]), Err(insertion_point) => Some(self.cell_starts[insertion_point.checked_sub(1)?]), } } /// Returns the (raw) cell number (1-based) for the given row (1-based). pub fn cell(&self, row: OneIndexed) -> Option<OneIndexed> { self.find_cell(row).map(|start| start.raw_cell_index) } /// Returns the row number (1-based) in the cell (1-based) for the /// given row (1-based). pub fn cell_row(&self, row: OneIndexed) -> Option<OneIndexed> { self.find_cell(row) .map(|start| OneIndexed::from_zero_indexed(row.get() - start.start_row.get())) } /// Returns an iterator over the starting rows of each cell (1-based). /// /// This yields one entry per Python cell (skipping over Markdown cell). pub fn iter(&self) -> impl Iterator<Item = CellStart> + '_ { self.cell_starts.iter().copied() } /// Translates the given [`LineColumn`] based on the indexing table. /// /// This will translate the row/column in the concatenated source code /// to the row/column in the Jupyter Notebook cell. pub fn translate_line_column(&self, source_location: &LineColumn) -> LineColumn { LineColumn { line: self .cell_row(source_location.line) .unwrap_or(OneIndexed::MIN), column: source_location.column, } } /// Translates the given [`SourceLocation`] based on the indexing table. /// /// This will translate the line/character in the concatenated source code /// to the line/character in the Jupyter Notebook cell. pub fn translate_source_location(&self, source_location: &SourceLocation) -> SourceLocation { SourceLocation { line: self .cell_row(source_location.line) .unwrap_or(OneIndexed::MIN), character_offset: source_location.character_offset, } } } #[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)] pub struct CellStart { /// The row in the concatenated notebook source code at which /// this cell starts. pub(super) start_row: OneIndexed, /// The absolute index of this cell in the notebook. pub(super) raw_cell_index: OneIndexed, } impl CellStart { pub fn start_row(&self) -> OneIndexed { self.start_row } pub fn cell_index(&self) -> OneIndexed { self.raw_cell_index } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_notebook/src/schema.rs
crates/ruff_notebook/src/schema.rs
//! The JSON schema of a Jupyter Notebook, entrypoint is [`RawNotebook`] //! //! Generated by <https://app.quicktype.io/> from //! <https://github.com/jupyter/nbformat/blob/16b53251aabf472ad9406ddb1f78b0421c014eeb/nbformat/v4/nbformat.v4.schema.json> //! Jupyter Notebook v4.5 JSON schema. //! //! The following changes were made to the generated version: //! * Only keep the required structs and enums. //! * `Cell::id` is optional because it wasn't required <v4.5 //! * `#[serde(deny_unknown_fields)]` was added where the schema had //! `"additionalProperties": false` //! * `#[serde(flatten)] pub other: BTreeMap<String, Value>` for //! `"additionalProperties": true` as preparation for round-trip support. //! * `#[serde(skip_serializing_none)]` was added to all structs where one or //! more fields were optional to avoid serializing `null` values. //! * `Cell::execution_count` is a required property only for code cells, but //! we serialize it for all cells. This is because we can't know if a cell is //! a code cell or not without looking at the `cell_type` property, which //! would require a custom serializer. use std::collections::{BTreeMap, HashMap}; use serde::{Deserialize, Serialize}; use serde_json::Value; use serde_with::skip_serializing_none; fn sort_alphabetically<T: Serialize, S: serde::Serializer>( value: &T, serializer: S, ) -> Result<S::Ok, S::Error> { let value = serde_json::to_value(value).map_err(serde::ser::Error::custom)?; value.serialize(serializer) } /// This is used to serialize any value implementing [`Serialize`] alphabetically. /// /// The reason for this is to maintain consistency in the generated JSON string, /// which is useful for diffing. The default serializer keeps the order of the /// fields as they are defined in the struct, which will not be consistent when /// there are `extra` fields. /// /// # Example /// /// ``` /// use std::collections::BTreeMap; /// /// use serde::Serialize; /// /// use ruff_notebook::SortAlphabetically; /// /// #[derive(Serialize)] /// struct MyStruct { /// a: String, /// #[serde(flatten)] /// extra: BTreeMap<String, String>, /// b: String, /// } /// /// let my_struct = MyStruct { /// a: "a".to_string(), /// extra: BTreeMap::from([ /// ("d".to_string(), "d".to_string()), /// ("c".to_string(), "c".to_string()), /// ]), /// b: "b".to_string(), /// }; /// /// let serialized = serde_json::to_string_pretty(&SortAlphabetically(&my_struct)).unwrap(); /// assert_eq!( /// serialized, /// r#"{ /// "a": "a", /// "b": "b", /// "c": "c", /// "d": "d" /// }"# /// ); /// ``` #[derive(Serialize)] pub struct SortAlphabetically<T: Serialize>(#[serde(serialize_with = "sort_alphabetically")] pub T); /// The root of the JSON of a Jupyter Notebook /// /// Generated by <https://app.quicktype.io/> from /// <https://github.com/jupyter/nbformat/blob/16b53251aabf472ad9406ddb1f78b0421c014eeb/nbformat/v4/nbformat.v4.schema.json> /// Jupyter Notebook v4.5 JSON schema. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[serde(deny_unknown_fields)] pub struct RawNotebook { /// Array of cells of the current notebook. pub cells: Vec<Cell>, /// Notebook root-level metadata. pub metadata: RawNotebookMetadata, /// Notebook format (major number). Incremented between backwards incompatible changes to the /// notebook format. pub nbformat: i64, /// Notebook format (minor number). Incremented for backward compatible changes to the /// notebook format. pub nbformat_minor: i64, } /// String identifying the type of cell. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] #[serde(tag = "cell_type")] pub enum Cell { #[serde(rename = "code")] Code(CodeCell), #[serde(rename = "markdown")] Markdown(MarkdownCell), #[serde(rename = "raw")] Raw(RawCell), } /// Notebook raw nbconvert cell. #[skip_serializing_none] #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[serde(deny_unknown_fields)] pub struct RawCell { pub attachments: Option<Value>, /// Technically, id isn't required (it's not even present) in schema v4.0 through v4.4, but /// it's required in v4.5. Main issue is that pycharm creates notebooks without an id /// <https://youtrack.jetbrains.com/issue/PY-59438/Jupyter-notebooks-created-with-PyCharm-are-missing-the-id-field-in-cells-in-the-.ipynb-json> pub id: Option<String>, /// Cell-level metadata. pub metadata: CellMetadata, pub source: SourceValue, } /// Notebook markdown cell. #[skip_serializing_none] #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[serde(deny_unknown_fields)] pub struct MarkdownCell { pub attachments: Option<Value>, /// Technically, id isn't required (it's not even present) in schema v4.0 through v4.4, but /// it's required in v4.5. Main issue is that pycharm creates notebooks without an id /// <https://youtrack.jetbrains.com/issue/PY-59438/Jupyter-notebooks-created-with-PyCharm-are-missing-the-id-field-in-cells-in-the-.ipynb-json> pub id: Option<String>, /// Cell-level metadata. pub metadata: CellMetadata, pub source: SourceValue, } /// Notebook code cell. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[serde(deny_unknown_fields)] pub struct CodeCell { /// The code cell's prompt number. Will be null if the cell has not been run. pub execution_count: Option<i64>, /// Technically, id isn't required (it's not even present) in schema v4.0 through v4.4, but /// it's required in v4.5. Main issue is that pycharm creates notebooks without an id /// <https://youtrack.jetbrains.com/issue/PY-59438/Jupyter-notebooks-created-with-PyCharm-are-missing-the-id-field-in-cells-in-the-.ipynb-json> #[serde(skip_serializing_if = "Option::is_none")] pub id: Option<String>, /// Cell-level metadata. pub metadata: CellMetadata, /// Execution, display, or stream outputs. pub outputs: Vec<Value>, pub source: SourceValue, } /// Cell-level metadata. #[skip_serializing_none] #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct CellMetadata { /// VS Code specific cell metadata. /// /// This is [`Some`] only if the cell's preferred language is different from the notebook's /// preferred language. /// <https://github.com/microsoft/vscode/blob/e6c009a3d4ee60f352212b978934f52c4689fbd9/extensions/ipynb/src/serializers.ts#L117-L122> pub vscode: Option<CodeCellMetadataVSCode>, /// For additional properties that isn't required by Ruff. #[serde(flatten)] pub extra: HashMap<String, Value>, } /// VS Code specific cell metadata. /// <https://github.com/microsoft/vscode/blob/e6c009a3d4ee60f352212b978934f52c4689fbd9/extensions/ipynb/src/serializers.ts#L104-L107> #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct CodeCellMetadataVSCode { /// <https://code.visualstudio.com/docs/languages/identifiers> pub language_id: String, } /// Notebook root-level metadata. #[skip_serializing_none] #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)] pub struct RawNotebookMetadata { /// The author(s) of the notebook document pub authors: Option<Value>, /// Kernel information. pub kernelspec: Option<Kernelspec>, /// Language information. pub language_info: Option<LanguageInfo>, /// Original notebook format (major number) before converting the notebook between versions. /// This should never be written to a file. pub orig_nbformat: Option<i64>, /// The title of the notebook document pub title: Option<String>, /// For additional properties. #[serde(flatten)] pub extra: BTreeMap<String, Value>, } /// Kernel information. #[skip_serializing_none] #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Kernelspec { /// The language name. This isn't mentioned in the spec but is populated by various tools and /// can be used as a fallback if [`language_info`] is missing. /// /// This is also used by VS Code to determine the preferred language of the notebook: /// <https://github.com/microsoft/vscode/blob/1c31e758985efe11bc0453a45ea0bb6887e670a4/extensions/ipynb/src/deserializers.ts#L20-L22>. /// /// [`language_info`]: RawNotebookMetadata::language_info pub language: Option<String>, /// For additional properties that isn't required by Ruff. #[serde(flatten)] pub extra: HashMap<String, Value>, } /// Language information. #[skip_serializing_none] #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct LanguageInfo { /// The codemirror mode to use for code in this language. pub codemirror_mode: Option<Value>, /// The file extension for files in this language. pub file_extension: Option<String>, /// The mimetype corresponding to files in this language. pub mimetype: Option<String>, /// The programming language which this kernel runs. pub name: String, /// The pygments lexer to use for code in this language. pub pygments_lexer: Option<String>, /// For additional properties. #[serde(flatten)] pub extra: BTreeMap<String, Value>, } /// mimetype output (e.g. text/plain), represented as either an array of strings or a /// string. /// /// Contents of the cell, represented as an array of lines. /// /// The stream's text output, represented as an array of strings. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[serde(untagged)] pub enum SourceValue { String(String), StringArray(Vec<String>), }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_notebook/src/cell.rs
crates/ruff_notebook/src/cell.rs
use std::fmt; use std::ops::{Deref, DerefMut}; use itertools::Itertools; use ruff_text_size::{TextRange, TextSize}; use crate::CellMetadata; use crate::schema::{Cell, SourceValue}; impl fmt::Display for SourceValue { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { SourceValue::String(string) => f.write_str(string), SourceValue::StringArray(string_array) => { for string in string_array { f.write_str(string)?; } Ok(()) } } } } impl Cell { /// Return the [`SourceValue`] of the cell. pub fn source(&self) -> &SourceValue { match self { Cell::Code(cell) => &cell.source, Cell::Markdown(cell) => &cell.source, Cell::Raw(cell) => &cell.source, } } pub fn is_code_cell(&self) -> bool { matches!(self, Cell::Code(_)) } pub fn metadata(&self) -> &CellMetadata { match self { Cell::Code(cell) => &cell.metadata, Cell::Markdown(cell) => &cell.metadata, Cell::Raw(cell) => &cell.metadata, } } /// Update the [`SourceValue`] of the cell. pub(crate) fn set_source(&mut self, source: SourceValue) { match self { Cell::Code(cell) => cell.source = source, Cell::Markdown(cell) => cell.source = source, Cell::Raw(cell) => cell.source = source, } } /// Return `true` if it's a valid code cell. /// /// A valid code cell is a cell where: /// 1. The cell type is [`Cell::Code`] /// 2. The source doesn't contain a cell magic /// 3. If the language id is set, it should be `python` pub(crate) fn is_valid_python_code_cell(&self) -> bool { let source = match self { Cell::Code(cell) if cell .metadata .vscode .as_ref() .is_none_or(|vscode| vscode.language_id == "python") => { &cell.source } _ => return false, }; // Ignore cells containing cell magic as they act on the entire cell // as compared to line magic which acts on a single line. !match source { SourceValue::String(string) => Self::is_magic_cell(string.lines()), SourceValue::StringArray(string_array) => { Self::is_magic_cell(string_array.iter().map(String::as_str)) } } } /// Returns `true` if a cell should be ignored due to the use of cell magics. fn is_magic_cell<'a>(lines: impl Iterator<Item = &'a str>) -> bool { let mut lines = lines.peekable(); // Detect automatic line magics (automagic), which aren't supported by the parser. If a line // magic uses automagic, Jupyter doesn't allow following it with non-magic lines anyway, so // we aren't missing out on any valid Python code. // // For example, this is valid: // ```jupyter // cat /path/to/file // cat /path/to/file // ``` // // But this is invalid: // ```jupyter // cat /path/to/file // x = 1 // ``` // // See: https://ipython.readthedocs.io/en/stable/interactive/magics.html if let Some(line) = lines.peek() { let mut tokens = line.split_whitespace(); // The first token must be an automagic, like `load_exit`. if tokens.next().is_some_and(|token| { matches!( token, "alias" | "alias_magic" | "autoawait" | "autocall" | "automagic" | "bookmark" | "cd" | "code_wrap" | "colors" | "conda" | "config" | "debug" | "dhist" | "dirs" | "doctest_mode" | "edit" | "env" | "gui" | "history" | "killbgscripts" | "load" | "load_ext" | "loadpy" | "logoff" | "logon" | "logstart" | "logstate" | "logstop" | "lsmagic" | "macro" | "magic" | "mamba" | "matplotlib" | "micromamba" | "notebook" | "page" | "pastebin" | "pdb" | "pdef" | "pdoc" | "pfile" | "pinfo" | "pinfo2" | "pip" | "popd" | "pprint" | "precision" | "prun" | "psearch" | "psource" | "pushd" | "pwd" | "pycat" | "pylab" | "quickref" | "recall" | "rehashx" | "reload_ext" | "rerun" | "reset" | "reset_selective" | "run" | "save" | "sc" | "set_env" | "sx" | "system" | "tb" | "time" | "timeit" | "unalias" | "unload_ext" | "who" | "who_ls" | "whos" | "xdel" | "xmode" ) }) { // The second token must _not_ be an operator, like `=` (to avoid false positives). // The assignment operators can never follow an automagic. Some binary operators // _can_, though (e.g., `cd -` is valid), so we omit them. if !tokens.next().is_some_and(|token| { matches!( token, "=" | "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**=" | "&=" | "|=" | "^=" ) }) { return true; } } } // Detect cell magics (which operate on multiple lines). lines.any(|line| { let Some(first) = line.split_whitespace().next() else { return false; }; if first.len() < 2 { return false; } let Some(command) = first.strip_prefix("%%") else { return false; }; // These cell magics are special in that the lines following them are valid // Python code and the variables defined in that scope are available to the // rest of the notebook. // // For example: // // Cell 1: // ```python // x = 1 // ``` // // Cell 2: // ```python // %%time // y = x // ``` // // Cell 3: // ```python // print(y) # Here, `y` is available. // ``` // // This is to avoid false positives when these variables are referenced // elsewhere in the notebook. // // Refer https://github.com/astral-sh/ruff/issues/13718 for `ipytest`. !matches!( command, "capture" | "debug" | "ipytest" | "prun" | "pypy" | "python" | "python3" | "time" | "timeit" ) }) } } /// Cell offsets are used to keep track of the start and end offsets of each /// cell in the concatenated source code. These offsets are in sorted order. #[derive(Clone, Debug, Default, PartialEq)] pub struct CellOffsets(Vec<TextSize>); impl CellOffsets { /// Create a new [`CellOffsets`] with the given capacity. pub(crate) fn with_capacity(capacity: usize) -> Self { Self(Vec::with_capacity(capacity)) } /// Push a new offset to the end of the [`CellOffsets`]. /// /// # Panics /// /// Panics if the offset is less than the last offset pushed. pub(crate) fn push(&mut self, offset: TextSize) { if let Some(last_offset) = self.0.last() { assert!( *last_offset <= offset, "Offsets must be pushed in sorted order" ); } self.0.push(offset); } /// Returns the range of the cell containing the given offset, if any. pub fn containing_range(&self, offset: TextSize) -> Option<TextRange> { self.iter().tuple_windows().find_map(|(start, end)| { if *start <= offset && offset < *end { Some(TextRange::new(*start, *end)) } else { None } }) } /// Returns `true` if the given range contains a cell boundary. /// /// A range starting at the cell boundary isn't considered to contain the cell boundary /// as it starts right after it. A range starting before a cell boundary /// and ending exactly at the boundary is considered to contain the cell boundary. /// /// # Examples /// Cell 1: /// /// ```py /// import c /// ``` /// /// Cell 2: /// /// ```py /// import os /// ``` /// /// The range `import c`..`import os`, contains a cell boundary because it starts before cell 2 and ends in cell 2 (`end=cell2_boundary`). /// The `import os` contains no cell boundary because it starts at the start of cell 2 (at the cell boundary) but doesn't cross into another cell. pub fn has_cell_boundary(&self, range: TextRange) -> bool { let after_range_start = self.partition_point(|offset| *offset <= range.start()); let Some(boundary) = self.get(after_range_start).copied() else { return false; }; range.contains_inclusive(boundary) } /// Returns an iterator over [`TextRange`]s covered by each cell. pub fn ranges(&self) -> impl Iterator<Item = TextRange> { self.iter() .tuple_windows() .map(|(start, end)| TextRange::new(*start, *end)) } } impl Deref for CellOffsets { type Target = [TextSize]; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for CellOffsets { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_trivia/src/textwrap.rs
crates/ruff_python_trivia/src/textwrap.rs
//! Functions related to adding and removing indentation from lines of //! text. use std::borrow::Cow; use std::cmp; use ruff_source_file::UniversalNewlines; use crate::PythonWhitespace; /// Indent each line by the given prefix. /// /// # Examples /// /// ``` /// # use ruff_python_trivia::textwrap::indent; /// /// assert_eq!(indent("First line.\nSecond line.\n", " "), /// " First line.\n Second line.\n"); /// ``` /// /// When indenting, trailing whitespace is stripped from the prefix. /// This means that empty lines remain empty afterwards: /// /// ``` /// # use ruff_python_trivia::textwrap::indent; /// /// assert_eq!(indent("First line.\n\n\nSecond line.\n", " "), /// " First line.\n\n\n Second line.\n"); /// ``` /// /// Notice how `"\n\n\n"` remained as `"\n\n\n"`. /// /// This feature is useful when you want to indent text and have a /// space between your prefix and the text. In this case, you _don't_ /// want a trailing space on empty lines: /// /// ``` /// # use ruff_python_trivia::textwrap::indent; /// /// assert_eq!(indent("foo = 123\n\nprint(foo)\n", "# "), /// "# foo = 123\n#\n# print(foo)\n"); /// ``` /// /// Notice how `"\n\n"` became `"\n#\n"` instead of `"\n# \n"` which /// would have trailing whitespace. /// /// Leading and trailing whitespace coming from the text itself is /// kept unchanged: /// /// ``` /// # use ruff_python_trivia::textwrap::indent; /// /// assert_eq!(indent(" \t Foo ", "->"), "-> \t Foo "); /// ``` pub fn indent<'a>(text: &'a str, prefix: &str) -> Cow<'a, str> { if prefix.is_empty() { return Cow::Borrowed(text); } let mut result = String::with_capacity(text.len() + prefix.len()); let trimmed_prefix = prefix.trim_whitespace_end(); for line in text.universal_newlines() { if line.trim_whitespace().is_empty() { result.push_str(trimmed_prefix); } else { result.push_str(prefix); } result.push_str(line.as_full_str()); } Cow::Owned(result) } /// Indent only the first line by the given prefix. /// /// This function is useful when you want to indent the first line of a multi-line /// expression while preserving the relative indentation of subsequent lines. /// /// # Examples /// /// ``` /// # use ruff_python_trivia::textwrap::indent_first_line; /// /// assert_eq!(indent_first_line("First line.\nSecond line.\n", " "), /// " First line.\nSecond line.\n"); /// ``` /// /// When indenting, trailing whitespace is stripped from the prefix. /// This means that empty lines remain empty afterwards: /// /// ``` /// # use ruff_python_trivia::textwrap::indent_first_line; /// /// assert_eq!(indent_first_line("\n\n\nSecond line.\n", " "), /// "\n\n\nSecond line.\n"); /// ``` /// /// Leading and trailing whitespace coming from the text itself is /// kept unchanged: /// /// ``` /// # use ruff_python_trivia::textwrap::indent_first_line; /// /// assert_eq!(indent_first_line(" \t Foo ", "->"), "-> \t Foo "); /// ``` pub fn indent_first_line<'a>(text: &'a str, prefix: &str) -> Cow<'a, str> { if prefix.is_empty() { return Cow::Borrowed(text); } let mut lines = text.universal_newlines(); let Some(first_line) = lines.next() else { return Cow::Borrowed(text); }; let mut result = String::with_capacity(text.len() + prefix.len()); // Indent only the first line if first_line.trim_whitespace().is_empty() { result.push_str(prefix.trim_whitespace_end()); } else { result.push_str(prefix); } result.push_str(first_line.as_full_str()); // Add remaining lines without indentation for line in lines { result.push_str(line.as_full_str()); } Cow::Owned(result) } /// Removes common leading whitespace from each line. /// /// This function will look at each non-empty line and determine the /// maximum amount of whitespace that can be removed from all lines. /// /// Lines that consist solely of whitespace are trimmed to a blank line. /// /// ``` /// # use ruff_python_trivia::textwrap::dedent; /// /// assert_eq!(dedent(" /// 1st line /// 2nd line /// 3rd line /// "), " /// 1st line /// 2nd line /// 3rd line /// "); /// ``` pub fn dedent(text: &str) -> Cow<'_, str> { // Find the minimum amount of leading whitespace on each line. let prefix_len = text .universal_newlines() .fold(usize::MAX, |prefix_len, line| { let leading_whitespace_len = line.len() - line.trim_whitespace_start().len(); if leading_whitespace_len == line.len() { // Skip empty lines. prefix_len } else { cmp::min(prefix_len, leading_whitespace_len) } }); // If there is no common prefix, no need to dedent. if prefix_len == usize::MAX { return Cow::Borrowed(text); } // Remove the common prefix from each line. let mut result = String::with_capacity(text.len()); for line in text.universal_newlines() { if line.trim_whitespace().is_empty() { if let Some(line_ending) = line.line_ending() { result.push_str(&line_ending); } } else { result.push_str(&line.as_full_str()[prefix_len..]); } } Cow::Owned(result) } /// Reduce a block's indentation to match the provided indentation. /// /// This function looks at the first line in the block to determine the /// current indentation, then removes whitespace from each line to /// match the provided indentation. /// /// Leading comments are ignored unless the block is only composed of comments. /// /// Lines that are indented by _less_ than the indent of the first line /// are left unchanged. /// /// Lines that consist solely of whitespace are trimmed to a blank line. /// /// # Panics /// If the first line is indented by less than the provided indent. pub fn dedent_to(text: &str, indent: &str) -> Option<String> { // Look at the indentation of the first non-empty line, to determine the "baseline" indentation. let mut first_comment = None; let existing_indent_len = text .universal_newlines() .find_map(|line| { let trimmed = line.trim_whitespace_start(); if trimmed.is_empty() { None } else if trimmed.starts_with('#') && first_comment.is_none() { first_comment = Some(line.len() - trimmed.len()); None } else { Some(line.len() - trimmed.len()) } }) .unwrap_or(first_comment.unwrap_or_default()); if existing_indent_len < indent.len() { return None; } // Determine the amount of indentation to remove. let dedent_len = existing_indent_len - indent.len(); let mut result = String::with_capacity(text.len() + indent.len()); for line in text.universal_newlines() { let trimmed = line.trim_whitespace_start(); if trimmed.is_empty() { if let Some(line_ending) = line.line_ending() { result.push_str(&line_ending); } } else { // Determine the current indentation level. let current_indent_len = line.len() - trimmed.len(); if current_indent_len < existing_indent_len { // If the current indentation level is less than the baseline, keep it as is. result.push_str(line.as_full_str()); } else { // Otherwise, reduce the indentation level. result.push_str(&line.as_full_str()[dedent_len..]); } } } Some(result) } #[cfg(test)] mod tests { use super::*; #[test] fn indent_empty() { assert_eq!(indent("\n", " "), "\n"); } #[test] #[rustfmt::skip] fn indent_nonempty() { let text = [ " foo\n", "bar\n", " baz\n", ].join(""); let expected = [ "// foo\n", "// bar\n", "// baz\n", ].join(""); assert_eq!(indent(&text, "// "), expected); } #[test] #[rustfmt::skip] fn indent_empty_line() { let text = [ " foo", "bar", "", " baz", ].join("\n"); let expected = [ "// foo", "// bar", "//", "// baz", ].join("\n"); assert_eq!(indent(&text, "// "), expected); } #[test] #[rustfmt::skip] fn indent_mixed_newlines() { let text = [ " foo\r\n", "bar\n", " baz\r", ].join(""); let expected = [ "// foo\r\n", "// bar\n", "// baz\r", ].join(""); assert_eq!(indent(&text, "// "), expected); } #[test] fn dedent_empty() { assert_eq!(dedent(""), ""); } #[test] #[rustfmt::skip] fn dedent_multi_line() { let x = [ " foo", " bar", " baz", ].join("\n"); let y = [ " foo", "bar", " baz" ].join("\n"); assert_eq!(dedent(&x), y); } #[test] #[rustfmt::skip] fn dedent_empty_line() { let x = [ " foo", " bar", " ", " baz" ].join("\n"); let y = [ " foo", "bar", "", " baz" ].join("\n"); assert_eq!(dedent(&x), y); } #[test] #[rustfmt::skip] fn dedent_blank_line() { let x = [ " foo", "", " bar", " foo", " bar", " baz", ].join("\n"); let y = [ "foo", "", " bar", " foo", " bar", " baz", ].join("\n"); assert_eq!(dedent(&x), y); } #[test] #[rustfmt::skip] fn dedent_whitespace_line() { let x = [ " foo", " ", " bar", " foo", " bar", " baz", ].join("\n"); let y = [ "foo", "", " bar", " foo", " bar", " baz", ].join("\n"); assert_eq!(dedent(&x), y); } #[test] #[rustfmt::skip] fn dedent_mixed_whitespace() { let x = [ "\tfoo", " bar", ].join("\n"); let y = [ "foo", " bar", ].join("\n"); assert_eq!(dedent(&x), y); } #[test] #[rustfmt::skip] fn dedent_tabbed_whitespace() { let x = [ "\t\tfoo", "\t\t\tbar", ].join("\n"); let y = [ "foo", "\tbar", ].join("\n"); assert_eq!(dedent(&x), y); } #[test] #[rustfmt::skip] fn dedent_mixed_tabbed_whitespace() { let x = [ "\t \tfoo", "\t \t\tbar", ].join("\n"); let y = [ "foo", "\tbar", ].join("\n"); assert_eq!(dedent(&x), y); } #[test] #[rustfmt::skip] fn dedent_preserve_no_terminating_newline() { let x = [ " foo", " bar", ].join("\n"); let y = [ "foo", " bar", ].join("\n"); assert_eq!(dedent(&x), y); } #[test] #[rustfmt::skip] fn dedent_mixed_newlines() { let x = [ " foo\r\n", " bar\n", " baz\r", ].join(""); let y = [ " foo\r\n", "bar\n", " baz\r" ].join(""); assert_eq!(dedent(&x), y); } #[test] fn dedent_non_python_whitespace() { let text = r"        C = int(f.rea1,0],[-1,0,1]], [[-1,-1,1],[1,1,-1],[0,-1,0]], [[-1,-1,-1],[1,1,0],[1,0,1]] ]"; assert_eq!(dedent(text), text); } #[test] fn indent_first_line_empty() { assert_eq!(indent_first_line("\n", " "), "\n"); } #[test] #[rustfmt::skip] fn indent_first_line_nonempty() { let text = [ " foo\n", "bar\n", " baz\n", ].join(""); let expected = [ "// foo\n", "bar\n", " baz\n", ].join(""); assert_eq!(indent_first_line(&text, "// "), expected); } #[test] #[rustfmt::skip] fn indent_first_line_empty_line() { let text = [ " foo", "bar", "", " baz", ].join("\n"); let expected = [ "// foo", "bar", "", " baz", ].join("\n"); assert_eq!(indent_first_line(&text, "// "), expected); } #[test] #[rustfmt::skip] fn indent_first_line_mixed_newlines() { let text = [ " foo\r\n", "bar\n", " baz\r", ].join(""); let expected = [ "// foo\r\n", "bar\n", " baz\r", ].join(""); assert_eq!(indent_first_line(&text, "// "), expected); } #[test] #[rustfmt::skip] fn adjust_indent() { let x = [ " foo", " bar", " ", " baz" ].join("\n"); let y = [ " foo", " bar", "", " baz" ].join("\n"); assert_eq!(dedent_to(&x, " "), Some(y)); let x = [ " foo", " bar", " baz", ].join("\n"); let y = [ "foo", " bar", "baz" ].join("\n"); assert_eq!(dedent_to(&x, ""), Some(y)); let x = [ " # foo", " # bar", "# baz" ].join("\n"); let y = [ " # foo", " # bar", "# baz" ].join("\n"); assert_eq!(dedent_to(&x, " "), Some(y)); let x = [ " # foo", " bar", " baz" ].join("\n"); let y = [ " # foo", " bar", " baz" ].join("\n"); assert_eq!(dedent_to(&x, " "), Some(y)); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_trivia/src/cursor.rs
crates/ruff_python_trivia/src/cursor.rs
use std::str::Chars; use ruff_text_size::{TextLen, TextSize}; pub const EOF_CHAR: char = '\0'; /// A [`Cursor`] over a string. /// /// Based on [`rustc`'s `Cursor`](https://github.com/rust-lang/rust/blob/d1b7355d3d7b4ead564dbecb1d240fcc74fff21b/compiler/rustc_lexer/src/cursor.rs) #[derive(Debug, Clone)] pub struct Cursor<'a> { chars: Chars<'a>, source_length: TextSize, } impl<'a> Cursor<'a> { pub fn new(source: &'a str) -> Self { Self { source_length: source.text_len(), chars: source.chars(), } } /// Retrieves the current offset of the cursor within the source code. pub fn offset(&self) -> TextSize { self.source_length - self.text_len() } /// Return the remaining input as a string slice. pub fn chars(&self) -> Chars<'a> { self.chars.clone() } /// Returns the remaining input as byte slice. pub fn as_bytes(&self) -> &'a [u8] { self.as_str().as_bytes() } /// Returns the remaining input as string slice. pub fn as_str(&self) -> &'a str { self.chars.as_str() } /// Peeks the next character from the input stream without consuming it. /// Returns [`EOF_CHAR`] if the file is at the end of the file. pub fn first(&self) -> char { self.chars.clone().next().unwrap_or(EOF_CHAR) } /// Peeks the second character from the input stream without consuming it. /// Returns [`EOF_CHAR`] if the position is past the end of the file. pub fn second(&self) -> char { let mut chars = self.chars.clone(); chars.next(); chars.next().unwrap_or(EOF_CHAR) } /// Peeks the next character from the input stream without consuming it. /// Returns [`EOF_CHAR`] if the file is at the end of the file. pub fn last(&self) -> char { self.chars.clone().next_back().unwrap_or(EOF_CHAR) } pub fn text_len(&self) -> TextSize { self.chars.as_str().text_len() } pub fn token_len(&self) -> TextSize { self.source_length - self.text_len() } pub fn start_token(&mut self) { self.source_length = self.text_len(); } /// Returns `true` if the file is at the end of the file. pub fn is_eof(&self) -> bool { self.chars.as_str().is_empty() } /// Consumes the next character pub fn bump(&mut self) -> Option<char> { self.chars.next() } /// Consumes the next character from the back pub fn bump_back(&mut self) -> Option<char> { self.chars.next_back() } pub fn eat_char(&mut self, c: char) -> bool { if self.first() == c { self.bump(); true } else { false } } /// Eats the next two characters if they are `c1` and `c2`. Does not /// consume any input otherwise, even if the first character matches. pub fn eat_char2(&mut self, c1: char, c2: char) -> bool { let mut chars = self.chars.clone(); if chars.next() == Some(c1) && chars.next() == Some(c2) { self.bump(); self.bump(); true } else { false } } /// Eats the next three characters if they are `c1`, `c2` and `c3` /// Does not consume any input otherwise, even if the first character matches. pub fn eat_char3(&mut self, c1: char, c2: char, c3: char) -> bool { let mut chars = self.chars.clone(); if chars.next() == Some(c1) && chars.next() == Some(c2) && chars.next() == Some(c3) { self.bump(); self.bump(); self.bump(); true } else { false } } pub fn eat_char_back(&mut self, c: char) -> bool { if self.last() == c { self.bump_back(); true } else { false } } /// Eats the next character if `predicate` returns `true`. pub fn eat_if(&mut self, mut predicate: impl FnMut(char) -> bool) -> bool { if predicate(self.first()) && !self.is_eof() { self.bump(); true } else { false } } /// Eats symbols while predicate returns true or until the end of file is reached. pub fn eat_while(&mut self, mut predicate: impl FnMut(char) -> bool) { // It was tried making optimized version of this for eg. line comments, but // LLVM can inline all of this and compile it down to fast iteration over bytes. while predicate(self.first()) && !self.is_eof() { self.bump(); } } /// Eats symbols from the back while predicate returns true or until the beginning of file is reached. pub fn eat_back_while(&mut self, mut predicate: impl FnMut(char) -> bool) { // It was tried making optimized version of this for eg. line comments, but // LLVM can inline all of this and compile it down to fast iteration over bytes. while predicate(self.last()) && !self.is_eof() { self.bump_back(); } } /// Skips the next `count` bytes. /// /// ## Panics /// - If `count` is larger than the remaining bytes in the input stream. /// - If `count` indexes into a multi-byte character. pub fn skip_bytes(&mut self, count: usize) { self.chars = self.chars.as_str()[count..].chars(); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_trivia/src/lib.rs
crates/ruff_python_trivia/src/lib.rs
mod comment_ranges; mod comments; mod cursor; mod pragmas; pub mod textwrap; mod tokenizer; mod whitespace; pub use comment_ranges::CommentRanges; pub use comments::*; pub use cursor::*; pub use pragmas::*; pub use tokenizer::*; pub use whitespace::*;
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_trivia/src/comments.rs
crates/ruff_python_trivia/src/comments.rs
use ruff_text_size::TextRange; use crate::{PythonWhitespace, is_python_whitespace}; #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum SuppressionKind { /// A `fmt: off` or `yapf: disable` comment Off, /// A `fmt: on` or `yapf: enable` comment On, /// A `fmt: skip` comment Skip, } impl SuppressionKind { /// Attempts to identify the `kind` of a `comment`. /// The comment string should be the full line with the comment on it. pub fn from_comment(comment: &str) -> Option<Self> { // Match against `# fmt: on`, `# fmt: off`, `# yapf: disable`, and `# yapf: enable`, which // must be on their own lines. let trimmed = comment .strip_prefix('#') .unwrap_or(comment) .trim_whitespace(); if let Some(command) = trimmed.strip_prefix("fmt:") { match command.trim_whitespace_start() { "off" => return Some(Self::Off), "on" => return Some(Self::On), "skip" => return Some(Self::Skip), _ => {} } } else if let Some(command) = trimmed.strip_prefix("yapf:") { match command.trim_whitespace_start() { "disable" => return Some(Self::Off), "enable" => return Some(Self::On), _ => {} } } // Search for `# fmt: skip` comments, which can be interspersed with other comments (e.g., // `# fmt: skip # noqa: E501`). for segment in comment.split('#') { let trimmed = segment.trim_whitespace(); if let Some(command) = trimmed.strip_prefix("fmt:") { if command.trim_whitespace_start() == "skip" { return Some(SuppressionKind::Skip); } } } None } /// Returns true if this comment is a `fmt: off` or `yapf: disable` own line suppression comment. pub fn is_suppression_on(slice: &str, position: CommentLinePosition) -> bool { position.is_own_line() && matches!(Self::from_comment(slice), Some(Self::On)) } /// Returns true if this comment is a `fmt: on` or `yapf: enable` own line suppression comment. pub fn is_suppression_off(slice: &str, position: CommentLinePosition) -> bool { position.is_own_line() && matches!(Self::from_comment(slice), Some(Self::Off)) } } /// The position of a comment in the source text. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum CommentLinePosition { /// A comment that is on the same line as the preceding token and is separated by at least one line break from the following token. /// /// # Examples /// /// ## End of line /// /// ```python /// a; # comment /// b; /// ``` /// /// `# comment` is an end of line comments because it is separated by at least one line break from the following token `b`. /// Comments that not only end, but also start on a new line are [`OwnLine`](CommentLinePosition::OwnLine) comments. EndOfLine, /// A Comment that is separated by at least one line break from the preceding token. /// /// # Examples /// /// ```python /// a; /// # comment /// b; /// ``` /// /// `# comment` line comments because they are separated by one line break from the preceding token `a`. OwnLine, } impl CommentLinePosition { pub const fn is_own_line(self) -> bool { matches!(self, Self::OwnLine) } pub const fn is_end_of_line(self) -> bool { matches!(self, Self::EndOfLine) } /// Finds the line position of a comment given a range over a valid /// comment. pub fn for_range(comment_range: TextRange, source_code: &str) -> Self { let before = &source_code[TextRange::up_to(comment_range.start())]; for c in before.chars().rev() { match c { '\n' | '\r' => { break; } c if is_python_whitespace(c) => continue, _ => return Self::EndOfLine, } } Self::OwnLine } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_trivia/src/comment_ranges.rs
crates/ruff_python_trivia/src/comment_ranges.rs
use std::fmt::{Debug, Formatter}; use std::ops::Deref; use itertools::Itertools; use ruff_source_file::LineRanges; use ruff_text_size::{Ranged, TextRange, TextSize}; use crate::{has_leading_content, has_trailing_content, is_python_whitespace}; /// Stores the ranges of comments sorted by [`TextRange::start`] in increasing order. No two ranges are overlapping. #[derive(Clone, Default)] pub struct CommentRanges { raw: Vec<TextRange>, } impl CommentRanges { pub fn new(ranges: Vec<TextRange>) -> Self { Self { raw: ranges } } /// Returns `true` if the given range intersects with any comment range. pub fn intersects(&self, target: TextRange) -> bool { self.raw .binary_search_by(|range| { if target.intersect(*range).is_some() { std::cmp::Ordering::Equal } else if range.end() < target.start() { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater } }) .is_ok() } /// Returns the comments who are within the range pub fn comments_in_range(&self, range: TextRange) -> &[TextRange] { let start = self .raw .partition_point(|comment| comment.start() < range.start()); // We expect there are few comments, so switching to find should be faster match self.raw[start..] .iter() .find_position(|comment| comment.end() > range.end()) { Some((in_range, _element)) => &self.raw[start..start + in_range], None => &self.raw[start..], } } /// Returns `true` if a statement or expression includes at least one comment. pub fn has_comments<T>(&self, node: &T, source: &str) -> bool where T: Ranged, { let start = if has_leading_content(node.start(), source) { node.start() } else { source.line_start(node.start()) }; let end = if has_trailing_content(node.end(), source) { node.end() } else { source.line_end(node.end()) }; self.intersects(TextRange::new(start, end)) } /// Given a [`CommentRanges`], determine which comments are grouped together /// in "comment blocks". A "comment block" is a sequence of consecutive /// own-line comments in which the comment hash (`#`) appears in the same /// column in each line, and at least one comment is non-empty. /// /// Returns a sorted vector containing the offset of the leading hash (`#`) /// for each comment in any block comment. /// /// ## Examples /// ```python /// # This is a block comment /// # because it spans multiple lines /// /// # This is also a block comment /// # even though it is indented /// /// # this is not a block comment /// /// x = 1 # this is not a block comment because /// y = 2 # the lines do not *only* contain comments /// /// # This is not a block comment because /// # not all consecutive lines have the /// # first `#` character in the same column /// /// """ /// # This is not a block comment because it is /// # contained within a multi-line string/comment /// """ /// ``` pub fn block_comments(&self, source: &str) -> Vec<TextSize> { let mut block_comments: Vec<TextSize> = Vec::new(); let mut current_block: Vec<TextSize> = Vec::new(); let mut current_block_column: Option<TextSize> = None; let mut current_block_non_empty = false; let mut prev_line_end = None; for comment_range in &self.raw { let offset = comment_range.start(); let line_start = source.line_start(offset); let line_end = source.full_line_end(offset); let column = offset - line_start; // If this is an end-of-line comment, reset the current block. if !Self::is_own_line(offset, source) { // Push the current block, and reset. if current_block.len() > 1 && current_block_non_empty { block_comments.extend(current_block); } current_block = vec![]; current_block_column = None; current_block_non_empty = false; prev_line_end = Some(line_end); continue; } // If there's a blank line between this comment and the previous // comment, reset the current block. if prev_line_end.is_some_and(|prev_line_end| { source.contains_line_break(TextRange::new(prev_line_end, line_start)) }) { // Push the current block. if current_block.len() > 1 && current_block_non_empty { block_comments.extend(current_block); } // Reset the block state. current_block = vec![offset]; current_block_column = Some(column); current_block_non_empty = !Self::is_empty(*comment_range, source); prev_line_end = Some(line_end); continue; } if let Some(current_column) = current_block_column { if column == current_column { // Add the comment to the current block. current_block.push(offset); current_block_non_empty |= !Self::is_empty(*comment_range, source); prev_line_end = Some(line_end); } else { // Push the current block. if current_block.len() > 1 && current_block_non_empty { block_comments.extend(current_block); } // Reset the block state. current_block = vec![offset]; current_block_column = Some(column); current_block_non_empty = !Self::is_empty(*comment_range, source); prev_line_end = Some(line_end); } } else { // Push the current block. if current_block.len() > 1 && current_block_non_empty { block_comments.extend(current_block); } // Reset the block state. current_block = vec![offset]; current_block_column = Some(column); current_block_non_empty = !Self::is_empty(*comment_range, source); prev_line_end = Some(line_end); } } // Push any lingering blocks. if current_block.len() > 1 && current_block_non_empty { block_comments.extend(current_block); } block_comments } /// Returns `true` if the given range is an empty comment. fn is_empty(range: TextRange, source: &str) -> bool { source[range].chars().skip(1).all(is_python_whitespace) } /// Returns `true` if a comment is an own-line comment (as opposed to an end-of-line comment). pub fn is_own_line(offset: TextSize, source: &str) -> bool { let range = TextRange::new(source.line_start(offset), offset); source[range].chars().all(is_python_whitespace) } } impl Deref for CommentRanges { type Target = [TextRange]; fn deref(&self) -> &Self::Target { self.raw.as_slice() } } impl Debug for CommentRanges { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.debug_tuple("CommentRanges").field(&self.raw).finish() } } impl<'a> IntoIterator for &'a CommentRanges { type Item = TextRange; type IntoIter = std::iter::Copied<std::slice::Iter<'a, TextRange>>; fn into_iter(self) -> Self::IntoIter { self.raw.iter().copied() } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_trivia/src/whitespace.rs
crates/ruff_python_trivia/src/whitespace.rs
use ruff_source_file::LineRanges; use ruff_text_size::{TextRange, TextSize}; /// Extract the leading indentation from a line. pub fn indentation_at_offset(offset: TextSize, source: &str) -> Option<&str> { let line_start = source.line_start(offset); let indentation = &source[TextRange::new(line_start, offset)]; indentation .chars() .all(is_python_whitespace) .then_some(indentation) } /// Return `true` if the node starting the given [`TextSize`] has leading content. pub fn has_leading_content(offset: TextSize, source: &str) -> bool { let line_start = source.line_start(offset); let leading = &source[TextRange::new(line_start, offset)]; leading.chars().any(|char| !is_python_whitespace(char)) } /// Return `true` if the node ending at the given [`TextSize`] has trailing content. pub fn has_trailing_content(offset: TextSize, source: &str) -> bool { let line_end = source.line_end(offset); let trailing = &source[TextRange::new(offset, line_end)]; for char in trailing.chars() { if char == '#' { return false; } if !is_python_whitespace(char) { return true; } } false } /// Returns `true` for [whitespace](https://docs.python.org/3/reference/lexical_analysis.html#whitespace-between-tokens) /// characters. pub const fn is_python_whitespace(c: char) -> bool { matches!( c, // Space, tab, or form-feed ' ' | '\t' | '\x0C' ) } /// Extract the leading indentation from a line. pub fn leading_indentation(line: &str) -> &str { line.find(|char: char| !is_python_whitespace(char)) .map_or(line, |index| &line[..index]) } pub trait PythonWhitespace { /// Like `str::trim()`, but only removes whitespace characters that Python considers /// to be [whitespace](https://docs.python.org/3/reference/lexical_analysis.html#whitespace-between-tokens). fn trim_whitespace(&self) -> &Self; /// Like `str::trim_start()`, but only removes whitespace characters that Python considers /// to be [whitespace](https://docs.python.org/3/reference/lexical_analysis.html#whitespace-between-tokens). fn trim_whitespace_start(&self) -> &Self; /// Like `str::trim_end()`, but only removes whitespace characters that Python considers /// to be [whitespace](https://docs.python.org/3/reference/lexical_analysis.html#whitespace-between-tokens). fn trim_whitespace_end(&self) -> &Self; } impl PythonWhitespace for str { fn trim_whitespace(&self) -> &Self { self.trim_matches(is_python_whitespace) } fn trim_whitespace_start(&self) -> &Self { self.trim_start_matches(is_python_whitespace) } fn trim_whitespace_end(&self) -> &Self { self.trim_end_matches(is_python_whitespace) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_trivia/src/pragmas.rs
crates/ruff_python_trivia/src/pragmas.rs
/// Returns `true` if a comment appears to be a pragma comment. /// /// ``` /// assert!(ruff_python_trivia::is_pragma_comment("# type: ignore")); /// assert!(ruff_python_trivia::is_pragma_comment("# noqa: F401")); /// assert!(ruff_python_trivia::is_pragma_comment("# noqa")); /// assert!(ruff_python_trivia::is_pragma_comment("# NoQA")); /// assert!(ruff_python_trivia::is_pragma_comment("# nosec")); /// assert!(ruff_python_trivia::is_pragma_comment("# nosec B602, B607")); /// assert!(ruff_python_trivia::is_pragma_comment("# isort: off")); /// assert!(ruff_python_trivia::is_pragma_comment("# isort: skip")); /// ``` pub fn is_pragma_comment(comment: &str) -> bool { let Some(content) = comment.strip_prefix('#') else { return false; }; let trimmed = content.trim_start(); // Case-insensitive match against `noqa` (which doesn't require a trailing colon). matches!( trimmed.as_bytes(), [b'n' | b'N', b'o' | b'O', b'q' | b'Q', b'a' | b'A', ..] ) || // Case-insensitive match against pragmas that don't require a trailing colon. trimmed.starts_with("nosec") || // Case-sensitive match against a variety of pragmas that _do_ require a trailing colon. trimmed .split_once(':') .is_some_and(|(maybe_pragma, _)| matches!(maybe_pragma, "isort" | "type" | "pyright" | "pylint" | "flake8" | "ruff" | "ty")) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_trivia/src/tokenizer.rs
crates/ruff_python_trivia/src/tokenizer.rs
use unicode_ident::{is_xid_continue, is_xid_start}; use ruff_text_size::{Ranged, TextLen, TextRange, TextSize}; use crate::{Cursor, is_python_whitespace}; /// Searches for the first non-trivia character after `offset`. /// /// The search skips over any whitespace and comments. /// /// Returns `Some` if the source code after `offset` contains any non-trivia character./// /// Returns `None` if the text after `offset` is empty or only contains trivia (whitespace or comments). pub fn first_non_trivia_token(offset: TextSize, code: &str) -> Option<SimpleToken> { SimpleTokenizer::starts_at(offset, code) .skip_trivia() .next() } /// Returns the only non-trivia, non-closing parenthesis token in `range`. /// /// Includes debug assertions that the range only contains that single token. pub fn find_only_token_in_range( range: TextRange, token_kind: SimpleTokenKind, code: &str, ) -> SimpleToken { let mut tokens = SimpleTokenizer::new(code, range) .skip_trivia() .skip_while(|token| token.kind == SimpleTokenKind::RParen); let token = tokens.next().expect("Expected a token"); debug_assert_eq!(token.kind(), token_kind); let mut tokens = tokens.skip_while(|token| token.kind == SimpleTokenKind::LParen); #[expect(clippy::debug_assert_with_mut_call)] { debug_assert_eq!(tokens.next(), None); } token } /// Returns the number of newlines between `offset` and the first non whitespace character in the source code. pub fn lines_before(offset: TextSize, code: &str) -> u32 { let mut cursor = Cursor::new(&code[TextRange::up_to(offset)]); let mut newlines = 0u32; while let Some(c) = cursor.bump_back() { match c { '\n' => { cursor.eat_char_back('\r'); newlines += 1; } '\r' => { newlines += 1; } c if is_python_whitespace(c) => { continue; } _ => { break; } } } newlines } /// Counts the empty lines between `offset` and the first non-whitespace character. pub fn lines_after(offset: TextSize, code: &str) -> u32 { let mut cursor = Cursor::new(&code[offset.to_usize()..]); let mut newlines = 0u32; while let Some(c) = cursor.bump() { match c { '\n' => { newlines += 1; } '\r' => { cursor.eat_char('\n'); newlines += 1; } c if is_python_whitespace(c) => { continue; } _ => { break; } } } newlines } /// Counts the empty lines after `offset`, ignoring any trailing trivia: end-of-line comments, /// own-line comments, and any intermediary newlines. pub fn lines_after_ignoring_trivia(offset: TextSize, code: &str) -> u32 { let mut newlines = 0u32; for token in SimpleTokenizer::starts_at(offset, code) { match token.kind() { SimpleTokenKind::Newline => { newlines += 1; } SimpleTokenKind::Whitespace => {} // If we see a comment, reset the newlines counter. SimpleTokenKind::Comment => { newlines = 0; } // As soon as we see a non-trivia token, we're done. _ => { break; } } } newlines } /// Counts the empty lines after `offset`, ignoring any trailing trivia on the same line as /// `offset`. #[expect(clippy::cast_possible_truncation)] pub fn lines_after_ignoring_end_of_line_trivia(offset: TextSize, code: &str) -> u32 { // SAFETY: We don't support files greater than 4GB, so casting to u32 is safe. SimpleTokenizer::starts_at(offset, code) .skip_while(|token| token.kind != SimpleTokenKind::Newline && token.kind.is_trivia()) .take_while(|token| { token.kind == SimpleTokenKind::Newline || token.kind == SimpleTokenKind::Whitespace }) .filter(|token| token.kind == SimpleTokenKind::Newline) .count() as u32 } fn is_identifier_start(c: char) -> bool { if c.is_ascii() { c.is_ascii_alphabetic() || c == '_' } else { is_xid_start(c) } } // Checks if the character c is a valid continuation character as described // in https://docs.python.org/3/reference/lexical_analysis.html#identifiers fn is_identifier_continuation(c: char) -> bool { // Arrange things such that ASCII codepoints never // result in the slower `is_xid_continue` getting called. if c.is_ascii() { matches!(c, 'a'..='z' | 'A'..='Z' | '_' | '0'..='9') } else { is_xid_continue(c) } } fn to_keyword_or_other(source: &str) -> SimpleTokenKind { match source { "and" => SimpleTokenKind::And, "as" => SimpleTokenKind::As, "assert" => SimpleTokenKind::Assert, "async" => SimpleTokenKind::Async, "await" => SimpleTokenKind::Await, "break" => SimpleTokenKind::Break, "class" => SimpleTokenKind::Class, "continue" => SimpleTokenKind::Continue, "def" => SimpleTokenKind::Def, "del" => SimpleTokenKind::Del, "elif" => SimpleTokenKind::Elif, "else" => SimpleTokenKind::Else, "except" => SimpleTokenKind::Except, "finally" => SimpleTokenKind::Finally, "for" => SimpleTokenKind::For, "from" => SimpleTokenKind::From, "global" => SimpleTokenKind::Global, "if" => SimpleTokenKind::If, "import" => SimpleTokenKind::Import, "in" => SimpleTokenKind::In, "is" => SimpleTokenKind::Is, "lambda" => SimpleTokenKind::Lambda, "nonlocal" => SimpleTokenKind::Nonlocal, "not" => SimpleTokenKind::Not, "or" => SimpleTokenKind::Or, "pass" => SimpleTokenKind::Pass, "raise" => SimpleTokenKind::Raise, "return" => SimpleTokenKind::Return, "try" => SimpleTokenKind::Try, "while" => SimpleTokenKind::While, "match" => SimpleTokenKind::Match, // Match is a soft keyword that depends on the context but we can always lex it as a keyword and leave it to the caller (parser) to decide if it should be handled as an identifier or keyword. "type" => SimpleTokenKind::Type, // Type is a soft keyword that depends on the context but we can always lex it as a keyword and leave it to the caller (parser) to decide if it should be handled as an identifier or keyword. "case" => SimpleTokenKind::Case, "with" => SimpleTokenKind::With, "yield" => SimpleTokenKind::Yield, _ => SimpleTokenKind::Name, // Potentially an identifier, but only if it isn't a string prefix. The caller (SimpleTokenizer) is responsible for enforcing that constraint. } } #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub struct SimpleToken { pub kind: SimpleTokenKind, pub range: TextRange, } impl SimpleToken { pub const fn kind(&self) -> SimpleTokenKind { self.kind } } impl Ranged for SimpleToken { fn range(&self) -> TextRange { self.range } } #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub enum SimpleTokenKind { /// A comment, not including the trailing new line. Comment, /// Sequence of ' ' or '\t' Whitespace, /// Start or end of the file EndOfFile, /// `\\` Continuation, /// `\n` or `\r` or `\r\n` Newline, /// `(` LParen, /// `)` RParen, /// `{` LBrace, /// `}` RBrace, /// `[` LBracket, /// `]` RBracket, /// `,` Comma, /// `:` Colon, /// `;` Semi, /// `/` Slash, /// `*` Star, /// `.` Dot, /// `+` Plus, /// `-` Minus, /// `=` Equals, /// `>` Greater, /// `<` Less, /// `%` Percent, /// `&` Ampersand, /// `^` Circumflex, /// `|` Vbar, /// `@` At, /// `~` Tilde, /// `==` EqEqual, /// `!=` NotEqual, /// `<=` LessEqual, /// `>=` GreaterEqual, /// `<<` LeftShift, /// `>>` RightShift, /// `**` DoubleStar, /// `**=` DoubleStarEqual, /// `+=` PlusEqual, /// `-=` MinusEqual, /// `*=` StarEqual, /// `/=` SlashEqual, /// `%=` PercentEqual, /// `&=` AmperEqual, /// `|=` VbarEqual, /// `^=` CircumflexEqual, /// `<<=` LeftShiftEqual, /// `>>=` RightShiftEqual, /// `//` DoubleSlash, /// `//=` DoubleSlashEqual, /// `:=` ColonEqual, /// `...` Ellipsis, /// `@=` AtEqual, /// `->` RArrow, /// `and` And, /// `as` As, /// `assert` Assert, /// `async` Async, /// `await` Await, /// `break` Break, /// `class` Class, /// `continue` Continue, /// `def` Def, /// `del` Del, /// `elif` Elif, /// `else` Else, /// `except` Except, /// `finally` Finally, /// `for` For, /// `from` From, /// `global` Global, /// `if` If, /// `import` Import, /// `in` In, /// `is` Is, /// `lambda` Lambda, /// `nonlocal` Nonlocal, /// `not` Not, /// `or` Or, /// `pass` Pass, /// `raise` Raise, /// `return` Return, /// `try` Try, /// `while` While, /// `match` Match, /// `type` Type, /// `case` Case, /// `with` With, /// `yield` Yield, /// An identifier or keyword. Name, /// Any other non trivia token. Other, /// Returned for each character after [`SimpleTokenKind::Other`] has been returned once. Bogus, } impl SimpleTokenKind { pub const fn is_trivia(self) -> bool { matches!( self, SimpleTokenKind::Whitespace | SimpleTokenKind::Newline | SimpleTokenKind::Comment | SimpleTokenKind::Continuation ) } pub const fn is_comment(self) -> bool { matches!(self, SimpleTokenKind::Comment) } } /// Simple zero allocation tokenizer handling most tokens. /// /// The tokenizer must start at an offset that is trivia (e.g. not inside of a multiline string). /// /// In case it finds something it can't parse, the tokenizer will return a /// [`SimpleTokenKind::Other`] and then only a final [`SimpleTokenKind::Bogus`] afterwards. pub struct SimpleTokenizer<'a> { offset: TextSize, /// `true` when it is known that the current `back` line has no comment for sure. bogus: bool, source: &'a str, cursor: Cursor<'a>, } impl<'a> SimpleTokenizer<'a> { pub fn new(source: &'a str, range: TextRange) -> Self { Self { offset: range.start(), bogus: false, source, cursor: Cursor::new(&source[range]), } } pub fn starts_at(offset: TextSize, source: &'a str) -> Self { let range = TextRange::new(offset, source.text_len()); Self::new(source, range) } fn next_token(&mut self) -> SimpleToken { self.cursor.start_token(); let Some(first) = self.cursor.bump() else { return SimpleToken { kind: SimpleTokenKind::EndOfFile, range: TextRange::empty(self.offset), }; }; if self.bogus { // Emit a single final bogus token let token = SimpleToken { kind: SimpleTokenKind::Bogus, range: TextRange::new(self.offset, self.source.text_len()), }; // Set the cursor to EOF self.cursor = Cursor::new(""); self.offset = self.source.text_len(); return token; } let kind = self.next_token_inner(first); let token_len = self.cursor.token_len(); let token = SimpleToken { kind, range: TextRange::at(self.offset, token_len), }; self.offset += token_len; token } fn next_token_inner(&mut self, first: char) -> SimpleTokenKind { match first { // Keywords and identifiers c if is_identifier_start(c) => { self.cursor.eat_while(is_identifier_continuation); let token_len = self.cursor.token_len(); let range = TextRange::at(self.offset, token_len); let kind = to_keyword_or_other(&self.source[range]); // If the next character is a quote, we may be in a string prefix. For example: // `f"foo`. if kind == SimpleTokenKind::Name && matches!(self.cursor.first(), '"' | '\'') && matches!( &self.source[range], "B" | "BR" | "Br" | "F" | "FR" | "Fr" | "R" | "RB" | "RF" | "Rb" | "Rf" | "U" | "b" | "bR" | "br" | "f" | "fR" | "fr" | "r" | "rB" | "rF" | "rb" | "rf" | "u" | "T" | "TR" | "Tr" | "RT" | "Rt" | "t" | "tR" | "tr" | "rT" | "rt" ) { self.bogus = true; SimpleTokenKind::Other } else { kind } } // Space, tab, or form feed. We ignore the true semantics of form feed, and treat it as // whitespace. ' ' | '\t' | '\x0C' => { self.cursor.eat_while(|c| matches!(c, ' ' | '\t' | '\x0C')); SimpleTokenKind::Whitespace } '\n' => SimpleTokenKind::Newline, '\r' => { self.cursor.eat_char('\n'); SimpleTokenKind::Newline } '#' => { self.cursor.eat_while(|c| !matches!(c, '\n' | '\r')); SimpleTokenKind::Comment } '\\' => SimpleTokenKind::Continuation, // Non-trivia, non-keyword tokens '=' => { if self.cursor.eat_char('=') { SimpleTokenKind::EqEqual } else { SimpleTokenKind::Equals } } '+' => { if self.cursor.eat_char('=') { SimpleTokenKind::PlusEqual } else { SimpleTokenKind::Plus } } '*' => { if self.cursor.eat_char('=') { SimpleTokenKind::StarEqual } else if self.cursor.eat_char('*') { if self.cursor.eat_char('=') { SimpleTokenKind::DoubleStarEqual } else { SimpleTokenKind::DoubleStar } } else { SimpleTokenKind::Star } } '/' => { if self.cursor.eat_char('=') { SimpleTokenKind::SlashEqual } else if self.cursor.eat_char('/') { if self.cursor.eat_char('=') { SimpleTokenKind::DoubleSlashEqual } else { SimpleTokenKind::DoubleSlash } } else { SimpleTokenKind::Slash } } '%' => { if self.cursor.eat_char('=') { SimpleTokenKind::PercentEqual } else { SimpleTokenKind::Percent } } '|' => { if self.cursor.eat_char('=') { SimpleTokenKind::VbarEqual } else { SimpleTokenKind::Vbar } } '^' => { if self.cursor.eat_char('=') { SimpleTokenKind::CircumflexEqual } else { SimpleTokenKind::Circumflex } } '&' => { if self.cursor.eat_char('=') { SimpleTokenKind::AmperEqual } else { SimpleTokenKind::Ampersand } } '-' => { if self.cursor.eat_char('=') { SimpleTokenKind::MinusEqual } else if self.cursor.eat_char('>') { SimpleTokenKind::RArrow } else { SimpleTokenKind::Minus } } '@' => { if self.cursor.eat_char('=') { SimpleTokenKind::AtEqual } else { SimpleTokenKind::At } } '!' => { if self.cursor.eat_char('=') { SimpleTokenKind::NotEqual } else { self.bogus = true; SimpleTokenKind::Other } } '~' => SimpleTokenKind::Tilde, ':' => { if self.cursor.eat_char('=') { SimpleTokenKind::ColonEqual } else { SimpleTokenKind::Colon } } ';' => SimpleTokenKind::Semi, '<' => { if self.cursor.eat_char('<') { if self.cursor.eat_char('=') { SimpleTokenKind::LeftShiftEqual } else { SimpleTokenKind::LeftShift } } else if self.cursor.eat_char('=') { SimpleTokenKind::LessEqual } else { SimpleTokenKind::Less } } '>' => { if self.cursor.eat_char('>') { if self.cursor.eat_char('=') { SimpleTokenKind::RightShiftEqual } else { SimpleTokenKind::RightShift } } else if self.cursor.eat_char('=') { SimpleTokenKind::GreaterEqual } else { SimpleTokenKind::Greater } } ',' => SimpleTokenKind::Comma, '.' => { if self.cursor.first() == '.' && self.cursor.second() == '.' { self.cursor.bump(); self.cursor.bump(); SimpleTokenKind::Ellipsis } else { SimpleTokenKind::Dot } } // Bracket tokens '(' => SimpleTokenKind::LParen, ')' => SimpleTokenKind::RParen, '[' => SimpleTokenKind::LBracket, ']' => SimpleTokenKind::RBracket, '{' => SimpleTokenKind::LBrace, '}' => SimpleTokenKind::RBrace, _ => { self.bogus = true; SimpleTokenKind::Other } } } pub fn skip_trivia(self) -> impl Iterator<Item = SimpleToken> + 'a { self.filter(|t| !t.kind().is_trivia()) } } impl Iterator for SimpleTokenizer<'_> { type Item = SimpleToken; fn next(&mut self) -> Option<Self::Item> { let token = self.next_token(); if token.kind == SimpleTokenKind::EndOfFile { None } else { Some(token) } } } /// Simple zero allocation backwards tokenizer for finding preceding tokens. /// /// The tokenizer must start at an offset that is trivia (e.g. not inside of a multiline string). /// It will fail when reaching a string. /// /// In case it finds something it can't parse, the tokenizer will return a /// [`SimpleTokenKind::Other`] and then only a final [`SimpleTokenKind::Bogus`] afterwards. pub struct BackwardsTokenizer<'a> { offset: TextSize, back_offset: TextSize, /// Not `&CommentRanges` to avoid a circular dependency. comment_ranges: &'a [TextRange], bogus: bool, source: &'a str, cursor: Cursor<'a>, } impl<'a> BackwardsTokenizer<'a> { pub fn new(source: &'a str, range: TextRange, comment_range: &'a [TextRange]) -> Self { Self { offset: range.start(), back_offset: range.end(), // Throw out any comments that follow the range. comment_ranges: &comment_range [..comment_range.partition_point(|comment| comment.start() <= range.end())], bogus: false, source, cursor: Cursor::new(&source[range]), } } pub fn up_to(offset: TextSize, source: &'a str, comment_range: &'a [TextRange]) -> Self { Self::new(source, TextRange::up_to(offset), comment_range) } pub fn skip_trivia(self) -> impl Iterator<Item = SimpleToken> + 'a { self.filter(|t| !t.kind().is_trivia()) } pub fn next_token(&mut self) -> SimpleToken { self.cursor.start_token(); self.back_offset = self.cursor.text_len() + self.offset; let Some(last) = self.cursor.bump_back() else { return SimpleToken { kind: SimpleTokenKind::EndOfFile, range: TextRange::empty(self.back_offset), }; }; if self.bogus { let token = SimpleToken { kind: SimpleTokenKind::Bogus, range: TextRange::up_to(self.back_offset), }; // Set the cursor to EOF self.cursor = Cursor::new(""); self.back_offset = TextSize::new(0); return token; } if let Some(comment) = self .comment_ranges .last() .filter(|comment| comment.contains_inclusive(self.back_offset)) { self.comment_ranges = &self.comment_ranges[..self.comment_ranges.len() - 1]; // Skip the comment without iterating over the chars manually. self.cursor = Cursor::new(&self.source[TextRange::new(self.offset, comment.start())]); debug_assert_eq!(self.cursor.text_len() + self.offset, comment.start()); return SimpleToken { kind: SimpleTokenKind::Comment, range: comment.range(), }; } let kind = match last { // Space, tab, or form feed. We ignore the true semantics of form feed, and treat it as // whitespace. Note that this will lex-out trailing whitespace from a comment as // whitespace rather than as part of the comment token, but this shouldn't matter for // our use case. ' ' | '\t' | '\x0C' => { self.cursor .eat_back_while(|c| matches!(c, ' ' | '\t' | '\x0C')); SimpleTokenKind::Whitespace } '\r' => SimpleTokenKind::Newline, '\n' => { self.cursor.eat_char_back('\r'); SimpleTokenKind::Newline } _ => self.next_token_inner(last), }; let token_len = self.cursor.token_len(); let start = self.back_offset - token_len; SimpleToken { kind, range: TextRange::at(start, token_len), } } /// Helper to parser the previous token once we skipped all whitespace fn next_token_inner(&mut self, last: char) -> SimpleTokenKind { match last { // Keywords and identifiers c if is_identifier_continuation(c) => { // if we only have identifier continuations but no start (e.g. 555) we // don't want to consume the chars, so in that case, we want to rewind the // cursor to here let savepoint = self.cursor.clone(); self.cursor.eat_back_while(is_identifier_continuation); let token_len = self.cursor.token_len(); let range = TextRange::at(self.back_offset - token_len, token_len); if self.source[range] .chars() .next() .is_some_and(is_identifier_start) { to_keyword_or_other(&self.source[range]) } else { self.cursor = savepoint; self.bogus = true; SimpleTokenKind::Other } } // Non-trivia tokens that are unambiguous when lexing backwards. // In other words: these are characters that _don't_ appear at the // end of a multi-character token (like `!=`). '\\' => SimpleTokenKind::Continuation, ':' => SimpleTokenKind::Colon, '~' => SimpleTokenKind::Tilde, '%' => SimpleTokenKind::Percent, '|' => SimpleTokenKind::Vbar, ',' => SimpleTokenKind::Comma, ';' => SimpleTokenKind::Semi, '(' => SimpleTokenKind::LParen, ')' => SimpleTokenKind::RParen, '[' => SimpleTokenKind::LBracket, ']' => SimpleTokenKind::RBracket, '{' => SimpleTokenKind::LBrace, '}' => SimpleTokenKind::RBrace, '&' => SimpleTokenKind::Ampersand, '^' => SimpleTokenKind::Circumflex, '+' => SimpleTokenKind::Plus, '-' => SimpleTokenKind::Minus, // Non-trivia tokens that _are_ ambiguous when lexing backwards. // In other words: these are characters that _might_ mark the end // of a multi-character token (like `!=` or `->` or `//` or `**`). '=' | '*' | '/' | '@' | '!' | '<' | '>' | '.' => { // This could be a single-token token, like `+` in `x + y`, or a // multi-character token, like `+=` in `x += y`. It could also be a sequence // of multi-character tokens, like `x ==== y`, which is invalid, _but_ it's // important that we produce the same token stream when lexing backwards as // we do when lexing forwards. So, identify the range of the sequence, lex // forwards, and return the last token. let mut cursor = self.cursor.clone(); cursor.eat_back_while(|c| { matches!( c, ':' | '~' | '%' | '|' | '&' | '^' | '+' | '-' | '=' | '*' | '/' | '@' | '!' | '<' | '>' | '.' ) }); let token_len = cursor.token_len(); let range = TextRange::at(self.back_offset - token_len, token_len); let forward_lexer = SimpleTokenizer::new(self.source, range); if let Some(token) = forward_lexer.last() { // If the token spans multiple characters, bump the cursor. Note, // though, that we already bumped the cursor to past the last character // in the token at the very start of `next_token_back`.y for _ in self.source[token.range].chars().rev().skip(1) { self.cursor.bump_back().unwrap(); } token.kind() } else { self.bogus = true; SimpleTokenKind::Other } } _ => { self.bogus = true; SimpleTokenKind::Other } } } } impl Iterator for BackwardsTokenizer<'_> { type Item = SimpleToken; fn next(&mut self) -> Option<Self::Item> { let token = self.next_token(); if token.kind == SimpleTokenKind::EndOfFile { None } else { Some(token) } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_annotate_snippets/src/lib.rs
crates/ruff_annotate_snippets/src/lib.rs
#![expect(clippy::needless_doctest_main)] //! A library for formatting of text or programming code snippets. //! //! It's primary purpose is to build an ASCII-graphical representation of the snippet //! with annotations. //! //! # Example //! //! ```rust #![doc = include_str!("../examples/expected_type.rs")] //! ``` //! #![doc = include_str!("../examples/expected_type.svg")] //! //! The crate uses a three stage process with two conversions between states: //! //! ```text //! Message --> Renderer --> impl Display //! ``` //! //! The input type - [Message] is a structure designed //! to align with likely output from any parser whose code snippet is to be //! annotated. //! //! The middle structure - [Renderer] is a structure designed //! to convert a snippet into an internal structure that is designed to store //! the snippet data in a way that is easy to format. //! [Renderer] also handles the user-configurable formatting //! options, such as color, or margins. //! //! Finally, `impl Display` into a final `String` output. //! //! # features //! - `testing-colors` - Makes [Renderer::styled] colors OS independent, which //! allows for easier testing when testing colored output. It should be added as //! a feature in `[dev-dependencies]`, which can be done with the following command: //! ```text //! cargo add annotate-snippets --dev --feature testing-colors //! ``` #![cfg_attr(docsrs, feature(doc_auto_cfg))] #![warn(clippy::print_stderr)] #![warn(clippy::print_stdout)] #![warn(missing_debug_implementations)] // Since this is a vendored copy of `annotate-snippets`, we squash Clippy // warnings from upstream in order to the reduce the diff. If our copy drifts // far from upstream such that patches become impractical to apply in both // places, then we can get rid of these suppressions and fix the lints. #![allow( clippy::return_self_not_must_use, clippy::cast_possible_truncation, clippy::cast_precision_loss, clippy::explicit_iter_loop, clippy::unused_self, clippy::unnecessary_wraps, clippy::range_plus_one, clippy::redundant_closure_for_method_calls, clippy::struct_field_names, clippy::cloned_instead_of_copied, clippy::cast_sign_loss, clippy::needless_as_bytes, clippy::unnecessary_map_or )] pub mod renderer; mod snippet; #[doc(inline)] pub use renderer::Renderer; pub use snippet::*;
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_annotate_snippets/src/snippet.rs
crates/ruff_annotate_snippets/src/snippet.rs
//! Structures used as an input for the library. //! //! Example: //! //! ``` //! use ruff_annotate_snippets::*; //! //! Level::Error.title("mismatched types") //! .snippet(Snippet::source("Foo").line_start(51).origin("src/format.rs")) //! .snippet(Snippet::source("Faa").line_start(129).origin("src/display.rs")); //! ``` use std::ops::Range; #[derive(Copy, Clone, Debug, Default, PartialEq)] pub(crate) struct Id<'a> { pub(crate) id: &'a str, pub(crate) url: Option<&'a str>, } /// Primary structure provided for formatting /// /// See [`Level::title`] to create a [`Message`] #[derive(Debug)] pub struct Message<'a> { pub(crate) level: Level, pub(crate) id: Option<Id<'a>>, pub(crate) title: &'a str, pub(crate) snippets: Vec<Snippet<'a>>, pub(crate) footer: Vec<Message<'a>>, pub(crate) is_fixable: bool, pub(crate) lineno_offset: usize, } impl<'a> Message<'a> { pub fn id(mut self, id: &'a str) -> Self { self.id = Some(Id { id, url: None }); self } pub fn id_with_url(mut self, id: &'a str, url: Option<&'a str>) -> Self { self.id = Some(Id { id, url }); self } pub fn snippet(mut self, slice: Snippet<'a>) -> Self { self.snippets.push(slice); self } pub fn snippets(mut self, slice: impl IntoIterator<Item = Snippet<'a>>) -> Self { self.snippets.extend(slice); self } pub fn footer(mut self, footer: Message<'a>) -> Self { self.footer.push(footer); self } pub fn footers(mut self, footer: impl IntoIterator<Item = Message<'a>>) -> Self { self.footer.extend(footer); self } /// Whether or not the diagnostic for this message is fixable. /// /// This is rendered as a `[*]` indicator after the `id` in an annotation header, if the /// annotation also has `Level::None`. pub fn is_fixable(mut self, yes: bool) -> Self { self.is_fixable = yes; self } /// Add an offset used for aligning the header sigil (`-->`) with the line number separators. /// /// For normal diagnostics this is computed automatically based on the lines to be rendered. /// This is intended only for use in the formatter, where we don't render a snippet directly but /// still want the header to align with the diff. pub fn lineno_offset(mut self, offset: usize) -> Self { self.lineno_offset = offset; self } } /// Structure containing the slice of text to be annotated and /// basic information about the location of the slice. /// /// One `Snippet` is meant to represent a single, continuous, /// slice of source code that you want to annotate. #[derive(Debug)] pub struct Snippet<'a> { pub(crate) origin: Option<&'a str>, pub(crate) line_start: usize, pub(crate) source: &'a str, pub(crate) annotations: Vec<Annotation<'a>>, pub(crate) fold: bool, /// The optional cell index in a Jupyter notebook, used for reporting source locations along /// with the ranges on `annotations`. pub(crate) cell_index: Option<usize>, } impl<'a> Snippet<'a> { pub fn source(source: &'a str) -> Self { Self { origin: None, line_start: 1, source, annotations: vec![], fold: false, cell_index: None, } } pub fn line_start(mut self, line_start: usize) -> Self { self.line_start = line_start; self } pub fn origin(mut self, origin: &'a str) -> Self { self.origin = Some(origin); self } pub fn annotation(mut self, annotation: Annotation<'a>) -> Self { self.annotations.push(annotation); self } pub fn annotations(mut self, annotation: impl IntoIterator<Item = Annotation<'a>>) -> Self { self.annotations.extend(annotation); self } /// Hide lines without [`Annotation`]s pub fn fold(mut self, fold: bool) -> Self { self.fold = fold; self } /// Attach a Jupyter notebook cell index. pub fn cell_index(mut self, index: Option<usize>) -> Self { self.cell_index = index; self } } /// An annotation for a [`Snippet`]. /// /// See [`Level::span`] to create a [`Annotation`] #[derive(Debug)] pub struct Annotation<'a> { /// The byte range of the annotation in the `source` string pub(crate) range: Range<usize>, pub(crate) label: Option<&'a str>, pub(crate) level: Level, pub(crate) is_file_level: bool, } impl<'a> Annotation<'a> { pub fn label(mut self, label: &'a str) -> Self { self.label = Some(label); self } pub fn hide_snippet(mut self, yes: bool) -> Self { self.is_file_level = yes; self } } /// Types of annotations. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Level { /// Do not attach any annotation. None, /// Error annotations are displayed using red color and "^" character. Error, /// Warning annotations are displayed using blue color and "-" character. Warning, Info, Note, Help, } impl Level { pub fn title(self, title: &str) -> Message<'_> { Message { level: self, id: None, title, snippets: vec![], footer: vec![], is_fixable: false, lineno_offset: 0, } } /// Create a [`Annotation`] with the given span for a [`Snippet`] pub fn span<'a>(self, span: Range<usize>) -> Annotation<'a> { Annotation { range: span, label: None, level: self, is_file_level: false, } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_annotate_snippets/src/renderer/display_list.rs
crates/ruff_annotate_snippets/src/renderer/display_list.rs
//! `display_list` module stores the output model for the snippet. //! //! `DisplayList` is a central structure in the crate, which contains //! the structured list of lines to be displayed. //! //! It is made of two types of lines: `Source` and `Raw`. All `Source` lines //! are structured using four columns: //! //! ```text //! /------------ (1) Line number column. //! | /--------- (2) Line number column delimiter. //! | | /------- (3) Inline marks column. //! | | | /--- (4) Content column with the source and annotations for slices. //! | | | | //! ============================================================================= //! error[E0308]: mismatched types //! --> src/format.rs:51:5 //! | //! 151 | / fn test() -> String { //! 152 | | return "test"; //! 153 | | } //! | |___^ error: expected `String`, for `&str`. //! | //! ``` //! //! The first two lines of the example above are `Raw` lines, while the rest //! are `Source` lines. //! //! `DisplayList` does not store column alignment information, and those are //! only calculated by the implementation of `std::fmt::Display` using information such as //! styling. //! //! The above snippet has been built out of the following structure: use crate::{Id, snippet}; use std::cmp::{Reverse, max, min}; use std::collections::HashMap; use std::fmt::Display; use std::ops::Range; use std::{cmp, fmt}; use unicode_width::UnicodeWidthStr; use crate::renderer::styled_buffer::StyledBuffer; use crate::renderer::{DEFAULT_TERM_WIDTH, Margin, Style, stylesheet::Stylesheet}; const ANONYMIZED_LINE_NUM: &str = "LL"; const ERROR_TXT: &str = "error"; const HELP_TXT: &str = "help"; const INFO_TXT: &str = "info"; const NOTE_TXT: &str = "note"; const WARNING_TXT: &str = "warning"; /// List of lines to be displayed. pub(crate) struct DisplayList<'a> { pub(crate) body: Vec<DisplaySet<'a>>, pub(crate) stylesheet: &'a Stylesheet, pub(crate) anonymized_line_numbers: bool, pub(crate) cut_indicator: &'static str, pub(crate) lineno_offset: usize, } impl PartialEq for DisplayList<'_> { fn eq(&self, other: &Self) -> bool { self.body == other.body && self.anonymized_line_numbers == other.anonymized_line_numbers } } impl fmt::Debug for DisplayList<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("DisplayList") .field("body", &self.body) .field("anonymized_line_numbers", &self.anonymized_line_numbers) .finish() } } impl Display for DisplayList<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let lineno_width = self.body.iter().fold(0, |max, set| { set.display_lines.iter().fold(max, |max, line| match line { DisplayLine::Source { lineno, .. } => cmp::max(lineno.unwrap_or(0), max), _ => max, }) }); let lineno_width = self.lineno_offset + if lineno_width == 0 { lineno_width } else if self.anonymized_line_numbers { ANONYMIZED_LINE_NUM.len() } else { ((lineno_width as f64).log10().floor() as usize) + 1 }; let multiline_depth = self.body.iter().fold(0, |max, set| { set.display_lines.iter().fold(max, |max2, line| match line { DisplayLine::Source { annotations, .. } => cmp::max( annotations.iter().fold(max2, |max3, line| { cmp::max( match line.annotation_part { DisplayAnnotationPart::Standalone => 0, DisplayAnnotationPart::LabelContinuation => 0, DisplayAnnotationPart::MultilineStart(depth) => depth + 1, DisplayAnnotationPart::MultilineEnd(depth) => depth + 1, }, max3, ) }), max, ), _ => max2, }) }); let mut buffer = StyledBuffer::new(); for set in self.body.iter() { self.format_set(set, lineno_width, multiline_depth, &mut buffer)?; } write!(f, "{}", buffer.render(self.stylesheet)?) } } impl<'a> DisplayList<'a> { pub(crate) fn new( message: snippet::Message<'a>, stylesheet: &'a Stylesheet, anonymized_line_numbers: bool, term_width: usize, cut_indicator: &'static str, ) -> DisplayList<'a> { let lineno_offset = message.lineno_offset; let body = format_message( message, term_width, anonymized_line_numbers, cut_indicator, true, ); Self { body, stylesheet, anonymized_line_numbers, cut_indicator, lineno_offset, } } fn format_set( &self, set: &DisplaySet<'_>, lineno_width: usize, multiline_depth: usize, buffer: &mut StyledBuffer, ) -> fmt::Result { for line in &set.display_lines { set.format_line( line, lineno_width, multiline_depth, self.stylesheet, self.anonymized_line_numbers, self.cut_indicator, buffer, )?; } Ok(()) } } #[derive(Debug, PartialEq)] pub(crate) struct DisplaySet<'a> { pub(crate) display_lines: Vec<DisplayLine<'a>>, pub(crate) margin: Margin, } impl DisplaySet<'_> { fn format_label( &self, line_offset: usize, label: &[DisplayTextFragment<'_>], stylesheet: &Stylesheet, buffer: &mut StyledBuffer, ) -> fmt::Result { for fragment in label { let style = match fragment.style { DisplayTextStyle::Regular => stylesheet.none(), DisplayTextStyle::Emphasis => stylesheet.emphasis(), }; buffer.append(line_offset, fragment.content, *style); } Ok(()) } fn format_annotation( &self, line_offset: usize, annotation: &Annotation<'_>, continuation: bool, stylesheet: &Stylesheet, buffer: &mut StyledBuffer, ) -> fmt::Result { let hide_severity = annotation.annotation_type.is_none(); let color = get_annotation_style(&annotation.annotation_type, stylesheet); let formatted_len = if let Some(id) = &annotation.id { let id_len = id.id.len(); if hide_severity { id_len } else { 2 + id_len + annotation_type_len(&annotation.annotation_type) } } else { annotation_type_len(&annotation.annotation_type) }; if continuation { for _ in 0..formatted_len + 2 { buffer.append(line_offset, " ", Style::new()); } return self.format_label(line_offset, &annotation.label, stylesheet, buffer); } if formatted_len == 0 { self.format_label(line_offset, &annotation.label, stylesheet, buffer) } else { // TODO(brent) All of this complicated checking of `hide_severity` should be reverted // once we have real severities in Ruff. This code is trying to account for two // different cases: // // - main diagnostic message // - subdiagnostic message // // In the first case, signaled by `hide_severity = true`, we want to print the ID (the // noqa code for a ruff lint diagnostic, e.g. `F401`, or `invalid-syntax` for a syntax // error) without brackets. Instead, for subdiagnostics, we actually want to print the // severity (usually `help`) regardless of the `hide_severity` setting. This is signaled // by an ID of `None`. // // With real severities these should be reported more like in ty: // // ``` // error[F401]: `math` imported but unused // error[invalid-syntax]: Cannot use `match` statement on Python 3.9... // ``` // // instead of the current versions intended to mimic the old Ruff output format: // // ``` // F401 `math` imported but unused // invalid-syntax: Cannot use `match` statement on Python 3.9... // ``` // // Note that the `invalid-syntax` colon is added manually in `ruff_db`, not here. We // could eventually add a colon to Ruff lint diagnostics (`F401:`) and then make the // colon below unconditional again. // // This also applies to the hard-coded `stylesheet.error()` styling of the // hidden-severity `id`. This should just be `*color` again later, but for now we don't // want an unformatted `id`, which is what `get_annotation_style` returns for // `DisplayAnnotationType::None`. let annotation_type = annotation_type_str(&annotation.annotation_type); if let Some(id) = annotation.id { if hide_severity { buffer.append( line_offset, &format!("{id} ", id = fmt_with_hyperlink(id.id, id.url, stylesheet)), *stylesheet.error(), ); } else { buffer.append( line_offset, &format!( "{annotation_type}[{id}]", id = fmt_with_hyperlink(id.id, id.url, stylesheet) ), *color, ); } } else { buffer.append(line_offset, annotation_type, *color); } if annotation.is_fixable { buffer.append(line_offset, "[", stylesheet.none); buffer.append(line_offset, "*", stylesheet.help); buffer.append(line_offset, "]", stylesheet.none); // In the hide-severity case, we need a space instead of the colon and space below. if hide_severity { buffer.append(line_offset, " ", stylesheet.none); } } if !is_annotation_empty(annotation) { if annotation.id.is_none() || !hide_severity { buffer.append(line_offset, ": ", stylesheet.none); } self.format_label(line_offset, &annotation.label, stylesheet, buffer)?; } Ok(()) } } #[inline] fn format_raw_line( &self, line_offset: usize, line: &DisplayRawLine<'_>, lineno_width: usize, stylesheet: &Stylesheet, buffer: &mut StyledBuffer, ) -> fmt::Result { match line { DisplayRawLine::Origin { path, pos, header_type, } => { let header_sigil = match header_type { DisplayHeaderType::Initial => "-->", DisplayHeaderType::Continuation => ":::", }; let lineno_color = stylesheet.line_no(); buffer.puts(line_offset, lineno_width, header_sigil, *lineno_color); buffer.puts(line_offset, lineno_width + 4, path, stylesheet.none); if let Some(Position { row, col, cell }) = pos { if let Some(cell) = cell { buffer.append(line_offset, ":", stylesheet.none); buffer.append(line_offset, &format!("cell {cell}"), stylesheet.none); } buffer.append(line_offset, ":", stylesheet.none); buffer.append(line_offset, row.to_string().as_str(), stylesheet.none); buffer.append(line_offset, ":", stylesheet.none); buffer.append(line_offset, col.to_string().as_str(), stylesheet.none); } Ok(()) } DisplayRawLine::Annotation { annotation, source_aligned, continuation, } => { if *source_aligned { if *continuation { for _ in 0..lineno_width + 3 { buffer.append(line_offset, " ", stylesheet.none); } } else { let lineno_color = stylesheet.line_no(); for _ in 0..lineno_width + 1 { buffer.append(line_offset, " ", stylesheet.none); } buffer.append(line_offset, "=", *lineno_color); buffer.append(line_offset, " ", *lineno_color); } } self.format_annotation(line_offset, annotation, *continuation, stylesheet, buffer) } } } // Adapted from https://github.com/rust-lang/rust/blob/d371d17496f2ce3a56da76aa083f4ef157572c20/compiler/rustc_errors/src/emitter.rs#L706-L1211 #[allow(clippy::too_many_arguments)] #[inline] fn format_line( &self, dl: &DisplayLine<'_>, lineno_width: usize, multiline_depth: usize, stylesheet: &Stylesheet, anonymized_line_numbers: bool, cut_indicator: &'static str, buffer: &mut StyledBuffer, ) -> fmt::Result { let line_offset = buffer.num_lines(); match dl { DisplayLine::Source { lineno, inline_marks, line, annotations, } => { let lineno_color = stylesheet.line_no(); if anonymized_line_numbers && lineno.is_some() { let num = format!("{ANONYMIZED_LINE_NUM:>lineno_width$} |"); buffer.puts(line_offset, 0, &num, *lineno_color); } else { match lineno { Some(n) => { let num = format!("{n:>lineno_width$} |"); buffer.puts(line_offset, 0, &num, *lineno_color); } None => { buffer.putc(line_offset, lineno_width + 1, '|', *lineno_color); } } } if let DisplaySourceLine::Content { text, .. } = line { // The width of the line number, a space, pipe, and a space // `123 | ` is `lineno_width + 3`. let width_offset = lineno_width + 3; let code_offset = if multiline_depth == 0 { width_offset } else { width_offset + multiline_depth + 1 }; // Add any inline marks to the code line if !inline_marks.is_empty() || 0 < multiline_depth { format_inline_marks( line_offset, inline_marks, lineno_width, stylesheet, buffer, )?; } let text = normalize_whitespace(text); let line_len = text.as_bytes().len(); let left = self.margin.left(line_len); let right = self.margin.right(line_len); // On long lines, we strip the source line, accounting for unicode. let mut taken = 0; let mut was_cut_right = false; let mut code = String::new(); for ch in text.chars().skip(left) { // Make sure that the trimming on the right will fall within the terminal width. // FIXME: `unicode_width` sometimes disagrees with terminals on how wide a `char` // is. For now, just accept that sometimes the code line will be longer than // desired. let next = char_width(ch).unwrap_or(1); if taken + next > right - left { was_cut_right = true; break; } taken += next; code.push(ch); } buffer.puts(line_offset, code_offset, &code, Style::new()); if self.margin.was_cut_left() { // We have stripped some code/whitespace from the beginning, make it clear. buffer.puts(line_offset, code_offset, cut_indicator, *lineno_color); } if was_cut_right { buffer.puts( line_offset, code_offset + taken - cut_indicator.width(), cut_indicator, *lineno_color, ); } let left: usize = text .chars() .take(left) .map(|ch| char_width(ch).unwrap_or(1)) .sum(); let mut annotations = annotations.clone(); annotations.sort_by_key(|a| Reverse(a.range.0)); let mut annotations_positions = vec![]; let mut line_len: usize = 0; let mut p = 0; for (i, annotation) in annotations.iter().enumerate() { for (j, next) in annotations.iter().enumerate() { // This label overlaps with another one and both take space ( // they have text and are not multiline lines). if overlaps(next, annotation, 0) && annotation.has_label() && j > i && p == 0 // We're currently on the first line, move the label one line down { // If we're overlapping with an un-labelled annotation with the same span // we can just merge them in the output if next.range.0 == annotation.range.0 && next.range.1 == annotation.range.1 && !next.has_label() { continue; } // This annotation needs a new line in the output. p += 1; break; } } annotations_positions.push((p, annotation)); for (j, next) in annotations.iter().enumerate() { if j > i { let l = next .annotation .label .iter() .map(|label| label.content) .collect::<Vec<_>>() .join("") .len() + 2; // Do not allow two labels to be in the same line if they // overlap including padding, to avoid situations like: // // fn foo(x: u32) { // -------^------ // | | // fn_spanx_span // // Both labels must have some text, otherwise they are not // overlapping. Do not add a new line if this annotation or // the next are vertical line placeholders. If either this // or the next annotation is multiline start/end, move it // to a new line so as not to overlap the horizontal lines. if (overlaps(next, annotation, l) && annotation.has_label() && next.has_label()) || (annotation.takes_space() && next.has_label()) || (annotation.has_label() && next.takes_space()) || (annotation.takes_space() && next.takes_space()) || (overlaps(next, annotation, l) && next.range.1 <= annotation.range.1 && next.has_label() && p == 0) // Avoid #42595. { // This annotation needs a new line in the output. p += 1; break; } } } line_len = max(line_len, p); } if line_len != 0 { line_len += 1; } if annotations_positions.iter().all(|(_, ann)| { matches!( ann.annotation_part, DisplayAnnotationPart::MultilineStart(_) ) }) { if let Some(max_pos) = annotations_positions.iter().map(|(pos, _)| *pos).max() { // Special case the following, so that we minimize overlapping multiline spans. // // 3 │ X0 Y0 Z0 // │ ┏━━━━━┛ │ │ < We are writing these lines // │ ┃┌───────┘ │ < by reverting the "depth" of // │ ┃│┌─────────┘ < their multiline spans. // 4 │ ┃││ X1 Y1 Z1 // 5 │ ┃││ X2 Y2 Z2 // │ ┃│└────╿──│──┘ `Z` label // │ ┃└─────│──┤ // │ ┗━━━━━━┥ `Y` is a good letter too // ╰╴ `X` is a good letter for (pos, _) in &mut annotations_positions { *pos = max_pos - *pos; } // We know then that we don't need an additional line for the span label, saving us // one line of vertical space. line_len = line_len.saturating_sub(1); } } // This is a special case where we have a multiline // annotation that is at the start of the line disregarding // any leading whitespace, and no other multiline // annotations overlap it. In this case, we want to draw // // 2 | fn foo() { // | _^ // 3 | | // 4 | | } // | |_^ test // // we simplify the output to: // // 2 | / fn foo() { // 3 | | // 4 | | } // | |_^ test if multiline_depth == 1 && annotations_positions.len() == 1 && annotations_positions .first() .map_or(false, |(_, annotation)| { matches!( annotation.annotation_part, DisplayAnnotationPart::MultilineStart(_) ) && text .chars() .take(annotation.range.0) .all(|c| c.is_whitespace()) }) { let (_, ann) = annotations_positions.remove(0); let style = get_annotation_style(&ann.annotation_type, stylesheet); buffer.putc(line_offset, 3 + lineno_width, '/', *style); } // Draw the column separator for any extra lines that were // created // // After this we will have: // // 2 | fn foo() { // | // | // | // 3 | // 4 | } // | if !annotations_positions.is_empty() { for pos in 0..=line_len { buffer.putc( line_offset + pos + 1, lineno_width + 1, '|', stylesheet.line_no, ); } } // Write the horizontal lines for multiline annotations // (only the first and last lines need this). // // After this we will have: // // 2 | fn foo() { // | __________ // | // | // 3 | // 4 | } // | _ for &(pos, annotation) in &annotations_positions { let style = get_annotation_style(&annotation.annotation_type, stylesheet); let pos = pos + 1; match annotation.annotation_part { DisplayAnnotationPart::MultilineStart(depth) | DisplayAnnotationPart::MultilineEnd(depth) => { for col in width_offset + depth ..(code_offset + annotation.range.0).saturating_sub(left) { buffer.putc(line_offset + pos, col + 1, '_', *style); } } _ => {} } } // Write the vertical lines for labels that are on a different line as the underline. // // After this we will have: // // 2 | fn foo() { // | __________ // | | | // | | // 3 | | // 4 | | } // | |_ for &(pos, annotation) in &annotations_positions { let style = get_annotation_style(&annotation.annotation_type, stylesheet); let pos = pos + 1; if pos > 1 && (annotation.has_label() || annotation.takes_space()) { for p in line_offset + 2..=line_offset + pos { buffer.putc( p, (code_offset + annotation.range.0).saturating_sub(left), '|', *style, ); } } match annotation.annotation_part { DisplayAnnotationPart::MultilineStart(depth) => { for p in line_offset + pos + 1..line_offset + line_len + 2 { buffer.putc(p, width_offset + depth, '|', *style); } } DisplayAnnotationPart::MultilineEnd(depth) => { for p in line_offset..=line_offset + pos { buffer.putc(p, width_offset + depth, '|', *style); } } _ => {} } } // Add in any inline marks for any extra lines that have // been created. Output should look like above. for inline_mark in inline_marks { let DisplayMarkType::AnnotationThrough(depth) = inline_mark.mark_type; let style = get_annotation_style(&inline_mark.annotation_type, stylesheet); if annotations_positions.is_empty() { buffer.putc(line_offset, width_offset + depth, '|', *style); } else { for p in line_offset..=line_offset + line_len + 1 { buffer.putc(p, width_offset + depth, '|', *style); } } } // Write the labels on the annotations that actually have a label. // // After this we will have: // // 2 | fn foo() { // | __________ // | | // | something about `foo` // 3 | // 4 | } // | _ test for &(pos, annotation) in &annotations_positions { if !is_annotation_empty(&annotation.annotation) { let style = get_annotation_style(&annotation.annotation_type, stylesheet); let mut formatted_len = if let Some(id) = &annotation.annotation.id { 2 + id.id.len() + annotation_type_len(&annotation.annotation.annotation_type) } else { annotation_type_len(&annotation.annotation.annotation_type) }; let (pos, col) = if pos == 0 { (pos + 1, (annotation.range.1 + 1).saturating_sub(left)) } else { (pos + 2, annotation.range.0.saturating_sub(left)) }; if annotation.annotation_part == DisplayAnnotationPart::LabelContinuation { formatted_len = 0; } else if formatted_len != 0 { formatted_len += 2; let id = match &annotation.annotation.id { Some(id) => format!( "[{id}]", id = fmt_with_hyperlink(&id.id, id.url, stylesheet) ), None => String::new(),
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_annotate_snippets/src/renderer/styled_buffer.rs
crates/ruff_annotate_snippets/src/renderer/styled_buffer.rs
//! Adapted from [styled_buffer] //! //! [styled_buffer]: https://github.com/rust-lang/rust/blob/894f7a4ba6554d3797404bbf550d9919df060b97/compiler/rustc_errors/src/styled_buffer.rs use crate::renderer::stylesheet::Stylesheet; use anstyle::Style; use std::fmt; use std::fmt::Write; #[derive(Debug)] pub(crate) struct StyledBuffer { lines: Vec<Vec<StyledChar>>, } #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct StyledChar { ch: char, style: Style, } impl StyledChar { pub(crate) const SPACE: Self = StyledChar::new(' ', Style::new()); pub(crate) const fn new(ch: char, style: Style) -> StyledChar { StyledChar { ch, style } } } impl StyledBuffer { pub(crate) fn new() -> StyledBuffer { StyledBuffer { lines: vec![] } } fn ensure_lines(&mut self, line: usize) { if line >= self.lines.len() { self.lines.resize(line + 1, Vec::new()); } } pub(crate) fn render(&self, stylesheet: &Stylesheet) -> Result<String, fmt::Error> { let mut str = String::new(); for (i, line) in self.lines.iter().enumerate() { let mut current_style = stylesheet.none; for ch in line { if ch.style != current_style { if !line.is_empty() { write!(str, "{}", current_style.render_reset())?; } current_style = ch.style; write!(str, "{}", current_style.render())?; } write!(str, "{}", ch.ch)?; } write!(str, "{}", current_style.render_reset())?; if i != self.lines.len() - 1 { writeln!(str)?; } } Ok(str) } /// Sets `chr` with `style` for given `line`, `col`. /// If `line` does not exist in our buffer, adds empty lines up to the given /// and fills the last line with unstyled whitespace. pub(crate) fn putc(&mut self, line: usize, col: usize, chr: char, style: Style) { self.ensure_lines(line); if col >= self.lines[line].len() { self.lines[line].resize(col + 1, StyledChar::SPACE); } self.lines[line][col] = StyledChar::new(chr, style); } /// Sets `string` with `style` for given `line`, starting from `col`. /// If `line` does not exist in our buffer, adds empty lines up to the given /// and fills the last line with unstyled whitespace. pub(crate) fn puts(&mut self, line: usize, col: usize, string: &str, style: Style) { let mut n = col; for c in string.chars() { self.putc(line, n, c, style); n += 1; } } /// For given `line` inserts `string` with `style` after old content of that line, /// adding lines if needed pub(crate) fn append(&mut self, line: usize, string: &str, style: Style) { if line >= self.lines.len() { self.puts(line, 0, string, style); } else { let col = self.lines[line].len(); self.puts(line, col, string, style); } } pub(crate) fn num_lines(&self) -> usize { self.lines.len() } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_annotate_snippets/src/renderer/stylesheet.rs
crates/ruff_annotate_snippets/src/renderer/stylesheet.rs
use anstyle::Style; #[derive(Clone, Copy, Debug)] pub(crate) struct Stylesheet { pub(crate) error: Style, pub(crate) warning: Style, pub(crate) info: Style, pub(crate) note: Style, pub(crate) help: Style, pub(crate) line_no: Style, pub(crate) emphasis: Style, pub(crate) none: Style, pub(crate) hyperlink: bool, } impl Default for Stylesheet { fn default() -> Self { Self::plain() } } impl Stylesheet { pub(crate) const fn plain() -> Self { Self { error: Style::new(), warning: Style::new(), info: Style::new(), note: Style::new(), help: Style::new(), line_no: Style::new(), emphasis: Style::new(), none: Style::new(), hyperlink: false, } } } impl Stylesheet { pub(crate) fn error(&self) -> &Style { &self.error } pub(crate) fn warning(&self) -> &Style { &self.warning } pub(crate) fn info(&self) -> &Style { &self.info } pub(crate) fn note(&self) -> &Style { &self.note } pub(crate) fn help(&self) -> &Style { &self.help } pub(crate) fn line_no(&self) -> &Style { &self.line_no } pub(crate) fn emphasis(&self) -> &Style { &self.emphasis } pub(crate) fn none(&self) -> &Style { &self.none } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_annotate_snippets/src/renderer/margin.rs
crates/ruff_annotate_snippets/src/renderer/margin.rs
use std::cmp::{max, min}; const ELLIPSIS_PASSING: usize = 6; const LONG_WHITESPACE: usize = 20; const LONG_WHITESPACE_PADDING: usize = 4; #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct Margin { /// The available whitespace in the left that can be consumed when centering. whitespace_left: usize, /// The column of the beginning of left-most span. span_left: usize, /// The column of the end of right-most span. span_right: usize, /// The beginning of the line to be displayed. computed_left: usize, /// The end of the line to be displayed. computed_right: usize, /// The current width of the terminal. 140 by default and in tests. term_width: usize, /// The end column of a span label, including the span. Doesn't account for labels not in the /// same line as the span. label_right: usize, } impl Margin { pub(crate) fn new( whitespace_left: usize, span_left: usize, span_right: usize, label_right: usize, term_width: usize, max_line_len: usize, ) -> Self { // The 6 is padding to give a bit of room for `...` when displaying: // ``` // error: message // --> file.rs:16:58 // | // 16 | ... fn foo(self) -> Self::Bar { // | ^^^^^^^^^ // ``` let mut m = Margin { whitespace_left: whitespace_left.saturating_sub(ELLIPSIS_PASSING), span_left: span_left.saturating_sub(ELLIPSIS_PASSING), span_right: span_right + ELLIPSIS_PASSING, computed_left: 0, computed_right: 0, term_width, label_right: label_right + ELLIPSIS_PASSING, }; m.compute(max_line_len); m } pub(crate) fn was_cut_left(&self) -> bool { self.computed_left > 0 } fn compute(&mut self, max_line_len: usize) { // When there's a lot of whitespace (>20), we want to trim it as it is useless. self.computed_left = if self.whitespace_left > LONG_WHITESPACE { self.whitespace_left - (LONG_WHITESPACE - LONG_WHITESPACE_PADDING) // We want some padding. } else { 0 }; // We want to show as much as possible, max_line_len is the right-most boundary for the // relevant code. self.computed_right = max(max_line_len, self.computed_left); if self.computed_right - self.computed_left > self.term_width { // Trimming only whitespace isn't enough, let's get craftier. if self.label_right - self.whitespace_left <= self.term_width { // Attempt to fit the code window only trimming whitespace. self.computed_left = self.whitespace_left; self.computed_right = self.computed_left + self.term_width; } else if self.label_right - self.span_left <= self.term_width { // Attempt to fit the code window considering only the spans and labels. let padding_left = (self.term_width - (self.label_right - self.span_left)) / 2; self.computed_left = self.span_left.saturating_sub(padding_left); self.computed_right = self.computed_left + self.term_width; } else if self.span_right - self.span_left <= self.term_width { // Attempt to fit the code window considering the spans and labels plus padding. let padding_left = (self.term_width - (self.span_right - self.span_left)) / 5 * 2; self.computed_left = self.span_left.saturating_sub(padding_left); self.computed_right = self.computed_left + self.term_width; } else { // Mostly give up but still don't show the full line. self.computed_left = self.span_left; self.computed_right = self.span_right; } } } pub(crate) fn left(&self, line_len: usize) -> usize { min(self.computed_left, line_len) } pub(crate) fn right(&self, line_len: usize) -> usize { if line_len.saturating_sub(self.computed_left) <= self.term_width { line_len } else { min(line_len, self.computed_right) } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_annotate_snippets/src/renderer/mod.rs
crates/ruff_annotate_snippets/src/renderer/mod.rs
//! The renderer for [`Message`]s //! //! # Example //! ``` //! use ruff_annotate_snippets::{Renderer, Snippet, Level}; //! let snippet = Level::Error.title("mismatched types") //! .snippet(Snippet::source("Foo").line_start(51).origin("src/format.rs")) //! .snippet(Snippet::source("Faa").line_start(129).origin("src/display.rs")); //! //! let renderer = Renderer::styled(); //! println!("{}", renderer.render(snippet)); //! ``` mod display_list; mod margin; mod styled_buffer; pub(crate) mod stylesheet; use crate::snippet::Message; pub use anstyle::*; use display_list::DisplayList; use margin::Margin; use std::fmt::Display; use stylesheet::Stylesheet; pub const DEFAULT_TERM_WIDTH: usize = 140; /// A renderer for [`Message`]s #[derive(Clone, Debug)] pub struct Renderer { anonymized_line_numbers: bool, term_width: usize, stylesheet: Stylesheet, cut_indicator: &'static str, } impl Renderer { /// No terminal styling pub const fn plain() -> Self { Self { anonymized_line_numbers: false, term_width: DEFAULT_TERM_WIDTH, stylesheet: Stylesheet::plain(), cut_indicator: "...", } } /// Default terminal styling /// /// # Note /// When testing styled terminal output, see the [`testing-colors` feature](crate#features) pub const fn styled() -> Self { const USE_WINDOWS_COLORS: bool = cfg!(windows) && !cfg!(feature = "testing-colors"); const BRIGHT_BLUE: Style = if USE_WINDOWS_COLORS { AnsiColor::BrightCyan.on_default() } else { AnsiColor::BrightBlue.on_default() }; Self { stylesheet: Stylesheet { error: AnsiColor::BrightRed.on_default().effects(Effects::BOLD), warning: if USE_WINDOWS_COLORS { AnsiColor::BrightYellow.on_default() } else { AnsiColor::Yellow.on_default() } .effects(Effects::BOLD), info: BRIGHT_BLUE.effects(Effects::BOLD), note: AnsiColor::BrightGreen.on_default().effects(Effects::BOLD), help: AnsiColor::BrightCyan.on_default().effects(Effects::BOLD), line_no: BRIGHT_BLUE.effects(Effects::BOLD), emphasis: if USE_WINDOWS_COLORS { AnsiColor::BrightWhite.on_default() } else { Style::new() } .effects(Effects::BOLD), none: Style::new(), hyperlink: true, }, ..Self::plain() } } /// Anonymize line numbers /// /// This enables (or disables) line number anonymization. When enabled, line numbers are replaced /// with `LL`. /// /// # Example /// /// ```text /// --> $DIR/whitespace-trimming.rs:4:193 /// | /// LL | ... let _: () = 42; /// | ^^ expected (), found integer /// | /// ``` pub const fn anonymized_line_numbers(mut self, anonymized_line_numbers: bool) -> Self { self.anonymized_line_numbers = anonymized_line_numbers; self } /// Set the terminal width pub const fn term_width(mut self, term_width: usize) -> Self { self.term_width = term_width; self } /// Set the output style for `error` pub const fn error(mut self, style: Style) -> Self { self.stylesheet.error = style; self } /// Set the output style for `warning` pub const fn warning(mut self, style: Style) -> Self { self.stylesheet.warning = style; self } /// Set the output style for `info` pub const fn info(mut self, style: Style) -> Self { self.stylesheet.info = style; self } /// Set the output style for `note` pub const fn note(mut self, style: Style) -> Self { self.stylesheet.note = style; self } /// Set the output style for `help` pub const fn help(mut self, style: Style) -> Self { self.stylesheet.help = style; self } /// Set the output style for line numbers pub const fn line_no(mut self, style: Style) -> Self { self.stylesheet.line_no = style; self } /// Set the output style for emphasis pub const fn emphasis(mut self, style: Style) -> Self { self.stylesheet.emphasis = style; self } /// Set the output style for none pub const fn none(mut self, style: Style) -> Self { self.stylesheet.none = style; self } pub const fn hyperlink(mut self, hyperlink: bool) -> Self { self.stylesheet.hyperlink = hyperlink; self } /// Set the string used for when a long line is cut. /// /// The default is `...` (three `U+002E` characters). pub const fn cut_indicator(mut self, string: &'static str) -> Self { self.cut_indicator = string; self } /// Render a snippet into a `Display`able object pub fn render<'a>(&'a self, msg: Message<'a>) -> impl Display + 'a { DisplayList::new( msg, &self.stylesheet, self.anonymized_line_numbers, self.term_width, self.cut_indicator, ) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_annotate_snippets/tests/rustc_tests.rs
crates/ruff_annotate_snippets/tests/rustc_tests.rs
//! These tests have been adapted from [Rust's parser tests][parser-tests]. //! //! [parser-tests]: https://github.com/rust-lang/rust/blob/894f7a4ba6554d3797404bbf550d9919df060b97/compiler/rustc_parse/src/parser/tests.rs use ruff_annotate_snippets::{Level, Renderer, Snippet}; use snapbox::{assert_data_eq, str}; #[test] fn ends_on_col0() { let source = r#" fn foo() { } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(10..13).label("test")), ); let expected = str![[r#" error: foo --> test.rs:2:10 | 2 | fn foo() { | __________^ 3 | | } | |_^ test | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn ends_on_col2() { let source = r#" fn foo() { } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(10..17).label("test")), ); let expected = str![[r#" error: foo --> test.rs:2:10 | 2 | fn foo() { | __________^ 3 | | 4 | | 5 | | } | |___^ test | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn non_nested() { let source = r#" fn foo() { X0 Y0 X1 Y1 X2 Y2 } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(14..32).label("`X` is a good letter")) .annotation( Level::Warning .span(17..35) .label("`Y` is a good letter too"), ), ); let expected = str![[r#" error: foo --> test.rs:3:3 | 3 | X0 Y0 | ____^ - | | ______| 4 | || X1 Y1 5 | || X2 Y2 | ||____^__- `Y` is a good letter too | |_____| | `X` is a good letter | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn nested() { let source = r#" fn foo() { X0 Y0 Y1 X1 } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(14..27).label("`X` is a good letter")) .annotation( Level::Warning .span(17..24) .label("`Y` is a good letter too"), ), ); let expected = str![[r#" error: foo --> test.rs:3:3 | 3 | X0 Y0 | ____^ - | | ______| 4 | || Y1 X1 | ||____-__^ `X` is a good letter | |____| | `Y` is a good letter too | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn different_overlap() { let source = r#" fn foo() { X0 Y0 Z0 X1 Y1 Z1 X2 Y2 Z2 X3 Y3 Z3 } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(17..38).label("`X` is a good letter")) .annotation( Level::Warning .span(31..49) .label("`Y` is a good letter too"), ), ); let expected = str![[r#" error: foo --> test.rs:3:6 | 3 | X0 Y0 Z0 | _______^ 4 | | X1 Y1 Z1 | | _________- 5 | || X2 Y2 Z2 | ||____^ `X` is a good letter 6 | | X3 Y3 Z3 | |____- `Y` is a good letter too | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn triple_overlap() { let source = r#" fn foo() { X0 Y0 Z0 X1 Y1 Z1 X2 Y2 Z2 } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(14..38).label("`X` is a good letter")) .annotation( Level::Warning .span(17..41) .label("`Y` is a good letter too"), ) .annotation(Level::Warning.span(20..44).label("`Z` label")), ); let expected = str![[r#" error: foo --> test.rs:3:3 | 3 | X0 Y0 Z0 | _____^ - - | | _______| | | || _________| 4 | ||| X1 Y1 Z1 5 | ||| X2 Y2 Z2 | |||____^__-__- `Z` label | ||_____|__| | |______| `Y` is a good letter too | `X` is a good letter | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn triple_exact_overlap() { let source = r#" fn foo() { X0 Y0 Z0 X1 Y1 Z1 X2 Y2 Z2 } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(14..38).label("`X` is a good letter")) .annotation( Level::Warning .span(14..38) .label("`Y` is a good letter too"), ) .annotation(Level::Warning.span(14..38).label("`Z` label")), ); // This should have a `^` but we currently don't support the idea of a // "primary" annotation, which would solve this let expected = str![[r#" error: foo --> test.rs:3:3 | 3 | / X0 Y0 Z0 4 | | X1 Y1 Z1 5 | | X2 Y2 Z2 | | - | |____| | `X` is a good letter | `Y` is a good letter too | `Z` label | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn minimum_depth() { let source = r#" fn foo() { X0 Y0 Z0 X1 Y1 Z1 X2 Y2 Z2 X3 Y3 Z3 } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(17..27).label("`X` is a good letter")) .annotation( Level::Warning .span(28..44) .label("`Y` is a good letter too"), ) .annotation(Level::Warning.span(36..52).label("`Z`")), ); let expected = str![[r#" error: foo --> test.rs:3:6 | 3 | X0 Y0 Z0 | _______^ 4 | | X1 Y1 Z1 | | ____^_- | ||____| | | `X` is a good letter 5 | | X2 Y2 Z2 | |___-______- `Y` is a good letter too | ___| | | 6 | | X3 Y3 Z3 | |_______- `Z` | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn non_overlapping() { let source = r#" fn foo() { X0 Y0 Z0 X1 Y1 Z1 X2 Y2 Z2 X3 Y3 Z3 } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(14..27).label("`X` is a good letter")) .annotation( Level::Warning .span(39..55) .label("`Y` is a good letter too"), ), ); let expected = str![[r#" error: foo --> test.rs:3:3 | 3 | / X0 Y0 Z0 4 | | X1 Y1 Z1 | |____^ `X` is a good letter 5 | X2 Y2 Z2 | ______- 6 | | X3 Y3 Z3 | |__________- `Y` is a good letter too | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn overlapping_start_and_end() { let source = r#" fn foo() { X0 Y0 Z0 X1 Y1 Z1 X2 Y2 Z2 X3 Y3 Z3 } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(17..27).label("`X` is a good letter")) .annotation( Level::Warning .span(31..55) .label("`Y` is a good letter too"), ), ); let expected = str![[r#" error: foo --> test.rs:3:6 | 3 | X0 Y0 Z0 | _______^ 4 | | X1 Y1 Z1 | | ____^____- | ||____| | | `X` is a good letter 5 | | X2 Y2 Z2 6 | | X3 Y3 Z3 | |__________- `Y` is a good letter too | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn multiple_labels_primary_without_message() { let source = r#" fn foo() { a { b { c } d } } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(18..25).label("")) .annotation(Level::Warning.span(14..27).label("`a` is a good letter")) .annotation(Level::Warning.span(22..23).label("")), ); let expected = str![[r#" error: foo --> test.rs:3:7 | 3 | a { b { c } d } | ----^^^^-^^-- `a` is a good letter | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn multiple_labels_secondary_without_message() { let source = r#" fn foo() { a { b { c } d } } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(14..27).label("`a` is a good letter")) .annotation(Level::Warning.span(18..25).label("")), ); let expected = str![[r#" error: foo --> test.rs:3:3 | 3 | a { b { c } d } | ^^^^-------^^ `a` is a good letter | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn multiple_labels_primary_without_message_2() { let source = r#" fn foo() { a { b { c } d } } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(18..25).label("`b` is a good letter")) .annotation(Level::Warning.span(14..27).label("")) .annotation(Level::Warning.span(22..23).label("")), ); let expected = str![[r#" error: foo --> test.rs:3:7 | 3 | a { b { c } d } | ----^^^^-^^-- | | | `b` is a good letter | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn multiple_labels_secondary_without_message_2() { let source = r#" fn foo() { a { b { c } d } } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(14..27).label("")) .annotation(Level::Warning.span(18..25).label("`b` is a good letter")), ); let expected = str![[r#" error: foo --> test.rs:3:3 | 3 | a { b { c } d } | ^^^^-------^^ | | | `b` is a good letter | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn multiple_labels_secondary_without_message_3() { let source = r#" fn foo() { a bc d } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(14..18).label("`a` is a good letter")) .annotation(Level::Warning.span(18..22).label("")), ); let expected = str![[r#" error: foo --> test.rs:3:3 | 3 | a bc d | ^^^^---- | | | `a` is a good letter | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn multiple_labels_without_message() { let source = r#" fn foo() { a { b { c } d } } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(14..27).label("")) .annotation(Level::Warning.span(18..25).label("")), ); let expected = str![[r#" error: foo --> test.rs:3:3 | 3 | a { b { c } d } | ^^^^-------^^ | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn multiple_labels_without_message_2() { let source = r#" fn foo() { a { b { c } d } } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(18..25).label("")) .annotation(Level::Warning.span(14..27).label("")) .annotation(Level::Warning.span(22..23).label("")), ); let expected = str![[r#" error: foo --> test.rs:3:7 | 3 | a { b { c } d } | ----^^^^-^^-- | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn multiple_labels_with_message() { let source = r#" fn foo() { a { b { c } d } } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(14..27).label("`a` is a good letter")) .annotation(Level::Warning.span(18..25).label("`b` is a good letter")), ); let expected = str![[r#" error: foo --> test.rs:3:3 | 3 | a { b { c } d } | ^^^^-------^^ | | | | | `b` is a good letter | `a` is a good letter | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn ingle_label_with_message() { let source = r#" fn foo() { a { b { c } d } } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(14..27).label("`a` is a good letter")), ); let expected = str![[r#" error: foo --> test.rs:3:3 | 3 | a { b { c } d } | ^^^^^^^^^^^^^ `a` is a good letter | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn single_label_without_message() { let source = r#" fn foo() { a { b { c } d } } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(14..27).label("")), ); let expected = str![[r#" error: foo --> test.rs:3:3 | 3 | a { b { c } d } | ^^^^^^^^^^^^^ | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn long_snippet() { let source = r#" fn foo() { X0 Y0 Z0 X1 Y1 Z1 1 2 3 4 5 6 7 8 9 10 X2 Y2 Z2 X3 Y3 Z3 } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(17..27).label("`X` is a good letter")) .annotation( Level::Warning .span(31..76) .label("`Y` is a good letter too"), ), ); let expected = str![[r#" error: foo --> test.rs:3:6 | 3 | X0 Y0 Z0 | _______^ 4 | | X1 Y1 Z1 | | ____^____- | ||____| | | `X` is a good letter 5 | | 1 ... | 15 | | X2 Y2 Z2 16 | | X3 Y3 Z3 | |__________- `Y` is a good letter too | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn long_snippet_multiple_spans() { let source = r#" fn foo() { X0 Y0 Z0 1 2 3 X1 Y1 Z1 4 5 6 X2 Y2 Z2 7 8 9 10 X3 Y3 Z3 } "#; let input = Level::Error.title("foo").snippet( Snippet::source(source) .line_start(1) .origin("test.rs") .fold(true) .annotation(Level::Error.span(17..73).label("`Y` is a good letter")) .annotation( Level::Warning .span(37..56) .label("`Z` is a good letter too"), ), ); let expected = str![[r#" error: foo --> test.rs:3:6 | 3 | X0 Y0 Z0 | _______^ 4 | | 1 5 | | 2 6 | | 3 7 | | X1 Y1 Z1 | | _________- 8 | || 4 9 | || 5 10 | || 6 11 | || X2 Y2 Z2 | ||__________- `Z` is a good letter too 12 | | 7 ... | 15 | | 10 16 | | X3 Y3 Z3 | |________^ `Y` is a good letter | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_annotate_snippets/tests/formatter.rs
crates/ruff_annotate_snippets/tests/formatter.rs
// Since this is a vendored copy of `annotate-snippets`, we squash Clippy // warnings from upstream in order to the reduce the diff. If our copy drifts // far from upstream such that patches become impractical to apply in both // places, then we can get rid of these suppressions and fix the lints. #![allow(clippy::redundant_clone, clippy::should_panic_without_expect)] use ruff_annotate_snippets::{Level, Renderer, Snippet}; use snapbox::{assert_data_eq, str}; #[test] fn test_i_29() { let snippets = Level::Error.title("oops").snippet( Snippet::source("First line\r\nSecond oops line") .origin("<current file>") .annotation(Level::Error.span(19..23).label("oops")) .fold(true), ); let expected = str![[r#" error: oops --> <current file>:2:8 | 2 | Second oops line | ^^^^ oops | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(snippets).to_string(), expected); } #[test] fn test_point_to_double_width_characters() { let snippets = Level::Error.title("").snippet( Snippet::source("こんにちは、世界") .origin("<current file>") .annotation(Level::Error.span(18..24).label("world")), ); let expected = str![[r#" error --> <current file>:1:7 | 1 | こんにちは、世界 | ^^^^ world | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(snippets).to_string(), expected); } #[test] fn test_point_to_double_width_characters_across_lines() { let snippets = Level::Error.title("").snippet( Snippet::source("おはよう\nございます") .origin("<current file>") .annotation(Level::Error.span(6..22).label("Good morning")), ); let expected = str![[r#" error --> <current file>:1:3 | 1 | おはよう | _____^ 2 | | ございます | |______^ Good morning | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(snippets).to_string(), expected); } #[test] fn test_point_to_double_width_characters_multiple() { let snippets = Level::Error.title("").snippet( Snippet::source("お寿司\n食べたい🍣") .origin("<current file>") .annotation(Level::Error.span(0..9).label("Sushi1")) .annotation(Level::Note.span(16..22).label("Sushi2")), ); let expected = str![[r#" error --> <current file>:1:1 | 1 | お寿司 | ^^^^^^ Sushi1 2 | 食べたい🍣 | ---- note: Sushi2 | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(snippets).to_string(), expected); } #[test] fn test_point_to_double_width_characters_mixed() { let snippets = Level::Error.title("").snippet( Snippet::source("こんにちは、新しいWorld!") .origin("<current file>") .annotation(Level::Error.span(18..32).label("New world")), ); let expected = str![[r#" error --> <current file>:1:7 | 1 | こんにちは、新しいWorld! | ^^^^^^^^^^^ New world | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(snippets).to_string(), expected); } #[test] fn test_format_title() { let input = Level::Error.title("This is a title").id("E0001"); let expected = str![r#"error[E0001]: This is a title"#]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } /// Tests that we can format a message *without* a header. /// /// This uses `Level::None`, which is somewhat of a hacky API addition I made /// to our vendored copy of `annotate-snippets` in order to do exactly what /// this test asserts: skip the header. #[test] fn test_format_skip_title() { let source = "# Docstring followed by a newline\n\ndef foobar(foot, bar={}):\n \"\"\"\n \"\"\"\n"; let src_annotation = Level::Error.span(56..58).label("B006"); let snippet = Snippet::source(source) .line_start(1) .annotation(src_annotation) .fold(false); let message = Level::None.title("").snippet(snippet); let expected = str![[r#" | 1 | # Docstring followed by a newline 2 | 3 | def foobar(foot, bar={}): | ^^ B006 4 | """ 5 | """ | "#]]; assert_data_eq!(Renderer::plain().render(message).to_string(), expected); } #[test] fn test_format_snippet_only() { let source = "This is line 1\nThis is line 2"; let input = Level::Error .title("") .snippet(Snippet::source(source).line_start(5402)); let expected = str![[r#" error | 5402 | This is line 1 5403 | This is line 2 | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn test_format_snippets_continuation() { let src_0 = "This is slice 1"; let src_1 = "This is slice 2"; let input = Level::Error .title("") .snippet(Snippet::source(src_0).line_start(5402).origin("file1.rs")) .snippet(Snippet::source(src_1).line_start(2).origin("file2.rs")); let expected = str![[r#" error --> file1.rs | 5402 | This is slice 1 | ::: file2.rs | 2 | This is slice 2 | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn test_format_snippet_annotation_standalone() { let line_1 = "This is line 1"; let line_2 = "This is line 2"; let source = [line_1, line_2].join("\n"); // In line 2 let range = 22..24; let input = Level::Error.title("").snippet( Snippet::source(&source) .line_start(5402) .annotation(Level::Info.span(range.clone()).label("Test annotation")), ); let expected = str![[r#" error | 5402 | This is line 1 5403 | This is line 2 | -- info: Test annotation | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn test_format_footer_title() { let input = Level::Error .title("") .footer(Level::Error.title("This __is__ a title")); let expected = str![[r#" error = error: This __is__ a title "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] #[should_panic] fn test_i26() { let source = "short"; let label = "label"; let input = Level::Error.title("").snippet( Snippet::source(source) .line_start(0) .annotation(Level::Error.span(0..source.len() + 2).label(label)), ); let renderer = Renderer::plain(); let _ = renderer.render(input).to_string(); } #[test] fn test_source_content() { let source = "This is an example\nof content lines"; let input = Level::Error .title("") .snippet(Snippet::source(source).line_start(56)); let expected = str![[r#" error | 56 | This is an example 57 | of content lines | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn test_source_annotation_standalone_singleline() { let source = "tests"; let input = Level::Error.title("").snippet( Snippet::source(source) .line_start(1) .annotation(Level::Help.span(0..5).label("Example string")), ); let expected = str![[r#" error | 1 | tests | ----- help: Example string | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn test_source_annotation_standalone_multiline() { let source = "tests"; let input = Level::Error.title("").snippet( Snippet::source(source) .line_start(1) .annotation(Level::Help.span(0..5).label("Example string")) .annotation(Level::Help.span(0..5).label("Second line")), ); let expected = str![[r#" error | 1 | tests | ----- | | | help: Example string | help: Second line | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn test_only_source() { let input = Level::Error .title("") .snippet(Snippet::source("").origin("file.rs")); let expected = str![[r#" error --> file.rs | | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn test_anon_lines() { let source = "This is an example\nof content lines\n\nabc"; let input = Level::Error .title("") .snippet(Snippet::source(source).line_start(56)); let expected = str![[r#" error | LL | This is an example LL | of content lines LL | LL | abc | "#]]; let renderer = Renderer::plain().anonymized_line_numbers(true); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn issue_130() { let input = Level::Error.title("dummy").snippet( Snippet::source("foo\nbar\nbaz") .origin("file/path") .line_start(3) .fold(true) .annotation(Level::Error.span(4..11)), // bar\nbaz ); let expected = str![[r#" error: dummy --> file/path:4:1 | 4 | / bar 5 | | baz | |___^ | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn unterminated_string_multiline() { let source = "\ a\" // ... "; let input = Level::Error.title("").snippet( Snippet::source(source) .origin("file/path") .line_start(3) .fold(true) .annotation(Level::Error.span(0..10)), // 1..10 works ); let expected = str![[r#" error --> file/path:3:1 | 3 | / a" 4 | | // ... | |_______^ | "#]]; let renderer = Renderer::plain().anonymized_line_numbers(false); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn char_and_nl_annotate_char() { let source = "a\r\nb"; let input = Level::Error.title("").snippet( Snippet::source(source) .origin("file/path") .line_start(3) .annotation(Level::Error.span(0..2)), // a\r ); let expected = str![[r#" error --> file/path:3:1 | 3 | a | ^ 4 | b |"#]]; let renderer = Renderer::plain().anonymized_line_numbers(false); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn char_eol_annotate_char() { let source = "a\r\nb"; let input = Level::Error.title("").snippet( Snippet::source(source) .origin("file/path") .line_start(3) .annotation(Level::Error.span(0..3)), // a\r\n ); let expected = str![[r#" error --> file/path:3:1 | 3 | a | ^ 4 | b |"#]]; let renderer = Renderer::plain().anonymized_line_numbers(false); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn char_eol_annotate_char_double_width() { let snippets = Level::Error.title("").snippet( Snippet::source("こん\r\nにちは\r\n世界") .origin("<current file>") .annotation(Level::Error.span(3..8)), // ん\r\n ); let expected = str![[r#" error --> <current file>:1:2 | 1 | こん | ^^ 2 | にちは 3 | 世界 | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(snippets).to_string(), expected); } #[test] fn annotate_eol() { let source = "a\r\nb"; let input = Level::Error.title("").snippet( Snippet::source(source) .origin("file/path") .line_start(3) .annotation(Level::Error.span(1..2)), // \r ); let expected = str![[r#" error --> file/path:3:2 | 3 | a | ^ 4 | b |"#]]; let renderer = Renderer::plain().anonymized_line_numbers(false); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn annotate_eol2() { let source = "a\r\nb"; let input = Level::Error.title("").snippet( Snippet::source(source) .origin("file/path") .line_start(3) .annotation(Level::Error.span(1..3)), // \r\n ); let expected = str![[r#" error --> file/path:3:2 | 3 | a | ^ 4 | b |"#]]; let renderer = Renderer::plain().anonymized_line_numbers(false); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn annotate_eol3() { let source = "a\r\nb"; let input = Level::Error.title("").snippet( Snippet::source(source) .origin("file/path") .line_start(3) .annotation(Level::Error.span(2..3)), // \n ); let expected = str![[r#" error --> file/path:3:2 | 3 | a | ^ 4 | b |"#]]; let renderer = Renderer::plain().anonymized_line_numbers(false); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn annotate_eol4() { let source = "a\r\nb"; let input = Level::Error.title("").snippet( Snippet::source(source) .origin("file/path") .line_start(3) .annotation(Level::Error.span(2..2)), // \n ); let expected = str![[r#" error --> file/path:3:2 | 3 | a | ^ 4 | b |"#]]; let renderer = Renderer::plain().anonymized_line_numbers(false); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn annotate_eol_double_width() { let snippets = Level::Error.title("").snippet( Snippet::source("こん\r\nにちは\r\n世界") .origin("<current file>") .annotation(Level::Error.span(7..8)), // \n ); let expected = str![[r#" error --> <current file>:1:3 | 1 | こん | ^ 2 | にちは 3 | 世界 | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(snippets).to_string(), expected); } #[test] fn multiline_eol_start() { let source = "a\r\nb"; let input = Level::Error.title("").snippet( Snippet::source(source) .origin("file/path") .line_start(3) .annotation(Level::Error.span(1..4)), // \r\nb ); let expected = str![[r#" error --> file/path:3:2 | 3 | a | __^ 4 | | b | |_^ |"#]]; let renderer = Renderer::plain().anonymized_line_numbers(false); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn multiline_eol_start2() { let source = "a\r\nb"; let input = Level::Error.title("").snippet( Snippet::source(source) .origin("file/path") .line_start(3) .annotation(Level::Error.span(2..4)), // \nb ); let expected = str![[r#" error --> file/path:3:2 | 3 | a | __^ 4 | | b | |_^ |"#]]; let renderer = Renderer::plain().anonymized_line_numbers(false); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn multiline_eol_start3() { let source = "a\nb"; let input = Level::Error.title("").snippet( Snippet::source(source) .origin("file/path") .line_start(3) .annotation(Level::Error.span(1..3)), // \nb ); let expected = str![[r#" error --> file/path:3:2 | 3 | a | __^ 4 | | b | |_^ |"#]]; let renderer = Renderer::plain().anonymized_line_numbers(false); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn multiline_eol_start_double_width() { let snippets = Level::Error.title("").snippet( Snippet::source("こん\r\nにちは\r\n世界") .origin("<current file>") .annotation(Level::Error.span(7..11)), // \r\nに ); let expected = str![[r#" error --> <current file>:1:3 | 1 | こん | _____^ 2 | | にちは | |__^ 3 | 世界 | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(snippets).to_string(), expected); } #[test] fn multiline_eol_start_eol_end() { let source = "a\nb\nc"; let input = Level::Error.title("").snippet( Snippet::source(source) .origin("file/path") .line_start(3) .annotation(Level::Error.span(1..4)), // \nb\n ); let expected = str![[r#" error --> file/path:3:2 | 3 | a | __^ 4 | | b | |__^ 5 | c | "#]]; let renderer = Renderer::plain().anonymized_line_numbers(false); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn multiline_eol_start_eol_end2() { let source = "a\r\nb\r\nc"; let input = Level::Error.title("").snippet( Snippet::source(source) .origin("file/path") .line_start(3) .annotation(Level::Error.span(2..5)), // \nb\r ); let expected = str![[r#" error --> file/path:3:2 | 3 | a | __^ 4 | | b | |__^ 5 | c | "#]]; let renderer = Renderer::plain().anonymized_line_numbers(false); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn multiline_eol_start_eol_end3() { let source = "a\r\nb\r\nc"; let input = Level::Error.title("").snippet( Snippet::source(source) .origin("file/path") .line_start(3) .annotation(Level::Error.span(2..6)), // \nb\r\n ); let expected = str![[r#" error --> file/path:3:2 | 3 | a | __^ 4 | | b | |__^ 5 | c | "#]]; let renderer = Renderer::plain().anonymized_line_numbers(false); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn multiline_eol_start_eof_end() { let source = "a\r\nb"; let input = Level::Error.title("").snippet( Snippet::source(source) .origin("file/path") .line_start(3) .annotation(Level::Error.span(1..5)), // \r\nb(EOF) ); let expected = str![[r#" error --> file/path:3:2 | 3 | a | __^ 4 | | b | |__^ | "#]]; let renderer = Renderer::plain().anonymized_line_numbers(false); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn multiline_eol_start_eof_end_double_width() { let source = "ん\r\nに"; let input = Level::Error.title("").snippet( Snippet::source(source) .origin("file/path") .line_start(3) .annotation(Level::Error.span(3..9)), // \r\nに(EOF) ); let expected = str![[r#" error --> file/path:3:2 | 3 | ん | ___^ 4 | | に | |___^ | "#]]; let renderer = Renderer::plain().anonymized_line_numbers(false); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn two_single_line_same_line() { let source = r#"bar = { version = "0.1.0", optional = true }"#; let input = Level::Error.title("unused optional dependency").snippet( Snippet::source(source) .origin("Cargo.toml") .line_start(4) .annotation( Level::Error .span(0..3) .label("I need this to be really long so I can test overlaps"), ) .annotation( Level::Info .span(27..42) .label("This should also be long but not too long"), ), ); let expected = str![[r#" error: unused optional dependency --> Cargo.toml:4:1 | 4 | bar = { version = "0.1.0", optional = true } | ^^^ --------------- info: This should also be long but not too long | | | I need this to be really long so I can test overlaps | "#]]; let renderer = Renderer::plain().anonymized_line_numbers(false); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn multi_and_single() { let source = r#"bar = { version = "0.1.0", optional = true } this is another line so is this bar = { version = "0.1.0", optional = true } "#; let input = Level::Error.title("unused optional dependency").snippet( Snippet::source(source) .line_start(4) .annotation( Level::Error .span(41..119) .label("I need this to be really long so I can test overlaps"), ) .annotation( Level::Info .span(27..42) .label("This should also be long but not too long"), ), ); let expected = str![[r#" error: unused optional dependency | 4 | bar = { version = "0.1.0", optional = true } | ____________________________--------------^ | | | | | info: This should also be long but not too long 5 | | this is another line 6 | | so is this 7 | | bar = { version = "0.1.0", optional = true } | |__________________________________________^ I need this to be really long so I can test overlaps | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn two_multi_and_single() { let source = r#"bar = { version = "0.1.0", optional = true } this is another line so is this bar = { version = "0.1.0", optional = true } "#; let input = Level::Error.title("unused optional dependency").snippet( Snippet::source(source) .line_start(4) .annotation( Level::Error .span(41..119) .label("I need this to be really long so I can test overlaps"), ) .annotation( Level::Error .span(8..102) .label("I need this to be really long so I can test overlaps"), ) .annotation( Level::Info .span(27..42) .label("This should also be long but not too long"), ), ); let expected = str![[r#" error: unused optional dependency | 4 | bar = { version = "0.1.0", optional = true } | _________^__________________--------------^ | | | | | |_________| info: This should also be long but not too long | || 5 | || this is another line 6 | || so is this 7 | || bar = { version = "0.1.0", optional = true } | ||_________________________^________________^ I need this to be really long so I can test overlaps | |__________________________| | I need this to be really long so I can test overlaps | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn three_multi_and_single() { let source = r#"bar = { version = "0.1.0", optional = true } this is another line so is this bar = { version = "0.1.0", optional = true } this is another line "#; let input = Level::Error.title("unused optional dependency").snippet( Snippet::source(source) .line_start(4) .annotation( Level::Error .span(41..119) .label("I need this to be really long so I can test overlaps"), ) .annotation( Level::Error .span(8..102) .label("I need this to be really long so I can test overlaps"), ) .annotation( Level::Error .span(48..126) .label("I need this to be really long so I can test overlaps"), ) .annotation( Level::Info .span(27..42) .label("This should also be long but not too long"), ), ); let expected = str![[r#" error: unused optional dependency | 4 | bar = { version = "0.1.0", optional = true } | __________^__________________--------------^ | | | | | |__________| info: This should also be long but not too long | || 5 | || this is another line | || ____^ 6 | ||| so is this 7 | ||| bar = { version = "0.1.0", optional = true } | |||_________________________^________________^ I need this to be really long so I can test overlaps | |_|_________________________| | | I need this to be really long so I can test overlaps 8 | | this is another line | |____^ I need this to be really long so I can test overlaps | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn origin_correct_start_line() { let source = "aaa\nbbb\nccc\nddd\n"; let input = Level::Error.title("title").snippet( Snippet::source(source) .origin("origin.txt") .fold(false) .annotation(Level::Error.span(8..8 + 3).label("annotation")), ); let expected = str![[r#" error: title --> origin.txt:3:1 | 1 | aaa 2 | bbb 3 | ccc | ^^^ annotation 4 | ddd | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn origin_correct_mid_line() { let source = "aaa\nbbb\nccc\nddd\n"; let input = Level::Error.title("title").snippet( Snippet::source(source) .origin("origin.txt") .fold(false) .annotation(Level::Error.span(8 + 1..8 + 3).label("annotation")), ); let expected = str![[r#" error: title --> origin.txt:3:2 | 1 | aaa 2 | bbb 3 | ccc | ^^ annotation 4 | ddd | "#]]; let renderer = Renderer::plain(); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn long_line_cut() { let source = "abcd abcd abcd abcd abcd abcd abcd"; let input = Level::Error.title("").snippet( Snippet::source(source) .line_start(1) .annotation(Level::Error.span(0..4)), ); let expected = str![[r#" error | 1 | abcd abcd a... | ^^^^ | "#]]; let renderer = Renderer::plain().term_width(18); assert_data_eq!(renderer.render(input).to_string(), expected); } #[test] fn long_line_cut_custom() { let source = "abcd abcd abcd abcd abcd abcd abcd"; let input = Level::Error.title("").snippet( Snippet::source(source) .line_start(1) .annotation(Level::Error.span(0..4)), ); // This trims a little less because `…` is visually smaller than `...`. let expected = str![[r#" error | 1 | abcd abcd abc… | ^^^^ | "#]]; let renderer = Renderer::plain().term_width(18).cut_indicator("…"); assert_data_eq!(renderer.render(input).to_string(), expected); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_annotate_snippets/tests/examples.rs
crates/ruff_annotate_snippets/tests/examples.rs
#[test] fn expected_type() { let target = "expected_type"; let expected = snapbox::file!["../examples/expected_type.svg": TermSvg]; assert_example(target, expected); } #[test] fn footer() { let target = "footer"; let expected = snapbox::file!["../examples/footer.svg": TermSvg]; assert_example(target, expected); } #[test] fn format() { let target = "format"; let expected = snapbox::file!["../examples/format.svg": TermSvg]; assert_example(target, expected); } #[test] fn multislice() { let target = "multislice"; let expected = snapbox::file!["../examples/multislice.svg": TermSvg]; assert_example(target, expected); } #[track_caller] fn assert_example(target: &str, expected: snapbox::Data) { let bin_path = snapbox::cmd::compile_example(target, ["--features=testing-colors"]).unwrap(); snapbox::cmd::Command::new(bin_path) .env("CLICOLOR_FORCE", "1") .assert() .success() .stdout_eq(expected.raw()); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_annotate_snippets/tests/fixtures/deserialize.rs
crates/ruff_annotate_snippets/tests/fixtures/deserialize.rs
use serde::Deserialize; use std::ops::Range; use ruff_annotate_snippets::renderer::DEFAULT_TERM_WIDTH; use ruff_annotate_snippets::{Annotation, Level, Message, Renderer, Snippet}; #[derive(Deserialize)] pub(crate) struct Fixture { #[serde(default)] pub(crate) renderer: RendererDef, pub(crate) message: MessageDef, } #[derive(Deserialize)] pub struct MessageDef { #[serde(with = "LevelDef")] pub level: Level, pub title: String, #[serde(default)] pub id: Option<String>, #[serde(default)] pub footer: Vec<MessageDef>, pub snippets: Vec<SnippetDef>, } impl<'a> From<&'a MessageDef> for Message<'a> { fn from(val: &'a MessageDef) -> Self { let MessageDef { level, title, id, footer, snippets, } = val; let mut message = level.title(title); if let Some(id) = id { message = message.id(id); } message = message.snippets(snippets.iter().map(Snippet::from)); message = message.footers(footer.iter().map(Into::into)); message } } #[derive(Deserialize)] pub struct SnippetDef { pub source: String, pub line_start: usize, pub origin: Option<String>, pub annotations: Vec<AnnotationDef>, #[serde(default)] pub fold: bool, } impl<'a> From<&'a SnippetDef> for Snippet<'a> { fn from(val: &'a SnippetDef) -> Self { let SnippetDef { source, line_start, origin, annotations, fold, } = val; let mut snippet = Snippet::source(source).line_start(*line_start).fold(*fold); if let Some(origin) = origin { snippet = snippet.origin(origin); } snippet = snippet.annotations(annotations.iter().map(Into::into)); snippet } } #[derive(Deserialize)] pub struct AnnotationDef { pub range: Range<usize>, pub label: String, #[serde(with = "LevelDef")] pub level: Level, } impl<'a> From<&'a AnnotationDef> for Annotation<'a> { fn from(val: &'a AnnotationDef) -> Self { let AnnotationDef { range, label, level, } = val; level.span(range.start..range.end).label(label) } } #[allow(dead_code)] #[derive(Deserialize)] #[serde(remote = "Level")] enum LevelDef { Error, Warning, Info, Note, Help, } #[derive(Default, Deserialize)] pub struct RendererDef { #[serde(default)] anonymized_line_numbers: bool, #[serde(default)] term_width: Option<usize>, #[serde(default)] color: bool, } impl From<RendererDef> for Renderer { fn from(val: RendererDef) -> Self { let RendererDef { anonymized_line_numbers, term_width, color, } = val; let renderer = if color { Renderer::styled() } else { Renderer::plain() }; renderer .anonymized_line_numbers(anonymized_line_numbers) .term_width(term_width.unwrap_or(DEFAULT_TERM_WIDTH)) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_annotate_snippets/tests/fixtures/main.rs
crates/ruff_annotate_snippets/tests/fixtures/main.rs
mod deserialize; use crate::deserialize::Fixture; use ruff_annotate_snippets::{Message, Renderer}; use snapbox::Data; use snapbox::data::DataFormat; use std::error::Error; fn main() { tryfn::Harness::new("tests/fixtures/", setup, test) .select(["*/*.toml"]) .test(); } fn setup(input_path: std::path::PathBuf) -> tryfn::Case { let parent = input_path .parent() .unwrap() .file_name() .unwrap() .to_str() .unwrap(); let file_name = input_path.file_name().unwrap().to_str().unwrap(); let name = format!("{parent}/{file_name}"); let expected = Data::read_from(&input_path.with_extension("svg"), None); tryfn::Case { name, fixture: input_path, expected, } } fn test(input_path: &std::path::Path) -> Result<Data, Box<dyn Error>> { let src = std::fs::read_to_string(input_path)?; let fixture: Fixture = toml::from_str(&src)?; let renderer: Renderer = fixture.renderer.into(); let message: Message<'_> = (&fixture.message).into(); let actual = renderer.render(message).to_string(); Ok(Data::from(actual).coerce_to(DataFormat::TermSvg)) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_annotate_snippets/examples/expected_type.rs
crates/ruff_annotate_snippets/examples/expected_type.rs
use ruff_annotate_snippets::{Level, Renderer, Snippet}; fn main() { let source = r#" annotations: vec![SourceAnnotation { label: "expected struct `annotate_snippets::snippet::Slice`, found reference" , range: <22, 25>,"#; let message = Level::Error.title("expected type, found `22`").snippet( Snippet::source(source) .line_start(26) .origin("examples/footer.rs") .fold(true) .annotation( Level::Error .span(193..195) .label("expected struct `annotate_snippets::snippet::Slice`, found reference"), ) .annotation(Level::Info.span(34..50).label("while parsing this struct")), ); let renderer = Renderer::styled(); anstream::println!("{}", renderer.render(message)); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_annotate_snippets/examples/footer.rs
crates/ruff_annotate_snippets/examples/footer.rs
use ruff_annotate_snippets::{Level, Renderer, Snippet}; fn main() { let message = Level::Error .title("mismatched types") .id("E0308") .snippet( Snippet::source(" slices: vec![\"A\",") .line_start(13) .origin("src/multislice.rs") .annotation(Level::Error.span(21..24).label( "expected struct `annotate_snippets::snippet::Slice`, found reference", )), ) .footer(Level::Note.title( "expected type: `snippet::Annotation`\n found type: `__&__snippet::Annotation`", )); let renderer = Renderer::styled(); anstream::println!("{}", renderer.render(message)); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_annotate_snippets/examples/format.rs
crates/ruff_annotate_snippets/examples/format.rs
use ruff_annotate_snippets::{Level, Renderer, Snippet}; fn main() { let source = r#") -> Option<String> { for ann in annotations { match (ann.range.0, ann.range.1) { (None, None) => continue, (Some(start), Some(end)) if start > end_index => continue, (Some(start), Some(end)) if start >= start_index => { let label = if let Some(ref label) = ann.label { format!(" {}", label) } else { String::from("") }; return Some(format!( "{}{}{}", " ".repeat(start - start_index), "^".repeat(end - start), label )); } _ => continue, } }"#; let message = Level::Error.title("mismatched types").id("E0308").snippet( Snippet::source(source) .line_start(51) .origin("src/format.rs") .annotation( Level::Warning .span(5..19) .label("expected `Option<String>` because of return type"), ) .annotation( Level::Error .span(26..724) .label("expected enum `std::option::Option`"), ), ); let renderer = Renderer::styled(); anstream::println!("{}", renderer.render(message)); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_annotate_snippets/examples/multislice.rs
crates/ruff_annotate_snippets/examples/multislice.rs
use ruff_annotate_snippets::{Level, Renderer, Snippet}; fn main() { let message = Level::Error .title("mismatched types") .snippet( Snippet::source("Foo") .line_start(51) .origin("src/format.rs"), ) .snippet( Snippet::source("Faa") .line_start(129) .origin("src/display.rs"), ); let renderer = Renderer::styled(); anstream::println!("{}", renderer.render(message)); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/reference.rs
crates/ruff_python_semantic/src/reference.rs
use std::ops::Deref; use bitflags::bitflags; use ruff_index::{IndexSlice, IndexVec, newtype_index}; use ruff_python_ast::ExprContext; use ruff_text_size::{Ranged, TextRange}; use crate::scope::ScopeId; use crate::{Exceptions, NodeId, SemanticModelFlags}; /// A resolved read reference to a name in a program. #[derive(Debug, Clone)] pub struct ResolvedReference { /// The expression that the reference occurs in. `None` if the reference is a global /// reference or a reference via an augmented assignment. node_id: Option<NodeId>, /// The scope in which the reference is defined. scope_id: ScopeId, /// The expression context in which the reference occurs (e.g., `Load`, `Store`, `Del`). ctx: ExprContext, /// The model state in which the reference occurs. flags: SemanticModelFlags, /// The range of the reference in the source code. range: TextRange, } impl ResolvedReference { /// The expression that the reference occurs in. pub const fn expression_id(&self) -> Option<NodeId> { self.node_id } /// The scope in which the reference is defined. pub const fn scope_id(&self) -> ScopeId { self.scope_id } /// Return `true` if the reference occurred in a `Load` operation. pub const fn is_load(&self) -> bool { self.ctx.is_load() } /// Return `true` if the context is in a typing context. pub const fn in_typing_context(&self) -> bool { self.flags.intersects(SemanticModelFlags::TYPING_CONTEXT) } /// Return `true` if the context is in a runtime context. pub const fn in_runtime_context(&self) -> bool { !self.flags.intersects(SemanticModelFlags::TYPING_CONTEXT) } /// Return `true` if the context is in a typing-only type annotation. pub const fn in_typing_only_annotation(&self) -> bool { self.flags .intersects(SemanticModelFlags::TYPING_ONLY_ANNOTATION) } /// Return `true` if the context is in a runtime-required type annotation. pub const fn in_runtime_evaluated_annotation(&self) -> bool { self.flags .intersects(SemanticModelFlags::RUNTIME_EVALUATED_ANNOTATION) } /// Return `true` if the context is in a string type definition. pub const fn in_string_type_definition(&self) -> bool { self.flags .intersects(SemanticModelFlags::STRING_TYPE_DEFINITION) } /// Return `true` if the context is in any kind of type definition. pub const fn in_type_definition(&self) -> bool { self.flags.intersects(SemanticModelFlags::TYPE_DEFINITION) } /// Return `true` if the context is in a type-checking block. pub const fn in_type_checking_block(&self) -> bool { self.flags .intersects(SemanticModelFlags::TYPE_CHECKING_BLOCK) } /// Return `true` if the context is in the r.h.s. of an `__all__` definition. pub const fn in_dunder_all_definition(&self) -> bool { self.flags .intersects(SemanticModelFlags::DUNDER_ALL_DEFINITION) } /// Return `true` if the context is in the r.h.s. of a [PEP 613] type alias. /// /// [PEP 613]: https://peps.python.org/pep-0613/ pub const fn in_annotated_type_alias_value(&self) -> bool { self.flags .intersects(SemanticModelFlags::ANNOTATED_TYPE_ALIAS) } /// Return `true` if the context is inside an `assert` statement pub const fn in_assert_statement(&self) -> bool { self.flags.intersects(SemanticModelFlags::ASSERT_STATEMENT) } } impl Ranged for ResolvedReference { /// The range of the reference in the source code. fn range(&self) -> TextRange { self.range } } /// Id uniquely identifying a read reference in a program. #[newtype_index] pub struct ResolvedReferenceId; /// The references of a program indexed by [`ResolvedReferenceId`]. #[derive(Debug, Default)] pub(crate) struct ResolvedReferences(IndexVec<ResolvedReferenceId, ResolvedReference>); impl ResolvedReferences { /// Pushes a new [`ResolvedReference`] and returns its [`ResolvedReferenceId`]. pub(crate) fn push( &mut self, scope_id: ScopeId, node_id: Option<NodeId>, ctx: ExprContext, flags: SemanticModelFlags, range: TextRange, ) -> ResolvedReferenceId { self.0.push(ResolvedReference { node_id, scope_id, ctx, flags, range, }) } } impl Deref for ResolvedReferences { type Target = IndexSlice<ResolvedReferenceId, ResolvedReference>; fn deref(&self) -> &Self::Target { &self.0 } } /// An unresolved read reference to a name in a program. #[derive(Debug, Clone)] pub struct UnresolvedReference { /// The range of the reference in the source code. range: TextRange, /// The set of exceptions that were handled when resolution was attempted. exceptions: Exceptions, /// Flags indicating the context in which the reference occurs. flags: UnresolvedReferenceFlags, } impl UnresolvedReference { /// Returns the name of the reference. pub fn name<'a>(&self, source: &'a str) -> &'a str { &source[self.range] } /// The range of the reference in the source code. pub const fn range(&self) -> TextRange { self.range } /// The set of exceptions that were handled when resolution was attempted. pub const fn exceptions(&self) -> Exceptions { self.exceptions } /// Returns `true` if the unresolved reference may be resolved by a wildcard import. pub const fn is_wildcard_import(&self) -> bool { self.flags .contains(UnresolvedReferenceFlags::WILDCARD_IMPORT) } } bitflags! { #[derive(Copy, Clone, Debug)] pub struct UnresolvedReferenceFlags: u8 { /// The unresolved reference may be resolved by a wildcard import. /// /// For example, the reference `x` in the following code may be resolved by the wildcard /// import of `module`: /// ```python /// from module import * /// /// print(x) /// ``` const WILDCARD_IMPORT = 1 << 0; } } #[derive(Debug, Default)] pub(crate) struct UnresolvedReferences(Vec<UnresolvedReference>); impl UnresolvedReferences { /// Pushes a new [`UnresolvedReference`]. pub(crate) fn push( &mut self, range: TextRange, exceptions: Exceptions, flags: UnresolvedReferenceFlags, ) { self.0.push(UnresolvedReference { range, exceptions, flags, }); } } impl Deref for UnresolvedReferences { type Target = Vec<UnresolvedReference>; fn deref(&self) -> &Self::Target { &self.0 } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/star_import.rs
crates/ruff_python_semantic/src/star_import.rs
#[derive(Debug, Clone)] pub struct StarImport<'a> { /// The level of the import. `0` indicates an absolute import. pub level: u32, /// The module being imported. `None` indicates a wildcard import. pub module: Option<&'a str>, }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/imports.rs
crates/ruff_python_semantic/src/imports.rs
use ruff_macros::CacheKey; use ruff_python_ast::helpers::collect_import_from_member; use ruff_python_ast::name::QualifiedName; use crate::{AnyImport, Imported}; /// A list of names imported via any import statement. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, CacheKey)] pub struct NameImports(Vec<NameImport>); /// A representation of an individual name imported via any import statement. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, CacheKey)] pub enum NameImport { Import(ModuleNameImport), ImportFrom(MemberNameImport), } /// A representation of an individual name imported via an `import` statement. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, CacheKey)] pub struct ModuleNameImport { pub name: Alias, } /// A representation of an individual name imported via a `from ... import` statement. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, CacheKey)] pub struct MemberNameImport { pub module: Option<String>, pub name: Alias, pub level: u32, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, CacheKey)] pub struct Alias { pub name: String, pub as_name: Option<String>, } impl NameImports { pub fn into_imports(self) -> Vec<NameImport> { self.0 } } impl NameImport { /// Returns the name under which the member is bound (e.g., given `from foo import bar as baz`, returns `baz`). pub fn bound_name(&self) -> &str { match self { NameImport::Import(import) => { import.name.as_name.as_deref().unwrap_or(&import.name.name) } NameImport::ImportFrom(import_from) => import_from .name .as_name .as_deref() .unwrap_or(&import_from.name.name), } } /// Returns the [`QualifiedName`] of the imported name (e.g., given `from foo import bar as baz`, returns `["foo", "bar"]`). pub fn qualified_name(&self) -> QualifiedName<'_> { match self { NameImport::Import(import) => QualifiedName::user_defined(&import.name.name), NameImport::ImportFrom(import_from) => collect_import_from_member( import_from.level, import_from.module.as_deref(), import_from.name.name.as_str(), ), } } } impl NameImport { /// Returns `true` if the [`NameImport`] matches the specified name and binding. pub fn matches(&self, name: &str, binding: &AnyImport) -> bool { name == self.bound_name() && self.qualified_name() == *binding.qualified_name() } } impl ModuleNameImport { /// Creates a new `Import` to import the specified module. pub fn module(name: String) -> Self { Self { name: Alias { name, as_name: None, }, } } pub fn alias(name: String, as_name: String) -> Self { Self { name: Alias { name, as_name: Some(as_name), }, } } } impl MemberNameImport { /// Creates a new `ImportFrom` to import a member from the specified module. pub fn member(module: String, name: String) -> Self { Self { module: Some(module), name: Alias { name, as_name: None, }, level: 0, } } pub fn alias(module: String, name: String, as_name: String) -> Self { Self { module: Some(module), name: Alias { name, as_name: Some(as_name), }, level: 0, } } } impl std::fmt::Display for NameImport { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { NameImport::Import(import) => write!(f, "{import}"), NameImport::ImportFrom(import_from) => write!(f, "{import_from}"), } } } impl std::fmt::Display for ModuleNameImport { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "import {}", self.name.name)?; if let Some(as_name) = self.name.as_name.as_ref() { write!(f, " as {as_name}")?; } Ok(()) } } impl std::fmt::Display for MemberNameImport { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "from ")?; if self.level > 0 { write!(f, "{}", ".".repeat(self.level as usize))?; } if let Some(module) = self.module.as_ref() { write!(f, "{module}")?; } write!(f, " import {}", self.name.name)?; if let Some(as_name) = self.name.as_name.as_ref() { write!(f, " as {as_name}")?; } Ok(()) } } pub trait FutureImport { /// Returns `true` if this import is from the `__future__` module. fn is_future_import(&self) -> bool; } impl FutureImport for ModuleNameImport { fn is_future_import(&self) -> bool { self.name.name == "__future__" } } impl FutureImport for MemberNameImport { fn is_future_import(&self) -> bool { self.module.as_deref() == Some("__future__") } } impl FutureImport for NameImport { fn is_future_import(&self) -> bool { match self { NameImport::Import(import) => import.is_future_import(), NameImport::ImportFrom(import_from) => import_from.is_future_import(), } } } #[cfg(feature = "serde")] impl serde::Serialize for NameImports { fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { self.0.serialize(serializer) } } #[cfg(feature = "serde")] impl serde::Serialize for NameImport { fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { match self { NameImport::Import(import) => serializer.collect_str(import), NameImport::ImportFrom(import_from) => serializer.collect_str(import_from), } } } #[cfg(feature = "serde")] impl<'de> serde::de::Deserialize<'de> for NameImports { fn deserialize<D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { use ruff_python_ast::{self as ast, Stmt}; use ruff_python_parser::Parsed; struct AnyNameImportsVisitor; impl serde::de::Visitor<'_> for AnyNameImportsVisitor { type Value = NameImports; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("an import statement") } fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> { let body = ruff_python_parser::parse_module(value) .map(Parsed::into_suite) .map_err(E::custom)?; let [stmt] = body.as_slice() else { return Err(E::custom("Expected a single statement")); }; let imports = match stmt { Stmt::ImportFrom(ast::StmtImportFrom { module, names, level, range: _, node_index: _, }) => names .iter() .map(|name| { NameImport::ImportFrom(MemberNameImport { module: module.as_deref().map(ToString::to_string), name: Alias { name: name.name.to_string(), as_name: name.asname.as_deref().map(ToString::to_string), }, level: *level, }) }) .collect(), Stmt::Import(ast::StmtImport { names, range: _, node_index: _, }) => names .iter() .map(|name| { NameImport::Import(ModuleNameImport { name: Alias { name: name.name.to_string(), as_name: name.asname.as_deref().map(ToString::to_string), }, }) }) .collect(), _ => { return Err(E::custom("Expected an import statement")); } }; Ok(NameImports(imports)) } } deserializer.deserialize_str(AnyNameImportsVisitor) } } #[cfg(feature = "schemars")] impl schemars::JsonSchema for NameImports { fn schema_name() -> std::borrow::Cow<'static, str> { std::borrow::Cow::Borrowed("NameImports") } fn json_schema(_gen: &mut schemars::SchemaGenerator) -> schemars::Schema { schemars::json_schema!({ "type": "string" }) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/lib.rs
crates/ruff_python_semantic/src/lib.rs
pub mod analyze; mod binding; mod branches; pub mod cfg; mod context; mod definition; mod globals; mod imports; mod model; mod nodes; mod reference; mod scope; mod star_import; pub use binding::*; pub use branches::*; pub use context::*; pub use definition::*; pub use globals::*; pub use imports::*; pub use model::*; pub use nodes::*; pub use reference::*; pub use scope::*; pub use star_import::*;
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/globals.rs
crates/ruff_python_semantic/src/globals.rs
//! When building a semantic model, we often need to know which names in a given scope are declared //! as `global`. This module provides data structures for storing and querying the set of `global` //! names in a given scope. use std::ops::Index; use ruff_python_ast::{self as ast, Stmt}; use ruff_text_size::{Ranged, TextRange}; use rustc_hash::FxHashMap; use ruff_index::{IndexVec, newtype_index}; use ruff_python_ast::statement_visitor::{StatementVisitor, walk_stmt}; /// Id uniquely identifying the set of global names for a given scope. #[newtype_index] pub struct GlobalsId; #[derive(Debug, Default)] pub(crate) struct GlobalsArena<'a>(IndexVec<GlobalsId, Globals<'a>>); impl<'a> GlobalsArena<'a> { /// Inserts a new set of global names into the global names arena and returns its unique id. pub(crate) fn push(&mut self, globals: Globals<'a>) -> GlobalsId { self.0.push(globals) } } impl<'a> Index<GlobalsId> for GlobalsArena<'a> { type Output = Globals<'a>; #[inline] fn index(&self, index: GlobalsId) -> &Self::Output { &self.0[index] } } /// The set of global names for a given scope, represented as a map from the name of the global to /// the range of the declaration in the source code. #[derive(Debug)] pub struct Globals<'a>(FxHashMap<&'a str, TextRange>); impl<'a> Globals<'a> { /// Extracts the set of global names from a given scope, or return `None` if the scope does not /// contain any `global` declarations. pub fn from_body(body: &'a [Stmt]) -> Option<Self> { let mut builder = GlobalsVisitor::new(); builder.visit_body(body); builder.finish() } pub(crate) fn get(&self, name: &str) -> Option<TextRange> { self.0.get(name).copied() } pub(crate) fn iter(&self) -> impl Iterator<Item = (&&'a str, &TextRange)> + '_ { self.0.iter() } } /// Extracts the set of global names from a given scope. #[derive(Debug)] struct GlobalsVisitor<'a>(FxHashMap<&'a str, TextRange>); impl<'a> GlobalsVisitor<'a> { fn new() -> Self { Self(FxHashMap::default()) } fn finish(self) -> Option<Globals<'a>> { (!self.0.is_empty()).then_some(Globals(self.0)) } } impl<'a> StatementVisitor<'a> for GlobalsVisitor<'a> { fn visit_stmt(&mut self, stmt: &'a Stmt) { match stmt { Stmt::Global(ast::StmtGlobal { names, range: _, node_index: _, }) => { for name in names { self.0.insert(name.as_str(), name.range()); } } Stmt::FunctionDef(_) | Stmt::ClassDef(_) => { // Don't recurse. } _ => walk_stmt(self, stmt), } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/scope.rs
crates/ruff_python_semantic/src/scope.rs
use std::ops::{Deref, DerefMut}; use bitflags::bitflags; use ruff_python_ast as ast; use rustc_hash::FxHashMap; use ruff_index::{Idx, IndexSlice, IndexVec, newtype_index}; use crate::binding::BindingId; use crate::globals::GlobalsId; use crate::star_import::StarImport; #[derive(Debug)] pub struct Scope<'a> { /// The kind of scope. pub kind: ScopeKind<'a>, /// The parent scope, if any. pub parent: Option<ScopeId>, /// A list of star imports in this scope. These represent _module_ imports (e.g., `sys` in /// `from sys import *`), rather than individual bindings (e.g., individual members in `sys`). star_imports: Vec<StarImport<'a>>, /// A map from bound name to binding ID. bindings: FxHashMap<&'a str, BindingId>, /// A map from binding ID to binding ID that it shadows. /// /// For example: /// ```python /// def f(): /// x = 1 /// x = 2 /// ``` /// /// In this case, the binding created by `x = 2` shadows the binding created by `x = 1`. shadowed_bindings: FxHashMap<BindingId, BindingId>, /// Index into the globals arena, if the scope contains any globally-declared symbols. globals_id: Option<GlobalsId>, /// Flags for the [`Scope`]. flags: ScopeFlags, } impl<'a> Scope<'a> { pub fn global() -> Self { Scope { kind: ScopeKind::Module, parent: None, star_imports: Vec::default(), bindings: FxHashMap::default(), shadowed_bindings: FxHashMap::default(), globals_id: None, flags: ScopeFlags::empty(), } } pub fn local(kind: ScopeKind<'a>, parent: ScopeId) -> Self { Scope { kind, parent: Some(parent), star_imports: Vec::default(), bindings: FxHashMap::default(), shadowed_bindings: FxHashMap::default(), globals_id: None, flags: ScopeFlags::empty(), } } /// Returns the [id](BindingId) of the binding bound to the given name. pub fn get(&self, name: &str) -> Option<BindingId> { self.bindings.get(name).copied() } /// Adds a new binding with the given name to this scope. pub fn add(&mut self, name: &'a str, id: BindingId) -> Option<BindingId> { if let Some(shadowed) = self.bindings.insert(name, id) { self.shadowed_bindings.insert(id, shadowed); Some(shadowed) } else { None } } /// Returns `true` if this scope has a binding with the given name. pub fn has(&self, name: &str) -> bool { self.bindings.contains_key(name) } /// Returns the IDs of all bindings defined in this scope. pub fn binding_ids(&self) -> impl Iterator<Item = BindingId> + '_ { self.bindings.values().copied() } /// Returns a tuple of the name and ID of all bindings defined in this scope. pub fn bindings(&self) -> impl Iterator<Item = (&'a str, BindingId)> + '_ { self.bindings.iter().map(|(&name, &id)| (name, id)) } /// Like [`Scope::get`], but returns all bindings with the given name, including /// those that were shadowed by later bindings. pub fn get_all(&self, name: &str) -> impl Iterator<Item = BindingId> + '_ { std::iter::successors(self.bindings.get(name).copied(), |id| { self.shadowed_bindings.get(id).copied() }) } /// Like [`Scope::bindings`], but returns all bindings added to the scope, including those that /// were shadowed by later bindings. pub fn all_bindings(&self) -> impl Iterator<Item = (&str, BindingId)> + '_ { self.bindings.iter().flat_map(|(&name, &id)| { std::iter::successors(Some(id), |id| self.shadowed_bindings.get(id).copied()) .map(move |id| (name, id)) }) } /// Returns the ID of the binding that the given binding shadows, if any. pub fn shadowed_binding(&self, id: BindingId) -> Option<BindingId> { self.shadowed_bindings.get(&id).copied() } /// Returns an iterator over all bindings that the given binding shadows, including itself. pub fn shadowed_bindings(&self, id: BindingId) -> impl Iterator<Item = BindingId> + '_ { std::iter::successors(Some(id), |id| self.shadowed_bindings.get(id).copied()) } /// Adds a reference to a star import (e.g., `from sys import *`) to this scope. pub fn add_star_import(&mut self, import: StarImport<'a>) { self.star_imports.push(import); } /// Returns `true` if this scope contains a star import (e.g., `from sys import *`). pub fn uses_star_imports(&self) -> bool { !self.star_imports.is_empty() } /// Set the globals pointer for this scope. pub(crate) fn set_globals_id(&mut self, globals: GlobalsId) { self.globals_id = Some(globals); } /// Returns the globals pointer for this scope. pub(crate) fn globals_id(&self) -> Option<GlobalsId> { self.globals_id } /// Sets the [`ScopeFlags::USES_LOCALS`] flag. pub fn set_uses_locals(&mut self) { self.flags.insert(ScopeFlags::USES_LOCALS); } /// Returns `true` if this scope uses locals (e.g., `locals()`). pub const fn uses_locals(&self) -> bool { self.flags.intersects(ScopeFlags::USES_LOCALS) } } bitflags! { /// Flags on a [`Scope`]. #[derive(Debug, Default, Copy, Clone, Eq, PartialEq)] pub struct ScopeFlags: u8 { /// The scope uses locals (e.g., `locals()`). const USES_LOCALS = 1 << 0; } } #[derive(Clone, Copy, Debug, is_macro::Is)] pub enum ScopeKind<'a> { Class(&'a ast::StmtClassDef), /// The implicit `__class__` scope surrounding a method which allows code in the /// method to access `__class__` at runtime. The closure sits in between the class /// scope and the function scope. /// /// Parameter defaults in methods cannot access `__class__`: /// /// ```pycon /// >>> class Bar: /// ... def method(self, x=__class__): ... /// ... /// Traceback (most recent call last): /// File "<python-input-6>", line 1, in <module> /// class Bar: /// def method(self, x=__class__): ... /// File "<python-input-6>", line 2, in Bar /// def method(self, x=__class__): ... /// ^^^^^^^^^ /// NameError: name '__class__' is not defined /// ``` /// /// However, type parameters in methods *can* access `__class__`: /// /// ```pycon /// >>> class Foo: /// ... def bar[T: __class__](): ... /// ... /// >>> Foo.bar.__type_params__[0].__bound__ /// <class '__main__.Foo'> /// ``` /// /// Note that this is still not 100% accurate! At runtime, the implicit `__class__` /// closure is only added if the name `super` (has to be a name -- `builtins.super` /// and similar don't count!) or the name `__class__` is used in any method of the /// class. However, accurately emulating that would be both complex and probably /// quite expensive unless we moved to a double-traversal of each scope similar to /// ty. It would also only matter in extreme and unlikely edge cases. So we ignore /// that subtlety for now. /// /// See <https://docs.python.org/3/reference/datamodel.html#creating-the-class-object>. DunderClassCell, Function(&'a ast::StmtFunctionDef), Generator { kind: GeneratorKind, is_async: bool, }, Module, /// A Python 3.12+ [annotation scope](https://docs.python.org/3/reference/executionmodel.html#annotation-scopes) Type, Lambda(&'a ast::ExprLambda), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GeneratorKind { Generator, ListComprehension, DictComprehension, SetComprehension, } /// Id uniquely identifying a scope in a program. /// /// Using a `u32` is sufficient because Ruff only supports parsing documents with a size of max `u32::max` /// and it is impossible to have more scopes than characters in the file (because defining a function or class /// requires more than one character). #[newtype_index] pub struct ScopeId; impl ScopeId { /// Returns the ID for the global scope #[inline] pub const fn global() -> Self { ScopeId::from_u32(0) } /// Returns `true` if this is the id of the global scope pub const fn is_global(&self) -> bool { self.index() == 0 } } /// The scopes of a program indexed by [`ScopeId`] #[derive(Debug)] pub struct Scopes<'a>(IndexVec<ScopeId, Scope<'a>>); impl<'a> Scopes<'a> { /// Returns a reference to the global scope pub(crate) fn global(&self) -> &Scope<'a> { &self[ScopeId::global()] } /// Returns a mutable reference to the global scope pub(crate) fn global_mut(&mut self) -> &mut Scope<'a> { &mut self[ScopeId::global()] } /// Pushes a new scope and returns its unique id pub(crate) fn push_scope(&mut self, kind: ScopeKind<'a>, parent: ScopeId) -> ScopeId { let next_id = ScopeId::new(self.0.len()); self.0.push(Scope::local(kind, parent)); next_id } /// Returns an iterator over all [`ScopeId`] ancestors, starting from the given [`ScopeId`]. pub fn ancestor_ids(&self, scope_id: ScopeId) -> impl Iterator<Item = ScopeId> + '_ { std::iter::successors(Some(scope_id), |&scope_id| self[scope_id].parent) } /// Returns an iterator over all [`Scope`] ancestors, starting from the given [`ScopeId`]. pub fn ancestors(&self, scope_id: ScopeId) -> impl Iterator<Item = &Scope<'a>> + '_ { std::iter::successors(Some(&self[scope_id]), |&scope| { scope.parent.map(|scope_id| &self[scope_id]) }) } } impl Default for Scopes<'_> { fn default() -> Self { Self(IndexVec::from_raw(vec![Scope::global()])) } } impl<'a> Deref for Scopes<'a> { type Target = IndexSlice<ScopeId, Scope<'a>>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for Scopes<'_> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/model.rs
crates/ruff_python_semantic/src/model.rs
use std::path::Path; use bitflags::bitflags; use rustc_hash::FxHashMap; use ruff_python_ast::helpers::{from_relative_import, map_subscript}; use ruff_python_ast::name::{QualifiedName, UnqualifiedName}; use ruff_python_ast::{self as ast, Expr, ExprContext, PySourceType, Stmt}; use ruff_text_size::{Ranged, TextRange, TextSize}; use crate::Imported; use crate::analyze::visibility; use crate::binding::{ Binding, BindingFlags, BindingId, BindingKind, Bindings, Exceptions, FromImport, Import, SubmoduleImport, }; use crate::branches::{BranchId, Branches}; use crate::context::ExecutionContext; use crate::definition::{Definition, DefinitionId, Definitions, Member, Module}; use crate::globals::{Globals, GlobalsArena}; use crate::nodes::{NodeId, NodeRef, Nodes}; use crate::reference::{ ResolvedReference, ResolvedReferenceId, ResolvedReferences, UnresolvedReference, UnresolvedReferenceFlags, UnresolvedReferences, }; use crate::scope::{Scope, ScopeId, ScopeKind, Scopes}; pub mod all; /// A semantic model for a Python module, to enable querying the module's semantic information. pub struct SemanticModel<'a> { typing_modules: &'a [String], module: Module<'a>, /// Stack of all AST nodes in the program. nodes: Nodes<'a>, /// The ID of the current AST node. node_id: Option<NodeId>, /// Stack of all branches in the program. branches: Branches, /// The ID of the current branch. branch_id: Option<BranchId>, /// Stack of all scopes, along with the identifier of the current scope. pub scopes: Scopes<'a>, pub scope_id: ScopeId, /// Stack of all definitions created in any scope, at any point in execution. pub definitions: Definitions<'a>, /// The ID of the current definition. pub definition_id: DefinitionId, /// A stack of all bindings created in any scope, at any point in execution. pub bindings: Bindings<'a>, /// Stack of all references created in any scope, at any point in execution. resolved_references: ResolvedReferences, /// Stack of all unresolved references created in any scope, at any point in execution. unresolved_references: UnresolvedReferences, /// Arena of global bindings. globals: GlobalsArena<'a>, /// Map from binding ID to binding ID that it shadows (in another scope). /// /// For example, given: /// ```python /// import x /// /// def f(): /// x = 1 /// ``` /// /// In this case, the binding created by `x = 1` shadows the binding created by `import x`, /// despite the fact that they're in different scopes. pub shadowed_bindings: FxHashMap<BindingId, BindingId>, /// Map from binding index to indexes of bindings that annotate it (in the same scope). /// /// For example, given: /// ```python /// x = 1 /// x: int /// ``` /// /// In this case, the binding created by `x = 1` is annotated by the binding created by /// `x: int`. We don't consider the latter binding to _shadow_ the former, because it doesn't /// change the value of the binding, and so we don't store in on the scope. But we _do_ want to /// track the annotation in some form, since it's a reference to `x`. /// /// Note that, given: /// ```python /// x: int /// ``` /// /// In this case, we _do_ store the binding created by `x: int` directly on the scope, and not /// as a delayed annotation. Annotations are thus treated as bindings only when they are the /// first binding in a scope; any annotations that follow are treated as "delayed" annotations. delayed_annotations: FxHashMap<BindingId, Vec<BindingId>>, /// Map from binding ID to the IDs of all scopes in which it is declared a `global` or /// `nonlocal`. /// /// For example, given: /// ```python /// x = 1 /// /// def f(): /// global x /// ``` /// /// In this case, the binding created by `x = 1` is rebound within the scope created by `f` /// by way of the `global x` statement. rebinding_scopes: FxHashMap<BindingId, Vec<ScopeId>>, /// Flags for the semantic model. pub flags: SemanticModelFlags, /// Modules that have been seen by the semantic model. pub seen: Modules, /// Exceptions that are handled by the current `try` block. /// /// For example, if we're visiting the `x = 1` assignment below, /// `AttributeError` is considered to be a "handled exception", /// but `TypeError` is not: /// /// ```py /// try: /// try: /// foo() /// except TypeError: /// pass /// except AttributeError: /// pass /// ``` pub handled_exceptions: Vec<Exceptions>, /// Map from [`ast::ExprName`] node (represented as a [`NameId`]) to the [`Binding`] to which /// it resolved (represented as a [`BindingId`]). resolved_names: FxHashMap<NameId, BindingId>, } impl<'a> SemanticModel<'a> { pub fn new(typing_modules: &'a [String], path: &Path, module: Module<'a>) -> Self { Self { typing_modules, module, nodes: Nodes::default(), node_id: None, branches: Branches::default(), branch_id: None, scopes: Scopes::default(), scope_id: ScopeId::global(), definitions: Definitions::for_module(module), definition_id: DefinitionId::module(), bindings: Bindings::default(), resolved_references: ResolvedReferences::default(), unresolved_references: UnresolvedReferences::default(), globals: GlobalsArena::default(), shadowed_bindings: FxHashMap::default(), delayed_annotations: FxHashMap::default(), rebinding_scopes: FxHashMap::default(), flags: SemanticModelFlags::new(path), seen: Modules::empty(), handled_exceptions: Vec::default(), resolved_names: FxHashMap::default(), } } /// Return the [`Binding`] for the given [`BindingId`]. #[inline] pub fn binding(&self, id: BindingId) -> &Binding<'a> { &self.bindings[id] } /// Resolve the [`ResolvedReference`] for the given [`ResolvedReferenceId`]. #[inline] pub fn reference(&self, id: ResolvedReferenceId) -> &ResolvedReference { &self.resolved_references[id] } /// Return `true` if the `Expr` is a reference to `typing.${target}`. pub fn match_typing_expr(&self, expr: &Expr, target: &str) -> bool { self.seen_typing() && self .resolve_qualified_name(expr) .is_some_and(|qualified_name| { self.match_typing_qualified_name(&qualified_name, target) }) } /// Return `true` if the call path is a reference to `typing.${target}`. pub fn match_typing_qualified_name( &self, qualified_name: &QualifiedName, target: &str, ) -> bool { if matches!( qualified_name.segments(), ["typing" | "_typeshed" | "typing_extensions", member] if *member == target ) { return true; } if self.typing_modules.iter().any(|module| { let module = QualifiedName::from_dotted_name(module); qualified_name == &module.append_member(target) }) { return true; } false } /// Return an iterator over the set of `typing` modules allowed in the semantic model. pub fn typing_modules(&self) -> impl Iterator<Item = &'a str> { ["typing", "_typeshed", "typing_extensions"] .iter() .copied() .chain(self.typing_modules.iter().map(String::as_str)) } /// Create a new [`Binding`] for a builtin. pub fn push_builtin(&mut self) -> BindingId { self.bindings.push(Binding { range: TextRange::default(), kind: BindingKind::Builtin, scope: ScopeId::global(), references: Vec::new(), flags: BindingFlags::empty(), source: None, context: ExecutionContext::Runtime, exceptions: Exceptions::empty(), }) } /// Create a new [`Binding`] for the given `name` and `range`. pub fn push_binding( &mut self, range: TextRange, kind: BindingKind<'a>, flags: BindingFlags, ) -> BindingId { self.bindings.push(Binding { range, kind, flags, references: Vec::new(), scope: self.scope_id, source: self.node_id, context: self.execution_context(), exceptions: self.exceptions(), }) } /// Return the [`BindingId`] that the given [`BindingId`] shadows, if any. /// /// Note that this will only return bindings that are shadowed by a binding in a parent scope. pub fn shadowed_binding(&self, binding_id: BindingId) -> Option<BindingId> { self.shadowed_bindings.get(&binding_id).copied() } /// Return `true` if `member` is bound as a builtin *in the scope we are currently visiting*. /// /// Note that a "builtin binding" does *not* include explicit lookups via the `builtins` /// module, e.g. `import builtins; builtins.open`. It *only* includes the bindings /// that are pre-populated in Python's global scope before any imports have taken place. pub fn has_builtin_binding(&self, member: &str) -> bool { self.has_builtin_binding_in_scope(member, self.scope_id) } /// Return `true` if `member` is bound as a builtin *in a given scope*. /// /// Note that a "builtin binding" does *not* include explicit lookups via the `builtins` /// module, e.g. `import builtins; builtins.open`. It *only* includes the bindings /// that are pre-populated in Python's global scope before any imports have taken place. pub fn has_builtin_binding_in_scope(&self, member: &str, scope: ScopeId) -> bool { self.lookup_symbol_in_scope(member, scope, false) .map(|binding_id| &self.bindings[binding_id]) .is_some_and(|binding| binding.kind.is_builtin()) } /// If `expr` is a reference to a builtins symbol, /// return the name of that symbol. Else, return `None`. /// /// This method returns `true` both for "builtin bindings" /// (present even without any imports, e.g. `open()`), and for explicit lookups /// via the `builtins` module (e.g. `import builtins; builtins.open()`). pub fn resolve_builtin_symbol<'expr>(&'a self, expr: &'expr Expr) -> Option<&'a str> where 'expr: 'a, { // Fast path: we only need to worry about name expressions if !self.seen_module(Modules::BUILTINS) { let name = &expr.as_name_expr()?.id; return if self.has_builtin_binding(name) { Some(name) } else { None }; } // Slow path: we have to consider names and attributes let qualified_name = self.resolve_qualified_name(expr)?; match qualified_name.segments() { ["" | "builtins", name] => Some(*name), _ => None, } } /// Return `true` if `expr` is a reference to `builtins.$target`, /// i.e. either `object` (where `object` is not overridden in the global scope), /// or `builtins.object` (where `builtins` is imported as a module at the top level) pub fn match_builtin_expr(&self, expr: &Expr, symbol: &str) -> bool { debug_assert!(!symbol.contains('.')); // fast path with more short-circuiting if !self.seen_module(Modules::BUILTINS) { let Expr::Name(ast::ExprName { id, .. }) = expr else { return false; }; return id == symbol && self.has_builtin_binding(symbol); } // slow path: we need to consider attribute accesses and aliased imports let Some(qualified_name) = self.resolve_qualified_name(expr) else { return false; }; matches!(qualified_name.segments(), ["" | "builtins", name] if *name == symbol) } /// Return `true` if `member` is an "available" symbol, i.e., a symbol that has not been bound /// in the current scope currently being visited, or in any containing scope. pub fn is_available(&self, member: &str) -> bool { self.is_available_in_scope(member, self.scope_id) } /// Return `true` if `member` is an "available" symbol in a given scope, i.e., /// a symbol that has not been bound in that current scope, or in any containing scope. pub fn is_available_in_scope(&self, member: &str, scope_id: ScopeId) -> bool { self.lookup_symbol_in_scope(member, scope_id, false) .map(|binding_id| &self.bindings[binding_id]) .is_none_or(|binding| binding.kind.is_builtin()) } /// Resolve a `del` reference to `symbol` at `range`. pub fn resolve_del(&mut self, symbol: &str, range: TextRange) { let is_unbound = self.scopes[self.scope_id] .get(symbol) .is_none_or(|binding_id| { // Treat the deletion of a name as a reference to that name. self.add_local_reference(binding_id, ExprContext::Del, range); self.bindings[binding_id].is_unbound() }); // If the binding is unbound, we need to add an unresolved reference. if is_unbound { self.unresolved_references.push( range, self.exceptions(), UnresolvedReferenceFlags::empty(), ); } } /// Resolve a `load` reference to an [`ast::ExprName`]. pub fn resolve_load(&mut self, name: &ast::ExprName) -> ReadResult { // PEP 563 indicates that if a forward reference can be resolved in the module scope, we // should prefer it over local resolutions. if self.in_forward_reference() { if let Some(binding_id) = self.scopes.global().get(name.id.as_str()) { if !self.bindings[binding_id].is_unbound() { // Mark the binding as used. let reference_id = self.resolved_references.push( ScopeId::global(), self.node_id, ExprContext::Load, self.flags, name.range, ); self.bindings[binding_id].references.push(reference_id); // Mark any submodule aliases as used. if let Some(binding_id) = self.resolve_submodule(name.id.as_str(), ScopeId::global(), binding_id) { let reference_id = self.resolved_references.push( ScopeId::global(), self.node_id, ExprContext::Load, self.flags, name.range, ); self.bindings[binding_id].references.push(reference_id); } self.resolved_names.insert(name.into(), binding_id); return ReadResult::Resolved(binding_id); } } } let mut import_starred = false; let mut class_variables_visible = true; for (index, scope_id) in self.scopes.ancestor_ids(self.scope_id).enumerate() { let scope = &self.scopes[scope_id]; if scope.kind.is_class() { // Do not allow usages of class symbols unless it is the immediate parent // (excluding type scopes), e.g.: // // ```python // class Foo: // a = 0 // // b = a # allowed // def c(self, arg=a): # allowed // print(arg) // // def d(self): // print(a) # not allowed // ``` if !class_variables_visible { continue; } } // Allow class variables to be visible for an additional scope level // when a type scope is seen — this covers the type scope present between // function and class definitions and their parent class scope. // // Also allow an additional level beyond that to cover the implicit // `__class__` closure created around methods and enclosing the type scope. class_variables_visible = matches!( (scope.kind, index), (ScopeKind::Type, 0) | (ScopeKind::DunderClassCell, 1) ); if let Some(binding_id) = scope.get(name.id.as_str()) { // Mark the binding as used. let reference_id = self.resolved_references.push( self.scope_id, self.node_id, ExprContext::Load, self.flags, name.range, ); self.bindings[binding_id].references.push(reference_id); // Mark any submodule aliases as used. if let Some(binding_id) = self.resolve_submodule(name.id.as_str(), scope_id, binding_id) { let reference_id = self.resolved_references.push( self.scope_id, self.node_id, ExprContext::Load, self.flags, name.range, ); self.bindings[binding_id].references.push(reference_id); } match self.bindings[binding_id].kind { // If it's a type annotation, don't treat it as resolved. For example, given: // // ```python // name: str // print(name) // ``` // // The `name` in `print(name)` should be treated as unresolved, but the `name` in // `name: str` should be treated as used. // // Stub files are an exception. In a stub file, it _is_ considered valid to // resolve to a type annotation. BindingKind::Annotation if !self.in_stub_file() => continue, // If it's a deletion, don't treat it as resolved, since the name is now // unbound. For example, given: // // ```python // x = 1 // del x // print(x) // ``` // // The `x` in `print(x)` should be treated as unresolved. // // Similarly, given: // // ```python // try: // pass // except ValueError as x: // pass // // print(x) // // The `x` in `print(x)` should be treated as unresolved. BindingKind::Deletion | BindingKind::UnboundException(None) => { self.unresolved_references.push( name.range, self.exceptions(), UnresolvedReferenceFlags::empty(), ); return ReadResult::UnboundLocal(binding_id); } BindingKind::ConditionalDeletion(binding_id) => { self.unresolved_references.push( name.range, self.exceptions(), UnresolvedReferenceFlags::empty(), ); return ReadResult::UnboundLocal(binding_id); } // If we hit an unbound exception that shadowed a bound name, resole to the // bound name. For example, given: // // ```python // x = 1 // // try: // pass // except ValueError as x: // pass // // print(x) // ``` // // The `x` in `print(x)` should resolve to the `x` in `x = 1`. BindingKind::UnboundException(Some(binding_id)) => { // Mark the binding as used. let reference_id = self.resolved_references.push( self.scope_id, self.node_id, ExprContext::Load, self.flags, name.range, ); self.bindings[binding_id].references.push(reference_id); // Mark any submodule aliases as used. if let Some(binding_id) = self.resolve_submodule(name.id.as_str(), scope_id, binding_id) { let reference_id = self.resolved_references.push( self.scope_id, self.node_id, ExprContext::Load, self.flags, name.range, ); self.bindings[binding_id].references.push(reference_id); } self.resolved_names.insert(name.into(), binding_id); return ReadResult::Resolved(binding_id); } BindingKind::Global(Some(binding_id)) | BindingKind::Nonlocal(binding_id, _) => { // Mark the shadowed binding as used. let reference_id = self.resolved_references.push( self.scope_id, self.node_id, ExprContext::Load, self.flags, name.range, ); self.bindings[binding_id].references.push(reference_id); // Treat it as resolved. self.resolved_names.insert(name.into(), binding_id); return ReadResult::Resolved(binding_id); } _ => { // Otherwise, treat it as resolved. self.resolved_names.insert(name.into(), binding_id); return ReadResult::Resolved(binding_id); } } } // Allow usages of `__module__` and `__qualname__` within class scopes, e.g.: // // ```python // class Foo: // print(__qualname__) // ``` // // Intentionally defer this check to _after_ the standard `scope.get` logic, so that // we properly attribute reads to overridden class members, e.g.: // // ```python // class Foo: // __qualname__ = "Bar" // print(__qualname__) // ``` if index == 0 && scope.kind.is_class() { if matches!(name.id.as_str(), "__module__" | "__qualname__") { return ReadResult::ImplicitGlobal; } } import_starred = import_starred || scope.uses_star_imports(); } if import_starred { self.unresolved_references.push( name.range, self.exceptions(), UnresolvedReferenceFlags::WILDCARD_IMPORT, ); ReadResult::WildcardImport } else { self.unresolved_references.push( name.range, self.exceptions(), UnresolvedReferenceFlags::empty(), ); ReadResult::NotFound } } /// Lookup a symbol in the current scope. pub fn lookup_symbol(&self, symbol: &str) -> Option<BindingId> { self.lookup_symbol_in_scope(symbol, self.scope_id, self.in_forward_reference()) } /// Lookup a symbol in a certain scope /// /// This is a carbon copy of [`Self::resolve_load`], but /// doesn't add any read references to the resolved symbol. pub fn lookup_symbol_in_scope( &self, symbol: &str, scope_id: ScopeId, in_forward_reference: bool, ) -> Option<BindingId> { if in_forward_reference { if let Some(binding_id) = self.scopes.global().get(symbol) { if !self.bindings[binding_id].is_unbound() { return Some(binding_id); } } } let mut class_variables_visible = true; for (index, scope_id) in self.scopes.ancestor_ids(scope_id).enumerate() { let scope = &self.scopes[scope_id]; if scope.kind.is_class() { if !class_variables_visible { continue; } } class_variables_visible = matches!( (scope.kind, index), (ScopeKind::Type, 0) | (ScopeKind::DunderClassCell, 1) ); if let Some(binding_id) = scope.get(symbol) { match self.bindings[binding_id].kind { BindingKind::Annotation => continue, BindingKind::Deletion | BindingKind::UnboundException(None) => return None, BindingKind::ConditionalDeletion(binding_id) => return Some(binding_id), BindingKind::UnboundException(Some(binding_id)) => return Some(binding_id), _ => return Some(binding_id), } } if index == 0 && scope.kind.is_class() { if matches!(symbol, "__module__" | "__qualname__") { return None; } } } None } /// Simulates a runtime load of a given [`ast::ExprName`]. /// /// This should not be run until after all the bindings have been visited. /// /// The main purpose of this method and what makes this different /// from methods like [`SemanticModel::lookup_symbol`] and /// [`SemanticModel::resolve_name`] is that it may be used /// to perform speculative name lookups. /// /// In most cases a load can be accurately modeled simply by calling /// [`SemanticModel::resolve_name`] at the right time during semantic /// analysis, however for speculative lookups this is not the case, /// since we're aiming to change the semantic meaning of our load. /// E.g. we want to check what would happen if we changed a forward /// reference to an immediate load or vice versa. /// /// Use caution when utilizing this method, since it was primarily designed /// to work for speculative lookups from within type definitions, which /// happen to share some nice properties, where attaching each binding /// to a range in the source code and ordering those bindings based on /// that range is a good enough approximation of which bindings are /// available at runtime for which reference. /// /// References from within an [`ast::Comprehension`] can produce incorrect /// results when referring to a [`BindingKind::NamedExprAssignment`]. pub fn simulate_runtime_load( &self, name: &ast::ExprName, typing_only_bindings_status: TypingOnlyBindingsStatus, ) -> Option<BindingId> { self.simulate_runtime_load_at_location_in_scope( name.id.as_str(), name.range, self.scope_id, typing_only_bindings_status, ) } /// Simulates a runtime load of the given symbol. /// /// This should not be run until after all the bindings have been visited. /// /// The main purpose of this method and what makes this different from /// [`SemanticModel::lookup_symbol_in_scope`] is that it may be used to /// perform speculative name lookups. /// /// In most cases a load can be accurately modeled simply by calling /// [`SemanticModel::lookup_symbol`] at the right time during semantic /// analysis, however for speculative lookups this is not the case, /// since we're aiming to change the semantic meaning of our load. /// E.g. we want to check what would happen if we changed a forward /// reference to an immediate load or vice versa. /// /// Use caution when utilizing this method, since it was primarily designed /// to work for speculative lookups from within type definitions, which /// happen to share some nice properties, where attaching each binding /// to a range in the source code and ordering those bindings based on /// that range is a good enough approximation of which bindings are /// available at runtime for which reference. /// /// References from within an [`ast::Comprehension`] can produce incorrect /// results when referring to a [`BindingKind::NamedExprAssignment`]. pub fn simulate_runtime_load_at_location_in_scope( &self, symbol: &str, symbol_range: TextRange, scope_id: ScopeId, typing_only_bindings_status: TypingOnlyBindingsStatus, ) -> Option<BindingId> { let mut seen_function = false; let mut class_variables_visible = true; let mut source_order_sensitive_lookup = true; for (index, scope_id) in self.scopes.ancestor_ids(scope_id).enumerate() { let scope = &self.scopes[scope_id]; // Only once we leave a function scope and its enclosing type scope should // we stop doing source-order lookups. We could e.g. have nested classes // where we lookup symbols from the innermost class scope, which can only see // things from the outer class(es) that have been defined before the inner // class. Source-order lookups take advantage of the fact that most of the // bindings are created sequentially in source order, so if we want to // determine whether or not a given reference can refer to another binding // we can look at their text ranges to check whether or not the binding // could actually be referred to. This is not as robust as back-tracking // the AST, since that can properly take care of the few out-of order // corner-cases, but back-tracking the AST from the reference to the binding // is a lot more expensive than comparing a pair of text ranges. if seen_function && !scope.kind.is_type() { source_order_sensitive_lookup = false; } if scope.kind.is_class() { if !class_variables_visible { continue; } } class_variables_visible = matches!( (scope.kind, index), (ScopeKind::Type, 0) | (ScopeKind::DunderClassCell, 1) ); seen_function |= scope.kind.is_function(); if let Some(binding_id) = scope.get(symbol) { if source_order_sensitive_lookup { // we need to look through all the shadowed bindings // since we may be shadowing a source-order accurate // runtime binding with a source-order inaccurate one for shadowed_id in scope.shadowed_bindings(binding_id) { let binding = &self.bindings[shadowed_id]; if typing_only_bindings_status.is_disallowed() && binding.context.is_typing() { continue; }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/nodes.rs
crates/ruff_python_semantic/src/nodes.rs
use std::ops::Index; use ruff_index::{IndexVec, newtype_index}; use ruff_python_ast::{Expr, Stmt}; use ruff_text_size::{Ranged, TextRange}; use crate::BranchId; /// Id uniquely identifying an AST node in a program. /// /// Using a `u32` is sufficient because Ruff only supports parsing documents with a size of max /// `u32::max` and it is impossible to have more nodes than characters in the file. We use a /// `NonZeroU32` to take advantage of memory layout optimizations. #[newtype_index] #[derive(Ord, PartialOrd)] pub struct NodeId; /// An AST node in a program, along with a pointer to its parent node (if any). #[derive(Debug)] struct NodeWithParent<'a> { /// A pointer to the AST node. node: NodeRef<'a>, /// The ID of the parent of this node, if any. parent: Option<NodeId>, /// The branch ID of this node, if any. branch: Option<BranchId>, } /// The nodes of a program indexed by [`NodeId`] #[derive(Debug, Default)] pub struct Nodes<'a> { nodes: IndexVec<NodeId, NodeWithParent<'a>>, } impl<'a> Nodes<'a> { /// Inserts a new AST node into the tree and returns its unique ID. pub(crate) fn insert( &mut self, node: NodeRef<'a>, parent: Option<NodeId>, branch: Option<BranchId>, ) -> NodeId { self.nodes.push(NodeWithParent { node, parent, branch, }) } /// Return the [`NodeId`] of the parent node. #[inline] pub fn parent_id(&self, node_id: NodeId) -> Option<NodeId> { self.nodes[node_id].parent } /// Return the [`BranchId`] of the branch node. #[inline] pub(crate) fn branch_id(&self, node_id: NodeId) -> Option<BranchId> { self.nodes[node_id].branch } /// Returns an iterator over all [`NodeId`] ancestors, starting from the given [`NodeId`]. pub(crate) fn ancestor_ids(&self, node_id: NodeId) -> impl Iterator<Item = NodeId> + '_ { std::iter::successors(Some(node_id), |&node_id| self.nodes[node_id].parent) } } impl<'a> Index<NodeId> for Nodes<'a> { type Output = NodeRef<'a>; #[inline] fn index(&self, index: NodeId) -> &Self::Output { &self.nodes[index].node } } /// A reference to an AST node. Like [`ruff_python_ast::AnyNodeRef`], but wraps the node /// itself (like [`Stmt`]) rather than the narrowed type (like [`ruff_python_ast::StmtAssign`]). /// /// TODO(charlie): Replace with [`ruff_python_ast::AnyNodeRef`]. This requires migrating /// the rest of the codebase to use [`ruff_python_ast::AnyNodeRef`] and related abstractions, /// like [`ruff_python_ast::ExprRef`] instead of [`Expr`]. #[derive(Copy, Clone, Debug, PartialEq)] pub enum NodeRef<'a> { Stmt(&'a Stmt), Expr(&'a Expr), } impl<'a> NodeRef<'a> { /// Returns the [`Stmt`] if this is a statement, or `None` if the reference is to another /// kind of AST node. pub fn as_statement(&self) -> Option<&'a Stmt> { match self { NodeRef::Stmt(stmt) => Some(stmt), NodeRef::Expr(_) => None, } } /// Returns the [`Expr`] if this is a expression, or `None` if the reference is to another /// kind of AST node. pub fn as_expression(&self) -> Option<&'a Expr> { match self { NodeRef::Stmt(_) => None, NodeRef::Expr(expr) => Some(expr), } } pub fn is_statement(&self) -> bool { self.as_statement().is_some() } pub fn is_expression(&self) -> bool { self.as_expression().is_some() } } impl Ranged for NodeRef<'_> { fn range(&self) -> TextRange { match self { NodeRef::Stmt(stmt) => stmt.range(), NodeRef::Expr(expr) => expr.range(), } } } impl<'a> From<&'a Expr> for NodeRef<'a> { fn from(expr: &'a Expr) -> Self { NodeRef::Expr(expr) } } impl<'a> From<&'a Stmt> for NodeRef<'a> { fn from(stmt: &'a Stmt) -> Self { NodeRef::Stmt(stmt) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/definition.rs
crates/ruff_python_semantic/src/definition.rs
//! Definitions within a Python program. In this context, a "definition" is any named entity that //! can be documented, such as a module, class, or function. use std::fmt::Debug; use std::ops::Deref; use std::path::Path; use ruff_index::{IndexSlice, IndexVec, newtype_index}; use ruff_python_ast::name::QualifiedName; use ruff_python_ast::{self as ast, Stmt, StmtFunctionDef}; use ruff_text_size::{Ranged, TextRange}; use crate::SemanticModel; use crate::analyze::visibility::{ Visibility, class_visibility, function_visibility, is_property, method_visibility, module_visibility, }; use crate::model::all::DunderAllName; /// Id uniquely identifying a definition in a program. #[newtype_index] pub struct DefinitionId; impl DefinitionId { /// Returns the ID for the module definition. #[inline] pub const fn module() -> Self { DefinitionId::from_u32(0) } } /// A Python module can either be defined as a module path (i.e., the dot-separated path to the /// module) or, if the module can't be resolved, as a file path (i.e., the path to the file defining /// the module). #[derive(Debug, Copy, Clone)] pub enum ModuleSource<'a> { /// A module path is a dot-separated path to the module. Path(&'a [String]), /// A file path is the path to the file defining the module, often a script outside of a /// package. File(&'a Path), } #[derive(Debug, Copy, Clone, is_macro::Is)] pub enum ModuleKind { /// A Python file that represents a module within a package. Module, /// A Python file that represents the root of a package (i.e., an `__init__.py` file). Package, } /// A Python module. #[derive(Debug, Copy, Clone)] pub struct Module<'a> { pub kind: ModuleKind, pub source: ModuleSource<'a>, pub python_ast: &'a [Stmt], pub name: Option<&'a str>, } impl<'a> Module<'a> { /// Return the fully-qualified path of the module. pub const fn qualified_name(&self) -> Option<&'a [String]> { if let ModuleSource::Path(path) = self.source { Some(path) } else { None } } /// Return the name of the module. pub const fn name(&self) -> Option<&'a str> { self.name } } #[derive(Debug, Copy, Clone, is_macro::Is)] pub enum MemberKind<'a> { /// A class definition within a program. Class(&'a ast::StmtClassDef), /// A nested class definition within a program. NestedClass(&'a ast::StmtClassDef), /// A function definition within a program. Function(&'a ast::StmtFunctionDef), /// A nested function definition within a program. NestedFunction(&'a ast::StmtFunctionDef), /// A method definition within a program. Method(&'a ast::StmtFunctionDef), } /// A member of a Python module. #[derive(Debug)] pub struct Member<'a> { pub kind: MemberKind<'a>, pub parent: DefinitionId, } impl<'a> Member<'a> { /// Return the name of the member. pub fn name(&self) -> &'a str { match self.kind { MemberKind::Class(class) => &class.name, MemberKind::NestedClass(class) => &class.name, MemberKind::Function(function) => &function.name, MemberKind::NestedFunction(function) => &function.name, MemberKind::Method(method) => &method.name, } } /// Return the body of the member. pub fn body(&self) -> &'a [Stmt] { match self.kind { MemberKind::Class(class) => &class.body, MemberKind::NestedClass(class) => &class.body, MemberKind::Function(function) => &function.body, MemberKind::NestedFunction(function) => &function.body, MemberKind::Method(method) => &method.body, } } } impl Ranged for Member<'_> { /// Return the range of the member. fn range(&self) -> TextRange { match self.kind { MemberKind::Class(class) => class.range(), MemberKind::NestedClass(class) => class.range(), MemberKind::Function(function) => function.range(), MemberKind::NestedFunction(function) => function.range(), MemberKind::Method(method) => method.range(), } } } /// A definition within a Python program. #[derive(Debug, is_macro::Is)] pub enum Definition<'a> { Module(Module<'a>), Member(Member<'a>), } impl<'a> Definition<'a> { /// Returns `true` if the [`Definition`] is a method definition. pub const fn is_method(&self) -> bool { matches!( self, Definition::Member(Member { kind: MemberKind::Method(_), .. }) ) } pub fn is_property<P, I>(&self, extra_properties: P, semantic: &SemanticModel) -> bool where P: IntoIterator<IntoIter = I>, I: Iterator<Item = QualifiedName<'a>> + Clone, { self.as_function_def() .is_some_and(|StmtFunctionDef { decorator_list, .. }| { is_property(decorator_list, extra_properties, semantic) }) } /// Return the name of the definition. pub fn name(&self) -> Option<&'a str> { match self { Definition::Module(module) => module.name(), Definition::Member(member) => Some(member.name()), } } /// Return the [`ast::StmtFunctionDef`] of the definition, if it's a function definition. pub fn as_function_def(&self) -> Option<&'a ast::StmtFunctionDef> { match self { Definition::Member(Member { kind: MemberKind::Function(function) | MemberKind::NestedFunction(function) | MemberKind::Method(function), .. }) => Some(function), _ => None, } } /// Return the [`ast::StmtClassDef`] of the definition, if it's a class definition. pub fn as_class_def(&self) -> Option<&'a ast::StmtClassDef> { match self { Definition::Member(Member { kind: MemberKind::Class(class) | MemberKind::NestedClass(class), .. }) => Some(class), _ => None, } } } /// The definitions within a Python program indexed by [`DefinitionId`]. #[derive(Debug, Default)] pub struct Definitions<'a>(IndexVec<DefinitionId, Definition<'a>>); impl<'a> Definitions<'a> { pub fn for_module(definition: Module<'a>) -> Self { Self(IndexVec::from_raw(vec![Definition::Module(definition)])) } /// Pushes a new member definition and returns its unique id. /// /// Members are assumed to be pushed in traversal order, such that parents are pushed before /// their children. pub(crate) fn push_member(&mut self, member: Member<'a>) -> DefinitionId { self.0.push(Definition::Member(member)) } /// Resolve the visibility of each definition in the collection. pub fn resolve(self, exports: Option<&[DunderAllName]>) -> ContextualizedDefinitions<'a> { let mut definitions: IndexVec<DefinitionId, ContextualizedDefinition<'a>> = IndexVec::with_capacity(self.len()); for definition in self { // Determine the visibility of the next definition, taking into account its parent's // visibility. let visibility = { match &definition { Definition::Module(module) => module_visibility(*module), Definition::Member(member) => match member.kind { MemberKind::Class(class) => { let parent = &definitions[member.parent]; if parent.visibility.is_private() || exports.is_some_and(|exports| { !exports.iter().any(|export| export.name() == member.name()) }) { Visibility::Private } else { class_visibility(class) } } MemberKind::NestedClass(class) => { let parent = &definitions[member.parent]; if parent.visibility.is_private() || parent.definition.as_function_def().is_some() { Visibility::Private } else { class_visibility(class) } } MemberKind::Function(function) => { let parent = &definitions[member.parent]; if parent.visibility.is_private() || exports.is_some_and(|exports| { !exports.iter().any(|export| export.name() == member.name()) }) { Visibility::Private } else { function_visibility(function) } } MemberKind::NestedFunction(_) => Visibility::Private, MemberKind::Method(function) => { let parent = &definitions[member.parent]; if parent.visibility.is_private() { Visibility::Private } else { method_visibility(function) } } }, } }; definitions.push(ContextualizedDefinition { definition, visibility, }); } ContextualizedDefinitions(definitions.raw) } /// Returns a reference to the Python AST. pub fn python_ast(&self) -> Option<&'a [Stmt]> { let module = self[DefinitionId::module()].as_module()?; Some(module.python_ast) } } impl<'a> Deref for Definitions<'a> { type Target = IndexSlice<DefinitionId, Definition<'a>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<'a> IntoIterator for Definitions<'a> { type Item = Definition<'a>; type IntoIter = std::vec::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } /// A [`Definition`] in a Python program with its resolved [`Visibility`]. pub struct ContextualizedDefinition<'a> { pub definition: Definition<'a>, pub visibility: Visibility, } /// A collection of [`Definition`] structs in a Python program with resolved [`Visibility`]. pub struct ContextualizedDefinitions<'a>(Vec<ContextualizedDefinition<'a>>); impl<'a> ContextualizedDefinitions<'a> { pub fn iter(&self) -> impl Iterator<Item = &ContextualizedDefinition<'a>> { self.0.iter() } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/binding.rs
crates/ruff_python_semantic/src/binding.rs
use std::borrow::Cow; use std::ops::{Deref, DerefMut}; use bitflags::bitflags; use crate::all::DunderAllName; use ruff_index::{IndexSlice, IndexVec, newtype_index}; use ruff_python_ast::helpers::extract_handled_exceptions; use ruff_python_ast::name::QualifiedName; use ruff_python_ast::{self as ast, Stmt}; use ruff_text_size::{Ranged, TextRange}; use crate::ScopeId; use crate::context::ExecutionContext; use crate::model::SemanticModel; use crate::nodes::NodeId; use crate::reference::ResolvedReferenceId; #[derive(Debug, Clone)] pub struct Binding<'a> { pub kind: BindingKind<'a>, pub range: TextRange, /// The [`ScopeId`] of the scope in which the [`Binding`] was defined. pub scope: ScopeId, /// The context in which the [`Binding`] was created. pub context: ExecutionContext, /// The statement in which the [`Binding`] was defined. pub source: Option<NodeId>, /// The references to the [`Binding`]. pub references: Vec<ResolvedReferenceId>, /// The exceptions that were handled when the [`Binding`] was defined. pub exceptions: Exceptions, /// Flags for the [`Binding`]. pub flags: BindingFlags, } impl<'a> Binding<'a> { /// Return `true` if this [`Binding`] is unused. /// /// This method is the opposite of [`Binding::is_used`]. pub fn is_unused(&self) -> bool { self.references.is_empty() } /// Return `true` if this [`Binding`] is used. /// /// This method is the opposite of [`Binding::is_unused`]. pub fn is_used(&self) -> bool { !self.is_unused() } /// Returns an iterator over all references for the current [`Binding`]. pub fn references(&self) -> impl Iterator<Item = ResolvedReferenceId> + '_ { self.references.iter().copied() } /// Return `true` if this [`Binding`] represents an explicit re-export /// (e.g., `FastAPI` in `from fastapi import FastAPI as FastAPI`). pub const fn is_explicit_export(&self) -> bool { self.flags.intersects(BindingFlags::EXPLICIT_EXPORT) } /// Return `true` if this [`Binding`] represents an external symbol /// (e.g., `FastAPI` in `from fastapi import FastAPI`). pub const fn is_external(&self) -> bool { self.flags.intersects(BindingFlags::EXTERNAL) } /// Return `true` if this [`Binding`] represents an aliased symbol /// (e.g., `app` in `from fastapi import FastAPI as app`). pub const fn is_alias(&self) -> bool { self.flags.intersects(BindingFlags::ALIAS) } /// Return `true` if this [`Binding`] represents a `nonlocal`. A [`Binding`] is a `nonlocal` /// if it's declared by a `nonlocal` statement, or shadows a [`Binding`] declared by a /// `nonlocal` statement. pub const fn is_nonlocal(&self) -> bool { self.flags.intersects(BindingFlags::NONLOCAL) } /// Return `true` if this [`Binding`] represents a `global`. A [`Binding`] is a `global` if it's /// declared by a `global` statement, or shadows a [`Binding`] declared by a `global` statement. pub const fn is_global(&self) -> bool { self.flags.intersects(BindingFlags::GLOBAL) } /// Return `true` if this [`Binding`] was deleted. pub const fn is_deleted(&self) -> bool { self.flags.intersects(BindingFlags::DELETED) } /// Return `true` if this [`Binding`] represents an assignment to `__all__` with an invalid /// value (e.g., `__all__ = "Foo"`). pub const fn is_invalid_all_format(&self) -> bool { self.flags.intersects(BindingFlags::INVALID_ALL_FORMAT) } /// Return `true` if this [`Binding`] represents an assignment to `__all__` that includes an /// invalid member (e.g., `__all__ = ["Foo", 1]`). pub const fn is_invalid_all_object(&self) -> bool { self.flags.intersects(BindingFlags::INVALID_ALL_OBJECT) } /// Return `true` if this [`Binding`] represents an unpacked assignment (e.g., `x` in /// `(x, y) = 1, 2`). pub const fn is_unpacked_assignment(&self) -> bool { self.flags.intersects(BindingFlags::UNPACKED_ASSIGNMENT) } /// Return `true` if this [`Binding`] represents an unbound variable /// (e.g., `x` in `x = 1; del x`). pub const fn is_unbound(&self) -> bool { matches!( self.kind, BindingKind::Annotation | BindingKind::Deletion | BindingKind::UnboundException(_) ) } /// Return `true` if this [`Binding`] represents an private declaration /// (e.g., `_x` in `_x = "private variable"`) pub const fn is_private_declaration(&self) -> bool { self.flags.contains(BindingFlags::PRIVATE_DECLARATION) } /// Return `true` if this [`Binding`] took place inside an exception handler, /// e.g. `y` in: /// ```python /// try: /// x = 42 /// except RuntimeError: /// y = 42 /// ``` pub const fn in_exception_handler(&self) -> bool { self.flags.contains(BindingFlags::IN_EXCEPT_HANDLER) } /// Return `true` if this [`Binding`] took place inside an `assert` statement, /// e.g. `y` in: /// ```python /// assert (y := x**2), y /// ``` pub const fn in_assert_statement(&self) -> bool { self.flags.contains(BindingFlags::IN_ASSERT_STATEMENT) } /// Return `true` if this [`Binding`] represents a [PEP 613] type alias /// e.g. `OptString` in: /// ```python /// from typing import TypeAlias /// /// OptString: TypeAlias = str | None /// ``` /// /// [PEP 613]: https://peps.python.org/pep-0613/ pub const fn is_annotated_type_alias(&self) -> bool { self.flags.intersects(BindingFlags::ANNOTATED_TYPE_ALIAS) } /// Return `true` if this [`Binding`] represents a [PEP 695] type alias /// e.g. `OptString` in: /// ```python /// type OptString = str | None /// ``` /// /// [PEP 695]: https://peps.python.org/pep-0695/#generic-type-alias pub const fn is_deferred_type_alias(&self) -> bool { self.flags.intersects(BindingFlags::DEFERRED_TYPE_ALIAS) } /// Return `true` if this [`Binding`] represents either kind of type alias pub const fn is_type_alias(&self) -> bool { self.flags.intersects(BindingFlags::TYPE_ALIAS) } /// Return `true` if this binding "redefines" the given binding, as per Pyflake's definition of /// redefinition. pub fn redefines(&self, existing: &Binding) -> bool { match &self.kind { // Submodule imports are only considered redefinitions if they import the same // submodule. For example, this is a redefinition: // ```python // import foo.bar // import foo.bar // ``` // // This, however, is not: // ```python // import foo.bar // import foo.baz // ``` BindingKind::Import(Import { qualified_name: redefinition, }) => { if let BindingKind::SubmoduleImport(SubmoduleImport { qualified_name: definition, }) = &existing.kind { return redefinition == definition; } } BindingKind::FromImport(FromImport { qualified_name: redefinition, }) => { if let BindingKind::SubmoduleImport(SubmoduleImport { qualified_name: definition, }) = &existing.kind { return redefinition == definition; } } BindingKind::SubmoduleImport(SubmoduleImport { qualified_name: redefinition, }) => match &existing.kind { BindingKind::Import(Import { qualified_name: definition, }) | BindingKind::SubmoduleImport(SubmoduleImport { qualified_name: definition, }) => { return redefinition == definition; } BindingKind::FromImport(FromImport { qualified_name: definition, }) => { return redefinition == definition; } _ => {} }, // Deletions, annotations, `__future__` imports, and builtins are never considered // redefinitions. BindingKind::Deletion | BindingKind::ConditionalDeletion(_) | BindingKind::Annotation | BindingKind::FutureImport | BindingKind::Builtin => { return false; } // Assignment-assignment bindings are not considered redefinitions, as in: // ```python // x = 1 // x = 2 // ``` BindingKind::Assignment | BindingKind::NamedExprAssignment => { if matches!( existing.kind, BindingKind::Assignment | BindingKind::NamedExprAssignment ) { return false; } } _ => {} } // Otherwise, the shadowed binding must be a class definition, function definition, // import, or assignment to be considered a redefinition. matches!( existing.kind, BindingKind::ClassDefinition(_) | BindingKind::FunctionDefinition(_) | BindingKind::Import(_) | BindingKind::FromImport(_) | BindingKind::Assignment | BindingKind::NamedExprAssignment ) } /// Returns the name of the binding (e.g., `x` in `x = 1`). pub fn name<'b>(&self, source: &'b str) -> &'b str { &source[self.range] } /// Returns the statement in which the binding was defined. pub fn statement<'b>(&self, semantic: &SemanticModel<'b>) -> Option<&'b Stmt> { self.source .map(|statement_id| semantic.statement(statement_id)) } /// Returns the expression in which the binding was defined /// (e.g. for the binding `x` in `y = (x := 1)`, return the node representing `x := 1`). /// /// This is only really applicable for assignment expressions. pub fn expression<'b>(&self, semantic: &SemanticModel<'b>) -> Option<&'b ast::Expr> { self.source .and_then(|expression_id| semantic.parent_expression(expression_id)) } /// Returns the range of the binding's parent. pub fn parent_range(&self, semantic: &SemanticModel) -> Option<TextRange> { self.statement(semantic).and_then(|parent| { if parent.is_import_from_stmt() { Some(parent.range()) } else { None } }) } pub fn as_any_import(&self) -> Option<AnyImport<'_, 'a>> { match &self.kind { BindingKind::Import(import) => Some(AnyImport::Import(import)), BindingKind::SubmoduleImport(import) => Some(AnyImport::SubmoduleImport(import)), BindingKind::FromImport(import) => Some(AnyImport::FromImport(import)), _ => None, } } } bitflags! { /// Flags on a [`Binding`]. #[derive(Debug, Default, Copy, Clone, Eq, PartialEq)] pub struct BindingFlags: u16 { /// The binding represents an explicit re-export. /// /// For example, the binding could be `FastAPI` in: /// ```python /// from fastapi import FastAPI as FastAPI /// ``` const EXPLICIT_EXPORT = 1 << 0; /// The binding represents an external symbol, like an import or a builtin. /// /// For example, the binding could be `FastAPI` in: /// ```python /// from fastapi import FastAPI /// ``` const EXTERNAL = 1 << 1; /// The binding is an aliased symbol. /// /// For example, the binding could be `app` in: /// ```python /// from fastapi import FastAPI as app /// ``` const ALIAS = 1 << 2; /// The binding is `nonlocal` to the declaring scope. This could be a binding created by /// a `nonlocal` statement, or a binding that shadows such a binding. /// /// For example, both of the bindings in the following function are `nonlocal`: /// ```python /// def f(): /// nonlocal x /// x = 1 /// ``` const NONLOCAL = 1 << 3; /// The binding is `global`. This could be a binding created by a `global` statement, or a /// binding that shadows such a binding. /// /// For example, both of the bindings in the following function are `global`: /// ```python /// def f(): /// global x /// x = 1 /// ``` const GLOBAL = 1 << 4; /// The binding was deleted (i.e., the target of a `del` statement). /// /// For example, the binding could be `x` in: /// ```python /// del x /// ``` /// /// The semantic model will typically shadow a deleted binding via an additional binding /// with [`BindingKind::Deletion`]; however, conditional deletions (e.g., /// `if condition: del x`) do _not_ generate a shadow binding. This flag is thus used to /// detect whether a binding was _ever_ deleted, even conditionally. const DELETED = 1 << 5; /// The binding represents an export via `__all__`, but the assigned value uses an invalid /// expression (i.e., a non-container type). /// /// For example: /// ```python /// __all__ = 1 /// ``` const INVALID_ALL_FORMAT = 1 << 6; /// The binding represents an export via `__all__`, but the assigned value contains an /// invalid member (i.e., a non-string). /// /// For example: /// ```python /// __all__ = [1] /// ``` const INVALID_ALL_OBJECT = 1 << 7; /// The binding represents a private declaration. /// /// For example, the binding could be `_T` in: /// ```python /// _T = "This is a private variable" /// ``` const PRIVATE_DECLARATION = 1 << 8; /// The binding represents an unpacked assignment. /// /// For example, the binding could be `x` in: /// ```python /// (x, y) = 1, 2 /// ``` const UNPACKED_ASSIGNMENT = 1 << 9; /// The binding took place inside an exception handling. /// /// For example, the `x` binding in the following example /// would *not* have this flag set, but the `y` binding *would*: /// ```python /// try: /// x = 42 /// except RuntimeError: /// y = 42 /// ``` const IN_EXCEPT_HANDLER = 1 << 10; /// The binding represents a [PEP 613] explicit type alias. /// /// [PEP 613]: https://peps.python.org/pep-0613/ const ANNOTATED_TYPE_ALIAS = 1 << 11; /// The binding represents a [PEP 695] type statement /// /// [PEP 695]: https://peps.python.org/pep-0695/#generic-type-alias const DEFERRED_TYPE_ALIAS = 1 << 12; /// The binding took place inside an `assert` statement /// /// For example, `x` in the following snippet: /// ```python /// assert (x := y**2) > 42, x /// ``` const IN_ASSERT_STATEMENT = 1 << 13; /// The binding represents any type alias. const TYPE_ALIAS = Self::ANNOTATED_TYPE_ALIAS.bits() | Self::DEFERRED_TYPE_ALIAS.bits(); } } impl Ranged for Binding<'_> { fn range(&self) -> TextRange { self.range } } /// ID uniquely identifying a [Binding] in a program. /// /// Using a `u32` to identify [Binding]s should be sufficient because Ruff only supports documents with a /// size smaller than or equal to `u32::MAX`. A document with the size of `u32::MAX` must have fewer than `u32::MAX` /// bindings because bindings must be separated by whitespace (and have an assignment). #[newtype_index] pub struct BindingId; /// The bindings in a program. /// /// Bindings are indexed by [`BindingId`] #[derive(Debug, Clone, Default)] pub struct Bindings<'a>(IndexVec<BindingId, Binding<'a>>); impl<'a> Bindings<'a> { /// Pushes a new [`Binding`] and returns its [`BindingId`]. pub fn push(&mut self, binding: Binding<'a>) -> BindingId { self.0.push(binding) } } impl<'a> Deref for Bindings<'a> { type Target = IndexSlice<BindingId, Binding<'a>>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for Bindings<'_> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<'a> FromIterator<Binding<'a>> for Bindings<'a> { fn from_iter<T: IntoIterator<Item = Binding<'a>>>(iter: T) -> Self { Self(IndexVec::from_iter(iter)) } } #[derive(Debug, Clone)] pub struct Export<'a> { /// The names of the bindings exported via `__all__`. pub names: Box<[DunderAllName<'a>]>, } /// A binding for an `import`, keyed on the name to which the import is bound. /// Ex) `import foo` would be keyed on "foo". /// Ex) `import foo as bar` would be keyed on "bar". #[derive(Debug, Clone)] pub struct Import<'a> { /// The full name of the module being imported. /// Ex) Given `import foo`, `qualified_name` would be "foo". /// Ex) Given `import foo as bar`, `qualified_name` would be "foo". pub qualified_name: Box<QualifiedName<'a>>, } /// A binding for a member imported from a module, keyed on the name to which the member is bound. /// Ex) `from foo import bar` would be keyed on "bar". /// Ex) `from foo import bar as baz` would be keyed on "baz". #[derive(Debug, Clone)] pub struct FromImport<'a> { /// The full name of the member being imported. /// Ex) Given `from foo import bar`, `qualified_name` would be "foo.bar". /// Ex) Given `from foo import bar as baz`, `qualified_name` would be "foo.bar". pub qualified_name: Box<QualifiedName<'a>>, } /// A binding for a submodule imported from a module, keyed on the name of the parent module. /// Ex) `import foo.bar` would be keyed on "foo". #[derive(Debug, Clone)] pub struct SubmoduleImport<'a> { /// The full name of the submodule being imported. /// Ex) Given `import foo.bar`, `qualified_name` would be "foo.bar". pub qualified_name: Box<QualifiedName<'a>>, } #[derive(Debug, Clone, is_macro::Is)] pub enum BindingKind<'a> { /// A binding for an annotated assignment without a value, like `x` in: /// ```python /// x: int /// ``` Annotation, /// A binding for a function argument, like `x` in: /// ```python /// def foo(x: int): /// ... /// ``` Argument, /// A binding for a named expression assignment, like `x` in: /// ```python /// if (x := 1): /// ... /// ``` NamedExprAssignment, /// A binding for a "standard" assignment, like `x` in: /// ```python /// x = 1 /// ``` Assignment, /// A binding for a generic type parameter, like `X` in: /// ```python /// def foo[X](x: X): /// ... /// /// class Foo[X](x: X): /// ... /// /// type Foo[X] = ... /// ``` TypeParam, /// A binding for a for-loop variable, like `x` in: /// ```python /// for x in range(10): /// ... /// ``` LoopVar, /// A binding for a with statement variable, like `x` in: /// ```python /// with open('foo.py') as x: /// ... /// ``` WithItemVar, /// A binding for a global variable, like `x` in: /// ```python /// def foo(): /// global x /// ``` Global(Option<BindingId>), /// A binding for a nonlocal variable, like `x` in: /// ```python /// def foo(): /// nonlocal x /// ``` Nonlocal(BindingId, ScopeId), /// A binding for a builtin, like `print` or `bool`. Builtin, /// A binding for a class, like `Foo` in: /// ```python /// class Foo: /// ... /// ``` ClassDefinition(ScopeId), /// A binding for a function, like `foo` in: /// ```python /// def foo(): /// ... /// ``` FunctionDefinition(ScopeId), /// A binding for an `__all__` export, like `__all__` in: /// ```python /// __all__ = ["foo", "bar"] /// ``` Export(Export<'a>), /// A binding for a `__future__` import, like: /// ```python /// from __future__ import annotations /// ``` FutureImport, /// A binding for a straight `import`, like `foo` in: /// ```python /// import foo /// ``` Import(Import<'a>), /// A binding for a member imported from a module, like `bar` in: /// ```python /// from foo import bar /// ``` FromImport(FromImport<'a>), /// A binding for a submodule imported from a module, like `bar` in: /// ```python /// import foo.bar /// ``` SubmoduleImport(SubmoduleImport<'a>), /// A binding for a deletion, like `x` in: /// ```python /// del x /// ``` Deletion, /// A binding for a deletion, like `x` in: /// ```python /// if x > 0: /// del x /// ``` ConditionalDeletion(BindingId), /// A binding to bind an exception to a local variable, like `x` in: /// ```python /// try: /// ... /// except Exception as x: /// ... /// ``` BoundException, /// A binding to unbind a bound local exception, like `x` in: /// ```python /// try: /// ... /// except Exception as x: /// ... /// ``` /// /// After the `except` block, `x` is unbound, despite the lack /// of an explicit `del` statement. /// /// Stores the ID of the binding that was shadowed in the enclosing /// scope, if any. UnboundException(Option<BindingId>), /// A binding to `__class__` in the implicit closure created around every method in a class /// body, if any method refers to either `__class__` or `super`. /// /// ```python /// class C: /// __class__ # NameError: name '__class__' is not defined /// /// def f(): /// print(__class__) # allowed /// /// def g(): /// nonlocal __class__ # also allowed because the scope is *not* the function scope /// ``` /// /// See <https://docs.python.org/3/reference/datamodel.html#creating-the-class-object> for more /// details. DunderClassCell, } bitflags! { #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct Exceptions: u8 { const NAME_ERROR = 1 << 0; const MODULE_NOT_FOUND_ERROR = 1 << 1; const IMPORT_ERROR = 1 << 2; const ATTRIBUTE_ERROR = 1 << 3; } } impl Exceptions { pub fn from_try_stmt( ast::StmtTry { handlers, .. }: &ast::StmtTry, semantic: &SemanticModel, ) -> Self { let mut handled_exceptions = Self::empty(); for type_ in extract_handled_exceptions(handlers) { handled_exceptions |= match semantic.resolve_builtin_symbol(type_) { Some("NameError") => Self::NAME_ERROR, Some("ModuleNotFoundError") => Self::MODULE_NOT_FOUND_ERROR, Some("ImportError") => Self::IMPORT_ERROR, Some("AttributeError") => Self::ATTRIBUTE_ERROR, _ => continue, } } handled_exceptions } } /// A trait for imported symbols. pub trait Imported<'a> { /// Returns the call path to the imported symbol. fn qualified_name(&self) -> &QualifiedName<'a>; /// Returns the module name of the imported symbol. fn module_name(&self) -> &[&'a str]; /// Returns the member name of the imported symbol. For a straight import, this is equivalent /// to the qualified name; for a `from` import, this is the name of the imported symbol. fn member_name(&self) -> Cow<'a, str>; /// Returns the source module of the imported symbol. /// /// For example: /// /// - `import foo` returns `["foo"]` /// - `import foo.bar` returns `["foo","bar"]` /// - `from foo import bar` returns `["foo"]` fn source_name(&self) -> &[&'a str]; } impl<'a> Imported<'a> for Import<'a> { /// For example, given `import foo`, returns `["foo"]`. fn qualified_name(&self) -> &QualifiedName<'a> { &self.qualified_name } /// For example, given `import foo`, returns `["foo"]`. fn module_name(&self) -> &[&'a str] { &self.qualified_name.segments()[..1] } /// For example, given `import foo`, returns `"foo"`. fn member_name(&self) -> Cow<'a, str> { Cow::Owned(self.qualified_name().to_string()) } fn source_name(&self) -> &[&'a str] { self.qualified_name.segments() } } impl<'a> Imported<'a> for SubmoduleImport<'a> { /// For example, given `import foo.bar`, returns `["foo", "bar"]`. fn qualified_name(&self) -> &QualifiedName<'a> { &self.qualified_name } /// For example, given `import foo.bar`, returns `["foo"]`. fn module_name(&self) -> &[&'a str] { &self.qualified_name.segments()[..1] } /// For example, given `import foo.bar`, returns `"foo.bar"`. fn member_name(&self) -> Cow<'a, str> { Cow::Owned(self.qualified_name().to_string()) } fn source_name(&self) -> &[&'a str] { self.qualified_name.segments() } } impl<'a> Imported<'a> for FromImport<'a> { /// For example, given `from foo import bar`, returns `["foo", "bar"]`. fn qualified_name(&self) -> &QualifiedName<'a> { &self.qualified_name } /// For example, given `from foo import bar`, returns `["foo"]`. fn module_name(&self) -> &[&'a str] { &self.qualified_name.segments()[..self.qualified_name.segments().len() - 1] } /// For example, given `from foo import bar`, returns `"bar"`. fn member_name(&self) -> Cow<'a, str> { Cow::Borrowed(self.qualified_name.segments()[self.qualified_name.segments().len() - 1]) } fn source_name(&self) -> &[&'a str] { self.module_name() } } /// A wrapper around an import [`BindingKind`] that can be any of the three types of imports. #[derive(Debug, Clone, is_macro::Is)] pub enum AnyImport<'a, 'ast> { Import(&'a Import<'ast>), SubmoduleImport(&'a SubmoduleImport<'ast>), FromImport(&'a FromImport<'ast>), } impl<'ast> Imported<'ast> for AnyImport<'_, 'ast> { fn qualified_name(&self) -> &QualifiedName<'ast> { match self { Self::Import(import) => import.qualified_name(), Self::SubmoduleImport(import) => import.qualified_name(), Self::FromImport(import) => import.qualified_name(), } } fn module_name(&self) -> &[&'ast str] { match self { Self::Import(import) => import.module_name(), Self::SubmoduleImport(import) => import.module_name(), Self::FromImport(import) => import.module_name(), } } fn member_name(&self) -> Cow<'ast, str> { match self { Self::Import(import) => import.member_name(), Self::SubmoduleImport(import) => import.member_name(), Self::FromImport(import) => import.member_name(), } } fn source_name(&self) -> &[&'ast str] { match self { Self::Import(import) => import.source_name(), Self::SubmoduleImport(import) => import.source_name(), Self::FromImport(import) => import.source_name(), } } } #[cfg(test)] mod tests { use crate::BindingKind; #[test] #[cfg(target_pointer_width = "64")] fn size() { assert!(std::mem::size_of::<BindingKind>() <= 24); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/context.rs
crates/ruff_python_semantic/src/context.rs
#[derive(Debug, Copy, Clone, is_macro::Is)] pub enum ExecutionContext { /// The reference occurs in a runtime context. Runtime, /// The reference occurs in a typing-only context. Typing, }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/branches.rs
crates/ruff_python_semantic/src/branches.rs
use std::ops::Index; use ruff_index::{IndexVec, newtype_index}; /// ID uniquely identifying a branch in a program. /// /// For example, given: /// ```python /// if x > 0: /// pass /// elif x > 1: /// pass /// else: /// pass /// ``` /// /// Each of the three arms of the `if`-`elif`-`else` would be considered a branch, and would be /// assigned their own unique [`BranchId`]. #[newtype_index] #[derive(Ord, PartialOrd)] pub struct BranchId; /// The branches of a program indexed by [`BranchId`] #[derive(Debug, Default)] pub(crate) struct Branches(IndexVec<BranchId, Option<BranchId>>); impl Branches { /// Inserts a new branch into the vector and returns its unique [`BranchID`]. pub(crate) fn insert(&mut self, parent: Option<BranchId>) -> BranchId { self.0.push(parent) } /// Return the [`BranchId`] of the parent branch. #[inline] pub(crate) fn parent_id(&self, node_id: BranchId) -> Option<BranchId> { self.0[node_id] } /// Returns an iterator over all [`BranchId`] ancestors, starting from the given [`BranchId`]. pub(crate) fn ancestor_ids(&self, node_id: BranchId) -> impl Iterator<Item = BranchId> + '_ { std::iter::successors(Some(node_id), |&node_id| self.0[node_id]) } } impl Index<BranchId> for Branches { type Output = Option<BranchId>; #[inline] fn index(&self, index: BranchId) -> &Self::Output { &self.0[index] } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/model/all.rs
crates/ruff_python_semantic/src/model/all.rs
//! Utilities for semantic analysis of `__all__` definitions use bitflags::bitflags; use ruff_python_ast::{self as ast, Expr, Stmt, helpers::map_subscript}; use ruff_text_size::{Ranged, TextRange}; use crate::SemanticModel; bitflags! { #[derive(Default, Debug, Copy, Clone, PartialEq, Eq)] pub struct DunderAllFlags: u8 { /// The right-hand-side assignment to __all__ uses an invalid expression (i.e., an /// expression that doesn't evaluate to a container type, like `__all__ = 1`). const INVALID_FORMAT = 1 << 0; /// The right-hand-side assignment to __all__ contains an invalid member (i.e., a /// non-string, like `__all__ = [1]`). const INVALID_OBJECT = 1 << 1; } } /// Abstraction for a string inside an `__all__` definition, /// e.g. `"foo"` in `__all__ = ["foo"]` #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct DunderAllName<'a> { /// The value of the string inside the `__all__` definition name: &'a str, /// The range of the string inside the `__all__` definition range: TextRange, } impl DunderAllName<'_> { pub fn name(&self) -> &str { self.name } } impl Ranged for DunderAllName<'_> { fn range(&self) -> TextRange { self.range } } /// Abstraction for a collection of names inside an `__all__` definition, /// e.g. `["foo", "bar"]` in `__all__ = ["foo", "bar"]` #[derive(Debug, Clone)] pub struct DunderAllDefinition<'a> { /// The range of the `__all__` identifier. range: TextRange, /// The names inside the `__all__` definition. names: Vec<DunderAllName<'a>>, } impl<'a> DunderAllDefinition<'a> { /// Initialize a new [`DunderAllDefinition`] instance. pub fn new(range: TextRange, names: Vec<DunderAllName<'a>>) -> Self { Self { range, names } } /// The names inside the `__all__` definition. pub fn names(&self) -> &[DunderAllName<'a>] { &self.names } } impl Ranged for DunderAllDefinition<'_> { fn range(&self) -> TextRange { self.range } } impl SemanticModel<'_> { /// Extract the names bound to a given __all__ assignment. pub fn extract_dunder_all_names<'expr>( &self, stmt: &'expr Stmt, ) -> (Vec<DunderAllName<'expr>>, DunderAllFlags) { fn add_to_names<'expr>( elts: &'expr [Expr], names: &mut Vec<DunderAllName<'expr>>, flags: &mut DunderAllFlags, ) { for elt in elts { if let Expr::StringLiteral(ast::ExprStringLiteral { value, range, node_index: _, }) = elt { names.push(DunderAllName { name: value.to_str(), range: *range, }); } else { *flags |= DunderAllFlags::INVALID_OBJECT; } } } let mut names: Vec<DunderAllName> = vec![]; let mut flags = DunderAllFlags::empty(); if let Some(value) = match stmt { Stmt::Assign(ast::StmtAssign { value, .. }) => Some(value), Stmt::AnnAssign(ast::StmtAnnAssign { value, .. }) => value.as_ref(), Stmt::AugAssign(ast::StmtAugAssign { value, .. }) => Some(value), _ => None, } { if let Expr::BinOp(ast::ExprBinOp { left, right, .. }) = value.as_ref() { let mut current_left = left; let mut current_right = right; loop { // Process the right side, which should be a "real" value. let (elts, new_flags) = self.extract_dunder_all_elts(current_right); flags |= new_flags; if let Some(elts) = elts { add_to_names(elts, &mut names, &mut flags); } // Process the left side, which can be a "real" value or the "rest" of the // binary operation. if let Expr::BinOp(ast::ExprBinOp { left, right, .. }) = current_left.as_ref() { current_left = left; current_right = right; } else { let (elts, new_flags) = self.extract_dunder_all_elts(current_left); flags |= new_flags; if let Some(elts) = elts { add_to_names(elts, &mut names, &mut flags); } break; } } } else { let (elts, new_flags) = self.extract_dunder_all_elts(value); flags |= new_flags; if let Some(elts) = elts { add_to_names(elts, &mut names, &mut flags); } } } (names, flags) } fn extract_dunder_all_elts<'expr>( &self, expr: &'expr Expr, ) -> (Option<&'expr [Expr]>, DunderAllFlags) { match expr { Expr::List(ast::ExprList { elts, .. }) => { return (Some(elts), DunderAllFlags::empty()); } Expr::Tuple(ast::ExprTuple { elts, .. }) => { return (Some(elts), DunderAllFlags::empty()); } Expr::ListComp(_) => { // Allow comprehensions, even though we can't statically analyze them. return (None, DunderAllFlags::empty()); } Expr::Name(ast::ExprName { id, .. }) => { // Ex) `__all__ = __all__ + multiprocessing.__all__` if id == "__all__" { return (None, DunderAllFlags::empty()); } } Expr::Attribute(ast::ExprAttribute { attr, .. }) => { // Ex) `__all__ = __all__ + multiprocessing.__all__` if attr == "__all__" { return (None, DunderAllFlags::empty()); } } Expr::Call(ast::ExprCall { func, arguments, .. }) => { // Allow `tuple()`, `list()`, and their generic forms, like `list[int]()`. if arguments.keywords.is_empty() && arguments.args.len() <= 1 { if self .resolve_builtin_symbol(map_subscript(func)) .is_some_and(|symbol| matches!(symbol, "tuple" | "list")) { let [arg] = arguments.args.as_ref() else { return (None, DunderAllFlags::empty()); }; match arg { Expr::List(ast::ExprList { elts, .. }) | Expr::Set(ast::ExprSet { elts, .. }) | Expr::Tuple(ast::ExprTuple { elts, .. }) => { return (Some(elts), DunderAllFlags::empty()); } _ => { // We can't analyze other expressions, but they must be // valid, since the `list` or `tuple` call will ultimately // evaluate to a list or tuple. return (None, DunderAllFlags::empty()); } } } } } Expr::Named(ast::ExprNamed { value, .. }) => { // Allow, e.g., `__all__ += (value := ["A", "B"])`. return self.extract_dunder_all_elts(value); } _ => {} } (None, DunderAllFlags::INVALID_FORMAT) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/analyze/visibility.rs
crates/ruff_python_semantic/src/analyze/visibility.rs
use ruff_python_ast::{self as ast, Decorator, Expr}; use ruff_python_ast::helpers::map_callable; use ruff_python_ast::name::{QualifiedName, UnqualifiedName}; use crate::model::SemanticModel; use crate::{Module, ModuleSource}; #[derive(Debug, Clone, Copy, is_macro::Is)] pub enum Visibility { Public, Private, } /// Returns `true` if a function is a "static method". pub fn is_staticmethod(decorator_list: &[Decorator], semantic: &SemanticModel) -> bool { decorator_list .iter() .any(|decorator| semantic.match_builtin_expr(&decorator.expression, "staticmethod")) } /// Returns `true` if a function is a "class method". pub fn is_classmethod(decorator_list: &[Decorator], semantic: &SemanticModel) -> bool { decorator_list .iter() .any(|decorator| semantic.match_builtin_expr(&decorator.expression, "classmethod")) } /// Returns `true` if a function definition is an `@overload`. pub fn is_overload(decorator_list: &[Decorator], semantic: &SemanticModel) -> bool { decorator_list .iter() .any(|decorator| semantic.match_typing_expr(&decorator.expression, "overload")) } /// Returns `true` if a function definition is an `@override` (PEP 698). pub fn is_override(decorator_list: &[Decorator], semantic: &SemanticModel) -> bool { decorator_list .iter() .any(|decorator| semantic.match_typing_expr(&decorator.expression, "override")) } /// Returns `true` if a function definition is an abstract method based on its decorators. pub fn is_abstract(decorator_list: &[Decorator], semantic: &SemanticModel) -> bool { decorator_list.iter().any(|decorator| { semantic .resolve_qualified_name(&decorator.expression) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), [ "abc", "abstractmethod" | "abstractclassmethod" | "abstractstaticmethod" | "abstractproperty" ] ) }) }) } /// Returns `true` if a function definition is a `@property`. /// `extra_properties` can be used to check additional non-standard /// `@property`-like decorators. pub fn is_property<'a, P, I>( decorator_list: &[Decorator], extra_properties: P, semantic: &SemanticModel, ) -> bool where P: IntoIterator<IntoIter = I>, I: Iterator<Item = QualifiedName<'a>> + Clone, { let extra_properties = extra_properties.into_iter(); decorator_list.iter().any(|decorator| { semantic .resolve_qualified_name(map_callable(&decorator.expression)) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), ["" | "builtins" | "enum", "property"] | ["functools", "cached_property"] | ["abc", "abstractproperty"] | ["types", "DynamicClassAttribute"] ) || extra_properties .clone() .any(|extra_property| extra_property == qualified_name) }) }) } /// Returns `true` if a function definition is an `attrs`-like validator based on its decorators. pub fn is_validator(decorator_list: &[Decorator], semantic: &SemanticModel) -> bool { decorator_list.iter().any(|decorator| { let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = &decorator.expression else { return false; }; if attr.as_str() != "validator" { return false; } let Expr::Name(value) = value.as_ref() else { return false; }; semantic .resolve_name(value) .is_some_and(|id| semantic.binding(id).kind.is_assignment()) }) } /// Returns `true` if a class is an `final`. pub fn is_final(decorator_list: &[Decorator], semantic: &SemanticModel) -> bool { decorator_list .iter() .any(|decorator| semantic.match_typing_expr(&decorator.expression, "final")) } /// Returns `true` if a function is a "magic method". pub fn is_magic(name: &str) -> bool { name.starts_with("__") && name.ends_with("__") } /// Returns `true` if a function is an `__init__`. pub fn is_init(name: &str) -> bool { name == "__init__" } /// Returns `true` if a function is a `__new__`. pub fn is_new(name: &str) -> bool { name == "__new__" } /// Returns `true` if a function is a `__call__`. pub fn is_call(name: &str) -> bool { name == "__call__" } /// Returns `true` if a function is a test one. pub fn is_test(name: &str) -> bool { name == "runTest" || name.starts_with("test") } /// Returns `true` if a module name indicates public visibility. fn is_public_module(module_name: &str) -> bool { !module_name.starts_with('_') || is_magic(module_name) } /// Returns `true` if a module name indicates private visibility. fn is_private_module(module_name: &str) -> bool { !is_public_module(module_name) } /// Return the stem of a module name (everything preceding the last dot). fn stem(path: &str) -> &str { if let Some(index) = path.rfind('.') { &path[..index] } else { path } } /// Infer the [`Visibility`] of a module from its path. pub(crate) fn module_visibility(module: Module) -> Visibility { match &module.source { ModuleSource::Path(path) => { if path.iter().any(|m| is_private_module(m)) { return Visibility::Private; } } ModuleSource::File(path) => { // Check to see if the filename itself indicates private visibility. // Ex) `_foo.py` (but not `__init__.py`) let mut components = path.iter().rev(); if let Some(filename) = components.next() { let module_name = filename.to_string_lossy(); let module_name = stem(&module_name); if is_private_module(module_name) { return Visibility::Private; } } } } Visibility::Public } /// Infer the [`Visibility`] of a function from its name. pub(crate) fn function_visibility(function: &ast::StmtFunctionDef) -> Visibility { if function.name.starts_with('_') { Visibility::Private } else { Visibility::Public } } /// Infer the [`Visibility`] of a method from its name and decorators. pub fn method_visibility(function: &ast::StmtFunctionDef) -> Visibility { // Is this a setter or deleter? if function.decorator_list.iter().any(|decorator| { UnqualifiedName::from_expr(&decorator.expression).is_some_and(|name| { name.segments() == [function.name.as_str(), "setter"] || name.segments() == [function.name.as_str(), "deleter"] }) }) { return Visibility::Private; } // Is the method non-private? if !function.name.starts_with('_') { return Visibility::Public; } // Is this a magic method? if is_magic(&function.name) { return Visibility::Public; } Visibility::Private } /// Infer the [`Visibility`] of a class from its name. pub(crate) fn class_visibility(class: &ast::StmtClassDef) -> Visibility { if class.name.starts_with('_') { Visibility::Private } else { Visibility::Public } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/analyze/imports.rs
crates/ruff_python_semantic/src/analyze/imports.rs
use ruff_python_ast::helpers::map_subscript; use ruff_python_ast::{self as ast, Expr, Stmt}; use crate::SemanticModel; /// Returns `true` if a [`Stmt`] is a `sys.path` modification, as in: /// ```python /// import sys /// /// sys.path.append("../") /// sys.path += ["../"] /// ``` pub fn is_sys_path_modification(stmt: &Stmt, semantic: &SemanticModel) -> bool { match stmt { Stmt::Expr(ast::StmtExpr { value, range: _, node_index: _, }) => match value.as_ref() { Expr::Call(ast::ExprCall { func, .. }) => semantic .resolve_qualified_name(func.as_ref()) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), [ "sys", "path", "append" | "insert" | "extend" | "remove" | "pop" | "clear" | "reverse" | "sort" ] ) }), _ => false, }, Stmt::AugAssign(ast::StmtAugAssign { target, .. }) => semantic .resolve_qualified_name(map_subscript(target)) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["sys", "path"])), _ => false, } } /// Returns `true` if a [`Stmt`] is an `os.environ` modification, as in: /// ```python /// import os /// /// os.environ["CUDA_VISIBLE_DEVICES"] = "4" /// ``` pub fn is_os_environ_modification(stmt: &Stmt, semantic: &SemanticModel) -> bool { match stmt { Stmt::Expr(ast::StmtExpr { value, .. }) => match value.as_ref() { Expr::Call(ast::ExprCall { func, .. }) => semantic .resolve_qualified_name(func.as_ref()) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), ["os", "putenv" | "unsetenv"] | [ "os", "environ", "update" | "pop" | "clear" | "setdefault" | "popitem" ] ) }), _ => false, }, Stmt::Delete(ast::StmtDelete { targets, .. }) => targets.iter().any(|target| { semantic .resolve_qualified_name(map_subscript(target)) .is_some_and(|qualified_name| { matches!(qualified_name.segments(), ["os", "environ"]) }) }), Stmt::Assign(ast::StmtAssign { targets, .. }) => targets.iter().any(|target| { semantic .resolve_qualified_name(map_subscript(target)) .is_some_and(|qualified_name| { matches!(qualified_name.segments(), ["os", "environ"]) }) }), Stmt::AnnAssign(ast::StmtAnnAssign { target, .. }) => semantic .resolve_qualified_name(map_subscript(target)) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["os", "environ"])), Stmt::AugAssign(ast::StmtAugAssign { target, .. }) => semantic .resolve_qualified_name(map_subscript(target)) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["os", "environ"])), _ => false, } } /// Returns `true` if a [`Stmt`] is a `matplotlib.use` activation, as in: /// ```python /// import matplotlib /// /// matplotlib.use("Agg") /// ``` pub fn is_matplotlib_activation(stmt: &Stmt, semantic: &SemanticModel) -> bool { let Stmt::Expr(ast::StmtExpr { value, range: _, node_index: _, }) = stmt else { return false; }; let Expr::Call(ast::ExprCall { func, .. }) = value.as_ref() else { return false; }; semantic .resolve_qualified_name(func.as_ref()) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["matplotlib", "use"])) } /// Returns `true` if a [`Stmt`] is a `pytest.importorskip()` call, as in: /// ```python /// import pytest /// /// pytest.importorskip("foo.bar") /// ``` pub fn is_pytest_importorskip(stmt: &Stmt, semantic: &SemanticModel) -> bool { let Stmt::Expr(ast::StmtExpr { value, .. }) = stmt else { return false; }; let Expr::Call(ast::ExprCall { func, .. }) = value.as_ref() else { return false; }; semantic .resolve_qualified_name(func.as_ref()) .is_some_and(|qualified_name| { matches!(qualified_name.segments(), ["pytest", "importorskip"]) }) } /// Returns `true` if a [`Stmt`] is a dynamic modification of the Python /// module search path, e.g., /// ```python /// import site /// /// site.addsitedir(...) /// ``` pub fn is_site_sys_path_modification(stmt: &Stmt, semantic: &SemanticModel) -> bool { if let Stmt::Expr(ast::StmtExpr { value, .. }) = stmt { if let Expr::Call(ast::ExprCall { func, .. }) = value.as_ref() { return semantic .resolve_qualified_name(func.as_ref()) .is_some_and(|qualified_name| { matches!(qualified_name.segments(), ["site", "addsitedir"]) }); } } false }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/analyze/class.rs
crates/ruff_python_semantic/src/analyze/class.rs
use std::collections::VecDeque; use rustc_hash::FxHashSet; use crate::analyze::typing; use crate::{BindingId, SemanticModel}; use ruff_python_ast as ast; use ruff_python_ast::helpers::map_subscript; use ruff_python_ast::name::QualifiedName; use ruff_python_ast::{ ExceptHandler, Expr, ExprName, ExprStarred, ExprSubscript, ExprTuple, Stmt, StmtFor, StmtIf, StmtMatch, StmtTry, StmtWhile, StmtWith, }; /// Return `true` if any base class matches a [`QualifiedName`] predicate. pub fn any_qualified_base_class( class_def: &ast::StmtClassDef, semantic: &SemanticModel, func: &dyn Fn(QualifiedName) -> bool, ) -> bool { any_base_class(class_def, semantic, &mut |expr| { semantic .resolve_qualified_name(map_subscript(expr)) .is_some_and(func) }) } /// Return `true` if any base class matches an [`Expr`] predicate. pub fn any_base_class( class_def: &ast::StmtClassDef, semantic: &SemanticModel, func: &mut dyn FnMut(&Expr) -> bool, ) -> bool { fn inner( class_def: &ast::StmtClassDef, semantic: &SemanticModel, func: &mut dyn FnMut(&Expr) -> bool, seen: &mut FxHashSet<BindingId>, ) -> bool { class_def.bases().iter().any(|expr| { // If the base class itself matches the pattern, then this does too. // Ex) `class Foo(BaseModel): ...` if func(expr) { return true; } // If the base class extends a class that matches the pattern, then this does too. // Ex) `class Bar(BaseModel): ...; class Foo(Bar): ...` if let Some(id) = semantic.lookup_attribute(map_subscript(expr)) { if seen.insert(id) { let binding = semantic.binding(id); if let Some(base_class) = binding .kind .as_class_definition() .map(|id| &semantic.scopes[*id]) .and_then(|scope| scope.kind.as_class()) { if inner(base_class, semantic, func, seen) { return true; } } } } false }) } if class_def.bases().is_empty() { return false; } inner(class_def, semantic, func, &mut FxHashSet::default()) } /// Returns an iterator over all base classes, beginning with the /// given class. /// /// The traversal of the class hierarchy is breadth-first, since /// this graph tends to have small width but could be rather deep. pub fn iter_super_class<'stmt>( class_def: &'stmt ast::StmtClassDef, semantic: &'stmt SemanticModel, ) -> impl Iterator<Item = &'stmt ast::StmtClassDef> { struct SuperClassIterator<'stmt> { semantic: &'stmt SemanticModel<'stmt>, to_visit: VecDeque<&'stmt ast::StmtClassDef>, seen: FxHashSet<BindingId>, } impl<'a> Iterator for SuperClassIterator<'a> { type Item = &'a ast::StmtClassDef; fn next(&mut self) -> Option<Self::Item> { let current = self.to_visit.pop_front()?; // Add all base classes to the to_visit list for expr in current.bases() { if let Some(id) = self.semantic.lookup_attribute(map_subscript(expr)) { if self.seen.insert(id) { let binding = self.semantic.binding(id); if let Some(base_class) = binding .kind .as_class_definition() .map(|id| &self.semantic.scopes[*id]) .and_then(|scope| scope.kind.as_class()) { self.to_visit.push_back(base_class); } } } } Some(current) } } SuperClassIterator { semantic, to_visit: VecDeque::from([class_def]), seen: FxHashSet::default(), } } /// Return `true` if any base class, including the given class, /// matches an [`ast::StmtClassDef`] predicate. pub fn any_super_class( class_def: &ast::StmtClassDef, semantic: &SemanticModel, func: &dyn Fn(&ast::StmtClassDef) -> bool, ) -> bool { iter_super_class(class_def, semantic).any(func) } #[derive(Clone, Debug)] pub struct ClassMemberDeclaration<'a> { kind: ClassMemberKind<'a>, boundness: ClassMemberBoundness, } impl<'a> ClassMemberDeclaration<'a> { pub fn kind(&self) -> &ClassMemberKind<'a> { &self.kind } pub fn boundness(&self) -> ClassMemberBoundness { self.boundness } } #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum ClassMemberBoundness { PossiblyUnbound, Bound, } impl ClassMemberBoundness { pub const fn is_bound(self) -> bool { matches!(self, Self::Bound) } pub const fn is_possibly_unbound(self) -> bool { matches!(self, Self::PossiblyUnbound) } } #[derive(Copy, Clone, Debug)] pub enum ClassMemberKind<'a> { Assign(&'a ast::StmtAssign), AnnAssign(&'a ast::StmtAnnAssign), FunctionDef(&'a ast::StmtFunctionDef), } pub fn any_member_declaration( class: &ast::StmtClassDef, func: &mut dyn FnMut(ClassMemberDeclaration) -> bool, ) -> bool { fn any_stmt_in_body( body: &[Stmt], func: &mut dyn FnMut(ClassMemberDeclaration) -> bool, boundness: ClassMemberBoundness, ) -> bool { body.iter().any(|stmt| { let kind = match stmt { Stmt::FunctionDef(function_def) => Some(ClassMemberKind::FunctionDef(function_def)), Stmt::Assign(assign) => Some(ClassMemberKind::Assign(assign)), Stmt::AnnAssign(assign) => Some(ClassMemberKind::AnnAssign(assign)), Stmt::With(StmtWith { body, .. }) => { if any_stmt_in_body(body, func, ClassMemberBoundness::PossiblyUnbound) { return true; } None } Stmt::For(StmtFor { body, orelse, .. }) | Stmt::While(StmtWhile { body, orelse, .. }) => { if any_stmt_in_body(body, func, ClassMemberBoundness::PossiblyUnbound) || any_stmt_in_body(orelse, func, ClassMemberBoundness::PossiblyUnbound) { return true; } None } Stmt::If(StmtIf { body, elif_else_clauses, .. }) => { if any_stmt_in_body(body, func, ClassMemberBoundness::PossiblyUnbound) || elif_else_clauses.iter().any(|it| { any_stmt_in_body(&it.body, func, ClassMemberBoundness::PossiblyUnbound) }) { return true; } None } Stmt::Match(StmtMatch { cases, .. }) => { if cases.iter().any(|it| { any_stmt_in_body(&it.body, func, ClassMemberBoundness::PossiblyUnbound) }) { return true; } None } Stmt::Try(StmtTry { body, handlers, orelse, finalbody, .. }) => { if any_stmt_in_body(body, func, ClassMemberBoundness::PossiblyUnbound) || any_stmt_in_body(orelse, func, ClassMemberBoundness::PossiblyUnbound) || any_stmt_in_body(finalbody, func, ClassMemberBoundness::PossiblyUnbound) || handlers.iter().any(|ExceptHandler::ExceptHandler(it)| { any_stmt_in_body(&it.body, func, ClassMemberBoundness::PossiblyUnbound) }) { return true; } None } // Technically, a method can be defined using a few more methods: // // ```python // class C1: // # Import // import __eq__ # Callable module // # ImportFrom // from module import __eq__ # Top level callable // # ExprNamed // (__eq__ := lambda self, other: True) // ``` // // Those cases are not yet supported because they're rare. Stmt::ClassDef(_) | Stmt::Return(_) | Stmt::Delete(_) | Stmt::AugAssign(_) | Stmt::TypeAlias(_) | Stmt::Raise(_) | Stmt::Assert(_) | Stmt::Import(_) | Stmt::ImportFrom(_) | Stmt::Global(_) | Stmt::Nonlocal(_) | Stmt::Expr(_) | Stmt::Pass(_) | Stmt::Break(_) | Stmt::Continue(_) | Stmt::IpyEscapeCommand(_) => None, }; if let Some(kind) = kind { if func(ClassMemberDeclaration { kind, boundness }) { return true; } } false }) } any_stmt_in_body(&class.body, func, ClassMemberBoundness::Bound) } /// Return `true` if `class_def` is a class that has one or more enum classes in its mro pub fn is_enumeration(class_def: &ast::StmtClassDef, semantic: &SemanticModel) -> bool { any_qualified_base_class(class_def, semantic, &|qualified_name| { matches!( qualified_name.segments(), [ "enum", "Enum" | "Flag" | "IntEnum" | "IntFlag" | "StrEnum" | "ReprEnum" | "CheckEnum" ] ) }) } /// Whether or not a class is a metaclass. Constructed by [`is_metaclass`]. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum IsMetaclass { Yes, No, Maybe, } impl IsMetaclass { pub const fn is_yes(self) -> bool { matches!(self, IsMetaclass::Yes) } } /// Check if a class has a metaclass-like `__new__` method signature. /// /// A metaclass-like `__new__` method signature has: /// 1. Exactly 5 parameters (including cls) /// 2. Second parameter annotated with `str` /// 3. Third parameter annotated with a `tuple` type /// 4. Fourth parameter annotated with a `dict` type /// 5. Fifth parameter is keyword-variadic (`**kwargs`) /// /// For example: /// /// ```python /// class MyMetaclass(django.db.models.base.ModelBase): /// def __new__(cls, name: str, bases: tuple[Any, ...], attrs: dict[str, Any], **kwargs: Any) -> MyMetaclass: /// ... /// ``` fn has_metaclass_new_signature(class_def: &ast::StmtClassDef, semantic: &SemanticModel) -> bool { // Look for a __new__ method in the class body for stmt in &class_def.body { let ast::Stmt::FunctionDef(ast::StmtFunctionDef { name, parameters, .. }) = stmt else { continue; }; if name != "__new__" { continue; } // Check if we have exactly 5 parameters (cls + 4 others) if parameters.len() != 5 { continue; } // Check that there is no variadic parameter if parameters.vararg.is_some() { continue; } // Check that the last parameter is keyword-variadic (**kwargs) if parameters.kwarg.is_none() { continue; } // Check parameter annotations, skipping the first parameter (cls) let mut param_iter = parameters.iter().skip(1); // Check second parameter (name: str) let Some(second_param) = param_iter.next() else { continue; }; if !second_param .annotation() .is_some_and(|annotation| semantic.match_builtin_expr(map_subscript(annotation), "str")) { continue; } // Check third parameter (bases: tuple[...]) let Some(third_param) = param_iter.next() else { continue; }; if !third_param.annotation().is_some_and(|annotation| { semantic.match_builtin_expr(map_subscript(annotation), "tuple") }) { continue; } // Check fourth parameter (attrs: dict[...]) let Some(fourth_param) = param_iter.next() else { continue; }; if !fourth_param.annotation().is_some_and(|annotation| { semantic.match_builtin_expr(map_subscript(annotation), "dict") }) { continue; } return true; } false } /// Returns `IsMetaclass::Yes` if the given class is definitely a metaclass, /// `IsMetaclass::No` if it's definitely *not* a metaclass, and /// `IsMetaclass::Maybe` otherwise. pub fn is_metaclass(class_def: &ast::StmtClassDef, semantic: &SemanticModel) -> IsMetaclass { let mut maybe = false; let is_base_class = any_base_class(class_def, semantic, &mut |expr| match expr { Expr::Call(ast::ExprCall { func, arguments, .. }) => { maybe = true; // Ex) `class Foo(type(Protocol)): ...` arguments.len() == 1 && semantic.match_builtin_expr(func.as_ref(), "type") } Expr::Subscript(ast::ExprSubscript { value, .. }) => { // Ex) `class Foo(type[int]): ...` semantic.match_builtin_expr(value.as_ref(), "type") } _ => semantic .resolve_qualified_name(expr) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), ["" | "builtins", "type"] | ["abc", "ABCMeta"] | ["enum", "EnumMeta" | "EnumType"] ) }), }); match (is_base_class, maybe) { (true, true) => IsMetaclass::Maybe, (true, false) => IsMetaclass::Yes, (false, _) => { // If it has >1 base class and a metaclass-like signature for `__new__`, // then it might be a metaclass. if class_def.bases().is_empty() { IsMetaclass::No } else if has_metaclass_new_signature(class_def, semantic) { IsMetaclass::Maybe } else { IsMetaclass::No } } } } /// Returns true if a class might be generic. /// /// A class is considered generic if at least one of its direct bases /// is subscripted with a `TypeVar`-like, /// or if it is defined using PEP 695 syntax. /// /// Therefore, a class *might* be generic if it uses PEP-695 syntax /// or at least one of its direct bases is a subscript expression that /// is subscripted with an object that *might* be a `TypeVar`-like. pub fn might_be_generic(class_def: &ast::StmtClassDef, semantic: &SemanticModel) -> bool { if class_def.type_params.is_some() { return true; } class_def.bases().iter().any(|base| { let Expr::Subscript(ExprSubscript { slice, .. }) = base else { return false; }; let Expr::Tuple(ExprTuple { elts, .. }) = slice.as_ref() else { return expr_might_be_typevar_like(slice, semantic); }; elts.iter() .any(|elt| expr_might_be_typevar_like(elt, semantic)) }) } fn expr_might_be_typevar_like(expr: &Expr, semantic: &SemanticModel) -> bool { is_known_typevar(expr, semantic) || expr_might_be_old_style_typevar_like(expr, semantic) } fn is_known_typevar(expr: &Expr, semantic: &SemanticModel) -> bool { semantic.match_typing_expr(expr, "AnyStr") } fn expr_might_be_old_style_typevar_like(expr: &Expr, semantic: &SemanticModel) -> bool { match expr { Expr::Attribute(..) => true, Expr::Name(name) => might_be_old_style_typevar_like(name, semantic), Expr::Starred(ExprStarred { value, .. }) => { expr_might_be_old_style_typevar_like(value, semantic) } _ => false, } } fn might_be_old_style_typevar_like(name: &ExprName, semantic: &SemanticModel) -> bool { let Some(binding) = semantic.only_binding(name).map(|id| semantic.binding(id)) else { return !semantic.has_builtin_binding(&name.id); }; typing::is_type_var_like(binding, semantic) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/analyze/function_type.rs
crates/ruff_python_semantic/src/analyze/function_type.rs
use ruff_python_ast::helpers::map_callable; use ruff_python_ast::name::{QualifiedName, UnqualifiedName}; use ruff_python_ast::{Decorator, Expr, Stmt, StmtExpr, StmtFunctionDef, StmtRaise}; use crate::model::SemanticModel; use crate::scope::Scope; #[derive(Debug, Copy, Clone)] pub enum FunctionType { Function, Method, ClassMethod, StaticMethod, /// `__new__` is an implicit static method but /// is treated similarly to class methods for several lint rules NewMethod, } /// Classify a function based on its scope, name, and decorators. pub fn classify( name: &str, decorator_list: &[Decorator], parent_scope: &Scope, semantic: &SemanticModel, classmethod_decorators: &[String], staticmethod_decorators: &[String], ) -> FunctionType { if !parent_scope.kind.is_class() { return FunctionType::Function; } if decorator_list .iter() .any(|decorator| is_static_method(decorator, semantic, staticmethod_decorators)) { FunctionType::StaticMethod } else if decorator_list .iter() .any(|decorator| is_class_method(decorator, semantic, classmethod_decorators)) { FunctionType::ClassMethod } else { match name { "__new__" => FunctionType::NewMethod, // Implicit static method. "__init_subclass__" | "__class_getitem__" => FunctionType::ClassMethod, // Implicit class methods. _ => FunctionType::Method, // Default to instance method. } } } /// Return `true` if this function is subject to the Liskov Substitution Principle. /// /// Type checkers will check nearly all methods for compliance with the Liskov Substitution /// Principle, but some methods are exempt. pub fn is_subject_to_liskov_substitution_principle( function_name: &str, decorator_list: &[Decorator], parent_scope: &Scope, semantic: &SemanticModel, classmethod_decorators: &[String], staticmethod_decorators: &[String], ) -> bool { let kind = classify( function_name, decorator_list, parent_scope, semantic, classmethod_decorators, staticmethod_decorators, ); match (kind, function_name) { (FunctionType::Function | FunctionType::NewMethod, _) => false, (FunctionType::Method, "__init__" | "__post_init__" | "__replace__") => false, (_, "__init_subclass__") => false, (FunctionType::Method | FunctionType::ClassMethod | FunctionType::StaticMethod, _) => true, } } /// Return `true` if a [`Decorator`] is indicative of a static method. /// Note: Implicit static methods like `__new__` are not considered. fn is_static_method( decorator: &Decorator, semantic: &SemanticModel, staticmethod_decorators: &[String], ) -> bool { let decorator = map_callable(&decorator.expression); // The decorator is an import, so should match against a qualified path. if semantic .resolve_qualified_name(decorator) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), ["" | "builtins", "staticmethod"] | ["abc", "abstractstaticmethod"] ) || staticmethod_decorators .iter() .any(|decorator| qualified_name == QualifiedName::from_dotted_name(decorator)) }) { return true; } // We do not have a resolvable call path, most likely from a decorator like // `@someproperty.setter`. Instead, match on the last element. if !staticmethod_decorators.is_empty() { if UnqualifiedName::from_expr(decorator).is_some_and(|name| { name.segments().last().is_some_and(|tail| { staticmethod_decorators .iter() .any(|decorator| tail == decorator) }) }) { return true; } } false } /// Return `true` if a [`Decorator`] is indicative of a class method. /// Note: Implicit class methods like `__init_subclass__` and `__class_getitem__` are not considered. fn is_class_method( decorator: &Decorator, semantic: &SemanticModel, classmethod_decorators: &[String], ) -> bool { let decorator = map_callable(&decorator.expression); // The decorator is an import, so should match against a qualified path. if semantic .resolve_qualified_name(decorator) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), ["" | "builtins", "classmethod"] | ["abc", "abstractclassmethod"] ) || classmethod_decorators .iter() .any(|decorator| qualified_name == QualifiedName::from_dotted_name(decorator)) }) { return true; } // We do not have a resolvable call path, most likely from a decorator like // `@someproperty.setter`. Instead, match on the last element. if !classmethod_decorators.is_empty() { if UnqualifiedName::from_expr(decorator).is_some_and(|name| { name.segments().last().is_some_and(|tail| { classmethod_decorators .iter() .any(|decorator| tail == decorator) }) }) { return true; } } false } /// Returns `true` if a function has an empty body, and is therefore a stub. /// /// A function body is considered to be empty if it contains only `pass` statements, `...` literals, /// `NotImplementedError` raises, or string literal statements (docstrings). pub fn is_stub(function_def: &StmtFunctionDef, semantic: &SemanticModel) -> bool { function_def.body.iter().all(|stmt| match stmt { Stmt::Pass(_) => true, Stmt::Expr(StmtExpr { value, range: _, node_index: _, }) => { matches!( value.as_ref(), Expr::StringLiteral(_) | Expr::EllipsisLiteral(_) ) } Stmt::Raise(StmtRaise { range: _, node_index: _, exc: exception, cause: _, }) => exception.as_ref().is_some_and(|exc| { semantic .resolve_builtin_symbol(map_callable(exc)) .is_some_and(|name| matches!(name, "NotImplementedError" | "NotImplemented")) }), _ => false, }) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/analyze/terminal.rs
crates/ruff_python_semantic/src/analyze/terminal.rs
use ruff_python_ast::{self as ast, ExceptHandler, Stmt}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Terminal { /// There is no known terminal. None, /// There is an implicit return (e.g., a path that doesn't return). Implicit, /// Every path through the function ends with a `raise` statement. Raise, /// No path through the function ends with a `return` statement. Return, /// Every path through the function ends with a `return` or `raise` statement. RaiseOrReturn, /// At least one path through the function ends with a `return` statement. ConditionalReturn, } impl Terminal { /// Returns the [`Terminal`] behavior of the function, if it can be determined. pub fn from_function(function: &ast::StmtFunctionDef) -> Terminal { Self::from_body(&function.body) } /// Returns `true` if the [`Terminal`] behavior includes at least one `return` path. pub fn has_any_return(self) -> bool { matches!( self, Self::Return | Self::RaiseOrReturn | Self::ConditionalReturn ) } /// Returns `true` if the [`Terminal`] behavior includes at least one implicit `return` path. pub fn has_implicit_return(self) -> bool { matches!(self, Self::None | Self::Implicit | Self::ConditionalReturn) } /// Returns the [`Terminal`] behavior of the body, if it can be determined. fn from_body(stmts: &[Stmt]) -> Terminal { let mut terminal = Terminal::None; for stmt in stmts { match stmt { Stmt::For(ast::StmtFor { body, orelse, .. }) | Stmt::While(ast::StmtWhile { body, orelse, .. }) => { if always_breaks(body) { continue; } terminal = terminal.and_then(Self::from_body(body)); if !sometimes_breaks(body) { terminal = terminal.and_then(Self::from_body(orelse)); } } Stmt::If(ast::StmtIf { body, elif_else_clauses, .. }) => { let branch_terminal = Terminal::branches( std::iter::once(Self::from_body(body)).chain( elif_else_clauses .iter() .map(|clause| Self::from_body(&clause.body)), ), ); // If the `if` statement is known to be exhaustive (by way of including an // `else`)... if elif_else_clauses.iter().any(|clause| clause.test.is_none()) { // And all branches return, then the `if` statement returns. terminal = terminal.and_then(branch_terminal); } else if branch_terminal.has_any_return() { // Otherwise, if any branch returns, we know this can't be a // non-returning function. terminal = terminal.and_then(Terminal::ConditionalReturn); } } Stmt::Match(ast::StmtMatch { cases, .. }) => { let branch_terminal = terminal.and_then(Terminal::branches( cases.iter().map(|case| Self::from_body(&case.body)), )); // If the `match` is known to be exhaustive (by way of including a wildcard // pattern)... if cases.iter().any(is_wildcard) { // And all branches return, then the `match` statement returns. terminal = terminal.and_then(branch_terminal); } else { // Otherwise, if any branch returns, we know this can't be a // non-returning function. if branch_terminal.has_any_return() { terminal = terminal.and_then(Terminal::ConditionalReturn); } } } Stmt::Try(ast::StmtTry { body, handlers, orelse, finalbody, .. }) => { // If the body returns, then this can't be a non-returning function. We assume // that _any_ statement in the body could raise an exception, so we don't // consider the body to be exhaustive. In other words, we assume the exception // handlers exist for a reason. let body_terminal = Self::from_body(body); if body_terminal.has_any_return() { terminal = terminal.and_then(Terminal::ConditionalReturn); } // If the `finally` block returns, the `try` block must also return. (Similarly, // if the `finally` block raises, the `try` block must also raise.) terminal = terminal.and_then(Self::from_body(finalbody)); let branch_terminal = Terminal::branches(handlers.iter().map(|handler| { let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { body, .. }) = handler; Self::from_body(body) })); if orelse.is_empty() { // If there's no `else`, we may fall through, so only mark that this can't // be a non-returning function if any of the branches return. if branch_terminal.has_any_return() { terminal = terminal.and_then(Terminal::ConditionalReturn); } } else { // If there's an `else`, we won't fall through. If all the handlers and // the `else` block return,, the `try` block also returns. terminal = terminal.and_then(branch_terminal.branch(Terminal::from_body(orelse))); } } Stmt::With(ast::StmtWith { body, .. }) => { terminal = terminal.and_then(Self::from_body(body)); } Stmt::Return(_) => { terminal = terminal.and_then(Terminal::RaiseOrReturn); } Stmt::Raise(_) => { terminal = terminal.and_then(Terminal::Raise); } _ => {} } } match terminal { Terminal::None => Terminal::Implicit, _ => terminal, } } /// Combine two [`Terminal`] operators, with one appearing after the other. fn and_then(self, other: Self) -> Self { match (self, other) { // If one of the operators is `None`, the result is the other operator. (Self::None, other) => other, (other, Self::None) => other, // If one of the operators is `Implicit`, the result is the other operator. (Self::Implicit, other) => other, (other, Self::Implicit) => other, // If both operators are conditional returns, the result is a conditional return. (Self::ConditionalReturn, Self::ConditionalReturn) => Self::ConditionalReturn, // If one of the operators is `Raise`, then the function ends with an explicit `raise` // or `return` statement. (Self::Raise, Self::ConditionalReturn) => Self::RaiseOrReturn, (Self::ConditionalReturn, Self::Raise) => Self::RaiseOrReturn, // If one of the operators is `Return`, then the function returns. (Self::Return, Self::ConditionalReturn) => Self::Return, (Self::ConditionalReturn, Self::Return) => Self::Return, // All paths through the function end with a `raise` statement. (Self::Raise, Self::Raise) => Self::Raise, // All paths through the function end with a `return` statement. (Self::Return, Self::Return) => Self::Return, // All paths through the function end with a `return` or `raise` statement. (Self::Raise, Self::Return) => Self::RaiseOrReturn, // All paths through the function end with a `return` or `raise` statement. (Self::Return, Self::Raise) => Self::RaiseOrReturn, // All paths through the function end with a `return` or `raise` statement. (Self::RaiseOrReturn, _) => Self::RaiseOrReturn, (_, Self::RaiseOrReturn) => Self::RaiseOrReturn, } } /// Combine two [`Terminal`] operators from different branches. fn branch(self, other: Self) -> Self { match (self, other) { // If one of the operators is `None`, the result is the other operator. (Self::None, other) => other, (other, Self::None) => other, // If one of the operators is `Implicit`, the other operator should be downgraded. (Self::Implicit, Self::Implicit) => Self::Implicit, (Self::Implicit, Self::Raise) => Self::Implicit, (Self::Raise, Self::Implicit) => Self::Implicit, (Self::Implicit, Self::Return) => Self::ConditionalReturn, (Self::Return, Self::Implicit) => Self::ConditionalReturn, (Self::Implicit, Self::RaiseOrReturn) => Self::ConditionalReturn, (Self::RaiseOrReturn, Self::Implicit) => Self::ConditionalReturn, (Self::Implicit, Self::ConditionalReturn) => Self::ConditionalReturn, (Self::ConditionalReturn, Self::Implicit) => Self::ConditionalReturn, // If both operators are conditional returns, the result is a conditional return. (Self::ConditionalReturn, Self::ConditionalReturn) => Self::ConditionalReturn, (Self::Raise, Self::ConditionalReturn) => Self::RaiseOrReturn, (Self::ConditionalReturn, Self::Raise) => Self::RaiseOrReturn, (Self::Return, Self::ConditionalReturn) => Self::Return, (Self::ConditionalReturn, Self::Return) => Self::Return, // All paths through the function end with a `raise` statement. (Self::Raise, Self::Raise) => Self::Raise, // All paths through the function end with a `return` statement. (Self::Return, Self::Return) => Self::Return, // All paths through the function end with a `return` or `raise` statement. (Self::Raise, Self::Return) => Self::RaiseOrReturn, // All paths through the function end with a `return` or `raise` statement. (Self::Return, Self::Raise) => Self::RaiseOrReturn, // All paths through the function end with a `return` or `raise` statement. (Self::RaiseOrReturn, _) => Self::RaiseOrReturn, (_, Self::RaiseOrReturn) => Self::RaiseOrReturn, } } /// Combine a series of [`Terminal`] operators. fn branches(iter: impl Iterator<Item = Terminal>) -> Terminal { iter.fold(Terminal::None, Terminal::branch) } } /// Returns `true` if the body may break via a `break` statement. fn sometimes_breaks(stmts: &[Stmt]) -> bool { for stmt in stmts { match stmt { Stmt::For(ast::StmtFor { body, orelse, .. }) => { if Terminal::from_body(body).has_any_return() { return false; } if sometimes_breaks(orelse) { return true; } } Stmt::While(ast::StmtWhile { body, orelse, .. }) => { if Terminal::from_body(body).has_any_return() { return false; } if sometimes_breaks(orelse) { return true; } } Stmt::If(ast::StmtIf { body, elif_else_clauses, .. }) => { if std::iter::once(body) .chain(elif_else_clauses.iter().map(|clause| &clause.body)) .any(|body| sometimes_breaks(body)) { return true; } } Stmt::Match(ast::StmtMatch { cases, .. }) => { if cases.iter().any(|case| sometimes_breaks(&case.body)) { return true; } } Stmt::Try(ast::StmtTry { body, handlers, orelse, finalbody, .. }) => { if sometimes_breaks(body) || handlers.iter().any(|handler| { let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { body, .. }) = handler; sometimes_breaks(body) }) || sometimes_breaks(orelse) || sometimes_breaks(finalbody) { return true; } } Stmt::With(ast::StmtWith { body, .. }) => { if sometimes_breaks(body) { return true; } } Stmt::Break(_) => return true, Stmt::Return(_) => return false, Stmt::Raise(_) => return false, _ => {} } } false } /// Returns `true` if the body may break via a `break` statement. fn always_breaks(stmts: &[Stmt]) -> bool { for stmt in stmts { match stmt { Stmt::Break(_) => return true, Stmt::Return(_) => return false, Stmt::Raise(_) => return false, _ => {} } } false } /// Returns true if the [`MatchCase`] is a wildcard pattern. fn is_wildcard(pattern: &ast::MatchCase) -> bool { /// Returns true if the [`Pattern`] is a wildcard pattern. fn is_wildcard_pattern(pattern: &ast::Pattern) -> bool { match pattern { ast::Pattern::MatchValue(_) | ast::Pattern::MatchSingleton(_) | ast::Pattern::MatchSequence(_) | ast::Pattern::MatchMapping(_) | ast::Pattern::MatchClass(_) | ast::Pattern::MatchStar(_) => false, ast::Pattern::MatchAs(ast::PatternMatchAs { pattern, .. }) => pattern.is_none(), ast::Pattern::MatchOr(ast::PatternMatchOr { patterns, .. }) => { patterns.iter().all(is_wildcard_pattern) } } } pattern.guard.is_none() && is_wildcard_pattern(&pattern.pattern) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/analyze/mod.rs
crates/ruff_python_semantic/src/analyze/mod.rs
pub mod class; pub mod function_type; pub mod imports; pub mod logging; pub mod terminal; pub mod type_inference; pub mod typing; pub mod visibility;
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/analyze/typing.rs
crates/ruff_python_semantic/src/analyze/typing.rs
//! Analysis rules for the `typing` module. use ruff_python_ast::helpers::{any_over_expr, map_subscript}; use ruff_python_ast::identifier::Identifier; use ruff_python_ast::name::QualifiedName; use ruff_python_ast::{ self as ast, Expr, ExprCall, ExprName, Operator, ParameterWithDefault, Parameters, Stmt, StmtAssign, }; use ruff_python_stdlib::typing::{ as_pep_585_generic, is_immutable_generic_type, is_immutable_non_generic_type, is_immutable_return_type, is_literal_member, is_mutable_return_type, is_pep_593_generic_member, is_pep_593_generic_type, is_standard_library_generic, is_standard_library_generic_member, is_standard_library_literal, is_typed_dict, is_typed_dict_member, }; use ruff_text_size::Ranged; use smallvec::{SmallVec, smallvec}; use crate::analyze::type_inference::{NumberLike, PythonType, ResolvedPythonType}; use crate::model::SemanticModel; use crate::{Binding, BindingKind, Modules}; #[derive(Debug, Copy, Clone)] pub enum Callable { Bool, Cast, NewType, TypeVar, NamedTuple, TypedDict, MypyExtension, TypeAliasType, } #[derive(Debug, Copy, Clone)] pub enum SubscriptKind { /// A subscript of the form `typing.Literal["foo", "bar"]`, i.e., a literal. Literal, /// A subscript of the form `typing.List[int]`, i.e., a generic. Generic, /// A subscript of the form `typing.Annotated[int, "foo"]`, i.e., a PEP 593 annotation. PEP593Annotation, /// A subscript of the form `typing.TypedDict[{"key": Type}]`, i.e., a [PEP 764] annotation. /// /// [PEP 764]: https://github.com/python/peps/pull/4082 TypedDict, } pub fn is_known_to_be_of_type_dict(semantic: &SemanticModel, expr: &ExprName) -> bool { let Some(binding) = semantic.only_binding(expr).map(|id| semantic.binding(id)) else { return false; }; is_dict(binding, semantic) } pub fn match_annotated_subscript<'a>( expr: &Expr, semantic: &SemanticModel, typing_modules: impl Iterator<Item = &'a str>, extend_generics: &[String], ) -> Option<SubscriptKind> { semantic .resolve_qualified_name(expr) .and_then(|qualified_name| { if is_standard_library_literal(qualified_name.segments()) { return Some(SubscriptKind::Literal); } if is_standard_library_generic(qualified_name.segments()) || extend_generics .iter() .map(|target| QualifiedName::from_dotted_name(target)) .any(|target| qualified_name == target) { return Some(SubscriptKind::Generic); } if is_pep_593_generic_type(qualified_name.segments()) { return Some(SubscriptKind::PEP593Annotation); } if is_typed_dict(qualified_name.segments()) { return Some(SubscriptKind::TypedDict); } for module in typing_modules { let module_qualified_name = QualifiedName::user_defined(module); if qualified_name.starts_with(&module_qualified_name) { if let Some(member) = qualified_name.segments().last() { if is_literal_member(member) { return Some(SubscriptKind::Literal); } if is_standard_library_generic_member(member) { return Some(SubscriptKind::Generic); } if is_pep_593_generic_member(member) { return Some(SubscriptKind::PEP593Annotation); } if is_typed_dict_member(member) { return Some(SubscriptKind::TypedDict); } } } } None }) } #[derive(Debug, Clone, Eq, PartialEq)] pub enum ModuleMember { /// A builtin symbol, like `"list"`. BuiltIn(&'static str), /// A module member, like `("collections", "deque")`. Member(&'static str, &'static str), } impl std::fmt::Display for ModuleMember { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { ModuleMember::BuiltIn(name) => std::write!(f, "{name}"), ModuleMember::Member(module, member) => std::write!(f, "{module}.{member}"), } } } /// Returns the PEP 585 standard library generic variant for a `typing` module reference, if such /// a variant exists. pub fn to_pep585_generic(expr: &Expr, semantic: &SemanticModel) -> Option<ModuleMember> { semantic .seen_module(Modules::TYPING | Modules::TYPING_EXTENSIONS) .then(|| semantic.resolve_qualified_name(expr)) .flatten() .and_then(|qualified_name| { let [module, member] = qualified_name.segments() else { return None; }; as_pep_585_generic(module, member).map(|(module, member)| { if module.is_empty() { ModuleMember::BuiltIn(member) } else { ModuleMember::Member(module, member) } }) }) } /// Return whether a given expression uses a PEP 585 standard library generic. pub fn is_pep585_generic( expr: &Expr, semantic: &SemanticModel, include_preview_generics: bool, ) -> bool { semantic .resolve_qualified_name(expr) .is_some_and(|qualified_name| match qualified_name.segments() { ["", "dict" | "frozenset" | "list" | "set" | "tuple" | "type"] | ["collections", "deque" | "defaultdict"] => true, ["asyncio", "Future" | "Task"] | ["collections", "ChainMap" | "Counter" | "OrderedDict"] | [ "contextlib", "AbstractAsyncContextManager" | "AbstractContextManager", ] | ["dataclasses", "Field"] | ["functools", "cached_property" | "partialmethod"] | ["os", "PathLike"] | [ "queue", "LifoQueue" | "PriorityQueue" | "Queue" | "SimpleQueue", ] | ["re", "Match" | "Pattern"] | ["shelve", "BsdDbShelf" | "DbfilenameShelf" | "Shelf"] | ["types", "MappingProxyType"] | [ "weakref", "WeakKeyDictionary" | "WeakMethod" | "WeakSet" | "WeakValueDictionary", ] | [ "collections", "abc", "AsyncGenerator" | "AsyncIterable" | "AsyncIterator" | "Awaitable" | "ByteString" | "Callable" | "Collection" | "Container" | "Coroutine" | "Generator" | "ItemsView" | "Iterable" | "Iterator" | "KeysView" | "Mapping" | "MappingView" | "MutableMapping" | "MutableSequence" | "MutableSet" | "Reversible" | "Sequence" | "Set" | "ValuesView", ] => include_preview_generics, _ => false, }) } #[derive(Debug, Copy, Clone)] pub enum Pep604Operator { /// The union operator, e.g., `Union[str, int]`, expressible as `str | int` after PEP 604. Union, /// The union operator, e.g., `Optional[str]`, expressible as `str | None` after PEP 604. Optional, } /// Return the PEP 604 operator variant to which the given subscript [`Expr`] corresponds, if any. pub fn to_pep604_operator( value: &Expr, slice: &Expr, semantic: &SemanticModel, ) -> Option<Pep604Operator> { /// Returns `true` if any argument in the slice is a quoted annotation. fn quoted_annotation(slice: &Expr) -> bool { match slice { Expr::StringLiteral(_) => true, Expr::Tuple(tuple) => tuple.iter().any(quoted_annotation), _ => false, } } /// Returns `true` if any argument in the slice is a starred expression. fn starred_annotation(slice: &Expr) -> bool { match slice { Expr::Starred(_) => true, Expr::Tuple(tuple) => tuple.iter().any(starred_annotation), _ => false, } } // If the typing modules were never imported, we'll never match below. if !semantic.seen_typing() { return None; } // If the slice is a forward reference (e.g., `Optional["Foo"]`), it can only be rewritten // if we're in a typing-only context. // // This, for example, is invalid, as Python will evaluate `"Foo" | None` at runtime in order to // populate the function's `__annotations__`: // ```python // def f(x: "Foo" | None): ... // ``` // // This, however, is valid: // ```python // def f(): // x: "Foo" | None // ``` if quoted_annotation(slice) { if semantic.execution_context().is_runtime() { return None; } } // If any of the elements are starred expressions, we can't rewrite the subscript: // ```python // def f(x: Union[*int, str]): ... // ``` if starred_annotation(slice) { return None; } semantic .resolve_qualified_name(value) .as_ref() .and_then(|qualified_name| { if semantic.match_typing_qualified_name(qualified_name, "Optional") { Some(Pep604Operator::Optional) } else if semantic.match_typing_qualified_name(qualified_name, "Union") { Some(Pep604Operator::Union) } else { None } }) } /// Return `true` if `Expr` represents a reference to a type annotation that resolves to an /// immutable type. pub fn is_immutable_annotation( expr: &Expr, semantic: &SemanticModel, extend_immutable_calls: &[QualifiedName], ) -> bool { match expr { Expr::Name(_) | Expr::Attribute(_) => { semantic .resolve_qualified_name(expr) .is_some_and(|qualified_name| { is_immutable_non_generic_type(qualified_name.segments()) || is_immutable_generic_type(qualified_name.segments()) || extend_immutable_calls.contains(&qualified_name) }) } Expr::Subscript(ast::ExprSubscript { value, slice, .. }) => semantic .resolve_qualified_name(value) .is_some_and(|qualified_name| { if is_immutable_generic_type(qualified_name.segments()) { true } else if matches!(qualified_name.segments(), ["typing", "Union"]) { if let Expr::Tuple(tuple) = &**slice { tuple.iter().all(|element| { is_immutable_annotation(element, semantic, extend_immutable_calls) }) } else { false } } else if matches!(qualified_name.segments(), ["typing", "Optional"]) { is_immutable_annotation(slice, semantic, extend_immutable_calls) } else if is_pep_593_generic_type(qualified_name.segments()) { if let Expr::Tuple(ast::ExprTuple { elts, .. }) = slice.as_ref() { elts.first().is_some_and(|elt| { is_immutable_annotation(elt, semantic, extend_immutable_calls) }) } else { false } } else { false } }), Expr::BinOp(ast::ExprBinOp { left, op: Operator::BitOr, right, range: _, node_index: _, }) => { is_immutable_annotation(left, semantic, extend_immutable_calls) && is_immutable_annotation(right, semantic, extend_immutable_calls) } Expr::NoneLiteral(_) => true, _ => false, } } /// Return `true` if `func` is a function that returns an immutable value. pub fn is_immutable_func( func: &Expr, semantic: &SemanticModel, extend_immutable_calls: &[QualifiedName], ) -> bool { semantic .resolve_qualified_name(map_subscript(func)) .is_some_and(|qualified_name| { is_immutable_return_type(qualified_name.segments()) || extend_immutable_calls.contains(&qualified_name) }) } /// Return `true` if `name` is bound to the `typing.NewType` call where the original type is /// immutable. /// /// For example: /// ```python /// from typing import NewType /// /// UserId = NewType("UserId", int) /// ``` /// /// Here, `name` would be `UserId`. pub fn is_immutable_newtype_call( name: &ast::ExprName, semantic: &SemanticModel, extend_immutable_calls: &[QualifiedName], ) -> bool { let Some(binding) = semantic.only_binding(name).map(|id| semantic.binding(id)) else { return false; }; if !binding.kind.is_assignment() { return false; } let Some(Stmt::Assign(StmtAssign { value, .. })) = binding.statement(semantic) else { return false; }; let Expr::Call(ExprCall { func, arguments, .. }) = value.as_ref() else { return false; }; if !semantic.match_typing_expr(func, "NewType") { return false; } if arguments.len() != 2 { return false; } let Some(original_type) = arguments.find_argument_value("tp", 1) else { return false; }; is_immutable_annotation(original_type, semantic, extend_immutable_calls) } /// Return `true` if `func` is a function that returns a mutable value. pub fn is_mutable_func(func: &Expr, semantic: &SemanticModel) -> bool { semantic .resolve_qualified_name(func) .as_ref() .map(QualifiedName::segments) .is_some_and(is_mutable_return_type) } /// Return `true` if `expr` is an expression that resolves to a mutable value. pub fn is_mutable_expr(expr: &Expr, semantic: &SemanticModel) -> bool { match expr { Expr::List(_) | Expr::Dict(_) | Expr::Set(_) | Expr::ListComp(_) | Expr::DictComp(_) | Expr::SetComp(_) => true, Expr::Call(ast::ExprCall { func, .. }) => is_mutable_func(map_subscript(func), semantic), _ => false, } } /// Return `true` if [`ast::StmtIf`] is a guard for a type-checking block. pub fn is_type_checking_block(stmt: &ast::StmtIf, semantic: &SemanticModel) -> bool { let ast::StmtIf { test, .. } = stmt; match test.as_ref() { // As long as the symbol's name is "TYPE_CHECKING" we will treat it like `typing.TYPE_CHECKING` // for this specific check even if it's defined somewhere else, like the current module. // Ex) `if TYPE_CHECKING:` Expr::Name(ast::ExprName { id, .. }) => { id == "TYPE_CHECKING" // Ex) `if TC:` with `from typing import TYPE_CHECKING as TC` || semantic.match_typing_expr(test, "TYPE_CHECKING") } // Ex) `if typing.TYPE_CHECKING:` Expr::Attribute(ast::ExprAttribute { attr, .. }) => attr == "TYPE_CHECKING", _ => false, } } /// Returns `true` if the [`ast::StmtIf`] is a version-checking block (e.g., `if sys.version_info >= ...:`). pub fn is_sys_version_block(stmt: &ast::StmtIf, semantic: &SemanticModel) -> bool { let ast::StmtIf { test, .. } = stmt; any_over_expr(test, &|expr| { semantic .resolve_qualified_name(expr) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), ["sys", "version_info" | "platform"] ) }) }) } /// Traverse a "union" type annotation, applying `func` to each union member. /// /// Supports traversal of `Union` and `|` union expressions. /// /// The function is called with each expression in the union (excluding declarations of nested /// unions) and the parent expression. pub fn traverse_union<'a, F>(func: &mut F, semantic: &SemanticModel, expr: &'a Expr) where F: FnMut(&'a Expr, &'a Expr), { traverse_union_options(func, semantic, expr, UnionTraversalOptions::default()); } /// Traverse a "union" type annotation, applying `func` to each union member. /// /// Supports traversal of `Union`, `|`, and `Optional` union expressions. /// /// The function is called with each expression in the union (excluding declarations of nested /// unions) and the parent expression. pub fn traverse_union_and_optional<'a, F>(func: &mut F, semantic: &SemanticModel, expr: &'a Expr) where F: FnMut(&'a Expr, &'a Expr), { traverse_union_options( func, semantic, expr, UnionTraversalOptions { traverse_optional: true, }, ); } #[derive(Debug, Clone, Copy, Default)] /// Options for traversing union types. /// /// See also [`traverse_union_options`]. struct UnionTraversalOptions { traverse_optional: bool, } fn traverse_union_options<'a, F>( func: &mut F, semantic: &SemanticModel, expr: &'a Expr, options: UnionTraversalOptions, ) where F: FnMut(&'a Expr, &'a Expr), { fn inner<'a, F>( func: &mut F, semantic: &SemanticModel, expr: &'a Expr, parent: Option<&'a Expr>, options: UnionTraversalOptions, ) where F: FnMut(&'a Expr, &'a Expr), { // Ex) `x | y` if let Expr::BinOp(ast::ExprBinOp { op: Operator::BitOr, left, right, range: _, node_index: _, }) = expr { // The union data structure usually looks like this: // a | b | c -> (a | b) | c // // However, parenthesized expressions can coerce it into any structure: // a | (b | c) // // So we have to traverse both branches in order (left, then right), to report members // in the order they appear in the source code. // Traverse the left then right arms inner(func, semantic, left, Some(expr), options); inner(func, semantic, right, Some(expr), options); return; } if let Expr::Subscript(ast::ExprSubscript { value, slice, .. }) = expr { // Ex) `Union[x, y]` if semantic.match_typing_expr(value, "Union") { if let Expr::Tuple(tuple) = &**slice { // Traverse each element of the tuple within the union recursively to handle cases // such as `Union[..., Union[...]]` tuple .iter() .for_each(|elem| inner(func, semantic, elem, Some(expr), options)); return; } // Ex) `Union[Union[a, b]]` and `Union[a | b | c]` inner(func, semantic, slice, Some(expr), options); return; } // Ex) `Optional[x]` if options.traverse_optional && semantic.match_typing_expr(value, "Optional") { inner(func, semantic, value, Some(expr), options); inner(func, semantic, slice, Some(expr), options); return; } } // Otherwise, call the function on expression, if it's not the top-level expression. if let Some(parent) = parent { func(expr, parent); } } inner(func, semantic, expr, None, options); } /// Traverse a "literal" type annotation, applying `func` to each literal member. /// /// The function is called with each expression in the literal (excluding declarations of nested /// literals) and the parent expression. pub fn traverse_literal<'a, F>(func: &mut F, semantic: &SemanticModel, expr: &'a Expr) where F: FnMut(&'a Expr, &'a Expr), { fn inner<'a, F>( func: &mut F, semantic: &SemanticModel, expr: &'a Expr, parent: Option<&'a Expr>, ) where F: FnMut(&'a Expr, &'a Expr), { // Ex) `Literal[x, y]` if let Expr::Subscript(ast::ExprSubscript { value, slice, .. }) = expr { if semantic.match_typing_expr(value, "Literal") { match &**slice { Expr::Tuple(tuple) => { // Traverse each element of the tuple within the literal recursively to handle cases // such as `Literal[..., Literal[...]]` for element in tuple { inner(func, semantic, element, Some(expr)); } } other => { // Ex) `Literal[Literal[...]]` inner(func, semantic, other, Some(expr)); } } } } else { // Otherwise, call the function on expression, if it's not the top-level expression. if let Some(parent) = parent { func(expr, parent); } } } inner(func, semantic, expr, None); } /// Abstraction for a type checker, conservatively checks for the intended type(s). pub trait TypeChecker { /// Check annotation expression to match the intended type(s). fn match_annotation(annotation: &Expr, semantic: &SemanticModel) -> bool; /// Check initializer expression to match the intended type(s). fn match_initializer(initializer: &Expr, semantic: &SemanticModel) -> bool; } /// Check if the type checker accepts the given binding with the given name. /// /// NOTE: this function doesn't perform more serious type inference, so it won't be able /// to understand if the value gets initialized from a call to a function always returning /// lists. This also implies no interfile analysis. pub fn check_type<T: TypeChecker>(binding: &Binding, semantic: &SemanticModel) -> bool { match binding.kind { BindingKind::Assignment => match binding.statement(semantic) { // Given: // // ```python // x = init_expr // ``` // // The type checker might know how to infer the type based on `init_expr`. Some(Stmt::Assign(ast::StmtAssign { targets, value, .. })) => targets .iter() .find_map(|target| match_value(binding, target, value)) .is_some_and(|value| T::match_initializer(value, semantic)), // ```python // x: annotation = some_expr // ``` // // In this situation, we check only the annotation. Some(Stmt::AnnAssign(ast::StmtAnnAssign { annotation, .. })) => { T::match_annotation(annotation, semantic) } _ => false, }, BindingKind::NamedExprAssignment => { // ```python // if (x := some_expr) is not None: // ... // ``` binding.source.is_some_and(|source| { semantic .expressions(source) .find_map(|expr| expr.as_named_expr()) .and_then(|ast::ExprNamed { target, value, .. }| { match_value(binding, target, value) }) .is_some_and(|value| T::match_initializer(value, semantic)) }) } BindingKind::WithItemVar => match binding.statement(semantic) { // ```python // with open("file.txt") as x: // ... // ``` Some(Stmt::With(ast::StmtWith { items, .. })) => items .iter() .find_map(|item| { let target = item.optional_vars.as_ref()?; let value = &item.context_expr; match_value(binding, target, value) }) .is_some_and(|value| T::match_initializer(value, semantic)), _ => false, }, BindingKind::Argument => match binding.statement(semantic) { // ```python // def foo(x: annotation): // ... // ``` // // We trust the annotation and see if the type checker matches the annotation. Some(Stmt::FunctionDef(ast::StmtFunctionDef { parameters, .. })) => { let Some(parameter) = find_parameter(parameters, binding) else { return false; }; let Some(annotation) = parameter.annotation() else { return false; }; T::match_annotation(annotation, semantic) } _ => false, }, BindingKind::Annotation => match binding.statement(semantic) { // ```python // x: annotation // ``` // // It's a typed declaration, type annotation is the only source of information. Some(Stmt::AnnAssign(ast::StmtAnnAssign { annotation, .. })) => { T::match_annotation(annotation, semantic) } _ => false, }, BindingKind::FunctionDefinition(_) => match binding.statement(semantic) { // ```python // def foo() -> int: // ... // ``` Some(Stmt::FunctionDef(ast::StmtFunctionDef { returns, .. })) => returns .as_ref() .is_some_and(|return_ann| T::match_annotation(return_ann, semantic)), _ => false, }, _ => false, } } /// Type checker for builtin types. trait BuiltinTypeChecker { /// Builtin type name. const BUILTIN_TYPE_NAME: &'static str; /// Type name as found in the `Typing` module. const TYPING_NAME: Option<&'static str>; /// [`PythonType`] associated with the intended type. const EXPR_TYPE: PythonType; /// Check annotation expression to match the intended type. fn match_annotation(annotation: &Expr, semantic: &SemanticModel) -> bool { let value = map_subscript(annotation); semantic.match_builtin_expr(value, Self::BUILTIN_TYPE_NAME) || Self::TYPING_NAME.is_some_and(|name| semantic.match_typing_expr(value, name)) } /// Check initializer expression to match the intended type. fn match_initializer(initializer: &Expr, semantic: &SemanticModel) -> bool { Self::match_expr_type(initializer) || Self::match_builtin_constructor(initializer, semantic) } /// Check if the type can be inferred from the given expression. fn match_expr_type(initializer: &Expr) -> bool { let init_type: ResolvedPythonType = initializer.into(); match init_type { ResolvedPythonType::Atom(atom) => atom == Self::EXPR_TYPE, _ => false, } } /// Check if the given expression corresponds to a constructor call of the builtin type. fn match_builtin_constructor(initializer: &Expr, semantic: &SemanticModel) -> bool { let Expr::Call(ast::ExprCall { func, .. }) = initializer else { return false; }; semantic.match_builtin_expr(func, Self::BUILTIN_TYPE_NAME) } } impl<T: BuiltinTypeChecker> TypeChecker for T { fn match_annotation(annotation: &Expr, semantic: &SemanticModel) -> bool { <Self as BuiltinTypeChecker>::match_annotation(annotation, semantic) } fn match_initializer(initializer: &Expr, semantic: &SemanticModel) -> bool { <Self as BuiltinTypeChecker>::match_initializer(initializer, semantic) } } struct ListChecker; impl BuiltinTypeChecker for ListChecker { const BUILTIN_TYPE_NAME: &'static str = "list"; const TYPING_NAME: Option<&'static str> = Some("List"); const EXPR_TYPE: PythonType = PythonType::List; } struct DictChecker; impl BuiltinTypeChecker for DictChecker { const BUILTIN_TYPE_NAME: &'static str = "dict"; const TYPING_NAME: Option<&'static str> = Some("Dict"); const EXPR_TYPE: PythonType = PythonType::Dict; } struct SetChecker; impl BuiltinTypeChecker for SetChecker { const BUILTIN_TYPE_NAME: &'static str = "set"; const TYPING_NAME: Option<&'static str> = Some("Set"); const EXPR_TYPE: PythonType = PythonType::Set; } struct StringChecker; impl BuiltinTypeChecker for StringChecker { const BUILTIN_TYPE_NAME: &'static str = "str"; const TYPING_NAME: Option<&'static str> = None; const EXPR_TYPE: PythonType = PythonType::String; } struct BytesChecker; impl BuiltinTypeChecker for BytesChecker { const BUILTIN_TYPE_NAME: &'static str = "bytes"; const TYPING_NAME: Option<&'static str> = None; const EXPR_TYPE: PythonType = PythonType::Bytes; } struct TupleChecker; impl BuiltinTypeChecker for TupleChecker { const BUILTIN_TYPE_NAME: &'static str = "tuple"; const TYPING_NAME: Option<&'static str> = Some("Tuple"); const EXPR_TYPE: PythonType = PythonType::Tuple; } struct IntChecker; impl BuiltinTypeChecker for IntChecker { const BUILTIN_TYPE_NAME: &'static str = "int"; const TYPING_NAME: Option<&'static str> = None; const EXPR_TYPE: PythonType = PythonType::Number(NumberLike::Integer); } struct FloatChecker; impl BuiltinTypeChecker for FloatChecker { const BUILTIN_TYPE_NAME: &'static str = "float"; const TYPING_NAME: Option<&'static str> = None; const EXPR_TYPE: PythonType = PythonType::Number(NumberLike::Float); } pub struct IoBaseChecker; impl TypeChecker for IoBaseChecker { fn match_annotation(annotation: &Expr, semantic: &SemanticModel) -> bool { semantic .resolve_qualified_name(annotation) .is_some_and(|qualified_name| { if semantic.match_typing_qualified_name(&qualified_name, "IO") { return true; } if semantic.match_typing_qualified_name(&qualified_name, "BinaryIO") { return true; } if semantic.match_typing_qualified_name(&qualified_name, "TextIO") { return true; } matches!( qualified_name.segments(), [ "io", "IOBase" | "RawIOBase" | "BufferedIOBase" | "TextIOBase" | "BytesIO" | "StringIO" | "BufferedReader" | "BufferedWriter" | "BufferedRandom" | "BufferedRWPair" | "TextIOWrapper" ] | ["os", "Path" | "PathLike"] | [ "pathlib", "Path" | "PurePath" | "PurePosixPath" | "PureWindowsPath" ] ) }) } fn match_initializer(initializer: &Expr, semantic: &SemanticModel) -> bool { let Expr::Call(ast::ExprCall { func, .. }) = initializer else { return false; }; // Ex) `pathlib.Path("file.txt")` if let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func.as_ref() { if attr.as_str() == "open" { if let Expr::Call(ast::ExprCall { func, .. }) = value.as_ref() { return semantic .resolve_qualified_name(func) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), [ "pathlib", "Path" | "PurePath" | "PurePosixPath" | "PureWindowsPath" ] ) }); } } } // Ex) `open("file.txt")` semantic .resolve_qualified_name(func) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), ["io", "open" | "open_code"] | ["os" | "" | "builtins", "open"] ) }) } } pub struct PathlibPathChecker; impl PathlibPathChecker { fn is_pathlib_path_constructor(semantic: &SemanticModel, expr: &Expr) -> bool { let Some(qualified_name) = semantic.resolve_qualified_name(expr) else { return false;
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/analyze/logging.rs
crates/ruff_python_semantic/src/analyze/logging.rs
use ruff_python_ast::helpers::is_const_true; use ruff_python_ast::name::{QualifiedName, UnqualifiedName}; use ruff_python_ast::{self as ast, Arguments, Expr, Keyword}; use crate::model::SemanticModel; /// Return `true` if the given `Expr` is a potential logging call. Matches /// `logging.error`, `logger.error`, `self.logger.error`, etc., but not /// arbitrary `foo.error` calls. /// /// It also matches direct `logging.error` calls when the `logging` module /// is aliased. Example: /// ```python /// import logging as bar /// /// # This is detected to be a logger candidate. /// bar.error() /// ``` pub fn is_logger_candidate( func: &Expr, semantic: &SemanticModel, logger_objects: &[String], ) -> bool { let Expr::Attribute(ast::ExprAttribute { value, .. }) = func else { return false; }; // If the attribute is an inline instantiation, match against known constructors. if let Expr::Call(ast::ExprCall { func, .. }) = &**value { return semantic .resolve_qualified_name(func) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), ["logging", "getLogger" | "Logger"] ) }); } // If the symbol was imported from another module, ensure that it's either a user-specified // logger object, the `logging` module itself, or `flask.current_app.logger`. if let Some(qualified_name) = semantic.resolve_qualified_name(value) { if matches!( qualified_name.segments(), ["logging"] | ["flask", "current_app", "logger"] ) { return true; } if logger_objects .iter() .any(|logger| QualifiedName::from_dotted_name(logger) == qualified_name) { return true; } return false; } // Otherwise, if the symbol was defined in the current module, match against some common // logger names. if let Some(name) = UnqualifiedName::from_expr(value) { if let Some(tail) = name.segments().last() { if tail.starts_with("log") || tail.ends_with("logger") || tail.ends_with("logging") || tail.starts_with("LOG") || tail.ends_with("LOGGER") || tail.ends_with("LOGGING") { return true; } } } false } /// If the keywords to a logging call contain `exc_info=True` or `exc_info=sys.exc_info()`, /// return the `Keyword` for `exc_info`. pub fn exc_info<'a>(arguments: &'a Arguments, semantic: &SemanticModel) -> Option<&'a Keyword> { let exc_info = arguments.find_keyword("exc_info")?; // Ex) `logging.error("...", exc_info=True)` if is_const_true(&exc_info.value) { return Some(exc_info); } // Ex) `logging.error("...", exc_info=sys.exc_info())` if exc_info .value .as_call_expr() .and_then(|call| semantic.resolve_qualified_name(&call.func)) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["sys", "exc_info"])) { return Some(exc_info); } None }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/analyze/type_inference.rs
crates/ruff_python_semantic/src/analyze/type_inference.rs
//! Analysis rules to perform basic type inference on individual expressions. use rustc_hash::FxHashSet; use ruff_python_ast as ast; use ruff_python_ast::{Expr, Operator, UnaryOp}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum ResolvedPythonType { /// The expression resolved to a single known type, like `str` or `int`. Atom(PythonType), /// The expression resolved to a union of known types, like `str | int`. Union(FxHashSet<PythonType>), /// The expression resolved to an unknown type, like a variable or function call. Unknown, /// The expression resolved to a `TypeError`, like `1 + "hello"`. TypeError, } impl ResolvedPythonType { #[must_use] pub fn union(self, other: Self) -> Self { match (self, other) { (Self::TypeError, _) | (_, Self::TypeError) => Self::TypeError, (Self::Unknown, _) | (_, Self::Unknown) => Self::Unknown, (Self::Atom(a), Self::Atom(b)) => { if a.is_subtype_of(b) { Self::Atom(b) } else if b.is_subtype_of(a) { Self::Atom(a) } else { Self::Union(FxHashSet::from_iter([a, b])) } } (Self::Atom(a), Self::Union(mut b)) => { // If `a` is a subtype of any of the types in `b`, then `a` is // redundant. if !b.iter().any(|b_element| a.is_subtype_of(*b_element)) { b.insert(a); } Self::Union(b) } (Self::Union(mut a), Self::Atom(b)) => { // If `b` is a subtype of any of the types in `a`, then `b` is // redundant. if !a.iter().any(|a_element| b.is_subtype_of(*a_element)) { a.insert(b); } Self::Union(a) } (Self::Union(mut a), Self::Union(b)) => { for b_element in b { // If `b_element` is a subtype of any of the types in `a`, then // `b_element` is redundant. if !a .iter() .any(|a_element| b_element.is_subtype_of(*a_element)) { a.insert(b_element); } } Self::Union(a) } } } } impl From<&Expr> for ResolvedPythonType { fn from(expr: &Expr) -> Self { match expr { // Primitives. Expr::Dict(_) => ResolvedPythonType::Atom(PythonType::Dict), Expr::DictComp(_) => ResolvedPythonType::Atom(PythonType::Dict), Expr::Set(_) => ResolvedPythonType::Atom(PythonType::Set), Expr::SetComp(_) => ResolvedPythonType::Atom(PythonType::Set), Expr::List(_) => ResolvedPythonType::Atom(PythonType::List), Expr::ListComp(_) => ResolvedPythonType::Atom(PythonType::List), Expr::Tuple(_) => ResolvedPythonType::Atom(PythonType::Tuple), Expr::Generator(_) => ResolvedPythonType::Atom(PythonType::Generator), Expr::FString(_) => ResolvedPythonType::Atom(PythonType::String), Expr::TString(_) => ResolvedPythonType::Unknown, Expr::StringLiteral(_) => ResolvedPythonType::Atom(PythonType::String), Expr::BytesLiteral(_) => ResolvedPythonType::Atom(PythonType::Bytes), Expr::NumberLiteral(ast::ExprNumberLiteral { value, .. }) => match value { ast::Number::Int(_) => { ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)) } ast::Number::Float(_) => { ResolvedPythonType::Atom(PythonType::Number(NumberLike::Float)) } ast::Number::Complex { .. } => { ResolvedPythonType::Atom(PythonType::Number(NumberLike::Complex)) } }, Expr::BooleanLiteral(_) => { ResolvedPythonType::Atom(PythonType::Number(NumberLike::Bool)) } Expr::NoneLiteral(_) => ResolvedPythonType::Atom(PythonType::None), Expr::EllipsisLiteral(_) => ResolvedPythonType::Atom(PythonType::Ellipsis), // Simple container expressions. Expr::Named(ast::ExprNamed { value, .. }) => ResolvedPythonType::from(value.as_ref()), Expr::If(ast::ExprIf { body, orelse, .. }) => { let body = ResolvedPythonType::from(body.as_ref()); let orelse = ResolvedPythonType::from(orelse.as_ref()); body.union(orelse) } // Boolean operators. Expr::BoolOp(ast::ExprBoolOp { values, .. }) => values .iter() .map(ResolvedPythonType::from) .reduce(ResolvedPythonType::union) .unwrap_or(ResolvedPythonType::Unknown), // Unary operators. Expr::UnaryOp(ast::ExprUnaryOp { operand, op, .. }) => match op { UnaryOp::Invert => match ResolvedPythonType::from(operand.as_ref()) { ResolvedPythonType::Atom(PythonType::Number( NumberLike::Bool | NumberLike::Integer, )) => ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)), ResolvedPythonType::Atom(_) => ResolvedPythonType::TypeError, _ => ResolvedPythonType::Unknown, }, // Ex) `not 1.0` UnaryOp::Not => ResolvedPythonType::Atom(PythonType::Number(NumberLike::Bool)), // Ex) `+1` or `-1` UnaryOp::UAdd | UnaryOp::USub => match ResolvedPythonType::from(operand.as_ref()) { ResolvedPythonType::Atom(PythonType::Number(number)) => { ResolvedPythonType::Atom(PythonType::Number( if number == NumberLike::Bool { NumberLike::Integer } else { number }, )) } ResolvedPythonType::Atom(_) => ResolvedPythonType::TypeError, _ => ResolvedPythonType::Unknown, }, }, // Binary operators. Expr::BinOp(ast::ExprBinOp { left, op, right, .. }) => { match op { Operator::Add => { match ( ResolvedPythonType::from(left.as_ref()), ResolvedPythonType::from(right.as_ref()), ) { // Ex) `"Hello" + "world"` ( ResolvedPythonType::Atom(PythonType::String), ResolvedPythonType::Atom(PythonType::String), ) => return ResolvedPythonType::Atom(PythonType::String), // Ex) `b"Hello" + b"world"` ( ResolvedPythonType::Atom(PythonType::Bytes), ResolvedPythonType::Atom(PythonType::Bytes), ) => return ResolvedPythonType::Atom(PythonType::Bytes), // Ex) `[1] + [2]` ( ResolvedPythonType::Atom(PythonType::List), ResolvedPythonType::Atom(PythonType::List), ) => return ResolvedPythonType::Atom(PythonType::List), // Ex) `(1, 2) + (3, 4)` ( ResolvedPythonType::Atom(PythonType::Tuple), ResolvedPythonType::Atom(PythonType::Tuple), ) => return ResolvedPythonType::Atom(PythonType::Tuple), // Ex) `1 + 1.0` ( ResolvedPythonType::Atom(PythonType::Number(left)), ResolvedPythonType::Atom(PythonType::Number(right)), ) => { return ResolvedPythonType::Atom(PythonType::Number( left.coerce(right), )); } // Ex) `"a" + 1` (ResolvedPythonType::Atom(_), ResolvedPythonType::Atom(_)) => { return ResolvedPythonType::TypeError; } _ => {} } } Operator::Sub => { match ( ResolvedPythonType::from(left.as_ref()), ResolvedPythonType::from(right.as_ref()), ) { // Ex) `1 - 1` ( ResolvedPythonType::Atom(PythonType::Number(left)), ResolvedPythonType::Atom(PythonType::Number(right)), ) => { return ResolvedPythonType::Atom(PythonType::Number( left.coerce(right), )); } // Ex) `{1, 2} - {2}` ( ResolvedPythonType::Atom(PythonType::Set), ResolvedPythonType::Atom(PythonType::Set), ) => return ResolvedPythonType::Atom(PythonType::Set), // Ex) `"a" - "b"` (ResolvedPythonType::Atom(_), ResolvedPythonType::Atom(_)) => { return ResolvedPythonType::TypeError; } _ => {} } } // Ex) "a" % "b" Operator::Mod => match ( ResolvedPythonType::from(left.as_ref()), ResolvedPythonType::from(right.as_ref()), ) { // Ex) `"Hello" % "world"` (ResolvedPythonType::Atom(PythonType::String), _) => { return ResolvedPythonType::Atom(PythonType::String); } // Ex) `b"Hello" % b"world"` (ResolvedPythonType::Atom(PythonType::Bytes), _) => { return ResolvedPythonType::Atom(PythonType::Bytes); } // Ex) `1 % 2` ( ResolvedPythonType::Atom(PythonType::Number(left)), ResolvedPythonType::Atom(PythonType::Number(right)), ) => { return ResolvedPythonType::Atom(PythonType::Number( left.coerce(right), )); } _ => {} }, Operator::Mult => match ( ResolvedPythonType::from(left.as_ref()), ResolvedPythonType::from(right.as_ref()), ) { // Ex) `2 * 4` ( ResolvedPythonType::Atom(PythonType::Number(left)), ResolvedPythonType::Atom(PythonType::Number(right)), ) => { return ResolvedPythonType::Atom(PythonType::Number( left.coerce(right), )); } // Ex) `"1" * 2` or `2 * "1"` ( ResolvedPythonType::Atom(PythonType::String), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)), ) | ( ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)), ResolvedPythonType::Atom(PythonType::String), ) => return ResolvedPythonType::Atom(PythonType::String), (ResolvedPythonType::Atom(_), ResolvedPythonType::Atom(_)) => { return ResolvedPythonType::TypeError; } _ => {} }, // Standard arithmetic operators, which coerce to the "highest" number type. Operator::FloorDiv | Operator::Pow => match ( ResolvedPythonType::from(left.as_ref()), ResolvedPythonType::from(right.as_ref()), ) { // Ex) `2 ** 4` ( ResolvedPythonType::Atom(PythonType::Number(left)), ResolvedPythonType::Atom(PythonType::Number(right)), ) => { return ResolvedPythonType::Atom(PythonType::Number( left.coerce(right), )); } (ResolvedPythonType::Atom(_), ResolvedPythonType::Atom(_)) => { return ResolvedPythonType::TypeError; } _ => {} }, // Division, which returns at least `float`. Operator::Div => match ( ResolvedPythonType::from(left.as_ref()), ResolvedPythonType::from(right.as_ref()), ) { // Ex) `1 / 2` ( ResolvedPythonType::Atom(PythonType::Number(left)), ResolvedPythonType::Atom(PythonType::Number(right)), ) => { let resolved = left.coerce(right); return ResolvedPythonType::Atom(PythonType::Number( if resolved == NumberLike::Integer { NumberLike::Float } else { resolved }, )); } (ResolvedPythonType::Atom(_), ResolvedPythonType::Atom(_)) => { return ResolvedPythonType::TypeError; } _ => {} }, // Bitwise operators, which only work on `int` and `bool`. Operator::BitAnd | Operator::BitOr | Operator::BitXor | Operator::LShift | Operator::RShift => { match ( ResolvedPythonType::from(left.as_ref()), ResolvedPythonType::from(right.as_ref()), ) { // Ex) `1 & 2` ( ResolvedPythonType::Atom(PythonType::Number(left)), ResolvedPythonType::Atom(PythonType::Number(right)), ) => { let resolved = left.coerce(right); return if resolved == NumberLike::Integer { ResolvedPythonType::Atom(PythonType::Number( NumberLike::Integer, )) } else { ResolvedPythonType::TypeError }; } (ResolvedPythonType::Atom(_), ResolvedPythonType::Atom(_)) => { return ResolvedPythonType::TypeError; } _ => {} } } Operator::MatMult => {} } ResolvedPythonType::Unknown } Expr::Lambda(_) | Expr::Await(_) | Expr::Yield(_) | Expr::YieldFrom(_) | Expr::Compare(_) | Expr::Call(_) | Expr::Attribute(_) | Expr::Subscript(_) | Expr::Starred(_) | Expr::Name(_) | Expr::Slice(_) | Expr::IpyEscapeCommand(_) => ResolvedPythonType::Unknown, } } } /// An extremely simple type inference system for individual expressions. /// /// This system can only represent and infer the types of simple data types /// such as strings, integers, floats, and containers. It cannot infer the /// types of variables or expressions that are not statically known from /// individual AST nodes alone. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum PythonType { /// A string literal, such as `"hello"`. String, /// A bytes literal, such as `b"hello"`. Bytes, /// An integer, float, or complex literal, such as `1` or `1.0`. Number(NumberLike), /// A `None` literal, such as `None`. None, /// An ellipsis literal, such as `...`. Ellipsis, /// A dictionary literal, such as `{}` or `{"a": 1}`. Dict, /// A list literal, such as `[]` or `[i for i in range(3)]`. List, /// A set literal, such as `set()` or `{i for i in range(3)}`. Set, /// A tuple literal, such as `()` or `(1, 2, 3)`. Tuple, /// A generator expression, such as `(x for x in range(10))`. Generator, } impl PythonType { /// Returns `true` if `self` is a subtype of `other`. fn is_subtype_of(self, other: Self) -> bool { match (self, other) { (PythonType::String, PythonType::String) => true, (PythonType::Bytes, PythonType::Bytes) => true, (PythonType::None, PythonType::None) => true, (PythonType::Ellipsis, PythonType::Ellipsis) => true, // The Numeric Tower (https://peps.python.org/pep-3141/) (PythonType::Number(NumberLike::Bool), PythonType::Number(NumberLike::Bool)) => true, (PythonType::Number(NumberLike::Integer), PythonType::Number(NumberLike::Integer)) => { true } (PythonType::Number(NumberLike::Float), PythonType::Number(NumberLike::Float)) => true, (PythonType::Number(NumberLike::Complex), PythonType::Number(NumberLike::Complex)) => { true } (PythonType::Number(NumberLike::Bool), PythonType::Number(NumberLike::Integer)) => true, (PythonType::Number(NumberLike::Bool), PythonType::Number(NumberLike::Float)) => true, (PythonType::Number(NumberLike::Bool), PythonType::Number(NumberLike::Complex)) => true, (PythonType::Number(NumberLike::Integer), PythonType::Number(NumberLike::Float)) => { true } (PythonType::Number(NumberLike::Integer), PythonType::Number(NumberLike::Complex)) => { true } (PythonType::Number(NumberLike::Float), PythonType::Number(NumberLike::Complex)) => { true } // This simple type hierarchy doesn't support generics. (PythonType::Dict, PythonType::Dict) => true, (PythonType::List, PythonType::List) => true, (PythonType::Set, PythonType::Set) => true, (PythonType::Tuple, PythonType::Tuple) => true, (PythonType::Generator, PythonType::Generator) => true, _ => false, } } } /// A numeric type, or a type that can be trivially coerced to a numeric type. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum NumberLike { /// An integer literal, such as `1` or `0x1`. Integer, /// A floating-point literal, such as `1.0` or `1e10`. Float, /// A complex literal, such as `1j` or `1+1j`. Complex, /// A boolean literal, such as `True` or `False`. Bool, } impl NumberLike { /// Coerces two number-like types to the "highest" number-like type. #[must_use] pub fn coerce(self, other: NumberLike) -> NumberLike { match (self, other) { (NumberLike::Complex, _) | (_, NumberLike::Complex) => NumberLike::Complex, (NumberLike::Float, _) | (_, NumberLike::Float) => NumberLike::Float, _ => NumberLike::Integer, } } } #[cfg(test)] mod tests { use ruff_python_ast::ModExpression; use ruff_python_parser::{Parsed, parse_expression}; use crate::analyze::type_inference::{NumberLike, PythonType, ResolvedPythonType}; fn parse(expression: &str) -> Parsed<ModExpression> { parse_expression(expression).unwrap() } #[test] fn type_inference() { // Atoms. assert_eq!( ResolvedPythonType::from(parse("1").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)) ); assert_eq!( ResolvedPythonType::from(parse("'Hello, world'").expr()), ResolvedPythonType::Atom(PythonType::String) ); assert_eq!( ResolvedPythonType::from(parse("b'Hello, world'").expr()), ResolvedPythonType::Atom(PythonType::Bytes) ); assert_eq!( ResolvedPythonType::from(parse("'Hello' % 'world'").expr()), ResolvedPythonType::Atom(PythonType::String) ); // Boolean operators. assert_eq!( ResolvedPythonType::from(parse("1 and 2").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)) ); assert_eq!( ResolvedPythonType::from(parse("1 and True").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)) ); // Binary operators. assert_eq!( ResolvedPythonType::from(parse("1.0 * 2").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Float)) ); assert_eq!( ResolvedPythonType::from(parse("2 * 1.0").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Float)) ); assert_eq!( ResolvedPythonType::from(parse("1.0 * 2j").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Complex)) ); assert_eq!( ResolvedPythonType::from(parse("'AA' * 2").expr()), ResolvedPythonType::Atom(PythonType::String) ); assert_eq!( ResolvedPythonType::from(parse("4 * 'AA'").expr()), ResolvedPythonType::Atom(PythonType::String) ); assert_eq!( ResolvedPythonType::from(parse("1 / True").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Float)) ); assert_eq!( ResolvedPythonType::from(parse("1 / 2").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Float)) ); assert_eq!( ResolvedPythonType::from(parse("{1, 2} - {2}").expr()), ResolvedPythonType::Atom(PythonType::Set) ); // Unary operators. assert_eq!( ResolvedPythonType::from(parse("-1").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)) ); assert_eq!( ResolvedPythonType::from(parse("-1.0").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Float)) ); assert_eq!( ResolvedPythonType::from(parse("-1j").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Complex)) ); assert_eq!( ResolvedPythonType::from(parse("-True").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)) ); assert_eq!( ResolvedPythonType::from(parse("not 'Hello'").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Bool)) ); assert_eq!( ResolvedPythonType::from(parse("not x.y.z").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Bool)) ); // Conditional expressions. assert_eq!( ResolvedPythonType::from(parse("1 if True else 2").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)) ); assert_eq!( ResolvedPythonType::from(parse("1 if True else 2.0").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Float)) ); assert_eq!( ResolvedPythonType::from(parse("1 if True else False").expr()), ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)) ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/cfg/mod.rs
crates/ruff_python_semantic/src/cfg/mod.rs
pub mod graph; pub mod visualize; #[cfg(test)] mod tests { use std::fmt::Write; use std::fs; use std::path::PathBuf; use crate::cfg::graph::build_cfg; use crate::cfg::visualize::draw_cfg; use insta; use ruff_python_parser::parse_module; use ruff_text_size::Ranged; use test_case::test_case; #[test_case("no_flow.py")] #[test_case("jumps.py")] fn control_flow_graph(filename: &str) { let path = PathBuf::from("resources/test/fixtures/cfg").join(filename); let source = fs::read_to_string(path).expect("failed to read file"); let stmts = parse_module(&source) .unwrap_or_else(|err| panic!("failed to parse source: '{source}': {err}")) .into_suite(); let mut output = String::new(); for (i, stmt) in stmts.into_iter().enumerate() { let func = stmt.as_function_def_stmt().expect( "Snapshot test for control flow graph should consist only of function definitions", ); let cfg = build_cfg(&func.body); let mermaid_graph = draw_cfg(cfg, &source); writeln!( output, "## Function {}\n\ ### Source\n\ ```python\n\ {}\n\ ```\n\n\ ### Control Flow Graph\n\ ```mermaid\n\ {}\n\ ```\n", i, &source[func.range()], mermaid_graph, ) .unwrap(); } insta::with_settings!({ omit_expression => true, input_file => filename, description => "This is a Mermaid graph. You can use https://mermaid.live to visualize it as a diagram." }, { insta::assert_snapshot!(format!("{filename}.md"), output); }); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/cfg/visualize.rs
crates/ruff_python_semantic/src/cfg/visualize.rs
//! Heavily inspired by rustc data structures use ruff_index::Idx; use ruff_text_size::Ranged; use std::fmt::{self, Display}; use crate::cfg::graph::{BlockId, BlockKind, Condition, ControlFlowGraph}; /// Returns control flow graph in Mermaid syntax. pub fn draw_cfg(graph: ControlFlowGraph, source: &str) -> String { CFGWithSource::new(graph, source).draw_graph() } trait MermaidGraph<'a>: DirectedGraph<'a> { fn draw_node(&self, node: Self::Node) -> MermaidNode; fn draw_edges(&self, node: Self::Node) -> impl Iterator<Item = (Self::Node, MermaidEdge)>; fn draw_graph(&self) -> String { let mut graph = Vec::new(); // Begin mermaid graph. graph.push("flowchart TD".to_string()); // Draw nodes let num_nodes = self.num_nodes(); for idx in 0..num_nodes { let node = Self::Node::new(idx); graph.push(format!("\tnode{}{}", idx, &self.draw_node(node))); } // Draw edges for idx in 0..num_nodes { graph.extend( self.draw_edges(Self::Node::new(idx)) .map(|(end_idx, edge)| format!("\tnode{}{}node{}", idx, edge, end_idx.index())), ); } graph.join("\n") } } pub struct MermaidNode { shape: MermaidNodeShape, content: String, } impl MermaidNode { pub fn with_content(content: String) -> Self { Self { shape: MermaidNodeShape::default(), content, } } fn mermaid_write_quoted_str(f: &mut fmt::Formatter<'_>, value: &str) -> fmt::Result { let mut parts = value.split('"'); if let Some(v) = parts.next() { write!(f, "{v}")?; } for v in parts { write!(f, "#quot;{v}")?; } Ok(()) } } impl Display for MermaidNode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let (open, close) = self.shape.open_close(); write!(f, "{open}\"")?; if self.content.is_empty() { write!(f, "empty")?; } else { MermaidNode::mermaid_write_quoted_str(f, &self.content)?; } write!(f, "\"{close}") } } #[derive(Debug, Default)] pub enum MermaidNodeShape { #[default] Rectangle, DoubleRectangle, RoundedRectangle, Stadium, Circle, DoubleCircle, Asymmetric, Rhombus, Hexagon, Parallelogram, Trapezoid, } impl MermaidNodeShape { fn open_close(&self) -> (&'static str, &'static str) { match self { Self::Rectangle => ("[", "]"), Self::DoubleRectangle => ("[[", "]]"), Self::RoundedRectangle => ("(", ")"), Self::Stadium => ("([", "])"), Self::Circle => ("((", "))"), Self::DoubleCircle => ("(((", ")))"), Self::Asymmetric => (">", "]"), Self::Rhombus => ("{", "}"), Self::Hexagon => ("{{", "}}"), Self::Parallelogram => ("[/", "/]"), Self::Trapezoid => ("[/", "\\]"), } } } #[derive(Debug, Default)] pub struct MermaidEdge { kind: MermaidEdgeKind, content: String, } impl Display for MermaidEdge { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if self.content.is_empty() { write!(f, "{}", self.kind) } else { write!(f, "{}|\"{}\"|", self.kind, self.content) } } } #[derive(Debug, Default)] pub enum MermaidEdgeKind { #[default] Arrow, DottedArrow, ThickArrow, BidirectionalArrow, } impl Display for MermaidEdgeKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { MermaidEdgeKind::Arrow => write!(f, "-->"), MermaidEdgeKind::DottedArrow => write!(f, "-..->"), MermaidEdgeKind::ThickArrow => write!(f, "==>"), MermaidEdgeKind::BidirectionalArrow => write!(f, "<-->"), } } } pub trait DirectedGraph<'a> { type Node: Idx; fn num_nodes(&self) -> usize; fn start_node(&self) -> Self::Node; fn successors(&self, node: Self::Node) -> impl ExactSizeIterator<Item = Self::Node> + '_; } struct CFGWithSource<'stmt> { cfg: ControlFlowGraph<'stmt>, source: &'stmt str, } impl<'stmt> CFGWithSource<'stmt> { fn new(cfg: ControlFlowGraph<'stmt>, source: &'stmt str) -> Self { Self { cfg, source } } } impl<'stmt> DirectedGraph<'stmt> for CFGWithSource<'stmt> { type Node = BlockId; fn num_nodes(&self) -> usize { self.cfg.num_blocks() } fn start_node(&self) -> Self::Node { self.cfg.initial() } fn successors(&self, node: Self::Node) -> impl ExactSizeIterator<Item = Self::Node> + '_ { self.cfg.outgoing(node).targets() } } impl<'stmt> MermaidGraph<'stmt> for CFGWithSource<'stmt> { fn draw_node(&self, node: Self::Node) -> MermaidNode { let statements: Vec<String> = self .cfg .stmts(node) .iter() .map(|stmt| self.source[stmt.range()].to_string()) .collect(); let content = match self.cfg.kind(node) { BlockKind::Generic => { if statements.is_empty() { "EMPTY".to_string() } else { statements.join("\n") } } BlockKind::Start => { if statements.is_empty() { "START".to_string() } else { statements.join("\n") } } BlockKind::Terminal => { return MermaidNode { content: "EXIT".to_string(), shape: MermaidNodeShape::DoubleCircle, }; } }; MermaidNode::with_content(content) } fn draw_edges(&self, node: Self::Node) -> impl Iterator<Item = (Self::Node, MermaidEdge)> { let edge_data = self.cfg.outgoing(node); edge_data .targets() .zip(edge_data.conditions()) .map(|(target, condition)| { let edge = match condition { Condition::Always => { if target == self.cfg.terminal() { MermaidEdge { kind: MermaidEdgeKind::ThickArrow, content: String::new(), } } else { MermaidEdge { kind: MermaidEdgeKind::Arrow, content: String::new(), } } } }; (target, edge) }) .collect::<Vec<_>>() .into_iter() } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_semantic/src/cfg/graph.rs
crates/ruff_python_semantic/src/cfg/graph.rs
use ruff_index::{IndexVec, newtype_index}; use ruff_python_ast::Stmt; use ruff_text_size::{Ranged, TextRange}; use smallvec::{SmallVec, smallvec}; /// Returns the control flow graph associated to an array of statements pub fn build_cfg(stmts: &[Stmt]) -> ControlFlowGraph<'_> { let mut builder = CFGBuilder::with_capacity(stmts.len()); builder.process_stmts(stmts); builder.finish() } /// Control flow graph #[derive(Debug)] pub struct ControlFlowGraph<'stmt> { /// Basic blocks - the nodes of the control flow graph blocks: IndexVec<BlockId, BlockData<'stmt>>, /// Entry point to the control flow graph initial: BlockId, /// Terminal block - will always be empty terminal: BlockId, } impl<'stmt> ControlFlowGraph<'stmt> { /// Index of entry point to the control flow graph pub fn initial(&self) -> BlockId { self.initial } /// Index of terminal block pub fn terminal(&self) -> BlockId { self.terminal } /// Number of basic blocks, or nodes, in the graph pub fn num_blocks(&self) -> usize { self.blocks.len() } /// Returns the statements comprising the basic block at the given index pub fn stmts(&self, block: BlockId) -> &'stmt [Stmt] { self.blocks[block].stmts } /// Returns the range of the statements comprising the basic block at the given index pub fn range(&self, block: BlockId) -> TextRange { self.blocks[block].range() } /// Returns the [`Edges`] going out of the basic block at the given index pub fn outgoing(&self, block: BlockId) -> &Edges { &self.blocks[block].out } /// Returns an iterator over the indices of the direct predecessors of the block at the given index pub fn predecessors(&self, block: BlockId) -> impl ExactSizeIterator<Item = BlockId> + '_ { self.blocks[block].parents.iter().copied() } /// Returns the [`BlockKind`] of the block at the given index pub(crate) fn kind(&self, block: BlockId) -> BlockKind { self.blocks[block].kind } } #[newtype_index] pub struct BlockId; /// Holds the data of a basic block. A basic block consists of a collection of /// [`Stmt`]s, together with outgoing edges to other basic blocks. #[derive(Debug, Default)] struct BlockData<'stmt> { kind: BlockKind, /// Slice of statements regarded as executing unconditionally in order stmts: &'stmt [Stmt], /// Outgoing edges, indicating possible paths of execution after the /// block has concluded out: Edges, /// Collection of indices for basic blocks having the current /// block as the target of an edge parents: SmallVec<[BlockId; 2]>, } impl Ranged for BlockData<'_> { fn range(&self) -> TextRange { let Some(first) = self.stmts.first() else { return TextRange::default(); }; let Some(last) = self.stmts.last() else { return TextRange::default(); }; TextRange::new(first.start(), last.end()) } } #[derive(Debug, Default, Clone, Copy)] pub(crate) enum BlockKind { #[default] Generic, /// Entry point of the control flow graph Start, /// Terminal block for the control flow graph Terminal, } /// Holds a collection of edges. Each edge is determined by: /// - a [`Condition`] for traversing the edge, and /// - a target block, specified by its [`BlockId`]. /// /// The conditions and targets are kept in two separate /// vectors which must always be kept the same length. #[derive(Debug, Default, Clone)] pub struct Edges { conditions: SmallVec<[Condition; 4]>, targets: SmallVec<[BlockId; 4]>, } impl Edges { /// Creates an unconditional edge to the target block fn always(target: BlockId) -> Self { Self { conditions: smallvec![Condition::Always], targets: smallvec![target], } } /// Returns iterator over indices of blocks targeted by given edges pub fn targets(&self) -> impl ExactSizeIterator<Item = BlockId> + '_ { self.targets.iter().copied() } /// Returns iterator over [`Condition`]s which must be satisfied to traverse corresponding edge pub fn conditions(&self) -> impl ExactSizeIterator<Item = &Condition> { self.conditions.iter() } fn is_empty(&self) -> bool { self.targets.is_empty() } pub fn filter_targets_by_conditions<'a, T: FnMut(&Condition) -> bool + 'a>( &'a self, mut predicate: T, ) -> impl Iterator<Item = BlockId> + 'a { self.conditions() .zip(self.targets()) .filter(move |(cond, _)| predicate(cond)) .map(|(_, block)| block) } } /// Represents a condition to be tested in a multi-way branch #[derive(Debug, Clone)] pub enum Condition { /// Unconditional edge Always, } struct CFGBuilder<'stmt> { /// Control flow graph under construction cfg: ControlFlowGraph<'stmt>, /// Current basic block index current: BlockId, /// Exit block index for current control flow exit: BlockId, } impl<'stmt> CFGBuilder<'stmt> { /// Returns [`CFGBuilder`] with vector of blocks initialized at given capacity and with both initial and terminal blocks populated. fn with_capacity(capacity: usize) -> Self { let mut blocks = IndexVec::with_capacity(capacity); let initial = blocks.push(BlockData { kind: BlockKind::Start, ..BlockData::default() }); let terminal = blocks.push(BlockData { kind: BlockKind::Terminal, ..BlockData::default() }); Self { cfg: ControlFlowGraph { blocks, initial, terminal, }, current: initial, exit: terminal, } } /// Runs the core logic for the builder. fn process_stmts(&mut self, stmts: &'stmt [Stmt]) { // SAFETY With notation as below, we always maintain the invariant // `start <= end + 1`. Since `end <= stmts.len() -1` we conclude that // `start <= stmts.len()`. It is therefore always safe to use `start` as // the beginning of a range for the purposes of slicing into `stmts`. let mut start = 0; for (end, stmt) in stmts.iter().enumerate() { let cache_exit = self.exit(); match stmt { Stmt::FunctionDef(_) | Stmt::ClassDef(_) | Stmt::Assign(_) | Stmt::AugAssign(_) | Stmt::AnnAssign(_) | Stmt::TypeAlias(_) | Stmt::Import(_) | Stmt::ImportFrom(_) | Stmt::Global(_) | Stmt::Nonlocal(_) | Stmt::Expr(_) | Stmt::Pass(_) | Stmt::Delete(_) | Stmt::IpyEscapeCommand(_) => {} // Loops Stmt::While(_) => {} Stmt::For(_) => {} // Switch statements Stmt::If(_) => {} Stmt::Match(_) => {} // Exception handling statements Stmt::Try(_) => {} Stmt::With(_) => {} // Jumps Stmt::Return(_) => { let edges = Edges::always(self.cfg.terminal()); self.set_current_block_stmts(&stmts[start..=end]); self.set_current_block_edges(edges); start = end + 1; if stmts.get(start).is_some() { let next_block = self.new_block(); self.move_to(next_block); } } Stmt::Break(_) => {} Stmt::Continue(_) => {} Stmt::Raise(_) => { let edges = Edges::always(self.cfg.terminal()); self.set_current_block_stmts(&stmts[start..=end]); self.set_current_block_edges(edges); start = end + 1; if stmts.get(start).is_some() { let next_block = self.new_block(); self.move_to(next_block); } } // An `assert` is a mixture of a switch and a jump. Stmt::Assert(_) => {} } // Restore exit self.update_exit(cache_exit); } // It can happen that we have statements left over // and not yet occupying a block. In that case, // `self.current` should be pointing to an empty block // and we push the remaining statements to it here. if start < stmts.len() { self.set_current_block_stmts(&stmts[start..]); } // Add edge to exit if not already present if self.cfg.blocks[self.current].out.is_empty() { let edges = Edges::always(self.exit()); self.set_current_block_edges(edges); } self.move_to(self.exit()); } /// Returns finished control flow graph fn finish(self) -> ControlFlowGraph<'stmt> { self.cfg } /// Current exit block, which may change during construction fn exit(&self) -> BlockId { self.exit } /// Point the current exit to block at provided index fn update_exit(&mut self, new_exit: BlockId) { self.exit = new_exit; } /// Moves current block to provided index fn move_to(&mut self, block: BlockId) { self.current = block; } /// Makes new block and returns index fn new_block(&mut self) -> BlockId { self.cfg.blocks.push(BlockData::default()) } /// Populates the current basic block with the given set of statements. /// /// This should only be called once on any given block. fn set_current_block_stmts(&mut self, stmts: &'stmt [Stmt]) { debug_assert!( self.cfg.blocks[self.current].stmts.is_empty(), "Attempting to set statements on an already populated basic block." ); self.cfg.blocks[self.current].stmts = stmts; } /// Draws provided edges out of the current basic block. /// /// This should only be called once on any given block. fn set_current_block_edges(&mut self, edges: Edges) { debug_assert!( self.cfg.blocks[self.current].out.is_empty(), "Attempting to set edges on a basic block that already has an outgoing edge." ); self.cfg.blocks[self.current].out = edges; } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_cache/src/lib.rs
crates/ruff_cache/src/lib.rs
use std::path::{Path, PathBuf}; pub use cache_key::{CacheKey, CacheKeyHasher}; mod cache_key; pub mod filetime; pub mod globset; pub const CACHE_DIR_NAME: &str = ".ruff_cache"; /// Return the cache directory for a given project root. pub fn cache_dir(project_root: &Path) -> PathBuf { project_root.join(CACHE_DIR_NAME) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_cache/src/globset.rs
crates/ruff_cache/src/globset.rs
use globset::{Glob, GlobMatcher}; use crate::{CacheKey, CacheKeyHasher}; impl CacheKey for GlobMatcher { fn cache_key(&self, state: &mut CacheKeyHasher) { self.glob().cache_key(state); } } impl CacheKey for Glob { fn cache_key(&self, state: &mut CacheKeyHasher) { self.glob().cache_key(state); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_cache/src/cache_key.rs
crates/ruff_cache/src/cache_key.rs
use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::hash::{Hash, Hasher}; use std::num::{ NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, }; use std::path::{Path, PathBuf}; use glob::Pattern; use itertools::Itertools; use regex::Regex; use seahash::SeaHasher; /// A type that be used as part of a cache key. /// /// A cache looks up artefacts by a cache key. Many cache keys are composed of sub-keys. For example, /// caching the lint results of a file depend at least on the file content, the user settings, and linter version. /// Types implementing the [`CacheKey`] trait can be used as part of a cache key by which artefacts are queried. /// /// ## Implementing `CacheKey` /// /// You can derive [`CacheKey`] with `#[derive(CacheKey)]` if all fields implement [`CacheKey`]. The resulting /// cache key will be the combination of the values from calling `cache_key` on each field. /// /// ``` /// # use ruff_macros::CacheKey; /// /// #[derive(CacheKey)] /// struct Test { /// name: String, /// version: u32, /// } /// ``` /// /// If you need more control over computing the cache key, you can of course implement the [`CacheKey]` yourself: /// /// ``` /// use ruff_cache::{CacheKey, CacheKeyHasher}; /// /// struct Test { /// name: String, /// version: u32, /// other: String /// } /// /// impl CacheKey for Test { /// fn cache_key(&self, state: &mut CacheKeyHasher) { /// self.name.cache_key(state); /// self.version.cache_key(state); /// } /// } /// ``` /// /// ## Portability /// /// Ideally, the cache key is portable across platforms but this is not yet a strict requirement. /// /// ## Using [`Hash`] /// /// You can defer to the [`Hash`] implementation for non-composite types. /// Be aware, that the [`Hash`] implementation may not be portable. /// /// ## Why a new trait rather than reusing [`Hash`]? /// The main reason is that hashes and cache keys have different constraints: /// /// * Cache keys are less performance sensitive: Hashes must be super fast to compute for performant hashed-collections. That's /// why some standard types don't implement [`Hash`] where it would be safe to implement [`CacheKey`], e.g. `HashSet` /// * Cache keys must be deterministic where hash keys do not have this constraint. That's why pointers don't implement [`CacheKey`] but they implement [`Hash`]. /// * Ideally, cache keys are portable /// /// [`Hash`](Hash) pub trait CacheKey { fn cache_key(&self, state: &mut CacheKeyHasher); fn cache_key_slice(data: &[Self], state: &mut CacheKeyHasher) where Self: Sized, { for piece in data { piece.cache_key(state); } } } impl CacheKey for bool { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_u8(u8::from(*self)); } } impl CacheKey for char { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_u32(*self as u32); } } impl CacheKey for usize { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_usize(*self); } } impl CacheKey for u128 { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_u128(*self); } } impl CacheKey for u64 { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_u64(*self); } } impl CacheKey for u32 { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_u32(*self); } } impl CacheKey for u16 { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_u16(*self); } } impl CacheKey for u8 { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_u8(*self); } } impl CacheKey for isize { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_isize(*self); } } impl CacheKey for i128 { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_i128(*self); } } impl CacheKey for i64 { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_i64(*self); } } impl CacheKey for i32 { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_i32(*self); } } impl CacheKey for i16 { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_i16(*self); } } impl CacheKey for i8 { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_i8(*self); } } macro_rules! impl_cache_key_non_zero { ($name:ident) => { impl CacheKey for $name { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { self.get().cache_key(state) } } }; } impl_cache_key_non_zero!(NonZeroU8); impl_cache_key_non_zero!(NonZeroU16); impl_cache_key_non_zero!(NonZeroU32); impl_cache_key_non_zero!(NonZeroU64); impl_cache_key_non_zero!(NonZeroU128); impl_cache_key_non_zero!(NonZeroI8); impl_cache_key_non_zero!(NonZeroI16); impl_cache_key_non_zero!(NonZeroI32); impl_cache_key_non_zero!(NonZeroI64); impl_cache_key_non_zero!(NonZeroI128); macro_rules! impl_cache_key_tuple { () => ( impl CacheKey for () { #[inline] fn cache_key(&self, _state: &mut CacheKeyHasher) {} } ); ( $($name:ident)+) => ( impl<$($name: CacheKey),+> CacheKey for ($($name,)+) where last_type!($($name,)+): ?Sized { #[expect(non_snake_case)] #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { let ($(ref $name,)+) = *self; $($name.cache_key(state);)+ } } ); } macro_rules! last_type { ($a:ident,) => { $a }; ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) }; } impl_cache_key_tuple! {} impl_cache_key_tuple! { T } impl_cache_key_tuple! { T B } impl_cache_key_tuple! { T B C } impl_cache_key_tuple! { T B C D } impl_cache_key_tuple! { T B C D E } impl_cache_key_tuple! { T B C D E F } impl_cache_key_tuple! { T B C D E F G } impl_cache_key_tuple! { T B C D E F G H } impl_cache_key_tuple! { T B C D E F G H I } impl_cache_key_tuple! { T B C D E F G H I J } impl_cache_key_tuple! { T B C D E F G H I J K } impl_cache_key_tuple! { T B C D E F G H I J K L } impl CacheKey for str { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { self.hash(&mut *state); } } impl CacheKey for String { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { self.hash(&mut *state); } } impl<T: CacheKey> CacheKey for Option<T> { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { match self { None => state.write_usize(0), Some(value) => { state.write_usize(1); value.cache_key(state); } } } } impl<T: CacheKey> CacheKey for [T] { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_usize(self.len()); CacheKey::cache_key_slice(self, state); } } impl<T: ?Sized + CacheKey> CacheKey for &T { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { (**self).cache_key(state); } } impl<T: ?Sized + CacheKey> CacheKey for &mut T { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { (**self).cache_key(state); } } impl<T> CacheKey for Vec<T> where T: CacheKey, { fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_usize(self.len()); CacheKey::cache_key_slice(self, state); } } impl<K, V, S> CacheKey for HashMap<K, V, S> where K: CacheKey + Ord, V: CacheKey, { fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_usize(self.len()); for (key, value) in self .iter() .sorted_by(|(left, _), (right, _)| left.cmp(right)) { key.cache_key(state); value.cache_key(state); } } } impl<V: CacheKey + Ord, S> CacheKey for HashSet<V, S> { fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_usize(self.len()); for value in self.iter().sorted() { value.cache_key(state); } } } impl<V: CacheKey> CacheKey for BTreeSet<V> { fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_usize(self.len()); for item in self { item.cache_key(state); } } } impl<K: CacheKey + Ord, V: CacheKey> CacheKey for BTreeMap<K, V> { fn cache_key(&self, state: &mut CacheKeyHasher) { state.write_usize(self.len()); for (key, value) in self { key.cache_key(state); value.cache_key(state); } } } impl CacheKey for Path { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { for component in self.components() { component.hash(&mut *state); } } } impl CacheKey for PathBuf { #[inline] fn cache_key(&self, state: &mut CacheKeyHasher) { self.as_path().cache_key(state); } } impl<V: ?Sized> CacheKey for Cow<'_, V> where V: CacheKey + ToOwned, { fn cache_key(&self, state: &mut CacheKeyHasher) { (**self).cache_key(state); } } impl CacheKey for Regex { fn cache_key(&self, state: &mut CacheKeyHasher) { self.as_str().cache_key(state); } } impl CacheKey for Pattern { fn cache_key(&self, state: &mut CacheKeyHasher) { self.as_str().cache_key(state); } } #[derive(Clone, Default)] pub struct CacheKeyHasher { inner: SeaHasher, } impl CacheKeyHasher { pub fn new() -> Self { Self { inner: SeaHasher::new(), } } } impl Hasher for CacheKeyHasher { #[inline] fn finish(&self) -> u64 { self.inner.finish() } #[inline] fn write(&mut self, bytes: &[u8]) { self.inner.write(bytes); } #[inline] fn write_u8(&mut self, i: u8) { self.inner.write_u8(i); } #[inline] fn write_u16(&mut self, i: u16) { self.inner.write_u16(i); } #[inline] fn write_u32(&mut self, i: u32) { self.inner.write_u32(i); } #[inline] fn write_u64(&mut self, i: u64) { self.inner.write_u64(i); } #[inline] fn write_u128(&mut self, i: u128) { self.inner.write_u128(i); } #[inline] fn write_usize(&mut self, i: usize) { self.inner.write_usize(i); } #[inline] fn write_i8(&mut self, i: i8) { self.inner.write_i8(i); } #[inline] fn write_i16(&mut self, i: i16) { self.inner.write_i16(i); } #[inline] fn write_i32(&mut self, i: i32) { self.inner.write_i32(i); } #[inline] fn write_i64(&mut self, i: i64) { self.inner.write_i64(i); } #[inline] fn write_i128(&mut self, i: i128) { self.inner.write_i128(i); } #[inline] fn write_isize(&mut self, i: isize) { self.inner.write_isize(i); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_cache/src/filetime.rs
crates/ruff_cache/src/filetime.rs
use std::hash::Hash; use filetime::FileTime; use crate::{CacheKey, CacheKeyHasher}; impl CacheKey for FileTime { fn cache_key(&self, state: &mut CacheKeyHasher) { self.hash(&mut *state); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_cache/tests/cache_key.rs
crates/ruff_cache/tests/cache_key.rs
use std::hash::{Hash, Hasher}; use ruff_cache::{CacheKey, CacheKeyHasher}; use ruff_macros::CacheKey; #[test] fn unit_struct_cache_key() { #[derive(CacheKey, Hash)] struct UnitStruct; let mut key = CacheKeyHasher::new(); UnitStruct.cache_key(&mut key); let mut hash = CacheKeyHasher::new(); UnitStruct.hash(&mut hash); assert_eq!(hash.finish(), key.finish()); } #[test] fn named_field_struct() { #[derive(CacheKey, Hash)] struct NamedFieldsStruct { a: String, b: String, } let mut key = CacheKeyHasher::new(); let named_fields = NamedFieldsStruct { a: "Hello".into(), b: "World".into(), }; named_fields.cache_key(&mut key); let mut hash = CacheKeyHasher::new(); named_fields.hash(&mut hash); assert_eq!(hash.finish(), key.finish()); } #[test] fn struct_ignored_fields() { #[derive(CacheKey)] struct NamedFieldsStruct { a: String, #[cache_key(ignore)] #[expect(unused)] b: String, } impl Hash for NamedFieldsStruct { fn hash<H: Hasher>(&self, state: &mut H) { self.a.hash(state); } } let mut key = CacheKeyHasher::new(); let named_fields = NamedFieldsStruct { a: "Hello".into(), b: "World".into(), }; named_fields.cache_key(&mut key); let mut hash = CacheKeyHasher::new(); named_fields.hash(&mut hash); assert_eq!(hash.finish(), key.finish()); } #[test] fn unnamed_field_struct() { #[derive(CacheKey, Hash)] struct UnnamedFieldsStruct(String, String); let mut key = CacheKeyHasher::new(); let unnamed_fields = UnnamedFieldsStruct("Hello".into(), "World".into()); unnamed_fields.cache_key(&mut key); let mut hash = CacheKeyHasher::new(); unnamed_fields.hash(&mut hash); assert_eq!(hash.finish(), key.finish()); } #[derive(CacheKey, Hash)] enum Enum { Unit, UnnamedFields(String, String), NamedFields { a: String, b: String }, } #[test] fn enum_unit_variant() { let mut key = CacheKeyHasher::new(); let variant = Enum::Unit; variant.cache_key(&mut key); let mut hash = CacheKeyHasher::new(); variant.hash(&mut hash); assert_eq!(hash.finish(), key.finish()); } #[test] fn enum_named_fields_variant() { let mut key = CacheKeyHasher::new(); let variant = Enum::NamedFields { a: "Hello".to_string(), b: "World".to_string(), }; variant.cache_key(&mut key); let mut hash = CacheKeyHasher::new(); variant.hash(&mut hash); assert_eq!(hash.finish(), key.finish()); } #[test] fn enum_unnamed_fields_variant() { let mut key = CacheKeyHasher::new(); let variant = Enum::UnnamedFields("Hello".to_string(), "World".to_string()); variant.cache_key(&mut key); let mut hash = CacheKeyHasher::new(); variant.hash(&mut hash); assert_eq!(hash.finish(), key.finish()); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_index/src/multiline_ranges.rs
crates/ruff_python_index/src/multiline_ranges.rs
use ruff_python_ast::token::{Token, TokenKind}; use ruff_text_size::{Ranged, TextRange}; /// Stores the range of all multiline strings in a file sorted by /// [`TextRange::start`]. pub struct MultilineRanges { ranges: Vec<TextRange>, } impl MultilineRanges { /// Returns `true` if the given range is inside a multiline string. pub fn contains_range(&self, target: TextRange) -> bool { self.ranges .binary_search_by(|range| { if range.contains_range(target) { std::cmp::Ordering::Equal } else if range.end() < target.start() { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater } }) .is_ok() } /// Returns `true` if the given range intersects with any multiline string. pub fn intersects(&self, target: TextRange) -> bool { self.ranges .binary_search_by(|range| { if target.intersect(*range).is_some() { std::cmp::Ordering::Equal } else if range.end() < target.start() { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater } }) .is_ok() } } #[derive(Default)] pub(crate) struct MultilineRangesBuilder { ranges: Vec<TextRange>, } impl MultilineRangesBuilder { pub(crate) fn visit_token(&mut self, token: &Token) { if matches!(token.kind(), TokenKind::String | TokenKind::FStringMiddle) { if token.is_triple_quoted_string() { self.ranges.push(token.range()); } } } pub(crate) fn finish(self) -> MultilineRanges { MultilineRanges { ranges: self.ranges, } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_index/src/lib.rs
crates/ruff_python_index/src/lib.rs
mod indexer; mod interpolated_string_ranges; mod multiline_ranges; pub use indexer::Indexer;
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_index/src/interpolated_string_ranges.rs
crates/ruff_python_index/src/interpolated_string_ranges.rs
use std::collections::BTreeMap; use ruff_python_ast::token::{Token, TokenKind}; use ruff_text_size::{Ranged, TextRange, TextSize}; /// Stores the ranges of all interpolated strings in a file sorted by [`TextRange::start`]. /// There can be multiple overlapping ranges for nested interpolated strings. /// /// Note that the ranges for all unterminated interpolated strings are not stored. #[derive(Debug)] pub struct InterpolatedStringRanges { // Mapping from the interpolated string start location to its range. raw: BTreeMap<TextSize, TextRange>, } impl InterpolatedStringRanges { /// Returns `true` if the given range intersects with any f-string range. pub fn intersects(&self, target: TextRange) -> bool { self.raw .values() .take_while(|range| range.start() < target.end()) .any(|range| target.intersect(*range).is_some()) } /// Return the [`TextRange`] of the innermost f-string at the given offset. pub fn innermost(&self, offset: TextSize) -> Option<TextRange> { self.raw .range(..=offset) .rev() .find(|(_, range)| range.contains(offset)) .map(|(_, range)| *range) } /// Return the [`TextRange`] of the outermost f-string at the given offset. pub fn outermost(&self, offset: TextSize) -> Option<TextRange> { // Explanation of the algorithm: // // ```python // # v // f"normal" f"another" f"first {f"second {f"third"} second"} first" // # ^^(1)^^^ // # ^^^^^^^^^^^^(2)^^^^^^^^^^^^ // # ^^^^^^^^^^^^^^^^^^^^^(3)^^^^^^^^^^^^^^^^^^^^ // # ^^^(4)^^^^ // # ^^^(5)^^^ // ``` // // The offset is marked with a `v` and the ranges are numbered in the order // they are yielded by the iterator in the reverse order. The algorithm // works as follows: // 1. Skip all ranges that don't contain the offset (1). // 2. Take all ranges that contain the offset (2, 3). // 3. Stop taking ranges when the offset is no longer contained. // 4. Take the last range that contained the offset (3, the outermost). self.raw .range(..=offset) .rev() .skip_while(|(_, range)| !range.contains(offset)) .take_while(|(_, range)| range.contains(offset)) .last() .map(|(_, range)| *range) } /// Returns an iterator over all interpolated string [`TextRange`] sorted by their /// start location. /// /// For nested interpolated strings, the outermost interpolated string is yielded first, moving /// inwards with each iteration. #[inline] pub fn values(&self) -> impl Iterator<Item = &TextRange> + '_ { self.raw.values() } /// Returns the number of interpolated string ranges stored. #[inline] pub fn len(&self) -> usize { self.raw.len() } } #[derive(Default)] pub(crate) struct InterpolatedStringRangesBuilder { start_locations: Vec<TextSize>, raw: BTreeMap<TextSize, TextRange>, } impl InterpolatedStringRangesBuilder { pub(crate) fn visit_token(&mut self, token: &Token) { // While the logic of this visitor makes it seem possible to pair, say, // an `FStringStart` with a `TStringEnd`, it is not actually possible to // encounter this in tokenized code free from lexical errors. match token.kind() { TokenKind::FStringStart | TokenKind::TStringStart => { self.start_locations.push(token.start()); } TokenKind::FStringEnd | TokenKind::TStringEnd => { if let Some(start) = self.start_locations.pop() { self.raw.insert(start, TextRange::new(start, token.end())); } } _ => {} } } pub(crate) fn finish(self) -> InterpolatedStringRanges { InterpolatedStringRanges { raw: self.raw } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_index/src/indexer.rs
crates/ruff_python_index/src/indexer.rs
//! Struct used to index source code, to enable efficient lookup of tokens that //! are omitted from the AST (e.g., commented lines). use ruff_python_ast::Stmt; use ruff_python_ast::token::{TokenKind, Tokens}; use ruff_python_trivia::{ CommentRanges, has_leading_content, has_trailing_content, is_python_whitespace, }; use ruff_source_file::LineRanges; use ruff_text_size::{Ranged, TextRange, TextSize}; use crate::interpolated_string_ranges::{ InterpolatedStringRanges, InterpolatedStringRangesBuilder, }; use crate::multiline_ranges::{MultilineRanges, MultilineRangesBuilder}; pub struct Indexer { /// Stores the start offset of continuation lines. continuation_lines: Vec<TextSize>, /// The range of all interpolated strings in the source document. interpolated_string_ranges: InterpolatedStringRanges, /// The range of all multiline strings in the source document. multiline_ranges: MultilineRanges, /// The range of all comments in the source document. comment_ranges: CommentRanges, } impl Indexer { pub fn from_tokens(tokens: &Tokens, source: &str) -> Self { assert!(TextSize::try_from(source.len()).is_ok()); let mut interpolated_string_ranges_builder = InterpolatedStringRangesBuilder::default(); let mut multiline_ranges_builder = MultilineRangesBuilder::default(); let mut continuation_lines = Vec::new(); let mut comment_ranges = Vec::new(); // Token, end let mut prev_end = TextSize::default(); let mut line_start = TextSize::default(); for token in tokens { let trivia = &source[TextRange::new(prev_end, token.start())]; // Get the trivia between the previous and the current token and detect any newlines. // This is necessary because `RustPython` doesn't emit `[Tok::Newline]` tokens // between any two tokens that form a continuation. That's why we have to extract the // newlines "manually". for (index, text) in trivia.match_indices(['\n', '\r']) { if text == "\r" && trivia.as_bytes().get(index + 1) == Some(&b'\n') { continue; } continuation_lines.push(line_start); // SAFETY: Safe because of the len assertion at the top of the function. #[expect(clippy::cast_possible_truncation)] { line_start = prev_end + TextSize::new((index + 1) as u32); } } interpolated_string_ranges_builder.visit_token(token); multiline_ranges_builder.visit_token(token); match token.kind() { TokenKind::Newline | TokenKind::NonLogicalNewline => { line_start = token.end(); } TokenKind::String => { // If the previous token was a string, find the start of the line that contains // the closing delimiter, since the token itself can span multiple lines. line_start = source.line_start(token.end()); } TokenKind::Comment => { comment_ranges.push(token.range()); } _ => {} } prev_end = token.end(); } Self { continuation_lines, interpolated_string_ranges: interpolated_string_ranges_builder.finish(), multiline_ranges: multiline_ranges_builder.finish(), comment_ranges: CommentRanges::new(comment_ranges), } } /// Returns the byte offset ranges of comments. pub const fn comment_ranges(&self) -> &CommentRanges { &self.comment_ranges } /// Returns the byte offset ranges of interpolated strings. pub const fn interpolated_string_ranges(&self) -> &InterpolatedStringRanges { &self.interpolated_string_ranges } /// Returns the byte offset ranges of multiline strings. pub const fn multiline_ranges(&self) -> &MultilineRanges { &self.multiline_ranges } /// Returns the line start positions of continuations (backslash). pub fn continuation_line_starts(&self) -> &[TextSize] { &self.continuation_lines } /// Returns `true` if the given offset is part of a continuation line. pub fn is_continuation(&self, offset: TextSize, source: &str) -> bool { let line_start = source.line_start(offset); self.continuation_lines.binary_search(&line_start).is_ok() } /// Given an offset at the end of a line (including newlines), return the offset of the /// continuation at the end of that line. fn find_continuation(&self, offset: TextSize, source: &str) -> Option<TextSize> { let newline_pos = usize::from(offset).saturating_sub(1); // Skip the newline. let newline_len = match source.as_bytes()[newline_pos] { b'\n' => { if source.as_bytes().get(newline_pos.saturating_sub(1)) == Some(&b'\r') { 2 } else { 1 } } b'\r' => 1, // No preceding line. _ => return None, }; self.is_continuation(offset - TextSize::from(newline_len), source) .then(|| offset - TextSize::from(newline_len) - TextSize::from(1)) } /// If the node starting at the given [`TextSize`] is preceded by at least one continuation line /// (i.e., a line ending in a backslash), return the starting offset of the first such continuation /// character. /// /// For example, given: /// ```python /// x = 1; \ /// y = 2 /// ``` /// /// When passed the offset of `y`, this function will return the offset of the backslash at the end /// of the first line. /// /// Similarly, given: /// ```python /// x = 1; \ /// \ /// y = 2; /// ``` /// /// When passed the offset of `y`, this function will again return the offset of the backslash at /// the end of the first line. pub fn preceded_by_continuations(&self, offset: TextSize, source: &str) -> Option<TextSize> { // Find the first preceding continuation. If the offset isn't the first non-whitespace // character on the line, then we can't have a continuation. let previous_line_end = source.line_start(offset); if !source[TextRange::new(previous_line_end, offset)] .chars() .all(is_python_whitespace) { return None; } let mut continuation = self.find_continuation(previous_line_end, source)?; // Continue searching for continuations, in the unlikely event that we have multiple // continuations in a row. loop { let previous_line_end = source.line_start(continuation); if source[TextRange::new(previous_line_end, continuation)] .chars() .all(is_python_whitespace) { if let Some(next_continuation) = self.find_continuation(previous_line_end, source) { continuation = next_continuation; continue; } } break; } Some(continuation) } /// Return `true` if a [`Stmt`] appears to be preceded by other statements in a multi-statement /// line. pub fn preceded_by_multi_statement_line(&self, stmt: &Stmt, source: &str) -> bool { has_leading_content(stmt.start(), source) || self .preceded_by_continuations(stmt.start(), source) .is_some() } /// Return `true` if a [`Stmt`] appears to be followed by other statements in a multi-statement /// line. pub fn followed_by_multi_statement_line(&self, stmt: &Stmt, source: &str) -> bool { has_trailing_content(stmt.end(), source) } /// Return `true` if a [`Stmt`] appears to be part of a multi-statement line. pub fn in_multi_statement_line(&self, stmt: &Stmt, source: &str) -> bool { self.followed_by_multi_statement_line(stmt, source) || self.preceded_by_multi_statement_line(stmt, source) } } #[cfg(test)] mod tests { use ruff_python_parser::parse_module; use ruff_text_size::{TextRange, TextSize}; use crate::Indexer; fn new_indexer(contents: &str) -> Indexer { let parsed = parse_module(contents).unwrap(); Indexer::from_tokens(parsed.tokens(), contents) } #[test] fn continuation() { let contents = r"x = 1"; assert_eq!(new_indexer(contents).continuation_line_starts(), &[]); let contents = r" # Hello, world! x = 1 y = 2 " .trim(); assert_eq!(new_indexer(contents).continuation_line_starts(), &[]); let contents = r#" x = \ 1 if True: z = \ \ 2 ( "abc" # Foo "def" \ "ghi" ) "# .trim(); assert_eq!( new_indexer(contents).continuation_line_starts(), [ // row 1 TextSize::from(0), // row 5 TextSize::from(22), // row 6 TextSize::from(32), // row 11 TextSize::from(71), ] ); let contents = r" x = 1; import sys import os if True: x = 1; import sys import os if True: x = 1; \ import os x = 1; \ import os " .trim(); assert_eq!( new_indexer(contents).continuation_line_starts(), [ // row 9 TextSize::from(84), // row 12 TextSize::from(116) ] ); let contents = r" f'foo { 'str1' \ 'str2' \ 'str3' f'nested { 'str4' 'str5' \ 'str6' }' }' " .trim(); assert_eq!( new_indexer(contents).continuation_line_starts(), [ // row 1 TextSize::new(0), // row 2 TextSize::new(17), // row 5 TextSize::new(63), ] ); let contents = r" x = ( 1 \ \ \ \ + 2) " .trim(); assert_eq!( new_indexer(contents).continuation_line_starts(), [ // row 3 TextSize::new(12), // row 4 TextSize::new(18), // row 5 TextSize::new(24), // row 7 TextSize::new(31), ] ); } #[test] fn test_f_string_ranges() { let contents = r#" f"normal f-string" f"start {f"inner {f"another"}"} end" f"implicit " f"concatenation" "# .trim(); assert_eq!( new_indexer(contents) .interpolated_string_ranges() .values() .copied() .collect::<Vec<_>>(), &[ TextRange::new(TextSize::from(0), TextSize::from(18)), TextRange::new(TextSize::from(19), TextSize::from(55)), TextRange::new(TextSize::from(28), TextSize::from(49)), TextRange::new(TextSize::from(37), TextSize::from(47)), TextRange::new(TextSize::from(56), TextSize::from(68)), TextRange::new(TextSize::from(69), TextSize::from(85)), ] ); } #[test] fn test_triple_quoted_f_string_ranges() { let contents = r#" f""" this is one multiline f-string """ f''' and this is another ''' f""" this is a {f"""nested multiline f-string"""} """ "# .trim(); assert_eq!( new_indexer(contents) .interpolated_string_ranges() .values() .copied() .collect::<Vec<_>>(), &[ TextRange::new(TextSize::from(0), TextSize::from(39)), TextRange::new(TextSize::from(40), TextSize::from(68)), TextRange::new(TextSize::from(69), TextSize::from(122)), TextRange::new(TextSize::from(85), TextSize::from(117)), ] ); } #[test] fn test_fstring_innermost_outermost() { let contents = r#" f"no nested f-string" if True: f"first {f"second {f"third"} second"} first" foo = "normal string" f"implicit " f"concatenation" f"first line { foo + f"second line {bar}" } third line" f"""this is a multi-line {f"""nested f-string"""} the end""" "# .trim(); let indexer = new_indexer(contents); // For reference, the ranges of the f-strings in the above code are as // follows where the ones inside parentheses are nested f-strings: // // [0..21, (36..80, 45..72, 55..63), 108..120, 121..137, (139..198, 164..184), (200..260, 226..248)] for (offset, innermost_range, outermost_range) in [ // Inside a normal f-string ( TextSize::new(130), TextRange::new(TextSize::new(121), TextSize::new(137)), TextRange::new(TextSize::new(121), TextSize::new(137)), ), // Left boundary ( TextSize::new(121), TextRange::new(TextSize::new(121), TextSize::new(137)), TextRange::new(TextSize::new(121), TextSize::new(137)), ), // Right boundary ( TextSize::new(136), // End offsets are exclusive TextRange::new(TextSize::new(121), TextSize::new(137)), TextRange::new(TextSize::new(121), TextSize::new(137)), ), // "first" left ( TextSize::new(40), TextRange::new(TextSize::new(36), TextSize::new(80)), TextRange::new(TextSize::new(36), TextSize::new(80)), ), // "second" left ( TextSize::new(50), TextRange::new(TextSize::new(45), TextSize::new(72)), TextRange::new(TextSize::new(36), TextSize::new(80)), ), // "third" ( TextSize::new(60), TextRange::new(TextSize::new(55), TextSize::new(63)), TextRange::new(TextSize::new(36), TextSize::new(80)), ), // "second" right ( TextSize::new(70), TextRange::new(TextSize::new(45), TextSize::new(72)), TextRange::new(TextSize::new(36), TextSize::new(80)), ), // "first" right ( TextSize::new(75), TextRange::new(TextSize::new(36), TextSize::new(80)), TextRange::new(TextSize::new(36), TextSize::new(80)), ), // Single-quoted f-strings spanning across multiple lines ( TextSize::new(160), TextRange::new(TextSize::new(139), TextSize::new(198)), TextRange::new(TextSize::new(139), TextSize::new(198)), ), ( TextSize::new(170), TextRange::new(TextSize::new(164), TextSize::new(184)), TextRange::new(TextSize::new(139), TextSize::new(198)), ), // Multi-line f-strings ( TextSize::new(220), TextRange::new(TextSize::new(200), TextSize::new(260)), TextRange::new(TextSize::new(200), TextSize::new(260)), ), ( TextSize::new(240), TextRange::new(TextSize::new(226), TextSize::new(248)), TextRange::new(TextSize::new(200), TextSize::new(260)), ), ] { assert_eq!( indexer .interpolated_string_ranges() .innermost(offset) .unwrap(), innermost_range ); assert_eq!( indexer .interpolated_string_ranges() .outermost(offset) .unwrap(), outermost_range ); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/workspace.rs
crates/ruff_server/src/workspace.rs
use std::ops::Deref; use lsp_types::{Url, WorkspaceFolder}; use thiserror::Error; use crate::session::{ClientOptions, WorkspaceOptionsMap}; #[derive(Debug)] pub struct Workspaces(Vec<Workspace>); impl Workspaces { pub fn new(workspaces: Vec<Workspace>) -> Self { Self(workspaces) } /// Create the workspaces from the provided workspace folders as provided by the client during /// initialization. pub(crate) fn from_workspace_folders( workspace_folders: Option<Vec<WorkspaceFolder>>, mut workspace_options: WorkspaceOptionsMap, ) -> std::result::Result<Workspaces, WorkspacesError> { let mut client_options_for_url = |url: &Url| { workspace_options.remove(url).unwrap_or_else(|| { tracing::info!( "No workspace options found for {}, using default options", url ); ClientOptions::default() }) }; let workspaces = if let Some(folders) = workspace_folders.filter(|folders| !folders.is_empty()) { folders .into_iter() .map(|folder| { let options = client_options_for_url(&folder.uri); Workspace::new(folder.uri).with_options(options) }) .collect() } else { let current_dir = std::env::current_dir().map_err(WorkspacesError::Io)?; tracing::info!( "No workspace(s) were provided during initialization. \ Using the current working directory as a default workspace: {}", current_dir.display() ); let uri = Url::from_file_path(current_dir) .map_err(|()| WorkspacesError::InvalidCurrentDir)?; let options = client_options_for_url(&uri); vec![Workspace::default(uri).with_options(options)] }; Ok(Workspaces(workspaces)) } } impl Deref for Workspaces { type Target = [Workspace]; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Error, Debug)] pub(crate) enum WorkspacesError { #[error(transparent)] Io(#[from] std::io::Error), #[error("Failed to create a URL from the current working directory")] InvalidCurrentDir, } #[derive(Debug)] pub struct Workspace { /// The [`Url`] pointing to the root of the workspace. url: Url, /// The client options for this workspace. options: Option<ClientOptions>, /// Whether this is the default workspace as created by the server. This will be the case when /// no workspace folders were provided during initialization. is_default: bool, } impl Workspace { /// Create a new workspace with the given root URL. pub fn new(url: Url) -> Self { Self { url, options: None, is_default: false, } } /// Create a new default workspace with the given root URL. pub fn default(url: Url) -> Self { Self { url, options: None, is_default: true, } } /// Set the client options for this workspace. #[must_use] pub fn with_options(mut self, options: ClientOptions) -> Self { self.options = Some(options); self } /// Returns the root URL of the workspace. pub(crate) fn url(&self) -> &Url { &self.url } /// Returns the client options for this workspace. pub(crate) fn options(&self) -> Option<&ClientOptions> { self.options.as_ref() } /// Returns true if this is the default workspace. pub(crate) fn is_default(&self) -> bool { self.is_default } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/lib.rs
crates/ruff_server/src/lib.rs
//! ## The Ruff Language Server use std::num::NonZeroUsize; use anyhow::Context as _; pub use edit::{DocumentKey, NotebookDocument, PositionEncoding, TextDocument}; use lsp_types::CodeActionKind; pub use server::{ConnectionSender, MainLoopSender, Server}; pub use session::{Client, ClientOptions, DocumentQuery, DocumentSnapshot, GlobalOptions, Session}; pub use workspace::{Workspace, Workspaces}; use crate::server::ConnectionInitializer; mod edit; mod fix; mod format; mod lint; mod logging; mod resolve; mod server; mod session; mod workspace; pub(crate) const SERVER_NAME: &str = "ruff"; pub(crate) const DIAGNOSTIC_NAME: &str = "Ruff"; pub(crate) const SOURCE_FIX_ALL_RUFF: CodeActionKind = CodeActionKind::new("source.fixAll.ruff"); pub(crate) const SOURCE_ORGANIZE_IMPORTS_RUFF: CodeActionKind = CodeActionKind::new("source.organizeImports.ruff"); pub(crate) const NOTEBOOK_SOURCE_FIX_ALL_RUFF: CodeActionKind = CodeActionKind::new("notebook.source.fixAll.ruff"); pub(crate) const NOTEBOOK_SOURCE_ORGANIZE_IMPORTS_RUFF: CodeActionKind = CodeActionKind::new("notebook.source.organizeImports.ruff"); /// A common result type used in most cases where a /// result type is needed. pub(crate) type Result<T> = anyhow::Result<T>; pub(crate) fn version() -> &'static str { ruff_linter::VERSION } pub fn run(preview: Option<bool>) -> Result<()> { let four = NonZeroUsize::new(4).unwrap(); // by default, we set the number of worker threads to `num_cpus`, with a maximum of 4. let worker_threads = std::thread::available_parallelism() .unwrap_or(four) .min(four); let (connection, io_threads) = ConnectionInitializer::stdio(); let server_result = Server::new(worker_threads, connection, preview) .context("Failed to start server")? .run(); let io_result = io_threads.join(); let result = match (server_result, io_result) { (Ok(()), Ok(())) => Ok(()), (Err(server), Err(io)) => Err(server).context(format!("IO thread error: {io}")), (Err(server), _) => Err(server), (_, Err(io)) => Err(io).context("IO thread error"), }; if let Err(err) = result.as_ref() { tracing::warn!("Server shut down with an error: {err}"); } else { tracing::info!("Server shut down"); } result }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/fix.rs
crates/ruff_server/src/fix.rs
use std::borrow::Cow; use rustc_hash::FxHashMap; use crate::{ PositionEncoding, edit::{Replacement, ToRangeExt}, resolve::is_document_excluded_for_linting, session::DocumentQuery, }; use ruff_linter::package::PackageRoot; use ruff_linter::{ linter::FixerResult, packaging::detect_package_root, settings::{LinterSettings, flags}, }; use ruff_notebook::SourceValue; use ruff_source_file::LineIndex; /// A simultaneous fix made across a single text document or among an arbitrary /// number of notebook cells. pub(crate) type Fixes = FxHashMap<lsp_types::Url, Vec<lsp_types::TextEdit>>; pub(crate) fn fix_all( query: &DocumentQuery, linter_settings: &LinterSettings, encoding: PositionEncoding, ) -> crate::Result<Fixes> { let source_kind = query.make_source_kind(); let settings = query.settings(); let document_path = query.virtual_file_path(); // If the document is excluded, return an empty list of fixes. if is_document_excluded_for_linting( &document_path, &settings.file_resolver, linter_settings, query.text_document_language_id(), ) { return Ok(Fixes::default()); } let file_path = query.file_path(); let package = if let Some(file_path) = &file_path { detect_package_root( file_path .parent() .expect("a path to a document should have a parent path"), &linter_settings.namespace_packages, ) .map(PackageRoot::root) } else { None }; let source_type = query.source_type(); // We need to iteratively apply all safe fixes onto a single file and then // create a diff between the modified file and the original source to use as a single workspace // edit. // If we simply generated the diagnostics with `check_path` and then applied fixes individually, // there's a possibility they could overlap or introduce new problems that need to be fixed, // which is inconsistent with how `ruff check --fix` works. let FixerResult { transformed, result, .. } = ruff_linter::linter::lint_fix( &document_path, package, flags::Noqa::Enabled, settings.unsafe_fixes, linter_settings, &source_kind, source_type, )?; if result.has_invalid_syntax() { // If there's a syntax error, then there won't be any fixes to apply. return Ok(Fixes::default()); } // fast path: if `transformed` is still borrowed, no changes were made and we can return early if let Cow::Borrowed(_) = transformed { return Ok(Fixes::default()); } if let (Some(source_notebook), Some(modified_notebook)) = (source_kind.as_ipy_notebook(), transformed.as_ipy_notebook()) { fn cell_source(cell: &ruff_notebook::Cell) -> String { match cell.source() { SourceValue::String(string) => string.clone(), SourceValue::StringArray(array) => array.join(""), } } let Some(notebook) = query.as_notebook() else { anyhow::bail!("Notebook document expected from notebook source kind"); }; let mut fixes = Fixes::default(); for ((source, modified), url) in source_notebook .cells() .iter() .map(cell_source) .zip(modified_notebook.cells().iter().map(cell_source)) .zip(notebook.urls()) { let source_index = LineIndex::from_source_text(&source); let modified_index = LineIndex::from_source_text(&modified); let Replacement { source_range, modified_range, } = Replacement::between( &source, source_index.line_starts(), &modified, modified_index.line_starts(), ); fixes.insert( url.clone(), vec![lsp_types::TextEdit { range: source_range.to_range(&source, &source_index, encoding), new_text: modified[modified_range].to_owned(), }], ); } Ok(fixes) } else { let source_index = LineIndex::from_source_text(source_kind.source_code()); let modified = transformed.source_code(); let modified_index = LineIndex::from_source_text(modified); let Replacement { source_range, modified_range, } = Replacement::between( source_kind.source_code(), source_index.line_starts(), modified, modified_index.line_starts(), ); Ok([( query.make_key().into_url(), vec![lsp_types::TextEdit { range: source_range.to_range(source_kind.source_code(), &source_index, encoding), new_text: modified[modified_range].to_owned(), }], )] .into_iter() .collect()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/session.rs
crates/ruff_server/src/session.rs
//! Data model, state management, and configuration resolution. use std::path::Path; use std::sync::Arc; use lsp_types::{ClientCapabilities, FileEvent, NotebookDocumentCellChange, Url}; use settings::ClientSettings; use crate::edit::{DocumentKey, DocumentVersion, NotebookDocument}; use crate::session::request_queue::RequestQueue; use crate::session::settings::GlobalClientSettings; use crate::workspace::Workspaces; use crate::{PositionEncoding, TextDocument}; pub(crate) use self::capabilities::ResolvedClientCapabilities; pub use self::index::DocumentQuery; pub(crate) use self::options::{AllOptions, WorkspaceOptionsMap}; pub use self::options::{ClientOptions, GlobalOptions}; pub use client::Client; mod capabilities; mod client; mod index; mod options; mod request_queue; mod settings; /// The global state for the LSP pub struct Session { /// Used to retrieve information about open documents and settings. index: index::Index, /// The global position encoding, negotiated during LSP initialization. position_encoding: PositionEncoding, /// Global settings provided by the client. global_settings: GlobalClientSettings, /// Tracks what LSP features the client supports and doesn't support. resolved_client_capabilities: Arc<ResolvedClientCapabilities>, /// Tracks the pending requests between client and server. request_queue: RequestQueue, /// Has the client requested the server to shutdown. shutdown_requested: bool, } /// An immutable snapshot of `Session` that references /// a specific document. pub struct DocumentSnapshot { resolved_client_capabilities: Arc<ResolvedClientCapabilities>, client_settings: Arc<settings::ClientSettings>, document_ref: index::DocumentQuery, position_encoding: PositionEncoding, } impl Session { pub fn new( client_capabilities: &ClientCapabilities, position_encoding: PositionEncoding, global: GlobalClientSettings, workspaces: &Workspaces, client: &Client, ) -> crate::Result<Self> { Ok(Self { position_encoding, index: index::Index::new(workspaces, &global, client)?, global_settings: global, resolved_client_capabilities: Arc::new(ResolvedClientCapabilities::new( client_capabilities, )), request_queue: RequestQueue::new(), shutdown_requested: false, }) } pub(crate) fn request_queue(&self) -> &RequestQueue { &self.request_queue } pub(crate) fn request_queue_mut(&mut self) -> &mut RequestQueue { &mut self.request_queue } pub(crate) fn is_shutdown_requested(&self) -> bool { self.shutdown_requested } pub(crate) fn set_shutdown_requested(&mut self, requested: bool) { self.shutdown_requested = requested; } pub fn key_from_url(&self, url: Url) -> DocumentKey { self.index.key_from_url(url) } /// Creates a document snapshot with the URL referencing the document to snapshot. pub fn take_snapshot(&self, url: Url) -> Option<DocumentSnapshot> { let key = self.key_from_url(url); Some(DocumentSnapshot { resolved_client_capabilities: self.resolved_client_capabilities.clone(), client_settings: self .index .client_settings(&key) .unwrap_or_else(|| self.global_settings.to_settings_arc()), document_ref: self.index.make_document_ref(key, &self.global_settings)?, position_encoding: self.position_encoding, }) } /// Iterates over the LSP URLs for all open text documents. These URLs are valid file paths. pub(super) fn text_document_urls(&self) -> impl Iterator<Item = &lsp_types::Url> + '_ { self.index.text_document_urls() } /// Iterates over the LSP URLs for all open notebook documents. These URLs are valid file paths. pub(super) fn notebook_document_urls(&self) -> impl Iterator<Item = &lsp_types::Url> + '_ { self.index.notebook_document_urls() } /// Updates a text document at the associated `key`. /// /// The document key must point to a text document, or this will throw an error. pub(crate) fn update_text_document( &mut self, key: &DocumentKey, content_changes: Vec<lsp_types::TextDocumentContentChangeEvent>, new_version: DocumentVersion, ) -> crate::Result<()> { let encoding = self.encoding(); self.index .update_text_document(key, content_changes, new_version, encoding) } /// Updates a notebook document at the associated `key` with potentially new /// cell, metadata, and version values. /// /// The document key must point to a notebook document or cell, or this will /// throw an error. pub fn update_notebook_document( &mut self, key: &DocumentKey, cells: Option<NotebookDocumentCellChange>, metadata: Option<serde_json::Map<String, serde_json::Value>>, version: DocumentVersion, ) -> crate::Result<()> { let encoding = self.encoding(); self.index .update_notebook_document(key, cells, metadata, version, encoding) } /// Registers a notebook document at the provided `url`. /// If a document is already open here, it will be overwritten. pub fn open_notebook_document(&mut self, url: Url, document: NotebookDocument) { self.index.open_notebook_document(url, document); } /// Registers a text document at the provided `url`. /// If a document is already open here, it will be overwritten. pub(crate) fn open_text_document(&mut self, url: Url, document: TextDocument) { self.index.open_text_document(url, document); } /// De-registers a document, specified by its key. /// Calling this multiple times for the same document is a logic error. pub(crate) fn close_document(&mut self, key: &DocumentKey) -> crate::Result<()> { self.index.close_document(key)?; Ok(()) } /// Reloads the settings index based on the provided changes. pub(crate) fn reload_settings(&mut self, changes: &[FileEvent], client: &Client) { self.index.reload_settings(changes, client); } /// Open a workspace folder at the given `url`. pub(crate) fn open_workspace_folder(&mut self, url: Url, client: &Client) -> crate::Result<()> { self.index .open_workspace_folder(url, &self.global_settings, client) } /// Close a workspace folder at the given `url`. pub(crate) fn close_workspace_folder(&mut self, url: &Url) -> crate::Result<()> { self.index.close_workspace_folder(url)?; Ok(()) } pub(crate) fn resolved_client_capabilities(&self) -> &ResolvedClientCapabilities { &self.resolved_client_capabilities } pub(crate) fn encoding(&self) -> PositionEncoding { self.position_encoding } /// Returns an iterator over the paths to the configuration files in the index. pub(crate) fn config_file_paths(&self) -> impl Iterator<Item = &Path> { self.index.config_file_paths() } /// Returns the resolved global client settings. pub(crate) fn global_client_settings(&self) -> &ClientSettings { self.global_settings.to_settings() } /// Returns the number of open documents in the session. pub(crate) fn open_documents_len(&self) -> usize { self.index.open_documents_len() } /// Returns an iterator over the workspace root folders in the session. pub(crate) fn workspace_root_folders(&self) -> impl Iterator<Item = &Path> { self.index.workspace_root_folders() } } impl DocumentSnapshot { pub(crate) fn resolved_client_capabilities(&self) -> &ResolvedClientCapabilities { &self.resolved_client_capabilities } pub(crate) fn client_settings(&self) -> &settings::ClientSettings { &self.client_settings } pub fn query(&self) -> &index::DocumentQuery { &self.document_ref } pub(crate) fn encoding(&self) -> PositionEncoding { self.position_encoding } /// Returns `true` if this snapshot represents a notebook cell. pub(crate) const fn is_notebook_cell(&self) -> bool { matches!( &self.document_ref, index::DocumentQuery::Notebook { cell_url: Some(_), .. } ) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/lint.rs
crates/ruff_server/src/lint.rs
//! Access to the Ruff linting API for the LSP use rustc_hash::FxHashMap; use serde::{Deserialize, Serialize}; use crate::{ DIAGNOSTIC_NAME, PositionEncoding, edit::{NotebookRange, ToRangeExt}, resolve::is_document_excluded_for_linting, session::DocumentQuery, }; use ruff_db::diagnostic::Diagnostic; use ruff_diagnostics::{Applicability, Edit, Fix}; use ruff_linter::{ Locator, directives::{Flags, extract_directives}, generate_noqa_edits, linter::check_path, package::PackageRoot, packaging::detect_package_root, settings::flags, source_kind::SourceKind, suppression::Suppressions, }; use ruff_notebook::Notebook; use ruff_python_codegen::Stylist; use ruff_python_index::Indexer; use ruff_python_parser::ParseOptions; use ruff_source_file::LineIndex; use ruff_text_size::{Ranged, TextRange}; /// This is serialized on the diagnostic `data` field. #[derive(Serialize, Deserialize, Debug, Clone)] pub(crate) struct AssociatedDiagnosticData { /// The message describing what the fix does, if it exists, or the diagnostic name otherwise. pub(crate) title: String, /// Edits to fix the diagnostic. If this is empty, a fix /// does not exist. pub(crate) edits: Vec<lsp_types::TextEdit>, /// The NOQA code for the diagnostic. pub(crate) code: String, /// Possible edit to add a `noqa` comment which will disable this diagnostic. pub(crate) noqa_edit: Option<lsp_types::TextEdit>, } /// Describes a fix for `fixed_diagnostic` that may have quick fix /// edits available, `noqa` comment edits, or both. #[derive(Clone, Debug)] pub(crate) struct DiagnosticFix { /// The original diagnostic to be fixed pub(crate) fixed_diagnostic: lsp_types::Diagnostic, /// The message describing what the fix does. pub(crate) title: String, /// The NOQA code for the diagnostic. pub(crate) code: String, /// Edits to fix the diagnostic. If this is empty, a fix /// does not exist. pub(crate) edits: Vec<lsp_types::TextEdit>, /// Possible edit to add a `noqa` comment which will disable this diagnostic. pub(crate) noqa_edit: Option<lsp_types::TextEdit>, } /// A series of diagnostics across a single text document or an arbitrary number of notebook cells. pub(crate) type DiagnosticsMap = FxHashMap<lsp_types::Url, Vec<lsp_types::Diagnostic>>; pub(crate) fn check( query: &DocumentQuery, encoding: PositionEncoding, show_syntax_errors: bool, ) -> DiagnosticsMap { let source_kind = query.make_source_kind(); let settings = query.settings(); let document_path = query.virtual_file_path(); // If the document is excluded, return an empty list of diagnostics. if is_document_excluded_for_linting( &document_path, &settings.file_resolver, &settings.linter, query.text_document_language_id(), ) { return DiagnosticsMap::default(); } let file_path = query.file_path(); let package = if let Some(file_path) = &file_path { detect_package_root( file_path .parent() .expect("a path to a document should have a parent path"), &settings.linter.namespace_packages, ) .map(PackageRoot::root) } else { None }; let source_type = query.source_type(); let target_version = settings.linter.resolve_target_version(&document_path); let parse_options = ParseOptions::from(source_type).with_target_version(target_version.parser_version()); // Parse once. let parsed = ruff_python_parser::parse_unchecked(source_kind.source_code(), parse_options) .try_into_module() .expect("PySourceType always parses to a ModModule"); // Map row and column locations to byte slices (lazily). let locator = Locator::new(source_kind.source_code()); // Detect the current code style (lazily). let stylist = Stylist::from_tokens(parsed.tokens(), locator.contents()); // Extra indices from the code. let indexer = Indexer::from_tokens(parsed.tokens(), locator.contents()); // Extract the `# noqa` and `# isort: skip` directives from the source. let directives = extract_directives(parsed.tokens(), Flags::all(), &locator, &indexer); // Parse range suppression comments let suppressions = Suppressions::from_tokens(&settings.linter, locator.contents(), parsed.tokens()); // Generate checks. let diagnostics = check_path( &document_path, package, &locator, &stylist, &indexer, &directives, &settings.linter, flags::Noqa::Enabled, &source_kind, source_type, &parsed, target_version, &suppressions, ); let noqa_edits = generate_noqa_edits( &document_path, &diagnostics, &locator, indexer.comment_ranges(), &settings.linter.external, &directives.noqa_line_for, stylist.line_ending(), &suppressions, ); let mut diagnostics_map = DiagnosticsMap::default(); // Populates all relevant URLs with an empty diagnostic list. // This ensures that documents without diagnostics still get updated. if let Some(notebook) = query.as_notebook() { for url in notebook.urls() { diagnostics_map.entry(url.clone()).or_default(); } } else { diagnostics_map .entry(query.make_key().into_url()) .or_default(); } let lsp_diagnostics = diagnostics .into_iter() .zip(noqa_edits) .filter_map(|(message, noqa_edit)| { if message.is_invalid_syntax() && !show_syntax_errors { None } else { Some(to_lsp_diagnostic( &message, noqa_edit, &source_kind, locator.to_index(), encoding, )) } }); if let Some(notebook) = query.as_notebook() { for (index, diagnostic) in lsp_diagnostics { let Some(uri) = notebook.cell_uri_by_index(index) else { tracing::warn!("Unable to find notebook cell at index {index}."); continue; }; diagnostics_map .entry(uri.clone()) .or_default() .push(diagnostic); } } else { diagnostics_map .entry(query.make_key().into_url()) .or_default() .extend(lsp_diagnostics.map(|(_, diagnostic)| diagnostic)); } diagnostics_map } /// Converts LSP diagnostics to a list of `DiagnosticFix`es by deserializing associated data on each diagnostic. pub(crate) fn fixes_for_diagnostics( diagnostics: Vec<lsp_types::Diagnostic>, ) -> crate::Result<Vec<DiagnosticFix>> { diagnostics .into_iter() .filter(|diagnostic| diagnostic.source.as_deref() == Some(DIAGNOSTIC_NAME)) .map(move |mut diagnostic| { let Some(data) = diagnostic.data.take() else { return Ok(None); }; let fixed_diagnostic = diagnostic; let associated_data: crate::lint::AssociatedDiagnosticData = serde_json::from_value(data).map_err(|err| { anyhow::anyhow!("failed to deserialize diagnostic data: {err}") })?; Ok(Some(DiagnosticFix { fixed_diagnostic, code: associated_data.code, title: associated_data.title, noqa_edit: associated_data.noqa_edit, edits: associated_data.edits, })) }) .filter_map(crate::Result::transpose) .collect() } /// Generates an LSP diagnostic with an associated cell index for the diagnostic to go in. /// If the source kind is a text document, the cell index will always be `0`. fn to_lsp_diagnostic( diagnostic: &Diagnostic, noqa_edit: Option<Edit>, source_kind: &SourceKind, index: &LineIndex, encoding: PositionEncoding, ) -> (usize, lsp_types::Diagnostic) { let diagnostic_range = diagnostic.range().unwrap_or_default(); let name = diagnostic.name(); let body = diagnostic.concise_message().to_string(); let fix = diagnostic.fix(); let suggestion = diagnostic.first_help_text(); let code = diagnostic.secondary_code(); let fix = fix.and_then(|fix| fix.applies(Applicability::Unsafe).then_some(fix)); let data = (fix.is_some() || noqa_edit.is_some()) .then(|| { let code = code?.to_string(); let edits = fix .into_iter() .flat_map(Fix::edits) .map(|edit| lsp_types::TextEdit { range: diagnostic_edit_range(edit.range(), source_kind, index, encoding), new_text: edit.content().unwrap_or_default().to_string(), }) .collect(); let noqa_edit = noqa_edit.map(|noqa_edit| lsp_types::TextEdit { range: diagnostic_edit_range(noqa_edit.range(), source_kind, index, encoding), new_text: noqa_edit.into_content().unwrap_or_default().into_string(), }); serde_json::to_value(AssociatedDiagnosticData { title: suggestion.unwrap_or(name).to_string(), noqa_edit, edits, code, }) .ok() }) .flatten(); let range: lsp_types::Range; let cell: usize; if let Some(notebook_index) = source_kind.as_ipy_notebook().map(Notebook::index) { NotebookRange { cell, range } = diagnostic_range.to_notebook_range( source_kind.source_code(), index, notebook_index, encoding, ); } else { cell = usize::default(); range = diagnostic_range.to_range(source_kind.source_code(), index, encoding); } let (severity, code) = if let Some(code) = code { (severity(code), code.to_string()) } else { ( match diagnostic.severity() { ruff_db::diagnostic::Severity::Info => lsp_types::DiagnosticSeverity::INFORMATION, ruff_db::diagnostic::Severity::Warning => lsp_types::DiagnosticSeverity::WARNING, ruff_db::diagnostic::Severity::Error => lsp_types::DiagnosticSeverity::ERROR, ruff_db::diagnostic::Severity::Fatal => lsp_types::DiagnosticSeverity::ERROR, }, diagnostic.id().to_string(), ) }; ( cell, lsp_types::Diagnostic { range, severity: Some(severity), tags: tags(diagnostic), code: Some(lsp_types::NumberOrString::String(code)), code_description: diagnostic.documentation_url().and_then(|url| { Some(lsp_types::CodeDescription { href: lsp_types::Url::parse(url).ok()?, }) }), source: Some(DIAGNOSTIC_NAME.into()), message: body, related_information: None, data, }, ) } fn diagnostic_edit_range( range: TextRange, source_kind: &SourceKind, index: &LineIndex, encoding: PositionEncoding, ) -> lsp_types::Range { if let Some(notebook_index) = source_kind.as_ipy_notebook().map(Notebook::index) { range .to_notebook_range(source_kind.source_code(), index, notebook_index, encoding) .range } else { range.to_range(source_kind.source_code(), index, encoding) } } fn severity(code: &str) -> lsp_types::DiagnosticSeverity { match code { // F821: undefined name <name> // E902: IOError "F821" | "E902" => lsp_types::DiagnosticSeverity::ERROR, _ => lsp_types::DiagnosticSeverity::WARNING, } } fn tags(diagnostic: &Diagnostic) -> Option<Vec<lsp_types::DiagnosticTag>> { diagnostic.primary_tags().map(|tags| { tags.iter() .map(|tag| match tag { ruff_db::diagnostic::DiagnosticTag::Unnecessary => { lsp_types::DiagnosticTag::UNNECESSARY } ruff_db::diagnostic::DiagnosticTag::Deprecated => { lsp_types::DiagnosticTag::DEPRECATED } }) .collect() }) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/format.rs
crates/ruff_server/src/format.rs
use std::io::Write; use std::path::Path; use std::process::{Command, Stdio}; use anyhow::Context; use ruff_formatter::{FormatOptions, PrintedRange}; use ruff_python_ast::PySourceType; use ruff_python_formatter::{FormatModuleError, PyFormatOptions, format_module_source}; use ruff_source_file::LineIndex; use ruff_text_size::TextRange; use ruff_workspace::FormatterSettings; use crate::edit::TextDocument; /// The backend to use for formatting. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Deserialize)] #[serde(rename_all = "lowercase")] pub(crate) enum FormatBackend { /// Use the built-in Ruff formatter. /// /// The formatter version will match the LSP version. #[default] Internal, /// Use uv for formatting. /// /// The formatter version may differ from the LSP version. Uv, } pub(crate) fn format( document: &TextDocument, source_type: PySourceType, formatter_settings: &FormatterSettings, path: &Path, backend: FormatBackend, ) -> crate::Result<Option<String>> { match backend { FormatBackend::Uv => format_external(document, source_type, formatter_settings, path), FormatBackend::Internal => format_internal(document, source_type, formatter_settings, path), } } /// Format using the built-in Ruff formatter. fn format_internal( document: &TextDocument, source_type: PySourceType, formatter_settings: &FormatterSettings, path: &Path, ) -> crate::Result<Option<String>> { let format_options = formatter_settings.to_format_options(source_type, document.contents(), Some(path)); match format_module_source(document.contents(), format_options) { Ok(formatted) => { let formatted = formatted.into_code(); if formatted == document.contents() { Ok(None) } else { Ok(Some(formatted)) } } // Special case - syntax/parse errors are handled here instead of // being propagated as visible server errors. Err(FormatModuleError::ParseError(error)) => { tracing::warn!("Unable to format document: {error}"); Ok(None) } Err(err) => Err(err.into()), } } /// Format using an external uv command. fn format_external( document: &TextDocument, source_type: PySourceType, formatter_settings: &FormatterSettings, path: &Path, ) -> crate::Result<Option<String>> { let format_options = formatter_settings.to_format_options(source_type, document.contents(), Some(path)); let uv_command = UvFormatCommand::from(format_options); uv_command.format_document(document.contents(), path) } pub(crate) fn format_range( document: &TextDocument, source_type: PySourceType, formatter_settings: &FormatterSettings, range: TextRange, path: &Path, backend: FormatBackend, ) -> crate::Result<Option<PrintedRange>> { match backend { FormatBackend::Uv => { format_range_external(document, source_type, formatter_settings, range, path) } FormatBackend::Internal => { format_range_internal(document, source_type, formatter_settings, range, path) } } } /// Format range using the built-in Ruff formatter fn format_range_internal( document: &TextDocument, source_type: PySourceType, formatter_settings: &FormatterSettings, range: TextRange, path: &Path, ) -> crate::Result<Option<PrintedRange>> { let format_options = formatter_settings.to_format_options(source_type, document.contents(), Some(path)); match ruff_python_formatter::format_range(document.contents(), range, format_options) { Ok(formatted) => { if formatted.as_code() == document.contents() { Ok(None) } else { Ok(Some(formatted)) } } // Special case - syntax/parse errors are handled here instead of // being propagated as visible server errors. Err(FormatModuleError::ParseError(error)) => { tracing::warn!("Unable to format document range: {error}"); Ok(None) } Err(err) => Err(err.into()), } } /// Format range using an external command, i.e., `uv`. fn format_range_external( document: &TextDocument, source_type: PySourceType, formatter_settings: &FormatterSettings, range: TextRange, path: &Path, ) -> crate::Result<Option<PrintedRange>> { let format_options = formatter_settings.to_format_options(source_type, document.contents(), Some(path)); let uv_command = UvFormatCommand::from(format_options); // Format the range using uv and convert the result to `PrintedRange` match uv_command.format_range(document.contents(), range, path, document.index())? { Some(formatted) => Ok(Some(PrintedRange::new(formatted, range))), None => Ok(None), } } /// Builder for uv format commands #[derive(Debug)] pub(crate) struct UvFormatCommand { options: PyFormatOptions, } impl From<PyFormatOptions> for UvFormatCommand { fn from(options: PyFormatOptions) -> Self { Self { options } } } impl UvFormatCommand { /// Build the command with all necessary arguments fn build_command( &self, path: &Path, range_with_index: Option<(TextRange, &LineIndex, &str)>, ) -> Command { let mut command = Command::new("uv"); command.arg("format"); command.arg("--"); let target_version = format!( "py{}{}", self.options.target_version().major, self.options.target_version().minor ); // Add only the formatting options that the CLI supports command.arg("--target-version"); command.arg(&target_version); command.arg("--line-length"); command.arg(self.options.line_width().to_string()); if self.options.preview().is_enabled() { command.arg("--preview"); } // Pass other formatting options via --config command.arg("--config"); command.arg(format!( "format.indent-style = '{}'", self.options.indent_style() )); command.arg("--config"); command.arg(format!("indent-width = {}", self.options.indent_width())); command.arg("--config"); command.arg(format!( "format.quote-style = '{}'", self.options.quote_style() )); command.arg("--config"); command.arg(format!( "format.line-ending = '{}'", self.options.line_ending().as_setting_str() )); command.arg("--config"); command.arg(format!( "format.skip-magic-trailing-comma = {}", match self.options.magic_trailing_comma() { ruff_python_formatter::MagicTrailingComma::Respect => "false", ruff_python_formatter::MagicTrailingComma::Ignore => "true", } )); if let Some((range, line_index, source)) = range_with_index { // The CLI expects line:column format let start_pos = line_index.line_column(range.start(), source); let end_pos = line_index.line_column(range.end(), source); let range_str = format!( "{}:{}-{}:{}", start_pos.line.get(), start_pos.column.get(), end_pos.line.get(), end_pos.column.get() ); command.arg("--range"); command.arg(&range_str); } command.arg("--stdin-filename"); command.arg(path.to_string_lossy().as_ref()); command.stdin(Stdio::piped()); command.stdout(Stdio::piped()); command.stderr(Stdio::piped()); command } /// Execute the format command on the given source. pub(crate) fn format( &self, source: &str, path: &Path, range_with_index: Option<(TextRange, &LineIndex)>, ) -> crate::Result<Option<String>> { let mut command = self.build_command(path, range_with_index.map(|(r, idx)| (r, idx, source))); let mut child = match command.spawn() { Ok(child) => child, Err(err) if err.kind() == std::io::ErrorKind::NotFound => { anyhow::bail!("uv was not found; is it installed and on the PATH?") } Err(err) => return Err(err).context("Failed to spawn uv"), }; let mut stdin = child .stdin .take() .context("Failed to get stdin from format subprocess")?; stdin .write_all(source.as_bytes()) .context("Failed to write to stdin")?; drop(stdin); let result = child .wait_with_output() .context("Failed to get output from format subprocess")?; if !result.status.success() { let stderr = String::from_utf8_lossy(&result.stderr); // We don't propagate format errors due to invalid syntax if stderr.contains("Failed to parse") { tracing::warn!("Unable to format document: {}", stderr); return Ok(None); } // Special-case for when `uv format` is not available if stderr.contains("unrecognized subcommand 'format'") { anyhow::bail!( "The installed version of uv does not support `uv format`; upgrade to a newer version" ); } anyhow::bail!("Failed to format document: {stderr}"); } let formatted = String::from_utf8(result.stdout) .context("Failed to parse stdout from format subprocess as utf-8")?; if formatted == source { Ok(None) } else { Ok(Some(formatted)) } } /// Format the entire document. pub(crate) fn format_document( &self, source: &str, path: &Path, ) -> crate::Result<Option<String>> { self.format(source, path, None) } /// Format a specific range. pub(crate) fn format_range( &self, source: &str, range: TextRange, path: &Path, line_index: &LineIndex, ) -> crate::Result<Option<String>> { self.format(source, path, Some((range, line_index))) } } #[cfg(test)] mod tests { use std::path::Path; use insta::assert_snapshot; use ruff_linter::settings::types::{CompiledPerFileTargetVersionList, PerFileTargetVersion}; use ruff_python_ast::{PySourceType, PythonVersion}; use ruff_text_size::{TextRange, TextSize}; use ruff_workspace::FormatterSettings; use crate::TextDocument; use crate::format::{FormatBackend, format, format_range}; #[test] fn format_per_file_version() { let document = TextDocument::new(r#" with open("a_really_long_foo") as foo, open("a_really_long_bar") as bar, open("a_really_long_baz") as baz: pass "#.to_string(), 0); let per_file_target_version = CompiledPerFileTargetVersionList::resolve(vec![PerFileTargetVersion::new( "test.py".to_string(), PythonVersion::PY310, Some(Path::new(".")), )]) .unwrap(); let result = format( &document, PySourceType::Python, &FormatterSettings { unresolved_target_version: PythonVersion::PY38, per_file_target_version, ..Default::default() }, Path::new("test.py"), FormatBackend::Internal, ) .expect("Expected no errors when formatting") .expect("Expected formatting changes"); assert_snapshot!(result, @r#" with ( open("a_really_long_foo") as foo, open("a_really_long_bar") as bar, open("a_really_long_baz") as baz, ): pass "#); // same as above but without the per_file_target_version override let result = format( &document, PySourceType::Python, &FormatterSettings { unresolved_target_version: PythonVersion::PY38, ..Default::default() }, Path::new("test.py"), FormatBackend::Internal, ) .expect("Expected no errors when formatting") .expect("Expected formatting changes"); assert_snapshot!(result, @r#" with open("a_really_long_foo") as foo, open("a_really_long_bar") as bar, open( "a_really_long_baz" ) as baz: pass "#); } #[test] fn format_per_file_version_range() -> anyhow::Result<()> { // prepare a document with formatting changes before and after the intended range (the // context manager) let document = TextDocument::new(r#" def fn(x: str) -> Foo | Bar: return foobar(x) with open("a_really_long_foo") as foo, open("a_really_long_bar") as bar, open("a_really_long_baz") as baz: pass sys.exit( 1 ) "#.to_string(), 0); let start = document.contents().find("with").unwrap(); let end = document.contents().find("pass").unwrap() + "pass".len(); let range = TextRange::new(TextSize::try_from(start)?, TextSize::try_from(end)?); let per_file_target_version = CompiledPerFileTargetVersionList::resolve(vec![PerFileTargetVersion::new( "test.py".to_string(), PythonVersion::PY310, Some(Path::new(".")), )]) .unwrap(); let result = format_range( &document, PySourceType::Python, &FormatterSettings { unresolved_target_version: PythonVersion::PY38, per_file_target_version, ..Default::default() }, range, Path::new("test.py"), FormatBackend::Internal, ) .expect("Expected no errors when formatting") .expect("Expected formatting changes"); assert_snapshot!(result.as_code(), @r#" with ( open("a_really_long_foo") as foo, open("a_really_long_bar") as bar, open("a_really_long_baz") as baz, ): pass "#); // same as above but without the per_file_target_version override let result = format_range( &document, PySourceType::Python, &FormatterSettings { unresolved_target_version: PythonVersion::PY38, ..Default::default() }, range, Path::new("test.py"), FormatBackend::Internal, ) .expect("Expected no errors when formatting") .expect("Expected formatting changes"); assert_snapshot!(result.as_code(), @r#" with open("a_really_long_foo") as foo, open("a_really_long_bar") as bar, open( "a_really_long_baz" ) as baz: pass "#); Ok(()) } #[cfg(feature = "test-uv")] mod uv_tests { use super::*; #[test] fn test_uv_format_document() { let document = TextDocument::new( r#" def hello( x,y ,z ): return x+y +z def world( ): pass "# .to_string(), 0, ); let result = format( &document, PySourceType::Python, &FormatterSettings::default(), Path::new("test.py"), FormatBackend::Uv, ) .expect("Expected no errors when formatting with uv") .expect("Expected formatting changes"); // uv should format this to a consistent style assert_snapshot!(result, @r#" def hello(x, y, z): return x + y + z def world(): pass "#); } #[test] fn test_uv_format_range() -> anyhow::Result<()> { let document = TextDocument::new( r#" def messy_function( a, b,c ): return a+b+c def another_function(x,y,z): result=x+y+z return result "# .to_string(), 0, ); // Find the range of the second function let start = document.contents().find("def another_function").unwrap(); let end = document.contents().find("return result").unwrap() + "return result".len(); let range = TextRange::new(TextSize::try_from(start)?, TextSize::try_from(end)?); let result = format_range( &document, PySourceType::Python, &FormatterSettings::default(), range, Path::new("test.py"), FormatBackend::Uv, ) .expect("Expected no errors when formatting range with uv") .expect("Expected formatting changes"); assert_snapshot!(result.as_code(), @r#" def messy_function( a, b,c ): return a+b+c def another_function(x, y, z): result = x + y + z return result "#); Ok(()) } #[test] fn test_uv_format_with_line_length() { use ruff_formatter::LineWidth; let document = TextDocument::new( r#" def hello(very_long_parameter_name_1, very_long_parameter_name_2, very_long_parameter_name_3): return very_long_parameter_name_1 + very_long_parameter_name_2 + very_long_parameter_name_3 "# .to_string(), 0, ); // Test with shorter line length let formatter_settings = FormatterSettings { line_width: LineWidth::try_from(60).unwrap(), ..Default::default() }; let result = format( &document, PySourceType::Python, &formatter_settings, Path::new("test.py"), FormatBackend::Uv, ) .expect("Expected no errors when formatting with uv") .expect("Expected formatting changes"); // With line length 60, the function should be wrapped assert_snapshot!(result, @r#" def hello( very_long_parameter_name_1, very_long_parameter_name_2, very_long_parameter_name_3, ): return ( very_long_parameter_name_1 + very_long_parameter_name_2 + very_long_parameter_name_3 ) "#); } #[test] fn test_uv_format_with_indent_style() { use ruff_formatter::IndentStyle; let document = TextDocument::new( r#" def hello(): if True: print("Hello") if False: print("World") "# .to_string(), 0, ); // Test with tabs instead of spaces let formatter_settings = FormatterSettings { indent_style: IndentStyle::Tab, ..Default::default() }; let result = format( &document, PySourceType::Python, &formatter_settings, Path::new("test.py"), FormatBackend::Uv, ) .expect("Expected no errors when formatting with uv") .expect("Expected formatting changes"); // Should have formatting changes (spaces to tabs) assert_snapshot!(result, @r#" def hello(): if True: print("Hello") if False: print("World") "#); } #[test] fn test_uv_format_syntax_error() { let document = TextDocument::new( r#" def broken(: pass "# .to_string(), 0, ); // uv should return None for syntax errors (as indicated by the TODO comment) let result = format( &document, PySourceType::Python, &FormatterSettings::default(), Path::new("test.py"), FormatBackend::Uv, ) .expect("Expected no errors from format function"); // Should return None since the syntax is invalid assert_eq!(result, None, "Expected None for syntax error"); } #[test] fn test_uv_format_with_quote_style() { use ruff_python_formatter::QuoteStyle; let document = TextDocument::new( r#" x = "hello" y = 'world' z = '''multi line''' "# .to_string(), 0, ); // Test with single quotes let formatter_settings = FormatterSettings { quote_style: QuoteStyle::Single, ..Default::default() }; let result = format( &document, PySourceType::Python, &formatter_settings, Path::new("test.py"), FormatBackend::Uv, ) .expect("Expected no errors when formatting with uv") .expect("Expected formatting changes"); assert_snapshot!(result, @r#" x = 'hello' y = 'world' z = """multi line""" "#); } #[test] fn test_uv_format_with_magic_trailing_comma() { use ruff_python_formatter::MagicTrailingComma; let document = TextDocument::new( r#" foo = [ 1, 2, 3, ] bar = [1, 2, 3,] "# .to_string(), 0, ); // Test with ignore magic trailing comma let formatter_settings = FormatterSettings { magic_trailing_comma: MagicTrailingComma::Ignore, ..Default::default() }; let result = format( &document, PySourceType::Python, &formatter_settings, Path::new("test.py"), FormatBackend::Uv, ) .expect("Expected no errors when formatting with uv") .expect("Expected formatting changes"); assert_snapshot!(result, @r#" foo = [1, 2, 3] bar = [1, 2, 3] "#); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/resolve.rs
crates/ruff_server/src/resolve.rs
use std::path::Path; use ruff_linter::settings::LinterSettings; use ruff_workspace::resolver::{match_any_exclusion, match_any_inclusion}; use ruff_workspace::{FileResolverSettings, FormatterSettings}; use crate::edit::LanguageId; /// Return `true` if the document at the given [`Path`] should be excluded from linting. pub(crate) fn is_document_excluded_for_linting( path: &Path, resolver_settings: &FileResolverSettings, linter_settings: &LinterSettings, language_id: Option<LanguageId>, ) -> bool { is_document_excluded( path, resolver_settings, Some(linter_settings), None, language_id, ) } /// Return `true` if the document at the given [`Path`] should be excluded from formatting. pub(crate) fn is_document_excluded_for_formatting( path: &Path, resolver_settings: &FileResolverSettings, formatter_settings: &FormatterSettings, language_id: Option<LanguageId>, ) -> bool { is_document_excluded( path, resolver_settings, None, Some(formatter_settings), language_id, ) } /// Return `true` if the document at the given [`Path`] should be excluded. /// /// The tool-specific settings should be provided if the request for the document is specific to /// that tool. For example, a diagnostics request should provide the linter settings while the /// formatting request should provide the formatter settings. /// /// The logic for the resolution considers both inclusion and exclusion and is as follows: /// 1. Check for global `exclude` and `extend-exclude` options along with tool specific `exclude` /// option (`lint.exclude`, `format.exclude`). /// 2. Check for global `include` and `extend-include` options. /// 3. Check if the language ID is Python, in which case the document is included. /// 4. If none of the above conditions are met, the document is excluded. fn is_document_excluded( path: &Path, resolver_settings: &FileResolverSettings, linter_settings: Option<&LinterSettings>, formatter_settings: Option<&FormatterSettings>, language_id: Option<LanguageId>, ) -> bool { if let Some(exclusion) = match_any_exclusion( path, resolver_settings, linter_settings.map(|s| &*s.exclude), formatter_settings.map(|s| &*s.exclude), ) { tracing::debug!("Ignored path via `{}`: {}", exclusion, path.display()); return true; } if let Some(inclusion) = match_any_inclusion(path, resolver_settings) { tracing::debug!("Included path via `{}`: {}", inclusion, path.display()); false } else if let Some(LanguageId::Python) = language_id { tracing::debug!("Included path via Python language ID: {}", path.display()); false } else { tracing::debug!( "Ignored path as it's not in the inclusion set: {}", path.display() ); true } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/server.rs
crates/ruff_server/src/server.rs
//! Scheduling, I/O, and API endpoints. use lsp_server::Connection; use lsp_types as types; use lsp_types::InitializeParams; use lsp_types::MessageType; use std::num::NonZeroUsize; use std::panic::PanicHookInfo; use std::str::FromStr; use std::sync::Arc; use types::ClientCapabilities; use types::CodeActionKind; use types::CodeActionOptions; use types::DiagnosticOptions; use types::NotebookCellSelector; use types::NotebookDocumentSyncOptions; use types::NotebookSelector; use types::OneOf; use types::TextDocumentSyncCapability; use types::TextDocumentSyncKind; use types::TextDocumentSyncOptions; use types::WorkDoneProgressOptions; use types::WorkspaceFoldersServerCapabilities; pub(crate) use self::connection::ConnectionInitializer; pub use self::connection::ConnectionSender; use self::schedule::spawn_main_loop; use crate::PositionEncoding; pub use crate::server::main_loop::MainLoopSender; pub(crate) use crate::server::main_loop::{Event, MainLoopReceiver}; use crate::session::{AllOptions, Client, Session}; use crate::workspace::Workspaces; pub(crate) use api::Error; mod api; mod connection; mod main_loop; mod schedule; pub(crate) type Result<T> = std::result::Result<T, api::Error>; pub struct Server { connection: Connection, client_capabilities: ClientCapabilities, worker_threads: NonZeroUsize, main_loop_receiver: MainLoopReceiver, main_loop_sender: MainLoopSender, session: Session, } impl Server { pub(crate) fn new( worker_threads: NonZeroUsize, connection: ConnectionInitializer, preview: Option<bool>, ) -> crate::Result<Self> { let (id, init_params) = connection.initialize_start()?; let client_capabilities = init_params.capabilities; let position_encoding = Self::find_best_position_encoding(&client_capabilities); let server_capabilities = Self::server_capabilities(position_encoding); let connection = connection.initialize_finish( id, &server_capabilities, crate::SERVER_NAME, crate::version(), )?; let (main_loop_sender, main_loop_receiver) = crossbeam::channel::bounded(32); let InitializeParams { initialization_options, workspace_folders, .. } = init_params; let client = Client::new(main_loop_sender.clone(), connection.sender.clone()); let mut all_options = AllOptions::from_value( initialization_options .unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::default())), &client, ); if let Some(preview) = preview { all_options.set_preview(preview); } let AllOptions { global: global_options, workspace: workspace_options, } = all_options; crate::logging::init_logging( global_options.tracing.log_level.unwrap_or_default(), global_options.tracing.log_file.as_deref(), ); let workspaces = Workspaces::from_workspace_folders( workspace_folders, workspace_options.unwrap_or_default(), )?; tracing::debug!("Negotiated position encoding: {position_encoding:?}"); let global = global_options.into_settings(client.clone()); Ok(Self { connection, worker_threads, main_loop_sender, main_loop_receiver, session: Session::new( &client_capabilities, position_encoding, global, &workspaces, &client, )?, client_capabilities, }) } pub fn run(mut self) -> crate::Result<()> { let client = Client::new( self.main_loop_sender.clone(), self.connection.sender.clone(), ); let _panic_hook = ServerPanicHookHandler::new(client); spawn_main_loop(move || self.main_loop())?.join() } fn find_best_position_encoding(client_capabilities: &ClientCapabilities) -> PositionEncoding { client_capabilities .general .as_ref() .and_then(|general_capabilities| general_capabilities.position_encodings.as_ref()) .and_then(|encodings| { encodings .iter() .filter_map(|encoding| PositionEncoding::try_from(encoding).ok()) .max() // this selects the highest priority position encoding }) .unwrap_or_default() } fn server_capabilities(position_encoding: PositionEncoding) -> types::ServerCapabilities { types::ServerCapabilities { position_encoding: Some(position_encoding.into()), code_action_provider: Some(types::CodeActionProviderCapability::Options( CodeActionOptions { code_action_kinds: Some( SupportedCodeAction::all() .map(SupportedCodeAction::to_kind) .collect(), ), work_done_progress_options: WorkDoneProgressOptions { work_done_progress: Some(true), }, resolve_provider: Some(true), }, )), workspace: Some(types::WorkspaceServerCapabilities { workspace_folders: Some(WorkspaceFoldersServerCapabilities { supported: Some(true), change_notifications: Some(OneOf::Left(true)), }), file_operations: None, }), document_formatting_provider: Some(OneOf::Left(true)), document_range_formatting_provider: Some(OneOf::Left(true)), diagnostic_provider: Some(types::DiagnosticServerCapabilities::Options( DiagnosticOptions { identifier: Some(crate::DIAGNOSTIC_NAME.into()), // multi-file analysis could change this inter_file_dependencies: false, workspace_diagnostics: false, work_done_progress_options: WorkDoneProgressOptions { work_done_progress: Some(true), }, }, )), execute_command_provider: Some(types::ExecuteCommandOptions { commands: SupportedCommand::all() .map(|command| command.identifier().to_string()) .to_vec(), work_done_progress_options: WorkDoneProgressOptions { work_done_progress: Some(false), }, }), hover_provider: Some(types::HoverProviderCapability::Simple(true)), notebook_document_sync: Some(types::OneOf::Left(NotebookDocumentSyncOptions { save: Some(false), notebook_selector: [NotebookSelector::ByCells { notebook: None, cells: vec![NotebookCellSelector { language: "python".to_string(), }], }] .to_vec(), })), text_document_sync: Some(TextDocumentSyncCapability::Options( TextDocumentSyncOptions { open_close: Some(true), change: Some(TextDocumentSyncKind::INCREMENTAL), will_save: Some(false), will_save_wait_until: Some(false), ..Default::default() }, )), ..Default::default() } } } /// The code actions we support. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(crate) enum SupportedCodeAction { /// Maps to the `quickfix` code action kind. Quick fix code actions are shown under /// their respective diagnostics. Quick fixes are only created where the fix applicability is /// at least [`ruff_diagnostics::Applicability::Unsafe`]. QuickFix, /// Maps to the `source.fixAll` and `source.fixAll.ruff` code action kinds. /// This is a source action that applies all safe fixes to the currently open document. SourceFixAll, /// Maps to `source.organizeImports` and `source.organizeImports.ruff` code action kinds. /// This is a source action that applies import sorting fixes to the currently open document. SourceOrganizeImports, /// Maps to the `notebook.source.fixAll` and `notebook.source.fixAll.ruff` code action kinds. /// This is a source action, specifically for notebooks, that applies all safe fixes /// to the currently open document. NotebookSourceFixAll, /// Maps to `source.organizeImports` and `source.organizeImports.ruff` code action kinds. /// This is a source action, specifically for notebooks, that applies import sorting fixes /// to the currently open document. NotebookSourceOrganizeImports, } impl SupportedCodeAction { /// Returns the LSP code action kind that map to this code action. fn to_kind(self) -> CodeActionKind { match self { Self::QuickFix => CodeActionKind::QUICKFIX, Self::SourceFixAll => crate::SOURCE_FIX_ALL_RUFF, Self::SourceOrganizeImports => crate::SOURCE_ORGANIZE_IMPORTS_RUFF, Self::NotebookSourceFixAll => crate::NOTEBOOK_SOURCE_FIX_ALL_RUFF, Self::NotebookSourceOrganizeImports => crate::NOTEBOOK_SOURCE_ORGANIZE_IMPORTS_RUFF, } } fn from_kind(kind: CodeActionKind) -> impl Iterator<Item = Self> { Self::all().filter(move |supported_kind| { supported_kind.to_kind().as_str().starts_with(kind.as_str()) }) } /// Returns all code actions kinds that the server currently supports. fn all() -> impl Iterator<Item = Self> { [ Self::QuickFix, Self::SourceFixAll, Self::SourceOrganizeImports, Self::NotebookSourceFixAll, Self::NotebookSourceOrganizeImports, ] .into_iter() } } #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum SupportedCommand { Debug, Format, FixAll, OrganizeImports, } impl SupportedCommand { const fn label(self) -> &'static str { match self { Self::FixAll => "Fix all auto-fixable problems", Self::Format => "Format document", Self::OrganizeImports => "Format imports", Self::Debug => "Print debug information", } } /// Returns the identifier of the command. const fn identifier(self) -> &'static str { match self { SupportedCommand::Format => "ruff.applyFormat", SupportedCommand::FixAll => "ruff.applyAutofix", SupportedCommand::OrganizeImports => "ruff.applyOrganizeImports", SupportedCommand::Debug => "ruff.printDebugInformation", } } /// Returns all the commands that the server currently supports. const fn all() -> [SupportedCommand; 4] { [ SupportedCommand::Format, SupportedCommand::FixAll, SupportedCommand::OrganizeImports, SupportedCommand::Debug, ] } } impl FromStr for SupportedCommand { type Err = anyhow::Error; fn from_str(name: &str) -> anyhow::Result<Self, Self::Err> { Ok(match name { "ruff.applyAutofix" => Self::FixAll, "ruff.applyFormat" => Self::Format, "ruff.applyOrganizeImports" => Self::OrganizeImports, "ruff.printDebugInformation" => Self::Debug, _ => return Err(anyhow::anyhow!("Invalid command `{name}`")), }) } } type PanicHook = Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send>; struct ServerPanicHookHandler { hook: Option<PanicHook>, // Hold on to the strong reference for as long as the panic hook is set. _client: Arc<Client>, } impl ServerPanicHookHandler { fn new(client: Client) -> Self { let hook = std::panic::take_hook(); let client = Arc::new(client); // Use a weak reference to the client because it must be dropped when exiting or the // io-threads join hangs forever (because client has a reference to the connection sender). let hook_client = Arc::downgrade(&client); // When we panic, try to notify the client. std::panic::set_hook(Box::new(move |panic_info| { use std::io::Write; let backtrace = std::backtrace::Backtrace::force_capture(); tracing::error!("{panic_info}\n{backtrace}"); // we also need to print to stderr directly for when using `$logTrace` because // the message won't be sent to the client. // But don't use `eprintln` because `eprintln` itself may panic if the pipe is broken. let mut stderr = std::io::stderr().lock(); writeln!(stderr, "{panic_info}\n{backtrace}").ok(); if let Some(client) = hook_client.upgrade() { client .show_message( "The Ruff language server exited with a panic. See the logs for more details.", MessageType::ERROR, ) .ok(); } })); Self { hook: Some(hook), _client: client, } } } impl Drop for ServerPanicHookHandler { fn drop(&mut self) { if std::thread::panicking() { // Calling `std::panic::set_hook` while panicking results in a panic. return; } if let Some(hook) = self.hook.take() { std::panic::set_hook(hook); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/edit.rs
crates/ruff_server/src/edit.rs
//! Types and utilities for working with text, modifying source files, and `Ruff <-> LSP` type conversion. mod notebook; mod range; mod replacement; mod text_document; use std::collections::HashMap; use lsp_types::{PositionEncodingKind, Url}; pub use notebook::NotebookDocument; pub(crate) use range::{NotebookRange, RangeExt, ToRangeExt}; pub(crate) use replacement::Replacement; pub use text_document::TextDocument; pub(crate) use text_document::{DocumentVersion, LanguageId}; use crate::{fix::Fixes, session::ResolvedClientCapabilities}; /// A convenient enumeration for supported text encodings. Can be converted to [`lsp_types::PositionEncodingKind`]. // Please maintain the order from least to greatest priority for the derived `Ord` impl. #[derive(Default, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub enum PositionEncoding { /// UTF 16 is the encoding supported by all LSP clients. #[default] UTF16, /// Second choice because UTF32 uses a fixed 4 byte encoding for each character (makes conversion relatively easy) UTF32, /// Ruff's preferred encoding UTF8, } impl From<PositionEncoding> for ruff_source_file::PositionEncoding { fn from(value: PositionEncoding) -> Self { match value { PositionEncoding::UTF8 => Self::Utf8, PositionEncoding::UTF16 => Self::Utf16, PositionEncoding::UTF32 => Self::Utf32, } } } /// A unique document ID, derived from a URL passed as part of an LSP request. /// This document ID can point to either be a standalone Python file, a full notebook, or a cell within a notebook. #[derive(Clone, Debug)] pub enum DocumentKey { Notebook(Url), NotebookCell(Url), Text(Url), } impl DocumentKey { /// Converts the key back into its original URL. pub(crate) fn into_url(self) -> Url { match self { DocumentKey::NotebookCell(url) | DocumentKey::Notebook(url) | DocumentKey::Text(url) => url, } } } impl std::fmt::Display for DocumentKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::NotebookCell(url) | Self::Notebook(url) | Self::Text(url) => url.fmt(f), } } } /// Tracks multi-document edits to eventually merge into a `WorkspaceEdit`. /// Compatible with clients that don't support `workspace.workspaceEdit.documentChanges`. #[derive(Debug)] pub(crate) enum WorkspaceEditTracker { DocumentChanges(Vec<lsp_types::TextDocumentEdit>), Changes(HashMap<Url, Vec<lsp_types::TextEdit>>), } impl From<PositionEncoding> for lsp_types::PositionEncodingKind { fn from(value: PositionEncoding) -> Self { match value { PositionEncoding::UTF8 => lsp_types::PositionEncodingKind::UTF8, PositionEncoding::UTF16 => lsp_types::PositionEncodingKind::UTF16, PositionEncoding::UTF32 => lsp_types::PositionEncodingKind::UTF32, } } } impl TryFrom<&lsp_types::PositionEncodingKind> for PositionEncoding { type Error = (); fn try_from(value: &PositionEncodingKind) -> Result<Self, Self::Error> { Ok(if value == &PositionEncodingKind::UTF8 { PositionEncoding::UTF8 } else if value == &PositionEncodingKind::UTF16 { PositionEncoding::UTF16 } else if value == &PositionEncodingKind::UTF32 { PositionEncoding::UTF32 } else { return Err(()); }) } } impl WorkspaceEditTracker { pub(crate) fn new(client_capabilities: &ResolvedClientCapabilities) -> Self { if client_capabilities.document_changes { Self::DocumentChanges(Vec::default()) } else { Self::Changes(HashMap::default()) } } /// Sets a series of [`Fixes`] for a text or notebook document. pub(crate) fn set_fixes_for_document( &mut self, fixes: Fixes, version: DocumentVersion, ) -> crate::Result<()> { for (uri, edits) in fixes { self.set_edits_for_document(uri, version, edits)?; } Ok(()) } /// Sets the edits made to a specific document. This should only be called /// once for each document `uri`, and will fail if this is called for the same `uri` /// multiple times. pub(crate) fn set_edits_for_document( &mut self, uri: Url, _version: DocumentVersion, edits: Vec<lsp_types::TextEdit>, ) -> crate::Result<()> { match self { Self::DocumentChanges(document_edits) => { if document_edits .iter() .any(|document| document.text_document.uri == uri) { return Err(anyhow::anyhow!( "Attempted to add edits for a document that was already edited" )); } document_edits.push(lsp_types::TextDocumentEdit { text_document: lsp_types::OptionalVersionedTextDocumentIdentifier { uri, // TODO(jane): Re-enable versioned edits after investigating whether it could work with notebook cells version: None, }, edits: edits.into_iter().map(lsp_types::OneOf::Left).collect(), }); Ok(()) } Self::Changes(changes) => { if changes.get(&uri).is_some() { return Err(anyhow::anyhow!( "Attempted to add edits for a document that was already edited" )); } changes.insert(uri, edits); Ok(()) } } } pub(crate) fn is_empty(&self) -> bool { match self { Self::DocumentChanges(document_edits) => document_edits.is_empty(), Self::Changes(changes) => changes.is_empty(), } } pub(crate) fn into_workspace_edit(self) -> lsp_types::WorkspaceEdit { match self { Self::DocumentChanges(document_edits) => lsp_types::WorkspaceEdit { document_changes: Some(lsp_types::DocumentChanges::Edits(document_edits)), ..Default::default() }, Self::Changes(changes) => lsp_types::WorkspaceEdit::new(changes), } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/logging.rs
crates/ruff_server/src/logging.rs
//! The logging system for `ruff server`. //! //! Log messages are controlled by the `logLevel` setting which defaults to `"info"`. Log messages //! are written to `stderr` by default, which should appear in the logs for most LSP clients. A //! `logFile` path can also be specified in the settings, and output will be directed there //! instead. use core::str; use serde::Deserialize; use std::{path::PathBuf, str::FromStr, sync::Arc}; use tracing::level_filters::LevelFilter; use tracing_subscriber::{ Layer, fmt::{format::FmtSpan, time::ChronoLocal, writer::BoxMakeWriter}, layer::SubscriberExt, }; pub(crate) fn init_logging(log_level: LogLevel, log_file: Option<&std::path::Path>) { let log_file = log_file .map(|path| { // this expands `logFile` so that tildes and environment variables // are replaced with their values, if possible. if let Some(expanded) = shellexpand::full(&path.to_string_lossy()) .ok() .and_then(|path| PathBuf::from_str(&path).ok()) { expanded } else { path.to_path_buf() } }) .and_then(|path| { std::fs::OpenOptions::new() .create(true) .append(true) .open(&path) .map_err(|err| { #[expect(clippy::print_stderr)] { eprintln!( "Failed to open file at {} for logging: {err}", path.display() ); } }) .ok() }); let logger = match log_file { Some(file) => BoxMakeWriter::new(Arc::new(file)), None => BoxMakeWriter::new(std::io::stderr), }; let is_trace_level = log_level == LogLevel::Trace; let subscriber = tracing_subscriber::Registry::default().with( tracing_subscriber::fmt::layer() .with_timer(ChronoLocal::new("%Y-%m-%d %H:%M:%S.%f".to_string())) .with_thread_names(is_trace_level) .with_target(is_trace_level) .with_ansi(false) .with_writer(logger) .with_span_events(FmtSpan::ENTER) .with_filter(LogLevelFilter { filter: log_level }), ); tracing::subscriber::set_global_default(subscriber) .expect("should be able to set global default subscriber"); tracing_log::LogTracer::init().unwrap(); } /// The log level for the server as provided by the client during initialization. /// /// The default log level is `info`. #[derive(Clone, Copy, Debug, Deserialize, Default, PartialEq, Eq, PartialOrd, Ord)] #[serde(rename_all = "lowercase")] pub(crate) enum LogLevel { Error, Warn, #[default] Info, Debug, Trace, } impl LogLevel { fn trace_level(self) -> tracing::Level { match self { Self::Error => tracing::Level::ERROR, Self::Warn => tracing::Level::WARN, Self::Info => tracing::Level::INFO, Self::Debug => tracing::Level::DEBUG, Self::Trace => tracing::Level::TRACE, } } } /// Filters out traces which have a log level lower than the `logLevel` set by the client. struct LogLevelFilter { filter: LogLevel, } impl<S> tracing_subscriber::layer::Filter<S> for LogLevelFilter { fn enabled( &self, meta: &tracing::Metadata<'_>, _: &tracing_subscriber::layer::Context<'_, S>, ) -> bool { let filter = if meta.target().starts_with("ruff") { self.filter.trace_level() } else { tracing::Level::INFO }; meta.level() <= &filter } fn max_level_hint(&self) -> Option<tracing::level_filters::LevelFilter> { Some(LevelFilter::from_level(self.filter.trace_level())) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/edit/notebook.rs
crates/ruff_server/src/edit/notebook.rs
use anyhow::Ok; use lsp_types::NotebookCellKind; use ruff_notebook::CellMetadata; use rustc_hash::{FxBuildHasher, FxHashMap}; use crate::{PositionEncoding, TextDocument}; use super::DocumentVersion; pub(super) type CellId = usize; /// The state of a notebook document in the server. Contains an array of cells whose /// contents are internally represented by [`TextDocument`]s. #[derive(Clone, Debug)] pub struct NotebookDocument { cells: Vec<NotebookCell>, metadata: ruff_notebook::RawNotebookMetadata, version: DocumentVersion, // Used to quickly find the index of a cell for a given URL. cell_index: FxHashMap<lsp_types::Url, CellId>, } /// A single cell within a notebook, which has text contents represented as a `TextDocument`. #[derive(Clone, Debug)] struct NotebookCell { url: lsp_types::Url, kind: NotebookCellKind, document: TextDocument, } impl NotebookDocument { pub fn new( version: DocumentVersion, cells: Vec<lsp_types::NotebookCell>, metadata: serde_json::Map<String, serde_json::Value>, cell_documents: Vec<lsp_types::TextDocumentItem>, ) -> crate::Result<Self> { let mut cell_contents: FxHashMap<_, _> = cell_documents .into_iter() .map(|document| (document.uri, document.text)) .collect(); let cells: Vec<_> = cells .into_iter() .map(|cell| { let contents = cell_contents.remove(&cell.document).unwrap_or_default(); NotebookCell::new(cell, contents, version) }) .collect(); Ok(Self { version, cell_index: Self::make_cell_index(cells.as_slice()), metadata: serde_json::from_value(serde_json::Value::Object(metadata))?, cells, }) } /// Generates a pseudo-representation of a notebook that lacks per-cell metadata and contextual information /// but should still work with Ruff's linter. pub fn make_ruff_notebook(&self) -> ruff_notebook::Notebook { let cells = self .cells .iter() .map(|cell| match cell.kind { NotebookCellKind::Code => ruff_notebook::Cell::Code(ruff_notebook::CodeCell { execution_count: None, id: None, metadata: CellMetadata::default(), outputs: vec![], source: ruff_notebook::SourceValue::String( cell.document.contents().to_string(), ), }), NotebookCellKind::Markup => { ruff_notebook::Cell::Markdown(ruff_notebook::MarkdownCell { attachments: None, id: None, metadata: CellMetadata::default(), source: ruff_notebook::SourceValue::String( cell.document.contents().to_string(), ), }) } }) .collect(); let raw_notebook = ruff_notebook::RawNotebook { cells, metadata: self.metadata.clone(), nbformat: 4, nbformat_minor: 5, }; ruff_notebook::Notebook::from_raw_notebook(raw_notebook, false) .unwrap_or_else(|err| panic!("Server notebook document could not be converted to Ruff's notebook document format: {err}")) } pub(crate) fn update( &mut self, cells: Option<lsp_types::NotebookDocumentCellChange>, metadata_change: Option<serde_json::Map<String, serde_json::Value>>, version: DocumentVersion, encoding: PositionEncoding, ) -> crate::Result<()> { self.version = version; if let Some(lsp_types::NotebookDocumentCellChange { structure, data, text_content, }) = cells { // The structural changes should be done first, as they may affect the cell index. if let Some(structure) = structure { let start = structure.array.start as usize; let delete = structure.array.delete_count as usize; // This is required because of the way the `NotebookCell` is modelled. We include // the `TextDocument` within the `NotebookCell` so when it's deleted, the // corresponding `TextDocument` is removed as well. But, when cells are // re-ordered, the change request doesn't provide the actual contents of the cell. // Instead, it only provides that (a) these cell URIs were removed, and (b) these // cell URIs were added. // https://github.com/astral-sh/ruff/issues/12573 let mut deleted_cells = FxHashMap::default(); // First, delete the cells and remove them from the index. if delete > 0 { for cell in self.cells.drain(start..start + delete) { self.cell_index.remove(&cell.url); deleted_cells.insert(cell.url, cell.document); } } // Second, insert the new cells with the available information. This array does not // provide the actual contents of the cells, so we'll initialize them with empty // contents. for cell in structure.array.cells.into_iter().flatten().rev() { let (content, version) = if let Some(text_document) = deleted_cells.remove(&cell.document) { let version = text_document.version(); (text_document.into_contents(), version) } else { (String::new(), 0) }; self.cells .insert(start, NotebookCell::new(cell, content, version)); } // Third, register the new cells in the index and update existing ones that came // after the insertion. for (index, cell) in self.cells.iter().enumerate().skip(start) { self.cell_index.insert(cell.url.clone(), index); } // Finally, update the text document that represents the cell with the actual // contents. This should be done at the end so that both the `cells` and // `cell_index` are updated before we start applying the changes to the cells. if let Some(did_open) = structure.did_open { for cell_text_document in did_open { if let Some(cell) = self.cell_by_uri_mut(&cell_text_document.uri) { cell.document = TextDocument::new( cell_text_document.text, cell_text_document.version, ); } } } } if let Some(cell_data) = data { for cell in cell_data { if let Some(existing_cell) = self.cell_by_uri_mut(&cell.document) { existing_cell.kind = cell.kind; } } } if let Some(content_changes) = text_content { for content_change in content_changes { if let Some(cell) = self.cell_by_uri_mut(&content_change.document.uri) { cell.document .apply_changes(content_change.changes, version, encoding); } } } } if let Some(metadata_change) = metadata_change { self.metadata = serde_json::from_value(serde_json::Value::Object(metadata_change))?; } Ok(()) } /// Get the current version of the notebook document. pub(crate) fn version(&self) -> DocumentVersion { self.version } /// Get the URI for a cell by its index within the cell array. pub(crate) fn cell_uri_by_index(&self, index: CellId) -> Option<&lsp_types::Url> { self.cells.get(index).map(|cell| &cell.url) } /// Get the text document representing the contents of a cell by the cell URI. pub(crate) fn cell_document_by_uri(&self, uri: &lsp_types::Url) -> Option<&TextDocument> { self.cells .get(*self.cell_index.get(uri)?) .map(|cell| &cell.document) } /// Returns a list of cell URIs in the order they appear in the array. pub(crate) fn urls(&self) -> impl Iterator<Item = &lsp_types::Url> { self.cells.iter().map(|cell| &cell.url) } fn cell_by_uri_mut(&mut self, uri: &lsp_types::Url) -> Option<&mut NotebookCell> { self.cells.get_mut(*self.cell_index.get(uri)?) } fn make_cell_index(cells: &[NotebookCell]) -> FxHashMap<lsp_types::Url, CellId> { let mut index = FxHashMap::with_capacity_and_hasher(cells.len(), FxBuildHasher); for (i, cell) in cells.iter().enumerate() { index.insert(cell.url.clone(), i); } index } } impl NotebookCell { pub(crate) fn new( cell: lsp_types::NotebookCell, contents: String, version: DocumentVersion, ) -> Self { Self { url: cell.document, kind: cell.kind, document: TextDocument::new(contents, version), } } } #[cfg(test)] mod tests { use super::NotebookDocument; enum TestCellContent { #[expect(dead_code)] Markup(String), Code(String), } fn create_test_url(index: usize) -> lsp_types::Url { lsp_types::Url::parse(&format!("cell:/test.ipynb#{index}")).unwrap() } fn create_test_notebook(test_cells: Vec<TestCellContent>) -> NotebookDocument { let mut cells = Vec::with_capacity(test_cells.len()); let mut cell_documents = Vec::with_capacity(test_cells.len()); for (index, test_cell) in test_cells.into_iter().enumerate() { let url = create_test_url(index); match test_cell { TestCellContent::Markup(content) => { cells.push(lsp_types::NotebookCell { kind: lsp_types::NotebookCellKind::Markup, document: url.clone(), metadata: None, execution_summary: None, }); cell_documents.push(lsp_types::TextDocumentItem { uri: url, language_id: "markdown".to_owned(), version: 0, text: content, }); } TestCellContent::Code(content) => { cells.push(lsp_types::NotebookCell { kind: lsp_types::NotebookCellKind::Code, document: url.clone(), metadata: None, execution_summary: None, }); cell_documents.push(lsp_types::TextDocumentItem { uri: url, language_id: "python".to_owned(), version: 0, text: content, }); } } } NotebookDocument::new(0, cells, serde_json::Map::default(), cell_documents).unwrap() } /// This test case checks that for a notebook with three code cells, when the client sends a /// change request to swap the first two cells, the notebook document is updated correctly. /// /// The swap operation as a change request is represented as deleting the first two cells and /// adding them back in the reverse order. #[test] fn swap_cells() { let mut notebook = create_test_notebook(vec![ TestCellContent::Code("cell = 0".to_owned()), TestCellContent::Code("cell = 1".to_owned()), TestCellContent::Code("cell = 2".to_owned()), ]); notebook .update( Some(lsp_types::NotebookDocumentCellChange { structure: Some(lsp_types::NotebookDocumentCellChangeStructure { array: lsp_types::NotebookCellArrayChange { start: 0, delete_count: 2, cells: Some(vec![ lsp_types::NotebookCell { kind: lsp_types::NotebookCellKind::Code, document: create_test_url(1), metadata: None, execution_summary: None, }, lsp_types::NotebookCell { kind: lsp_types::NotebookCellKind::Code, document: create_test_url(0), metadata: None, execution_summary: None, }, ]), }, did_open: None, did_close: None, }), data: None, text_content: None, }), None, 1, crate::PositionEncoding::default(), ) .unwrap(); assert_eq!( notebook.make_ruff_notebook().source_code(), "cell = 1 cell = 0 cell = 2 " ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/edit/range.rs
crates/ruff_server/src/edit/range.rs
use super::PositionEncoding; use super::notebook; use lsp_types as types; use ruff_notebook::NotebookIndex; use ruff_source_file::LineIndex; use ruff_source_file::{OneIndexed, SourceLocation}; use ruff_text_size::TextRange; pub(crate) struct NotebookRange { pub(crate) cell: notebook::CellId, pub(crate) range: types::Range, } pub(crate) trait RangeExt { fn to_text_range(&self, text: &str, index: &LineIndex, encoding: PositionEncoding) -> TextRange; } pub(crate) trait ToRangeExt { fn to_range(&self, text: &str, index: &LineIndex, encoding: PositionEncoding) -> types::Range; fn to_notebook_range( &self, text: &str, source_index: &LineIndex, notebook_index: &NotebookIndex, encoding: PositionEncoding, ) -> NotebookRange; } fn u32_index_to_usize(index: u32) -> usize { usize::try_from(index).expect("u32 fits in usize") } impl RangeExt for lsp_types::Range { fn to_text_range( &self, text: &str, index: &LineIndex, encoding: PositionEncoding, ) -> TextRange { let start = index.offset( SourceLocation { line: OneIndexed::from_zero_indexed(u32_index_to_usize(self.start.line)), character_offset: OneIndexed::from_zero_indexed(u32_index_to_usize( self.start.character, )), }, text, encoding.into(), ); let end = index.offset( SourceLocation { line: OneIndexed::from_zero_indexed(u32_index_to_usize(self.end.line)), character_offset: OneIndexed::from_zero_indexed(u32_index_to_usize( self.end.character, )), }, text, encoding.into(), ); TextRange::new(start, end) } } impl ToRangeExt for TextRange { fn to_range(&self, text: &str, index: &LineIndex, encoding: PositionEncoding) -> types::Range { types::Range { start: source_location_to_position(&index.source_location( self.start(), text, encoding.into(), )), end: source_location_to_position(&index.source_location( self.end(), text, encoding.into(), )), } } fn to_notebook_range( &self, text: &str, source_index: &LineIndex, notebook_index: &NotebookIndex, encoding: PositionEncoding, ) -> NotebookRange { let start = source_index.source_location(self.start(), text, encoding.into()); let mut end = source_index.source_location(self.end(), text, encoding.into()); let starting_cell = notebook_index.cell(start.line); // weird edge case here - if the end of the range is where the newline after the cell got added (making it 'out of bounds') // we need to move it one character back (which should place it at the end of the last line). // we test this by checking if the ending offset is in a different (or nonexistent) cell compared to the cell of the starting offset. if notebook_index.cell(end.line) != starting_cell { end.line = end.line.saturating_sub(1); end.character_offset = source_index .source_location( self.end().checked_sub(1.into()).unwrap_or_default(), text, encoding.into(), ) .character_offset; } let start = source_location_to_position(&notebook_index.translate_source_location(&start)); let end = source_location_to_position(&notebook_index.translate_source_location(&end)); NotebookRange { cell: starting_cell .map(OneIndexed::to_zero_indexed) .unwrap_or_default(), range: types::Range { start, end }, } } } fn source_location_to_position(location: &SourceLocation) -> types::Position { types::Position { line: u32::try_from(location.line.to_zero_indexed()).expect("row usize fits in u32"), character: u32::try_from(location.character_offset.to_zero_indexed()) .expect("character usize fits in u32"), } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/edit/replacement.rs
crates/ruff_server/src/edit/replacement.rs
use ruff_text_size::{TextLen, TextRange, TextSize}; #[derive(Debug)] pub(crate) struct Replacement { pub(crate) source_range: TextRange, pub(crate) modified_range: TextRange, } impl Replacement { /// Creates a [`Replacement`] that describes the `source_range` of `source` to replace /// with `modified` sliced by `modified_range`. pub(crate) fn between( source: &str, source_line_starts: &[TextSize], modified: &str, modified_line_starts: &[TextSize], ) -> Self { let mut source_start = TextSize::default(); let mut modified_start = TextSize::default(); for (source_line_start, modified_line_start) in source_line_starts .iter() .copied() .zip(modified_line_starts.iter().copied()) .skip(1) { if source[TextRange::new(source_start, source_line_start)] != modified[TextRange::new(modified_start, modified_line_start)] { break; } source_start = source_line_start; modified_start = modified_line_start; } let mut source_end = source.text_len(); let mut modified_end = modified.text_len(); for (source_line_start, modified_line_start) in source_line_starts .iter() .rev() .copied() .zip(modified_line_starts.iter().rev().copied()) { if source_line_start < source_start || modified_line_start < modified_start || source[TextRange::new(source_line_start, source_end)] != modified[TextRange::new(modified_line_start, modified_end)] { break; } source_end = source_line_start; modified_end = modified_line_start; } Replacement { source_range: TextRange::new(source_start, source_end), modified_range: TextRange::new(modified_start, modified_end), } } } #[cfg(test)] mod tests { use ruff_source_file::LineIndex; use ruff_text_size::TextRange; use super::Replacement; fn compute_replacement(source: &str, modified: &str) -> (Replacement, String) { let source_index = LineIndex::from_source_text(source); let modified_index = LineIndex::from_source_text(modified); let replacement = Replacement::between( source, source_index.line_starts(), modified, modified_index.line_starts(), ); let mut expected = source.to_string(); expected.replace_range( replacement.source_range.start().to_usize()..replacement.source_range.end().to_usize(), &modified[replacement.modified_range], ); (replacement, expected) } #[test] fn delete_first_line() { let source = "aaaa bbbb cccc "; let modified = "bbbb cccc "; let (replacement, expected) = compute_replacement(source, modified); assert_eq!(replacement.source_range, TextRange::new(0.into(), 5.into())); assert_eq!(replacement.modified_range, TextRange::empty(0.into())); assert_eq!(modified, &expected); } #[test] fn delete_middle_line() { let source = "aaaa bbbb cccc dddd "; let modified = "aaaa bbbb dddd "; let (replacement, expected) = compute_replacement(source, modified); assert_eq!( replacement.source_range, TextRange::new(10.into(), 15.into()) ); assert_eq!(replacement.modified_range, TextRange::empty(10.into())); assert_eq!(modified, &expected); } #[test] fn delete_multiple_lines() { let source = "aaaa bbbb cccc dddd eeee ffff "; let modified = "aaaa cccc dddd ffff "; let (replacement, expected) = compute_replacement(source, modified); assert_eq!( replacement.source_range, TextRange::new(5.into(), 25.into()) ); assert_eq!( replacement.modified_range, TextRange::new(5.into(), 15.into()) ); assert_eq!(modified, &expected); } #[test] fn insert_first_line() { let source = "bbbb cccc "; let modified = "aaaa bbbb cccc "; let (replacement, expected) = compute_replacement(source, modified); assert_eq!(replacement.source_range, TextRange::empty(0.into())); assert_eq!( replacement.modified_range, TextRange::new(0.into(), 5.into()) ); assert_eq!(modified, &expected); } #[test] fn insert_middle_line() { let source = "aaaa cccc "; let modified = "aaaa bbbb cccc "; let (replacement, expected) = compute_replacement(source, modified); assert_eq!(replacement.source_range, TextRange::empty(5.into())); assert_eq!( replacement.modified_range, TextRange::new(5.into(), 10.into()) ); assert_eq!(modified, &expected); } #[test] fn insert_multiple_lines() { let source = "aaaa cccc eeee "; let modified = "aaaa bbbb cccc dddd "; let (replacement, expected) = compute_replacement(source, modified); assert_eq!( replacement.source_range, TextRange::new(5.into(), 15.into()) ); assert_eq!( replacement.modified_range, TextRange::new(5.into(), 20.into()) ); assert_eq!(modified, &expected); } #[test] fn replace_lines() { let source = "aaaa bbbb cccc "; let modified = "aaaa bbcb cccc "; let (replacement, expected) = compute_replacement(source, modified); assert_eq!( replacement.source_range, TextRange::new(5.into(), 10.into()) ); assert_eq!( replacement.modified_range, TextRange::new(5.into(), 10.into()) ); assert_eq!(modified, &expected); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/edit/text_document.rs
crates/ruff_server/src/edit/text_document.rs
use lsp_types::TextDocumentContentChangeEvent; use ruff_source_file::LineIndex; use crate::PositionEncoding; use super::RangeExt; pub(crate) type DocumentVersion = i32; /// The state of an individual document in the server. Stays up-to-date /// with changes made by the user, including unsaved changes. #[derive(Debug, Clone)] pub struct TextDocument { /// The string contents of the document. contents: String, /// A computed line index for the document. This should always reflect /// the current version of `contents`. Using a function like [`Self::modify`] /// will re-calculate the line index automatically when the `contents` value is updated. index: LineIndex, /// The latest version of the document, set by the LSP client. The server will panic in /// debug mode if we attempt to update the document with an 'older' version. version: DocumentVersion, /// The language ID of the document as provided by the client. language_id: Option<LanguageId>, } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum LanguageId { Python, Other, } impl From<&str> for LanguageId { fn from(language_id: &str) -> Self { match language_id { "python" => Self::Python, _ => Self::Other, } } } impl TextDocument { pub fn new(contents: String, version: DocumentVersion) -> Self { let index = LineIndex::from_source_text(&contents); Self { contents, index, version, language_id: None, } } #[must_use] pub fn with_language_id(mut self, language_id: &str) -> Self { self.language_id = Some(LanguageId::from(language_id)); self } pub fn into_contents(self) -> String { self.contents } pub fn contents(&self) -> &str { &self.contents } pub fn index(&self) -> &LineIndex { &self.index } pub fn version(&self) -> DocumentVersion { self.version } pub fn language_id(&self) -> Option<LanguageId> { self.language_id } pub fn apply_changes( &mut self, changes: Vec<lsp_types::TextDocumentContentChangeEvent>, new_version: DocumentVersion, encoding: PositionEncoding, ) { if let [ lsp_types::TextDocumentContentChangeEvent { range: None, text, .. }, ] = changes.as_slice() { tracing::debug!("Fast path - replacing entire document"); self.modify(|contents, version| { contents.clone_from(text); *version = new_version; }); return; } let mut new_contents = self.contents().to_string(); let mut active_index = self.index().clone(); for TextDocumentContentChangeEvent { range, text: change, .. } in changes { if let Some(range) = range { let range = range.to_text_range(&new_contents, &active_index, encoding); new_contents.replace_range( usize::from(range.start())..usize::from(range.end()), &change, ); } else { new_contents = change; } active_index = LineIndex::from_source_text(&new_contents); } self.modify_with_manual_index(|contents, version, index| { *index = active_index; *contents = new_contents; *version = new_version; }); } pub fn update_version(&mut self, new_version: DocumentVersion) { self.modify_with_manual_index(|_, version, _| { *version = new_version; }); } // A private function for modifying the document's internal state fn modify(&mut self, func: impl FnOnce(&mut String, &mut DocumentVersion)) { self.modify_with_manual_index(|c, v, i| { func(c, v); *i = LineIndex::from_source_text(c); }); } // A private function for overriding how we update the line index by default. fn modify_with_manual_index( &mut self, func: impl FnOnce(&mut String, &mut DocumentVersion, &mut LineIndex), ) { let old_version = self.version; func(&mut self.contents, &mut self.version, &mut self.index); debug_assert!(self.version >= old_version); } } #[cfg(test)] mod tests { use crate::{PositionEncoding, TextDocument}; use lsp_types::{Position, TextDocumentContentChangeEvent}; #[test] fn redo_edit() { let mut document = TextDocument::new( r#"""" 测试comment 一些测试内容 """ import click @click.group() def interface(): pas "# .to_string(), 0, ); // Add an `s`, remove it again (back to the original code), and then re-add the `s` document.apply_changes( vec![ TextDocumentContentChangeEvent { range: Some(lsp_types::Range::new( Position::new(9, 7), Position::new(9, 7), )), range_length: Some(0), text: "s".to_string(), }, TextDocumentContentChangeEvent { range: Some(lsp_types::Range::new( Position::new(9, 7), Position::new(9, 8), )), range_length: Some(1), text: String::new(), }, TextDocumentContentChangeEvent { range: Some(lsp_types::Range::new( Position::new(9, 7), Position::new(9, 7), )), range_length: Some(0), text: "s".to_string(), }, ], 1, PositionEncoding::UTF16, ); assert_eq!( &document.contents, r#"""" 测试comment 一些测试内容 """ import click @click.group() def interface(): pass "# ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/session/settings.rs
crates/ruff_server/src/session/settings.rs
use std::{path::PathBuf, sync::Arc}; use thiserror::Error; use ruff_linter::RuleSelector; use ruff_linter::line_width::LineLength; use ruff_workspace::options::Options; use crate::{ ClientOptions, format::FormatBackend, session::{ Client, options::{ClientConfiguration, ConfigurationPreference}, }, }; pub struct GlobalClientSettings { pub(super) options: ClientOptions, /// Lazily initialized client settings to avoid showing error warnings /// when a field of the global settings has any errors but the field is overridden /// in the workspace settings. This can avoid showing unnecessary errors /// when the workspace settings e.g. select some rules that aren't available in a specific workspace /// and said workspace overrides the selected rules. pub(super) settings: std::cell::OnceCell<Arc<ClientSettings>>, pub(super) client: Client, } impl GlobalClientSettings { pub(super) fn options(&self) -> &ClientOptions { &self.options } fn settings_impl(&self) -> &Arc<ClientSettings> { self.settings.get_or_init(|| { let settings = self.options.clone().into_settings(); let settings = match settings { Ok(settings) => settings, Err(settings) => { self.client.show_error_message( "Ruff received invalid settings from the editor. Refer to the logs for more information." ); settings } }; Arc::new(settings) }) } /// Lazily resolves the client options to the settings. pub(super) fn to_settings(&self) -> &ClientSettings { self.settings_impl() } /// Lazily resolves the client options to the settings. pub(super) fn to_settings_arc(&self) -> Arc<ClientSettings> { self.settings_impl().clone() } } /// Resolved client settings for a specific document. These settings are meant to be /// used directly by the server, and are *not* a 1:1 representation with how the client /// sends them. #[derive(Clone, Debug)] #[cfg_attr(test, derive(PartialEq, Eq))] #[expect(clippy::struct_excessive_bools)] pub(crate) struct ClientSettings { pub(super) fix_all: bool, pub(super) organize_imports: bool, pub(super) lint_enable: bool, pub(super) disable_rule_comment_enable: bool, pub(super) fix_violation_enable: bool, pub(super) show_syntax_errors: bool, pub(super) editor_settings: EditorSettings, } /// Contains the resolved values of 'editor settings' - Ruff configuration for the linter/formatter that was passed in via /// LSP client settings. These fields are optional because we don't want to override file-based linter/formatting settings /// if these were un-set. #[derive(Clone, Debug)] #[cfg_attr(test, derive(Default, PartialEq, Eq))] pub(crate) struct EditorSettings { pub(super) configuration: Option<ResolvedConfiguration>, pub(super) lint_preview: Option<bool>, pub(super) format_preview: Option<bool>, pub(super) format_backend: Option<FormatBackend>, pub(super) select: Option<Vec<RuleSelector>>, pub(super) extend_select: Option<Vec<RuleSelector>>, pub(super) ignore: Option<Vec<RuleSelector>>, pub(super) exclude: Option<Vec<String>>, pub(super) line_length: Option<LineLength>, pub(super) configuration_preference: ConfigurationPreference, } /// The resolved configuration from the client settings. #[derive(Clone, Debug)] #[cfg_attr(test, derive(PartialEq, Eq))] pub(crate) enum ResolvedConfiguration { FilePath(PathBuf), Inline(Box<Options>), } impl TryFrom<ClientConfiguration> for ResolvedConfiguration { type Error = ResolvedConfigurationError; fn try_from(value: ClientConfiguration) -> Result<Self, Self::Error> { match value { ClientConfiguration::String(path) => Ok(ResolvedConfiguration::FilePath( PathBuf::from(shellexpand::full(&path)?.as_ref()), )), ClientConfiguration::Object(map) => { let options = toml::Table::try_from(map)?.try_into::<Options>()?; if options.extend.is_some() { Err(ResolvedConfigurationError::ExtendNotSupported) } else { Ok(ResolvedConfiguration::Inline(Box::new(options))) } } } } } /// An error that can occur when trying to resolve the `configuration` value from the client /// settings. #[derive(Debug, Error)] pub(crate) enum ResolvedConfigurationError { #[error(transparent)] EnvVarLookupError(#[from] shellexpand::LookupError<std::env::VarError>), #[error("error serializing configuration to TOML: {0}")] InvalidToml(#[from] toml::ser::Error), #[error(transparent)] InvalidRuffSchema(#[from] toml::de::Error), #[error("using `extend` is unsupported for inline configuration")] ExtendNotSupported, } impl ClientSettings { pub(crate) fn fix_all(&self) -> bool { self.fix_all } pub(crate) fn organize_imports(&self) -> bool { self.organize_imports } pub(crate) fn lint(&self) -> bool { self.lint_enable } pub(crate) fn noqa_comments(&self) -> bool { self.disable_rule_comment_enable } pub(crate) fn fix_violation(&self) -> bool { self.fix_violation_enable } pub(crate) fn show_syntax_errors(&self) -> bool { self.show_syntax_errors } pub(crate) fn editor_settings(&self) -> &EditorSettings { &self.editor_settings } } impl EditorSettings { pub(crate) fn format_backend(&self) -> FormatBackend { self.format_backend.unwrap_or_default() } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/session/index.rs
crates/ruff_server/src/session/index.rs
use std::borrow::Cow; use std::ops::{Deref, DerefMut}; use std::path::PathBuf; use std::{collections::BTreeMap, path::Path, sync::Arc}; use anyhow::anyhow; use lsp_types::{FileEvent, Url}; use rustc_hash::{FxHashMap, FxHashSet}; use thiserror::Error; pub(crate) use ruff_settings::RuffSettings; use crate::edit::LanguageId; use crate::session::Client; use crate::session::options::Combine; use crate::session::settings::GlobalClientSettings; use crate::workspace::{Workspace, Workspaces}; use crate::{ PositionEncoding, TextDocument, edit::{DocumentKey, DocumentVersion, NotebookDocument}, }; use super::settings::ClientSettings; mod ruff_settings; /// Stores and tracks all open documents in a session, along with their associated settings. #[derive(Default)] pub(crate) struct Index { /// Maps all document file URLs to the associated document controller documents: FxHashMap<Url, DocumentController>, /// Maps opaque cell URLs to a notebook URL (document) notebook_cells: FxHashMap<Url, Url>, /// Maps a workspace folder root to its settings. settings: WorkspaceSettingsIndex, } /// Settings associated with a workspace. struct WorkspaceSettings { client_settings: Arc<ClientSettings>, ruff_settings: ruff_settings::RuffSettingsIndex, } /// A mutable handler to an underlying document. #[derive(Debug)] enum DocumentController { Text(Arc<TextDocument>), Notebook(Arc<NotebookDocument>), } /// A read-only query to an open document. /// This query can 'select' a text document, full notebook, or a specific notebook cell. /// It also includes document settings. #[derive(Clone)] pub enum DocumentQuery { Text { file_url: Url, document: Arc<TextDocument>, settings: Arc<RuffSettings>, }, Notebook { /// The selected notebook cell, if it exists. cell_url: Option<Url>, /// The URL of the notebook. file_url: Url, notebook: Arc<NotebookDocument>, settings: Arc<RuffSettings>, }, } impl Index { pub(super) fn new( workspaces: &Workspaces, global: &GlobalClientSettings, client: &Client, ) -> crate::Result<Self> { let mut settings = WorkspaceSettingsIndex::default(); for workspace in &**workspaces { settings.register_workspace(workspace, global, client)?; } Ok(Self { documents: FxHashMap::default(), notebook_cells: FxHashMap::default(), settings, }) } pub(super) fn text_document_urls(&self) -> impl Iterator<Item = &Url> + '_ { self.documents .iter() .filter(|(_, doc)| doc.as_text().is_some()) .map(|(url, _)| url) } pub(super) fn notebook_document_urls(&self) -> impl Iterator<Item = &Url> + '_ { self.documents .iter() .filter(|(_, doc)| doc.as_notebook().is_some()) .map(|(url, _)| url) } pub(super) fn update_text_document( &mut self, key: &DocumentKey, content_changes: Vec<lsp_types::TextDocumentContentChangeEvent>, new_version: DocumentVersion, encoding: PositionEncoding, ) -> crate::Result<()> { let controller = self.document_controller_for_key(key)?; let Some(document) = controller.as_text_mut() else { anyhow::bail!("Text document URI does not point to a text document"); }; if content_changes.is_empty() { document.update_version(new_version); return Ok(()); } document.apply_changes(content_changes, new_version, encoding); Ok(()) } pub(super) fn key_from_url(&self, url: Url) -> DocumentKey { if self.notebook_cells.contains_key(&url) { DocumentKey::NotebookCell(url) } else if Path::new(url.path()) .extension() .is_some_and(|ext| ext.eq_ignore_ascii_case("ipynb")) { DocumentKey::Notebook(url) } else { DocumentKey::Text(url) } } pub(super) fn update_notebook_document( &mut self, key: &DocumentKey, cells: Option<lsp_types::NotebookDocumentCellChange>, metadata: Option<serde_json::Map<String, serde_json::Value>>, new_version: DocumentVersion, encoding: PositionEncoding, ) -> crate::Result<()> { // update notebook cell index if let Some(lsp_types::NotebookDocumentCellChangeStructure { did_open: Some(did_open), .. }) = cells.as_ref().and_then(|cells| cells.structure.as_ref()) { let Some(path) = self.url_for_key(key).cloned() else { anyhow::bail!("Tried to open unavailable document `{key}`"); }; for opened_cell in did_open { self.notebook_cells .insert(opened_cell.uri.clone(), path.clone()); } // deleted notebook cells are closed via textDocument/didClose - we don't close them here. } let controller = self.document_controller_for_key(key)?; let Some(notebook) = controller.as_notebook_mut() else { anyhow::bail!("Notebook document URI does not point to a notebook document"); }; notebook.update(cells, metadata, new_version, encoding)?; Ok(()) } pub(super) fn open_workspace_folder( &mut self, url: Url, global: &GlobalClientSettings, client: &Client, ) -> crate::Result<()> { // TODO(jane): Find a way for workspace client settings to be added or changed dynamically. self.settings .register_workspace(&Workspace::new(url), global, client) } pub(super) fn close_workspace_folder(&mut self, workspace_url: &Url) -> crate::Result<()> { let workspace_path = workspace_url.to_file_path().map_err(|()| { anyhow!("Failed to convert workspace URL to file path: {workspace_url}") })?; self.settings .remove(&workspace_path) .ok_or_else(|| anyhow!("Tried to remove non-existent workspace URI {workspace_url}"))?; // O(n) complexity, which isn't ideal... but this is an uncommon operation. self.documents .retain(|url, _| !Path::new(url.path()).starts_with(&workspace_path)); self.notebook_cells .retain(|_, url| !Path::new(url.path()).starts_with(&workspace_path)); Ok(()) } pub(super) fn make_document_ref( &self, key: DocumentKey, global: &GlobalClientSettings, ) -> Option<DocumentQuery> { let url = self.url_for_key(&key)?.clone(); let document_settings = self .settings_for_url(&url) .map(|settings| { if let Ok(file_path) = url.to_file_path() { settings.ruff_settings.get(&file_path) } else { // For a new unsaved and untitled document, use the ruff settings from the top of the workspace // but only IF: // * It is the only workspace // * The ruff setting is at the top of the workspace (in the root folder) // Otherwise, use the fallback settings. if self.settings.len() == 1 { let workspace_path = self.settings.keys().next().unwrap(); settings.ruff_settings.get(&workspace_path.join("untitled")) } else { tracing::debug!("Use the fallback settings for the new document '{url}'."); settings.ruff_settings.fallback() } } }) .unwrap_or_else(|| { tracing::warn!( "No settings available for {} - falling back to default settings", url ); // The path here is only for completeness, it's okay to use a non-existing path // in case this is an unsaved (untitled) document. let path = Path::new(url.path()); let root = path.parent().unwrap_or(path); Arc::new(RuffSettings::fallback( global.to_settings().editor_settings(), root, )) }); let controller = self.documents.get(&url)?; let cell_url = match key { DocumentKey::NotebookCell(cell_url) => Some(cell_url), _ => None, }; Some(controller.make_ref(cell_url, url, document_settings)) } /// Reload the settings for all the workspace folders that contain the changed files. /// /// This method avoids re-indexing the same workspace multiple times if multiple files /// belonging to the same workspace have been changed. /// /// The file events are expected to only contain paths that map to configuration files. This is /// registered in [`try_register_capabilities`] method. /// /// [`try_register_capabilities`]: crate::server::Server::try_register_capabilities pub(super) fn reload_settings(&mut self, changes: &[FileEvent], client: &Client) { let mut indexed = FxHashSet::default(); for change in changes { let Ok(changed_path) = change.uri.to_file_path() else { // Files that don't map to a path can't be a workspace configuration file. return; }; let Some(enclosing_folder) = changed_path.parent() else { return; }; for (root, settings) in self .settings .range_mut(..=enclosing_folder.to_path_buf()) .rev() { if !enclosing_folder.starts_with(root) { break; } if indexed.contains(root) { continue; } indexed.insert(root.clone()); settings.ruff_settings = ruff_settings::RuffSettingsIndex::new( client, root, settings.client_settings.editor_settings(), false, ); } } } pub(super) fn open_text_document(&mut self, url: Url, document: TextDocument) { self.documents .insert(url, DocumentController::new_text(document)); } pub(super) fn open_notebook_document(&mut self, notebook_url: Url, document: NotebookDocument) { for cell_url in document.urls() { self.notebook_cells .insert(cell_url.clone(), notebook_url.clone()); } self.documents .insert(notebook_url, DocumentController::new_notebook(document)); } pub(super) fn close_document(&mut self, key: &DocumentKey) -> crate::Result<()> { // Notebook cells URIs are removed from the index here, instead of during // `update_notebook_document`. This is because a notebook cell, as a text document, // is requested to be `closed` by VS Code after the notebook gets updated. // This is not documented in the LSP specification explicitly, and this assumption // may need revisiting in the future as we support more editors with notebook support. if let DocumentKey::NotebookCell(uri) = key { if self.notebook_cells.remove(uri).is_none() { tracing::warn!("Tried to remove a notebook cell that does not exist: {uri}",); } return Ok(()); } let Some(url) = self.url_for_key(key).cloned() else { anyhow::bail!("Tried to close unavailable document `{key}`"); }; let Some(_) = self.documents.remove(&url) else { anyhow::bail!("tried to close document that didn't exist at {url}") }; Ok(()) } pub(super) fn client_settings(&self, key: &DocumentKey) -> Option<Arc<ClientSettings>> { let url = self.url_for_key(key)?; let WorkspaceSettings { client_settings, .. } = self.settings_for_url(url)?; Some(client_settings.clone()) } fn document_controller_for_key( &mut self, key: &DocumentKey, ) -> crate::Result<&mut DocumentController> { let Some(url) = self.url_for_key(key).cloned() else { anyhow::bail!("Tried to open unavailable document `{key}`"); }; let Some(controller) = self.documents.get_mut(&url) else { anyhow::bail!("Document controller not available at `{url}`"); }; Ok(controller) } fn url_for_key<'a>(&'a self, key: &'a DocumentKey) -> Option<&'a Url> { match key { DocumentKey::Notebook(path) | DocumentKey::Text(path) => Some(path), DocumentKey::NotebookCell(uri) => self.notebook_cells.get(uri), } } fn settings_for_url(&self, url: &Url) -> Option<&WorkspaceSettings> { if let Ok(path) = url.to_file_path() { self.settings_for_path(&path) } else { // If there's only a single workspace, use that configuration for an untitled document. if self.settings.len() == 1 { tracing::debug!( "Falling back to configuration of the only active workspace for the new document '{url}'." ); self.settings.values().next() } else { None } } } fn settings_for_path(&self, path: &Path) -> Option<&WorkspaceSettings> { self.settings .range(..path.to_path_buf()) .next_back() .map(|(_, settings)| settings) } /// Returns an iterator over the workspace root folders contained in this index. pub(super) fn workspace_root_folders(&self) -> impl Iterator<Item = &Path> { self.settings.keys().map(PathBuf::as_path) } /// Returns the number of open documents. pub(super) fn open_documents_len(&self) -> usize { self.documents.len() } /// Returns an iterator over the paths to the configuration files in the index. pub(super) fn config_file_paths(&self) -> impl Iterator<Item = &Path> { self.settings .values() .flat_map(|WorkspaceSettings { ruff_settings, .. }| ruff_settings.config_file_paths()) } } /// Maps a workspace folder root to its settings. #[derive(Default)] struct WorkspaceSettingsIndex { index: BTreeMap<PathBuf, WorkspaceSettings>, } impl WorkspaceSettingsIndex { /// Register a workspace folder with the given settings. /// /// If the `workspace_settings` is [`Some`], it is preferred over the global settings for the /// workspace. Otherwise, the global settings are used exclusively. fn register_workspace( &mut self, workspace: &Workspace, global: &GlobalClientSettings, client: &Client, ) -> crate::Result<()> { let workspace_url = workspace.url(); if workspace_url.scheme() != "file" { tracing::info!("Ignoring non-file workspace URL: {workspace_url}"); client.show_warning_message(format_args!( "Ruff does not support non-file workspaces; Ignoring {workspace_url}" )); return Ok(()); } let workspace_path = workspace_url.to_file_path().map_err(|()| { anyhow!("Failed to convert workspace URL to file path: {workspace_url}") })?; let client_settings = if let Some(workspace_options) = workspace.options() { let options = workspace_options.clone().combine(global.options().clone()); let settings = match options.into_settings() { Ok(settings) => settings, Err(settings) => { client.show_error_message(format_args!( "The settings for the workspace {workspace_path} are invalid. Refer to the logs for more information.", workspace_path = workspace_path.display() )); settings } }; Arc::new(settings) } else { global.to_settings_arc() }; let workspace_settings_index = ruff_settings::RuffSettingsIndex::new( client, &workspace_path, client_settings.editor_settings(), workspace.is_default(), ); tracing::info!("Registering workspace: {}", workspace_path.display()); self.insert( workspace_path, WorkspaceSettings { client_settings, ruff_settings: workspace_settings_index, }, ); Ok(()) } } impl Deref for WorkspaceSettingsIndex { type Target = BTreeMap<PathBuf, WorkspaceSettings>; fn deref(&self) -> &Self::Target { &self.index } } impl DerefMut for WorkspaceSettingsIndex { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.index } } impl DocumentController { fn new_text(document: TextDocument) -> Self { Self::Text(Arc::new(document)) } fn new_notebook(document: NotebookDocument) -> Self { Self::Notebook(Arc::new(document)) } fn make_ref( &self, cell_url: Option<Url>, file_url: Url, settings: Arc<RuffSettings>, ) -> DocumentQuery { match &self { Self::Notebook(notebook) => DocumentQuery::Notebook { cell_url, file_url, notebook: notebook.clone(), settings, }, Self::Text(document) => DocumentQuery::Text { file_url, document: document.clone(), settings, }, } } pub(crate) fn as_notebook_mut(&mut self) -> Option<&mut NotebookDocument> { Some(match self { Self::Notebook(notebook) => Arc::make_mut(notebook), Self::Text(_) => return None, }) } pub(crate) fn as_notebook(&self) -> Option<&NotebookDocument> { match self { Self::Notebook(notebook) => Some(notebook), Self::Text(_) => None, } } pub(crate) fn as_text(&self) -> Option<&TextDocument> { match self { Self::Text(document) => Some(document), Self::Notebook(_) => None, } } pub(crate) fn as_text_mut(&mut self) -> Option<&mut TextDocument> { Some(match self { Self::Text(document) => Arc::make_mut(document), Self::Notebook(_) => return None, }) } } impl DocumentQuery { /// Retrieve the original key that describes this document query. pub(crate) fn make_key(&self) -> DocumentKey { match self { Self::Text { file_url, .. } => DocumentKey::Text(file_url.clone()), Self::Notebook { cell_url: Some(cell_uri), .. } => DocumentKey::NotebookCell(cell_uri.clone()), Self::Notebook { file_url, .. } => DocumentKey::Notebook(file_url.clone()), } } /// Get the document settings associated with this query. pub(crate) fn settings(&self) -> &RuffSettings { match self { Self::Text { settings, .. } | Self::Notebook { settings, .. } => settings, } } /// Generate a source kind used by the linter. pub(crate) fn make_source_kind(&self) -> ruff_linter::source_kind::SourceKind { match self { Self::Text { document, .. } => { ruff_linter::source_kind::SourceKind::Python(document.contents().to_string()) } Self::Notebook { notebook, .. } => { ruff_linter::source_kind::SourceKind::ipy_notebook(notebook.make_ruff_notebook()) } } } /// Attempts to access the underlying notebook document that this query is selecting. pub fn as_notebook(&self) -> Option<&NotebookDocument> { match self { Self::Notebook { notebook, .. } => Some(notebook), Self::Text { .. } => None, } } /// Get the source type of the document associated with this query. pub(crate) fn source_type(&self) -> ruff_python_ast::PySourceType { match self { Self::Text { .. } => ruff_python_ast::PySourceType::from(self.virtual_file_path()), Self::Notebook { .. } => ruff_python_ast::PySourceType::Ipynb, } } /// Get the version of document selected by this query. pub(crate) fn version(&self) -> DocumentVersion { match self { Self::Text { document, .. } => document.version(), Self::Notebook { notebook, .. } => notebook.version(), } } /// Get the URL for the document selected by this query. pub(crate) fn file_url(&self) -> &Url { match self { Self::Text { file_url, .. } | Self::Notebook { file_url, .. } => file_url, } } /// Get the path for the document selected by this query. /// /// Returns `None` if this is an unsaved (untitled) document. /// /// The path isn't guaranteed to point to a real path on the filesystem. This is the case /// for unsaved (untitled) documents. pub(crate) fn file_path(&self) -> Option<PathBuf> { self.file_url().to_file_path().ok() } /// Get the path for the document selected by this query, ignoring whether the file exists on disk. /// /// Returns the URL's path if this is an unsaved (untitled) document. pub(crate) fn virtual_file_path(&self) -> Cow<'_, Path> { self.file_path() .map(Cow::Owned) .unwrap_or_else(|| Cow::Borrowed(Path::new(self.file_url().path()))) } /// Attempt to access the single inner text document selected by the query. /// If this query is selecting an entire notebook document, this will return `None`. pub(crate) fn as_single_document(&self) -> Result<&TextDocument, SingleDocumentError> { match self { Self::Text { document, .. } => Ok(document), Self::Notebook { notebook, file_url, cell_url: cell_uri, .. } => { if let Some(cell_uri) = cell_uri { let cell = notebook .cell_document_by_uri(cell_uri) .ok_or_else(|| SingleDocumentError::CellDoesNotExist(cell_uri.clone()))?; Ok(cell) } else { Err(SingleDocumentError::Notebook(file_url.clone())) } } } } pub(crate) fn text_document_language_id(&self) -> Option<LanguageId> { if let DocumentQuery::Text { document, .. } = self { document.language_id() } else { None } } } #[derive(Debug, Error)] pub(crate) enum SingleDocumentError { #[error("Expected a single text document, but found a notebook document: {0}")] Notebook(Url), #[error("Cell with URL {0} does not exist in the internal notebook document")] CellDoesNotExist(Url), }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/session/client.rs
crates/ruff_server/src/session/client.rs
use crate::Session; use crate::server::{ConnectionSender, Event, MainLoopSender}; use anyhow::{Context, anyhow}; use lsp_server::{ErrorCode, Message, Notification, RequestId, ResponseError}; use serde_json::Value; use std::any::TypeId; use std::fmt::Display; pub(crate) type ClientResponseHandler = Box<dyn FnOnce(&Client, lsp_server::Response) + Send>; #[derive(Clone, Debug)] pub struct Client { /// Channel to send messages back to the main loop. main_loop_sender: MainLoopSender, /// Channel to send messages directly to the LSP client without going through the main loop. /// /// This is generally preferred because it reduces pressure on the main loop but it may not always be /// possible if access to data on [`Session`] is required, which background tasks don't have. client_sender: ConnectionSender, } impl Client { pub fn new(main_loop_sender: MainLoopSender, client_sender: ConnectionSender) -> Self { Self { main_loop_sender, client_sender, } } /// Sends a request of kind `R` to the client, with associated parameters. /// /// The request is sent immediately. /// The `response_handler` will be dispatched as soon as the client response /// is processed on the main-loop. The handler always runs on the main-loop thread. /// /// # Note /// This method takes a `session` so that we can register the pending-request /// and send the response directly to the client. If this ever becomes too limiting (because we /// need to send a request from somewhere where we don't have access to session), consider introducing /// a new `send_deferred_request` method that doesn't take a session and instead sends /// an `Action` to the main loop to send the request (the main loop has always access to session). pub(crate) fn send_request<R>( &self, session: &Session, params: R::Params, response_handler: impl FnOnce(&Client, R::Result) + Send + 'static, ) -> crate::Result<()> where R: lsp_types::request::Request, { let response_handler = Box::new(move |client: &Client, response: lsp_server::Response| { let _span = tracing::debug_span!("client_response", id=%response.id, method = R::METHOD) .entered(); match (response.error, response.result) { (Some(err), _) => { tracing::error!( "Got an error from the client (code {code}, method {method}): {message}", code = err.code, message = err.message, method = R::METHOD ); } (None, Some(response)) => match serde_json::from_value(response) { Ok(response) => response_handler(client, response), Err(error) => { tracing::error!( "Failed to deserialize client response (method={method}): {error}", method = R::METHOD ); } }, (None, None) => { if TypeId::of::<R::Result>() == TypeId::of::<()>() { // We can't call `response_handler(())` directly here, but // since we _know_ the type expected is `()`, we can use // `from_value(Value::Null)`. `R::Result` implements `DeserializeOwned`, // so this branch works in the general case but we'll only // hit it if the concrete type is `()`, so the `unwrap()` is safe here. response_handler(client, serde_json::from_value(Value::Null).unwrap()); } else { tracing::error!( "Invalid client response: did not contain a result or error (method={method})", method = R::METHOD ); } } } }); let id = session .request_queue() .outgoing() .register(response_handler); self.client_sender .send(Message::Request(lsp_server::Request { id, method: R::METHOD.to_string(), params: serde_json::to_value(params).context("Failed to serialize params")?, })) .with_context(|| { format!("Failed to send request method={method}", method = R::METHOD) })?; Ok(()) } /// Sends a notification to the client. pub(crate) fn send_notification<N>(&self, params: N::Params) -> crate::Result<()> where N: lsp_types::notification::Notification, { let method = N::METHOD.to_string(); self.client_sender .send(lsp_server::Message::Notification(Notification::new( method, params, ))) .map_err(|error| { anyhow!( "Failed to send notification (method={method}): {error}", method = N::METHOD ) }) } /// Sends a notification without any parameters to the client. /// /// This is useful for notifications that don't require any data. #[expect(dead_code)] pub(crate) fn send_notification_no_params(&self, method: &str) -> crate::Result<()> { self.client_sender .send(lsp_server::Message::Notification(Notification::new( method.to_string(), Value::Null, ))) .map_err(|error| anyhow!("Failed to send notification (method={method}): {error}",)) } /// Sends a response to the client for a given request ID. /// /// The response isn't sent immediately. Instead, it's queued up in the main loop /// and checked for cancellation (each request must have exactly one response). pub(crate) fn respond<R>( &self, id: &RequestId, result: crate::server::Result<R>, ) -> crate::Result<()> where R: serde::Serialize, { let response = match result { Ok(res) => lsp_server::Response::new_ok(id.clone(), res), Err(crate::server::Error { code, error }) => { lsp_server::Response::new_err(id.clone(), code as i32, error.to_string()) } }; self.main_loop_sender .send(Event::SendResponse(response)) .map_err(|error| anyhow!("Failed to send response for request {id}: {error}")) } /// Sends an error response to the client for a given request ID. /// /// The response isn't sent immediately. Instead, it's queued up in the main loop. pub(crate) fn respond_err( &self, id: RequestId, error: lsp_server::ResponseError, ) -> crate::Result<()> { let response = lsp_server::Response { id, result: None, error: Some(error), }; self.main_loop_sender .send(Event::SendResponse(response)) .map_err(|error| anyhow!("Failed to send response: {error}")) } /// Shows a message to the user. /// /// This opens a pop up in VS Code showing `message`. pub(crate) fn show_message( &self, message: impl Display, message_type: lsp_types::MessageType, ) -> crate::Result<()> { self.send_notification::<lsp_types::notification::ShowMessage>( lsp_types::ShowMessageParams { typ: message_type, message: message.to_string(), }, ) } /// Sends a request to display a warning to the client with a formatted message. The warning is /// sent in a `window/showMessage` notification. /// /// Logs an error if the message could not be sent. pub(crate) fn show_warning_message(&self, message: impl Display) { let result = self.show_message(message, lsp_types::MessageType::WARNING); if let Err(err) = result { tracing::error!("Failed to send warning message to the client: {err}"); } } /// Sends a request to display an error to the client with a formatted message. The error is /// sent in a `window/showMessage` notification. /// /// Logs an error if the message could not be sent. pub(crate) fn show_error_message(&self, message: impl Display) { let result = self.show_message(message, lsp_types::MessageType::ERROR); if let Err(err) = result { tracing::error!("Failed to send error message to the client: {err}"); } } pub(crate) fn cancel(&self, session: &mut Session, id: RequestId) -> crate::Result<()> { let method_name = session.request_queue_mut().incoming_mut().cancel(&id); if let Some(method_name) = method_name { tracing::debug!("Cancelled request id={id} method={method_name}"); let error = ResponseError { code: ErrorCode::RequestCanceled as i32, message: "request was cancelled by client".to_owned(), data: None, }; // Use `client_sender` here instead of `respond_err` because // `respond_err` filters out responses for canceled requests (which we just did!). self.client_sender .send(Message::Response(lsp_server::Response { id, result: None, error: Some(error), }))?; } Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_server/src/session/options.rs
crates/ruff_server/src/session/options.rs
use std::{path::PathBuf, str::FromStr as _}; use lsp_types::Url; use rustc_hash::FxHashMap; use serde::Deserialize; use serde_json::{Map, Value}; use ruff_linter::{RuleSelector, line_width::LineLength, rule_selector::ParseError}; use crate::{ format::FormatBackend, session::{ Client, settings::{ClientSettings, EditorSettings, GlobalClientSettings, ResolvedConfiguration}, }, }; pub(crate) type WorkspaceOptionsMap = FxHashMap<Url, ClientOptions>; /// Determines how multiple conflicting configurations should be resolved - in this /// case, the configuration from the client settings and configuration from local /// `.toml` files (aka 'workspace' configuration). #[derive(Clone, Copy, Debug, Deserialize, Default, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub(crate) enum ConfigurationPreference { /// Configuration set in the editor takes priority over configuration set in `.toml` files. #[default] EditorFirst, /// Configuration set in `.toml` files takes priority over configuration set in the editor. FilesystemFirst, /// `.toml` files are ignored completely, and only the editor configuration is used. EditorOnly, } /// A direct representation of of `configuration` schema within the client settings. #[derive(Clone, Debug, Deserialize)] #[cfg_attr(test, derive(PartialEq, Eq))] #[serde(untagged)] pub(super) enum ClientConfiguration { /// A path to a configuration file. String(String), /// An object containing the configuration options. Object(Map<String, Value>), } #[derive(Debug, Deserialize, Default)] #[cfg_attr(test, derive(PartialEq, Eq))] #[serde(rename_all = "camelCase")] pub struct GlobalOptions { #[serde(flatten)] client: ClientOptions, // These settings are only needed for tracing, and are only read from the global configuration. // These will not be in the resolved settings. #[serde(flatten)] pub(crate) tracing: TracingOptions, } impl GlobalOptions { pub(crate) fn set_preview(&mut self, preview: bool) { self.client.set_preview(preview); } #[cfg(test)] pub(crate) fn client(&self) -> &ClientOptions { &self.client } pub fn into_settings(self, client: Client) -> GlobalClientSettings { GlobalClientSettings { options: self.client, settings: std::cell::OnceCell::default(), client, } } } /// This is a direct representation of the settings schema sent by the client. #[derive(Clone, Debug, Deserialize, Default)] #[cfg_attr(test, derive(PartialEq, Eq))] #[serde(rename_all = "camelCase")] pub struct ClientOptions { configuration: Option<ClientConfiguration>, fix_all: Option<bool>, organize_imports: Option<bool>, lint: Option<LintOptions>, format: Option<FormatOptions>, code_action: Option<CodeActionOptions>, exclude: Option<Vec<String>>, line_length: Option<LineLength>, configuration_preference: Option<ConfigurationPreference>, /// If `true` or [`None`], show syntax errors as diagnostics. /// /// This is useful when using Ruff with other language servers, allowing the user to refer /// to syntax errors from only one source. show_syntax_errors: Option<bool>, } impl ClientOptions { /// Resolves the options. /// /// Returns `Ok` if all options are valid. Otherwise, returns `Err` with the partially resolved settings /// (ignoring any invalid settings). Error messages about the invalid settings are logged with tracing. #[expect( clippy::result_large_err, reason = "The error is as large as the Ok variant" )] pub(crate) fn into_settings(self) -> Result<ClientSettings, ClientSettings> { let code_action = self.code_action.unwrap_or_default(); let lint = self.lint.unwrap_or_default(); let format = self.format.unwrap_or_default(); let mut contains_invalid_settings = false; let configuration = self.configuration.and_then(|configuration| { match ResolvedConfiguration::try_from(configuration) { Ok(configuration) => Some(configuration), Err(err) => { tracing::error!("Failed to load settings from `configuration`: {err}"); contains_invalid_settings = true; None } } }); let editor_settings = EditorSettings { configuration, lint_preview: lint.preview, format_preview: format.preview, format_backend: format.backend, select: lint.select.and_then(|select| { Self::resolve_rules( &select, RuleSelectorKey::Select, &mut contains_invalid_settings, ) }), extend_select: lint.extend_select.and_then(|select| { Self::resolve_rules( &select, RuleSelectorKey::ExtendSelect, &mut contains_invalid_settings, ) }), ignore: lint.ignore.and_then(|ignore| { Self::resolve_rules( &ignore, RuleSelectorKey::Ignore, &mut contains_invalid_settings, ) }), exclude: self.exclude.clone(), line_length: self.line_length, configuration_preference: self.configuration_preference.unwrap_or_default(), }; let resolved = ClientSettings { editor_settings, fix_all: self.fix_all.unwrap_or(true), organize_imports: self.organize_imports.unwrap_or(true), lint_enable: lint.enable.unwrap_or(true), disable_rule_comment_enable: code_action .disable_rule_comment .and_then(|disable| disable.enable) .unwrap_or(true), fix_violation_enable: code_action .fix_violation .and_then(|fix| fix.enable) .unwrap_or(true), show_syntax_errors: self.show_syntax_errors.unwrap_or(true), }; if contains_invalid_settings { Err(resolved) } else { Ok(resolved) } } fn resolve_rules( rules: &[String], key: RuleSelectorKey, contains_invalid_settings: &mut bool, ) -> Option<Vec<RuleSelector>> { let (mut known, mut unknown) = (vec![], vec![]); for rule in rules { match RuleSelector::from_str(rule) { Ok(selector) => known.push(selector), Err(ParseError::Unknown(_)) => unknown.push(rule), } } if !unknown.is_empty() { *contains_invalid_settings = true; tracing::error!("Unknown rule selectors found in `{key}`: {unknown:?}"); } if known.is_empty() { None } else { Some(known) } } /// Update the preview flag for the linter and the formatter with the given value. pub(crate) fn set_preview(&mut self, preview: bool) { match self.lint.as_mut() { None => self.lint = Some(LintOptions::default().with_preview(preview)), Some(lint) => lint.set_preview(preview), } match self.format.as_mut() { None => self.format = Some(FormatOptions::default().with_preview(preview)), Some(format) => format.set_preview(preview), } } } impl Combine for ClientOptions { fn combine_with(&mut self, other: Self) { self.configuration.combine_with(other.configuration); self.fix_all.combine_with(other.fix_all); self.organize_imports.combine_with(other.organize_imports); self.lint.combine_with(other.lint); self.format.combine_with(other.format); self.code_action.combine_with(other.code_action); self.exclude.combine_with(other.exclude); self.line_length.combine_with(other.line_length); self.configuration_preference .combine_with(other.configuration_preference); self.show_syntax_errors .combine_with(other.show_syntax_errors); } } /// Settings needed to initialize tracing. These will only be /// read from the global configuration. #[derive(Debug, Deserialize, Default)] #[cfg_attr(test, derive(PartialEq, Eq))] #[serde(rename_all = "camelCase")] pub(crate) struct TracingOptions { pub(crate) log_level: Option<crate::logging::LogLevel>, /// Path to the log file - tildes and environment variables are supported. pub(crate) log_file: Option<PathBuf>, } /// This is a direct representation of the workspace settings schema, /// which inherits the schema of [`ClientOptions`] and adds extra fields /// to describe the workspace it applies to. #[derive(Debug, Deserialize)] #[cfg_attr(test, derive(PartialEq, Eq))] #[serde(rename_all = "camelCase")] struct WorkspaceOptions { #[serde(flatten)] options: ClientOptions, workspace: Url, } #[derive(Clone, Debug, Default, Deserialize)] #[cfg_attr(test, derive(PartialEq, Eq))] #[serde(rename_all = "camelCase")] struct LintOptions { enable: Option<bool>, preview: Option<bool>, select: Option<Vec<String>>, extend_select: Option<Vec<String>>, ignore: Option<Vec<String>>, } impl LintOptions { fn with_preview(mut self, preview: bool) -> LintOptions { self.preview = Some(preview); self } fn set_preview(&mut self, preview: bool) { self.preview = Some(preview); } } impl Combine for LintOptions { fn combine_with(&mut self, other: Self) { self.enable.combine_with(other.enable); self.preview.combine_with(other.preview); self.select.combine_with(other.select); self.extend_select.combine_with(other.extend_select); self.ignore.combine_with(other.ignore); } } #[derive(Clone, Debug, Default, Deserialize)] #[cfg_attr(test, derive(PartialEq, Eq))] #[serde(rename_all = "camelCase")] struct FormatOptions { preview: Option<bool>, backend: Option<FormatBackend>, } impl Combine for FormatOptions { fn combine_with(&mut self, other: Self) { self.preview.combine_with(other.preview); self.backend.combine_with(other.backend); } } impl FormatOptions { fn with_preview(mut self, preview: bool) -> FormatOptions { self.preview = Some(preview); self } fn set_preview(&mut self, preview: bool) { self.preview = Some(preview); } } #[derive(Clone, Debug, Default, Deserialize)] #[cfg_attr(test, derive(PartialEq, Eq))] #[serde(rename_all = "camelCase")] struct CodeActionOptions { disable_rule_comment: Option<CodeActionParameters>, fix_violation: Option<CodeActionParameters>, } impl Combine for CodeActionOptions { fn combine_with(&mut self, other: Self) { self.disable_rule_comment .combine_with(other.disable_rule_comment); self.fix_violation.combine_with(other.fix_violation); } } #[derive(Clone, Debug, Deserialize)] #[cfg_attr(test, derive(PartialEq, Eq))] #[serde(rename_all = "camelCase")] struct CodeActionParameters { enable: Option<bool>, } impl Combine for CodeActionParameters { fn combine_with(&mut self, other: Self) { self.enable.combine_with(other.enable); } } /// This is the exact schema for initialization options sent in by the client /// during initialization. #[derive(Debug, Deserialize)] #[cfg_attr(test, derive(PartialEq, Eq))] #[serde(untagged)] enum InitializationOptions { #[serde(rename_all = "camelCase")] HasWorkspaces { #[serde(rename = "globalSettings")] global: GlobalOptions, #[serde(rename = "settings")] workspace: Vec<WorkspaceOptions>, }, GlobalOnly { #[serde(default)] settings: GlobalOptions, }, } impl Default for InitializationOptions { fn default() -> Self { Self::GlobalOnly { settings: GlobalOptions::default(), } } } /// Built from the initialization options provided by the client. #[derive(Debug)] pub(crate) struct AllOptions { pub(crate) global: GlobalOptions, /// If this is `None`, the client only passed in global settings. pub(crate) workspace: Option<WorkspaceOptionsMap>, } impl AllOptions { /// Initializes the controller from the serialized initialization options. /// This fails if `options` are not valid initialization options. pub(crate) fn from_value(options: serde_json::Value, client: &Client) -> Self { Self::from_init_options( serde_json::from_value(options) .map_err(|err| { tracing::error!("Failed to deserialize initialization options: {err}. Falling back to default client settings..."); client.show_error_message("Ruff received invalid client settings - falling back to default client settings."); }) .unwrap_or_default(), ) } /// Update the preview flag for both the global and all workspace settings. pub(crate) fn set_preview(&mut self, preview: bool) { self.global.set_preview(preview); if let Some(workspace_options) = self.workspace.as_mut() { for options in workspace_options.values_mut() { options.set_preview(preview); } } } fn from_init_options(options: InitializationOptions) -> Self { let (global_options, workspace_options) = match options { InitializationOptions::GlobalOnly { settings: options } => (options, None), InitializationOptions::HasWorkspaces { global: global_options, workspace: workspace_options, } => (global_options, Some(workspace_options)), }; Self { global: global_options, workspace: workspace_options.map(|workspace_options| { workspace_options .into_iter() .map(|workspace_options| { (workspace_options.workspace, workspace_options.options) }) .collect() }), } } } #[derive(Copy, Clone)] enum RuleSelectorKey { Select, ExtendSelect, Ignore, } impl std::fmt::Display for RuleSelectorKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { RuleSelectorKey::Select => f.write_str("lint.select"), RuleSelectorKey::ExtendSelect => f.write_str("lint.extendSelect"), RuleSelectorKey::Ignore => f.write_str("lint.ignore"), } } } pub(crate) trait Combine { #[must_use] fn combine(mut self, other: Self) -> Self where Self: Sized, { self.combine_with(other); self } fn combine_with(&mut self, other: Self); } impl Combine for FormatBackend { fn combine_with(&mut self, other: Self) { *self = other; } } impl<T> Combine for Option<T> where T: Combine, { fn combine(self, other: Self) -> Self where Self: Sized, { match (self, other) { (Some(a), Some(b)) => Some(a.combine(b)), (None, Some(b)) => Some(b), (a, _) => a, } } fn combine_with(&mut self, other: Self) { match (self, other) { (Some(a), Some(b)) => { a.combine_with(b); } (a @ None, Some(b)) => { *a = Some(b); } _ => {} } } } impl<T> Combine for Vec<T> { fn combine_with(&mut self, _other: Self) { // No-op, use own elements } } /// Implements [`Combine`] for a value that always returns `self` when combined with another value. macro_rules! impl_noop_combine { ($name:ident) => { impl Combine for $name { #[inline(always)] fn combine_with(&mut self, _other: Self) {} #[inline(always)] fn combine(self, _other: Self) -> Self { self } } }; } // std types impl_noop_combine!(bool); impl_noop_combine!(usize); impl_noop_combine!(u8); impl_noop_combine!(u16); impl_noop_combine!(u32); impl_noop_combine!(u64); impl_noop_combine!(u128); impl_noop_combine!(isize); impl_noop_combine!(i8); impl_noop_combine!(i16); impl_noop_combine!(i32); impl_noop_combine!(i64); impl_noop_combine!(i128); impl_noop_combine!(String); // Custom types impl_noop_combine!(ConfigurationPreference); impl_noop_combine!(ClientConfiguration); impl_noop_combine!(LineLength); #[cfg(test)] mod tests { use insta::assert_debug_snapshot; use ruff_python_formatter::QuoteStyle; use ruff_workspace::options::{ FormatOptions as RuffFormatOptions, LintCommonOptions, LintOptions, Options, }; use serde::de::DeserializeOwned; #[cfg(not(windows))] use ruff_linter::registry::Linter; use super::*; #[cfg(not(windows))] const VS_CODE_INIT_OPTIONS_FIXTURE: &str = include_str!("../../resources/test/fixtures/settings/vs_code_initialization_options.json"); const GLOBAL_ONLY_INIT_OPTIONS_FIXTURE: &str = include_str!("../../resources/test/fixtures/settings/global_only.json"); const EMPTY_INIT_OPTIONS_FIXTURE: &str = include_str!("../../resources/test/fixtures/settings/empty.json"); // This fixture contains multiple workspaces with empty initialization options. It only sets // the `cwd` and the `workspace` value. const EMPTY_MULTIPLE_WORKSPACE_INIT_OPTIONS_FIXTURE: &str = include_str!("../../resources/test/fixtures/settings/empty_multiple_workspace.json"); const INLINE_CONFIGURATION_FIXTURE: &str = include_str!("../../resources/test/fixtures/settings/inline_configuration.json"); fn deserialize_fixture<T: DeserializeOwned>(content: &str) -> T { serde_json::from_str(content).expect("test fixture JSON should deserialize") } #[cfg(not(windows))] #[test] fn test_vs_code_init_options_deserialize() { let options: InitializationOptions = deserialize_fixture(VS_CODE_INIT_OPTIONS_FIXTURE); assert_debug_snapshot!(options, @r#" HasWorkspaces { global: GlobalOptions { client: ClientOptions { configuration: None, fix_all: Some( false, ), organize_imports: Some( true, ), lint: Some( LintOptions { enable: Some( true, ), preview: Some( true, ), select: Some( [ "F", "I", ], ), extend_select: None, ignore: None, }, ), format: Some( FormatOptions { preview: None, backend: None, }, ), code_action: Some( CodeActionOptions { disable_rule_comment: Some( CodeActionParameters { enable: Some( false, ), }, ), fix_violation: Some( CodeActionParameters { enable: Some( false, ), }, ), }, ), exclude: None, line_length: None, configuration_preference: None, show_syntax_errors: Some( true, ), }, tracing: TracingOptions { log_level: None, log_file: None, }, }, workspace: [ WorkspaceOptions { options: ClientOptions { configuration: None, fix_all: Some( true, ), organize_imports: Some( true, ), lint: Some( LintOptions { enable: Some( true, ), preview: None, select: None, extend_select: None, ignore: None, }, ), format: Some( FormatOptions { preview: None, backend: None, }, ), code_action: Some( CodeActionOptions { disable_rule_comment: Some( CodeActionParameters { enable: Some( false, ), }, ), fix_violation: Some( CodeActionParameters { enable: Some( false, ), }, ), }, ), exclude: None, line_length: None, configuration_preference: None, show_syntax_errors: Some( true, ), }, workspace: Url { scheme: "file", cannot_be_a_base: false, username: "", password: None, host: None, port: None, path: "/Users/test/projects/pandas", query: None, fragment: None, }, }, WorkspaceOptions { options: ClientOptions { configuration: None, fix_all: Some( true, ), organize_imports: Some( true, ), lint: Some( LintOptions { enable: Some( true, ), preview: Some( false, ), select: None, extend_select: None, ignore: None, }, ), format: Some( FormatOptions { preview: None, backend: None, }, ), code_action: Some( CodeActionOptions { disable_rule_comment: Some( CodeActionParameters { enable: Some( true, ), }, ), fix_violation: Some( CodeActionParameters { enable: Some( false, ), }, ), }, ), exclude: None, line_length: None, configuration_preference: None, show_syntax_errors: Some( true, ), }, workspace: Url { scheme: "file", cannot_be_a_base: false, username: "", password: None, host: None, port: None, path: "/Users/test/projects/scipy", query: None, fragment: None, }, }, ], } "#); } #[cfg(not(windows))] #[test] fn test_vs_code_workspace_settings_resolve() { let options = deserialize_fixture(VS_CODE_INIT_OPTIONS_FIXTURE); let AllOptions { global, workspace: workspace_options, } = AllOptions::from_init_options(options); let path = Url::from_str("file:///Users/test/projects/pandas").expect("path should be valid"); let all_workspace_options = workspace_options.expect("workspace options should exist"); let workspace_options = all_workspace_options .get(&path) .expect("workspace options should exist") .clone(); let workspace_settings = workspace_options .combine(global.client().clone()) .into_settings() .unwrap(); assert_eq!( workspace_settings, ClientSettings { fix_all: true, organize_imports: true, lint_enable: true, disable_rule_comment_enable: false, fix_violation_enable: false, show_syntax_errors: true, editor_settings: EditorSettings { configuration: None, lint_preview: Some(true), format_preview: None, format_backend: None, select: Some(vec![ RuleSelector::Linter(Linter::Pyflakes), RuleSelector::Linter(Linter::Isort) ]), extend_select: None, ignore: None, exclude: None, line_length: None, configuration_preference: ConfigurationPreference::default(), }, } ); let path = Url::from_str("file:///Users/test/projects/scipy").expect("path should be valid"); let workspace_options = all_workspace_options .get(&path) .expect("workspace setting should exist") .clone(); let workspace_settings = workspace_options .combine(global.client().clone()) .into_settings() .unwrap(); assert_eq!( workspace_settings, ClientSettings { fix_all: true, organize_imports: true, lint_enable: true, disable_rule_comment_enable: true, fix_violation_enable: false, show_syntax_errors: true, editor_settings: EditorSettings { configuration: None, lint_preview: Some(false), format_preview: None, format_backend: None, select: Some(vec![ RuleSelector::Linter(Linter::Pyflakes), RuleSelector::Linter(Linter::Isort) ]), extend_select: None, ignore: None, exclude: None, line_length: None, configuration_preference: ConfigurationPreference::EditorFirst, }, } ); } #[test] fn test_global_only_init_options_deserialize() { let options: InitializationOptions = deserialize_fixture(GLOBAL_ONLY_INIT_OPTIONS_FIXTURE); assert_debug_snapshot!(options, @r#" GlobalOnly { settings: GlobalOptions { client: ClientOptions { configuration: None, fix_all: Some( false, ), organize_imports: None, lint: Some( LintOptions { enable: None, preview: None, select: None, extend_select: None, ignore: Some( [ "RUF001", ], ), }, ), format: None, code_action: Some( CodeActionOptions { disable_rule_comment: Some( CodeActionParameters { enable: Some( false, ), }, ), fix_violation: None, }, ), exclude: Some( [ "third_party", ], ), line_length: Some( LineLength( 80, ), ), configuration_preference: None, show_syntax_errors: None, }, tracing: TracingOptions { log_level: Some( Warn, ), log_file: None, }, }, } "#); } #[test] fn test_global_only_resolves_correctly() { let (main_loop_sender, main_loop_receiver) = crossbeam::channel::unbounded(); let (client_sender, client_receiver) = crossbeam::channel::unbounded(); let options = deserialize_fixture(GLOBAL_ONLY_INIT_OPTIONS_FIXTURE); let AllOptions { global, .. } = AllOptions::from_init_options(options); let client = Client::new(main_loop_sender, client_sender); let global = global.into_settings(client); assert_eq!( global.to_settings(), &ClientSettings { fix_all: false, organize_imports: true, lint_enable: true, disable_rule_comment_enable: false, fix_violation_enable: true, show_syntax_errors: true, editor_settings: EditorSettings { configuration: None, lint_preview: None, format_preview: None, format_backend: None, select: None, extend_select: None, ignore: Some(vec![RuleSelector::from_str("RUF001").unwrap()]), exclude: Some(vec!["third_party".into()]), line_length: Some(LineLength::try_from(80).unwrap()),
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true