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 |
|---|---|---|---|---|---|---|---|---|
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-storage-service/src/common.rs | linera-storage-service/src/common.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use std::path::PathBuf;
use linera_base::command::resolve_binary;
use linera_views::{lru_caching::LruCachingConfig, store::KeyValueStoreError};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tonic::Status;
// The maximal block size on GRPC is 4M.
//
// That size occurs in almost every use of GRPC and in particular the
// `tonic` library. In particular for the `tonic` library, the limit is
// both for incoming and outgoing messages.
// We decrease the 4194304 to 4000000 to leave space for the rest of the message
// (that includes length prefixes)
pub const MAX_PAYLOAD_SIZE: usize = 4000000;
/// Key tags to create the sub keys used for storing data on storage.
#[repr(u8)]
pub enum KeyPrefix {
/// Key prefix for the storage of the keys of the map
Key,
/// Key prefix for the storage of existence or not of the namespaces.
Namespace,
/// Key prefix for the root key
RootKey,
}
#[derive(Debug, Error)]
pub enum StorageServiceStoreError {
/// Store already exists during a create operation
#[error("Store already exists during a create operation")]
StoreAlreadyExists,
/// Not matching entry
#[error("Not matching entry")]
NotMatchingEntry,
/// Failed to find the linera-storage-server binary
#[error("Failed to find the linera-storage-server binary")]
FailedToFindStorageServerBinary,
/// gRPC error
#[error(transparent)]
GrpcError(#[from] Box<Status>),
/// The key size must be at most 1 MB
#[error("The key size must be at most 1 MB")]
KeyTooLong,
/// Transport error
#[error(transparent)]
TransportError(#[from] tonic::transport::Error),
/// Var error
#[error(transparent)]
VarError(#[from] std::env::VarError),
/// An error occurred during BCS serialization
#[error(transparent)]
BcsError(#[from] bcs::Error),
}
impl From<Status> for StorageServiceStoreError {
fn from(error: Status) -> Self {
Box::new(error).into()
}
}
impl KeyValueStoreError for StorageServiceStoreError {
const BACKEND: &'static str = "service";
}
pub fn storage_service_test_endpoint() -> Result<String, StorageServiceStoreError> {
Ok(std::env::var("LINERA_STORAGE_SERVICE")?)
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct StorageServiceStoreInternalConfig {
/// The endpoint used by the shared store
pub endpoint: String,
/// Maximum number of concurrent database queries allowed for this client.
pub max_concurrent_queries: Option<usize>,
/// Preferred buffer size for async streams.
pub max_stream_queries: usize,
}
/// The config type
pub type StorageServiceStoreConfig = LruCachingConfig<StorageServiceStoreInternalConfig>;
impl StorageServiceStoreInternalConfig {
pub fn http_address(&self) -> String {
format!("http://{}", self.endpoint)
}
}
/// Obtains the binary of the executable.
/// The path depends whether the test are run in the directory "linera-storage-service"
/// or in the main directory
pub async fn get_service_storage_binary() -> Result<PathBuf, StorageServiceStoreError> {
let binary = resolve_binary("linera-storage-server", "linera-storage-service").await;
if let Ok(binary) = binary {
return Ok(binary);
}
let binary = resolve_binary("../linera-storage-server", "linera-storage-service").await;
if let Ok(binary) = binary {
return Ok(binary);
}
Err(StorageServiceStoreError::FailedToFindStorageServerBinary)
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-storage-service/tests/store_test.rs | linera-storage-service/tests/store_test.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
#![cfg(feature = "storage-service")]
use anyhow::Result;
use linera_storage_service::client::StorageServiceDatabaseInternal;
use linera_views::{
batch::Batch,
store::TestKeyValueDatabase as _,
test_utils::{
get_random_byte_vector, get_random_test_scenarios, namespace_admin_test,
root_key_admin_test, run_reads, run_test_batch_from_blank, run_writes_from_blank,
run_writes_from_state,
},
};
#[tokio::test]
async fn test_storage_service_reads() -> Result<()> {
for scenario in get_random_test_scenarios() {
let store = StorageServiceDatabaseInternal::new_test_store().await?;
run_reads(store, scenario).await;
}
Ok(())
}
#[tokio::test]
async fn test_storage_service_writes_from_blank() -> Result<()> {
let store = StorageServiceDatabaseInternal::new_test_store().await?;
run_writes_from_blank(&store).await;
Ok(())
}
#[tokio::test]
async fn test_storage_service_writes_from_state() -> Result<()> {
let store = StorageServiceDatabaseInternal::new_test_store().await?;
run_writes_from_state(&store).await;
Ok(())
}
#[tokio::test]
async fn test_storage_service_namespace_admin() {
namespace_admin_test::<StorageServiceDatabaseInternal>().await;
}
#[tokio::test]
async fn test_storage_service_root_key_admin() {
root_key_admin_test::<StorageServiceDatabaseInternal>().await;
}
#[tokio::test]
async fn test_storage_service_big_raw_write() -> Result<()> {
let store = StorageServiceDatabaseInternal::new_test_store().await?;
let n = 5000000;
let mut rng = linera_views::random::make_deterministic_rng();
let vector = get_random_byte_vector(&mut rng, &[], n);
let mut batch = Batch::new();
let key_prefix = vec![43];
batch.put_key_value_bytes(vec![43, 57], vector);
run_test_batch_from_blank(&store, key_prefix, batch).await;
Ok(())
}
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
linera-io/linera-protocol | https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-storage-service/benches/store.rs | linera-storage-service/benches/store.rs | // Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use linera_storage_service::client::StorageServiceDatabase;
use linera_views::test_utils::performance;
use tokio::runtime::Runtime;
fn bench_storage_service(criterion: &mut Criterion) {
criterion.bench_function("store_storage_service_contains_key", |bencher| {
bencher
.to_async(Runtime::new().expect("Failed to create Tokio runtime"))
.iter_custom(|iterations| async move {
performance::contains_key::<StorageServiceDatabase, _>(iterations, black_box).await
})
});
criterion.bench_function("store_storage_service_contains_keys", |bencher| {
bencher
.to_async(Runtime::new().expect("Failed to create Tokio runtime"))
.iter_custom(|iterations| async move {
performance::contains_keys::<StorageServiceDatabase, _>(iterations, black_box).await
})
});
criterion.bench_function("store_storage_service_find_keys_by_prefix", |bencher| {
bencher
.to_async(Runtime::new().expect("Failed to create Tokio runtime"))
.iter_custom(|iterations| async move {
performance::find_keys_by_prefix::<StorageServiceDatabase, _>(iterations, black_box)
.await
})
});
criterion.bench_function(
"store_storage_service_find_key_values_by_prefix",
|bencher| {
bencher
.to_async(Runtime::new().expect("Failed to create Tokio runtime"))
.iter_custom(|iterations| async move {
performance::find_key_values_by_prefix::<StorageServiceDatabase, _>(
iterations, black_box,
)
.await
})
},
);
criterion.bench_function("store_storage_service_read_value_bytes", |bencher| {
bencher
.to_async(Runtime::new().expect("Failed to create Tokio runtime"))
.iter_custom(|iterations| async move {
performance::read_value_bytes::<StorageServiceDatabase, _>(iterations, black_box)
.await
})
});
criterion.bench_function("store_storage_service_read_multi_values_bytes", |bencher| {
bencher
.to_async(Runtime::new().expect("Failed to create Tokio runtime"))
.iter_custom(|iterations| async move {
performance::read_multi_values_bytes::<StorageServiceDatabase, _>(
iterations, black_box,
)
.await
})
});
criterion.bench_function("store_storage_service_write_batch", |bencher| {
bencher
.to_async(Runtime::new().expect("Failed to create Tokio runtime"))
.iter_custom(|iterations| async move {
performance::write_batch::<StorageServiceDatabase>(iterations).await
})
});
}
criterion_group!(benches, bench_storage_service,);
criterion_main!(benches);
| rust | Apache-2.0 | 69f159d2106f7fc70870ce70074c55850bf1303b | 2026-01-04T15:33:08.660695Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/build.rs | build.rs | fn main() {
if std::env::var("CARGO_CFG_TARGET_OS").unwrap() == "windows" {
println!("cargo:rerun-if-changed=logo.ico");
let mut res = winresource::WindowsResource::new();
if std::path::Path::new("logo.ico").exists() {
res.set_icon("logo.ico");
} else {
println!("cargo:warning=logo.ico not found, skipping icon embedding");
return;
}
res.compile()
.map_err(|e| {
println!("cargo:warning=Failed to compile Windows resources: {e}");
})
.ok();
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/example_projects/wasm32_without_js/rustpython-without-js/src/lib.rs | example_projects/wasm32_without_js/rustpython-without-js/src/lib.rs | use rustpython_vm::{Interpreter};
unsafe extern "C" {
fn kv_get(kp: i32, kl: i32, vp: i32, vl: i32) -> i32;
/// kp and kl are the key pointer and length in wasm memory, vp and vl are for the value
fn kv_put(kp: i32, kl: i32, vp: i32, vl: i32) -> i32;
fn print(p: i32, l: i32) -> i32;
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn eval(s: *const u8, l: usize) -> i32 {
// let src = unsafe { std::slice::from_raw_parts(s, l) };
// let src = std::str::from_utf8(src).unwrap();
// TODO: use src
let src = "1 + 3";
// 2. Execute Python code
let interpreter = Interpreter::without_stdlib(Default::default());
let result = interpreter.enter(|vm| {
let scope = vm.new_scope_with_builtins();
let res = match vm.run_block_expr(scope, src) {
Ok(val) => val,
Err(_) => return Err(-1), // Python execution error
};
let repr_str = match res.repr(vm) {
Ok(repr) => repr.as_str().to_string(),
Err(_) => return Err(-1), // Failed to get string representation
};
Ok(repr_str)
});
let result = match result {
Ok(r) => r,
Err(code) => return code,
};
let msg = format!("eval result: {result}");
unsafe {
print(
msg.as_str().as_ptr() as usize as i32,
msg.len() as i32,
)
};
0
}
#[unsafe(no_mangle)]
unsafe extern "Rust" fn __getrandom_v03_custom(
_dest: *mut u8,
_len: usize,
) -> Result<(), getrandom::Error> {
// Err(getrandom::Error::UNSUPPORTED)
// WARNING: This function **MUST** perform proper getrandom
Ok(())
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/example_projects/wasm32_without_js/wasm-runtime/src/main.rs | example_projects/wasm32_without_js/wasm-runtime/src/main.rs | use std::collections::HashMap;
use wasmer::{
Function, FunctionEnv, FunctionEnvMut, Instance, Memory, Module, Store, Value, imports,
};
struct Ctx {
kv: HashMap<Vec<u8>, Vec<u8>>,
mem: Option<Memory>,
}
/// kp and kl are the key pointer and length in wasm memory, vp and vl are for the return value
/// if read value is bigger than vl then it will be truncated to vl, returns read bytes
fn kv_get(mut ctx: FunctionEnvMut<Ctx>, kp: i32, kl: i32, vp: i32, vl: i32) -> i32 {
let (c, s) = ctx.data_and_store_mut();
let mut key = vec![0u8; kl as usize];
if c.mem
.as_ref()
.unwrap()
.view(&s)
.read(kp as u64, &mut key)
.is_err()
{
return -1;
}
match c.kv.get(&key) {
Some(val) => {
let len = val.len().min(vl as usize);
if c.mem
.as_ref()
.unwrap()
.view(&s)
.write(vp as u64, &val[..len])
.is_err()
{
return -1;
}
len as i32
}
None => 0,
}
}
/// kp and kl are the key pointer and length in wasm memory, vp and vl are for the value
fn kv_put(mut ctx: FunctionEnvMut<Ctx>, kp: i32, kl: i32, vp: i32, vl: i32) -> i32 {
let (c, s) = ctx.data_and_store_mut();
let mut key = vec![0u8; kl as usize];
let mut val = vec![0u8; vl as usize];
let m = c.mem.as_ref().unwrap().view(&s);
if m.read(kp as u64, &mut key).is_err() || m.read(vp as u64, &mut val).is_err() {
return -1;
}
c.kv.insert(key, val);
0
}
// // p and l are the buffer pointer and length in wasm memory.
// fn get_code(mut ctx:FunctionEnvMut<Ctx>, p: i32, l: i32) -> i32 {
// let file_name = std::env::args().nth(2).expect("file_name is not given");
// let code : String = std::fs::read_to_string(file_name).expect("file read failed");
// if code.len() > l as usize {
// eprintln!("code is too long");
// return -1;
// }
// let (c, s) = ctx.data_and_store_mut();
// let m = c.mem.as_ref().unwrap().view(&s);
// if m.write(p as u64, code.as_bytes()).is_err() {
// return -2;
// }
// 0
// }
// p and l are the message pointer and length in wasm memory.
fn print(mut ctx: FunctionEnvMut<Ctx>, p: i32, l: i32) -> i32 {
let (c, s) = ctx.data_and_store_mut();
let mut msg = vec![0u8; l as usize];
let m = c.mem.as_ref().unwrap().view(&s);
if m.read(p as u64, &mut msg).is_err() {
return -1;
}
let s = std::str::from_utf8(&msg).expect("print got non-utf8 str");
println!("{s}");
0
}
fn main() {
let mut store = Store::default();
let module = Module::new(
&store,
&std::fs::read(&std::env::args().nth(1).unwrap()).unwrap(),
)
.unwrap();
// Prepare initial KV store with Python code
let mut initial_kv = HashMap::new();
initial_kv.insert(
b"code".to_vec(),
b"a=10;b='str';f'{a}{b}'".to_vec(), // Python code to execute
);
let env = FunctionEnv::new(
&mut store,
Ctx {
kv: initial_kv,
mem: None,
},
);
let imports = imports! {
"env" => {
"kv_get" => Function::new_typed_with_env(&mut store, &env, kv_get),
"kv_put" => Function::new_typed_with_env(&mut store, &env, kv_put),
// "get_code" => Function::new_typed_with_env(&mut store, &env, get_code),
"print" => Function::new_typed_with_env(&mut store, &env, print),
}
};
let inst = Instance::new(&mut store, &module, &imports).unwrap();
env.as_mut(&mut store).mem = inst.exports.get_memory("memory").ok().cloned();
let res = inst
.exports
.get_function("eval")
.unwrap()
// TODO: actually pass source code
.call(&mut store, &[wasmer::Value::I32(0), wasmer::Value::I32(0)])
.unwrap();
println!(
"Result: {}",
match res[0] {
Value::I32(v) => v,
_ => -1,
}
);
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/example_projects/barebone/src/main.rs | example_projects/barebone/src/main.rs | use rustpython_vm::Interpreter;
pub fn main() {
let interp = Interpreter::without_stdlib(Default::default());
let value = interp.enter(|vm| {
let max = vm.builtins.get_attr("max", vm)?;
let value = max.call((vm.ctx.new_int(5), vm.ctx.new_int(10)), vm)?;
vm.print((vm.ctx.new_str("python print"), value.clone()))?;
Ok(value)
});
match value {
Ok(value) => println!("Rust repr: {:?}", value),
Err(err) => {
interp.finalize(err);
}
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/example_projects/frozen_stdlib/src/main.rs | example_projects/frozen_stdlib/src/main.rs | // spell-checker:ignore aheui
/// Setting up a project with a frozen stdlib can be done *either* by using `rustpython::InterpreterConfig` or `rustpython_vm::Interpreter::with_init`.
/// See each function for example.
///
/// See also: `aheui-rust.md` for freezing your own package.
use rustpython_vm::{PyResult, VirtualMachine};
fn run(keyword: &str, vm: &VirtualMachine) -> PyResult<()> {
let json = vm.import("json", 0)?;
let json_loads = json.get_attr("loads", vm)?;
let template = r#"{"key": "value"}"#;
let json_string = template.replace("value", keyword);
let dict = json_loads.call((vm.ctx.new_str(json_string),), vm)?;
vm.print((dict,))?;
Ok(())
}
fn interpreter_with_config() {
let interpreter = rustpython::InterpreterConfig::new()
.init_stdlib()
.interpreter();
// Use interpreter.enter to reuse the same interpreter later
interpreter.run(|vm| run("rustpython::InterpreterConfig", vm));
}
fn interpreter_with_vm() {
let interpreter = rustpython_vm::Interpreter::with_init(Default::default(), |vm| {
// This is unintuitive, but the stdlib is out of the vm crate.
// Any suggestion to improve this is welcome.
vm.add_frozen(rustpython_pylib::FROZEN_STDLIB);
});
// Use interpreter.enter to reuse the same interpreter later
interpreter.run(|vm| run("rustpython_vm::Interpreter::with_init", vm));
}
fn main() {
interpreter_with_config();
interpreter_with_vm();
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/src/settings.rs | src/settings.rs | use lexopt::Arg::*;
use lexopt::ValueExt;
use rustpython_vm::{Settings, vm::CheckHashPycsMode};
use std::str::FromStr;
use std::{cmp, env};
pub enum RunMode {
Script(String),
Command(String),
Module(String),
InstallPip(InstallPipMode),
Repl,
}
pub enum InstallPipMode {
/// Install pip using the ensurepip pip module. This has a higher chance of
/// success, but may not install the latest version of pip.
Ensurepip,
/// Install pip using the get-pip.py script, which retrieves the latest pip version.
/// This can be broken due to incompatibilities with cpython.
GetPip,
}
impl FromStr for InstallPipMode {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"ensurepip" => Ok(Self::Ensurepip),
"get-pip" => Ok(Self::GetPip),
_ => Err("--install-pip takes ensurepip or get-pip as first argument"),
}
}
}
#[derive(Default)]
struct CliArgs {
bytes_warning: u8,
dont_write_bytecode: bool,
debug: u8,
ignore_environment: bool,
inspect: bool,
isolate: bool,
optimize: u8,
safe_path: bool,
quiet: bool,
random_hash_seed: bool,
no_user_site: bool,
no_site: bool,
unbuffered: bool,
verbose: u8,
warning_control: Vec<String>,
implementation_option: Vec<String>,
check_hash_based_pycs: CheckHashPycsMode,
#[cfg(feature = "flame-it")]
profile_output: Option<std::ffi::OsString>,
#[cfg(feature = "flame-it")]
profile_format: Option<String>,
}
const USAGE_STRING: &str = "\
usage: {PROG} [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options (and corresponding environment variables):
-b : issue warnings about converting bytes/bytearray to str and comparing
bytes/bytearray with str or bytes with int. (-bb: issue errors)
-B : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d : turn on parser debugging output (for experts only, only works on
debug builds); also PYTHONDEBUG=x
-E : ignore PYTHON* environment variables (such as PYTHONPATH)
-h : print this help message and exit (also -? or --help)
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-I : isolate Python from the user's environment (implies -E and -s)
-m mod : run library module as a script (terminates option list)
-O : remove assert and __debug__-dependent statements; add .opt-1 before
.pyc extension; also PYTHONOPTIMIZE=x
-OO : do -O changes and also discard docstrings; add .opt-2 before
.pyc extension
-P : don't prepend a potentially unsafe path to sys.path; also
PYTHONSAFEPATH
-q : don't print version and copyright messages on interactive startup
-s : don't add user site directory to sys.path; also PYTHONNOUSERSITE=x
-S : don't imply 'import site' on initialization
-u : force the stdout and stderr streams to be unbuffered;
this option has no effect on stdin; also PYTHONUNBUFFERED=x
-v : verbose (trace import statements); also PYTHONVERBOSE=x
can be supplied multiple times to increase verbosity
-V : print the Python version number and exit (also --version)
when given twice, print more information about the build
-W arg : warning control; arg is action:message:category:module:lineno
also PYTHONWARNINGS=arg
-x : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option
--check-hash-based-pycs always|default|never:
control how Python invalidates hash-based .pyc files
--help-env: print help about Python environment variables and exit
--help-xoptions: print help about implementation-specific -X options and exit
--help-all: print complete help information and exit
RustPython extensions:
Arguments:
file : program read from script file
- : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]
";
fn parse_args() -> Result<(CliArgs, RunMode, Vec<String>), lexopt::Error> {
let mut args = CliArgs::default();
let mut parser = lexopt::Parser::from_env();
fn argv(argv0: String, mut parser: lexopt::Parser) -> Result<Vec<String>, lexopt::Error> {
std::iter::once(Ok(argv0))
.chain(parser.raw_args()?.map(|arg| arg.string()))
.collect()
}
while let Some(arg) = parser.next()? {
match arg {
Short('b') => args.bytes_warning += 1,
Short('B') => args.dont_write_bytecode = true,
Short('c') => {
let cmd = parser.value()?.string()?;
return Ok((args, RunMode::Command(cmd), argv("-c".to_owned(), parser)?));
}
Short('d') => args.debug += 1,
Short('E') => args.ignore_environment = true,
Short('h' | '?') | Long("help") => help(parser),
Short('i') => args.inspect = true,
Short('I') => args.isolate = true,
Short('m') => {
let module = parser.value()?.string()?;
let argv = argv("PLACEHOLDER".to_owned(), parser)?;
return Ok((args, RunMode::Module(module), argv));
}
Short('O') => args.optimize += 1,
Short('P') => args.safe_path = true,
Short('q') => args.quiet = true,
Short('R') => args.random_hash_seed = true,
Short('S') => args.no_site = true,
Short('s') => args.no_user_site = true,
Short('u') => args.unbuffered = true,
Short('v') => args.verbose += 1,
Short('V') | Long("version") => version(),
Short('W') => args.warning_control.push(parser.value()?.string()?),
// TODO: Short('x') =>
Short('X') => args.implementation_option.push(parser.value()?.string()?),
Long("check-hash-based-pycs") => {
args.check_hash_based_pycs = parser.value()?.parse()?
}
// TODO: make these more specific
Long("help-env") => help(parser),
Long("help-xoptions") => help(parser),
Long("help-all") => help(parser),
#[cfg(feature = "flame-it")]
Long("profile-output") => args.profile_output = Some(parser.value()?),
#[cfg(feature = "flame-it")]
Long("profile-format") => args.profile_format = Some(parser.value()?.string()?),
Long("install-pip") => {
let (mode, argv) = if let Some(val) = parser.optional_value() {
(val.parse()?, vec![val.string()?])
} else if let Ok(argv0) = parser.value() {
let mode = argv0.parse()?;
(mode, argv(argv0.string()?, parser)?)
} else {
(
InstallPipMode::Ensurepip,
["ensurepip", "--upgrade", "--default-pip"]
.map(str::to_owned)
.into(),
)
};
return Ok((args, RunMode::InstallPip(mode), argv));
}
Value(script_name) => {
let script_name = script_name.string()?;
let mode = if script_name == "-" {
RunMode::Repl
} else {
RunMode::Script(script_name.clone())
};
return Ok((args, mode, argv(script_name, parser)?));
}
_ => return Err(arg.unexpected()),
}
}
Ok((args, RunMode::Repl, vec![]))
}
fn help(parser: lexopt::Parser) -> ! {
let usage = USAGE_STRING.replace("{PROG}", parser.bin_name().unwrap_or("rustpython"));
print!("{usage}");
std::process::exit(0);
}
fn version() -> ! {
println!("Python {}", rustpython_vm::version::get_version());
std::process::exit(0);
}
/// Create settings by examining command line arguments and environment
/// variables.
pub fn parse_opts() -> Result<(Settings, RunMode), lexopt::Error> {
let (args, mode, argv) = parse_args()?;
let mut settings = Settings::default();
settings.isolated = args.isolate;
settings.ignore_environment = settings.isolated || args.ignore_environment;
settings.bytes_warning = args.bytes_warning.into();
settings.import_site = !args.no_site;
let ignore_environment = settings.ignore_environment;
if !ignore_environment {
settings.path_list.extend(get_paths("RUSTPYTHONPATH"));
settings.path_list.extend(get_paths("PYTHONPATH"));
}
// Now process command line flags:
let get_env = |env| (!ignore_environment).then(|| env::var_os(env)).flatten();
let env_count = |env| {
get_env(env).filter(|v| !v.is_empty()).map_or(0, |val| {
val.to_str().and_then(|v| v.parse::<u8>().ok()).unwrap_or(1)
})
};
settings.optimize = cmp::max(args.optimize, env_count("PYTHONOPTIMIZE"));
settings.verbose = cmp::max(args.verbose, env_count("PYTHONVERBOSE"));
settings.debug = cmp::max(args.debug, env_count("PYTHONDEBUG"));
let env_bool = |env| get_env(env).is_some_and(|v| !v.is_empty());
settings.user_site_directory =
!(settings.isolated || args.no_user_site || env_bool("PYTHONNOUSERSITE"));
settings.quiet = args.quiet;
settings.write_bytecode = !(args.dont_write_bytecode || env_bool("PYTHONDONTWRITEBYTECODE"));
settings.safe_path = settings.isolated || args.safe_path || env_bool("PYTHONSAFEPATH");
settings.inspect = args.inspect || env_bool("PYTHONINSPECT");
settings.interactive = args.inspect;
settings.buffered_stdio = !args.unbuffered;
if let Some(val) = get_env("PYTHONINTMAXSTRDIGITS") {
settings.int_max_str_digits = match val.to_str().and_then(|s| s.parse().ok()) {
Some(digits @ (0 | 640..)) => digits,
_ => {
error!(
"Fatal Python error: config_init_int_max_str_digits: PYTHONINTMAXSTRDIGITS: invalid limit; must be >= 640 or 0 for unlimited.\nPython runtime state: preinitialized"
);
std::process::exit(1);
}
};
}
settings.check_hash_pycs_mode = args.check_hash_based_pycs;
let xopts = args.implementation_option.into_iter().map(|s| {
let (name, value) = match s.split_once('=') {
Some((name, value)) => (name.to_owned(), Some(value)),
None => (s, None),
};
match &*name {
"dev" => settings.dev_mode = true,
"faulthandler" => settings.faulthandler = true,
"warn_default_encoding" => settings.warn_default_encoding = true,
"no_sig_int" => settings.install_signal_handlers = false,
"no_debug_ranges" => settings.code_debug_ranges = false,
"int_max_str_digits" => {
settings.int_max_str_digits = match value.unwrap().parse() {
Ok(digits) if digits == 0 || digits >= 640 => digits,
_ => {
error!(
"Fatal Python error: config_init_int_max_str_digits: \
-X int_max_str_digits: \
invalid limit; must be >= 640 or 0 for unlimited.\n\
Python runtime state: preinitialized"
);
std::process::exit(1);
}
};
}
_ => {}
}
(name, value.map(str::to_owned))
});
settings.xoptions.extend(xopts);
settings.warn_default_encoding =
settings.warn_default_encoding || env_bool("PYTHONWARNDEFAULTENCODING");
settings.faulthandler = settings.faulthandler || env_bool("PYTHONFAULTHANDLER");
if env_bool("PYTHONNODEBUGRANGES") {
settings.code_debug_ranges = false;
}
// Parse PYTHONIOENCODING=encoding[:errors]
if let Some(val) = get_env("PYTHONIOENCODING")
&& let Some(val_str) = val.to_str()
&& !val_str.is_empty()
{
if let Some((enc, err)) = val_str.split_once(':') {
if !enc.is_empty() {
settings.stdio_encoding = Some(enc.to_owned());
}
if !err.is_empty() {
settings.stdio_errors = Some(err.to_owned());
}
} else {
settings.stdio_encoding = Some(val_str.to_owned());
}
}
if settings.dev_mode {
settings.warnoptions.push("default".to_owned());
settings.faulthandler = true;
}
if settings.bytes_warning > 0 {
let warn = if settings.bytes_warning > 1 {
"error::BytesWarning"
} else {
"default::BytesWarning"
};
settings.warnoptions.push(warn.to_owned());
}
settings.warnoptions.extend(args.warning_control);
settings.hash_seed = match (!args.random_hash_seed)
.then(|| get_env("PYTHONHASHSEED"))
.flatten()
{
Some(s) if s == "random" || s.is_empty() => None,
Some(s) => {
let seed = s.parse_with(|s| {
s.parse::<u32>().map_err(|_| {
"Fatal Python init error: PYTHONHASHSEED must be \
\"random\" or an integer in range [0; 4294967295]"
})
})?;
Some(seed)
}
None => None,
};
settings.argv = argv;
#[cfg(feature = "flame-it")]
{
settings.profile_output = args.profile_output;
settings.profile_format = args.profile_format;
}
Ok((settings, mode))
}
/// Helper function to retrieve a sequence of paths from an environment variable.
fn get_paths(env_variable_name: &str) -> impl Iterator<Item = String> + '_ {
env::var_os(env_variable_name)
.filter(|v| !v.is_empty())
.into_iter()
.flat_map(move |paths| {
split_paths(&paths)
.map(|path| {
path.into_os_string()
.into_string()
.unwrap_or_else(|_| panic!("{env_variable_name} isn't valid unicode"))
})
.collect::<Vec<_>>()
})
}
#[cfg(not(target_os = "wasi"))]
pub(crate) use env::split_paths;
#[cfg(target_os = "wasi")]
pub(crate) fn split_paths<T: AsRef<std::ffi::OsStr> + ?Sized>(
s: &T,
) -> impl Iterator<Item = std::path::PathBuf> + '_ {
use std::os::wasi::ffi::OsStrExt;
let s = s.as_ref().as_bytes();
s.split(|b| *b == b':')
.map(|x| std::ffi::OsStr::from_bytes(x).to_owned().into())
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/src/lib.rs | src/lib.rs | //! This is the `rustpython` binary. If you're looking to embed RustPython into your application,
//! you're likely looking for the [`rustpython_vm`] crate.
//!
//! You can install `rustpython` with `cargo install rustpython`, or if you'd like to inject your
//! own native modules you can make a binary crate that depends on the `rustpython` crate (and
//! probably [`rustpython_vm`], too), and make a `main.rs` that looks like:
//!
//! ```no_run
//! use rustpython_vm::{pymodule, py_freeze};
//! fn main() {
//! rustpython::run(|vm| {
//! vm.add_native_module("my_mod".to_owned(), Box::new(my_mod::make_module));
//! vm.add_frozen(py_freeze!(source = "def foo(): pass", module_name = "other_thing"));
//! });
//! }
//!
//! #[pymodule]
//! mod my_mod {
//! use rustpython_vm::builtins::PyStrRef;
//TODO: use rustpython_vm::prelude::*;
//!
//! #[pyfunction]
//! fn do_thing(x: i32) -> i32 {
//! x + 1
//! }
//!
//! #[pyfunction]
//! fn other_thing(s: PyStrRef) -> (String, usize) {
//! let new_string = format!("hello from rust, {}!", s);
//! let prev_len = s.as_str().len();
//! (new_string, prev_len)
//! }
//! }
//! ```
//!
//! The binary will have all the standard arguments of a python interpreter (including a REPL!) but
//! it will have your modules loaded into the vm.
#![cfg_attr(all(target_os = "wasi", target_env = "p2"), feature(wasip2))]
#![allow(clippy::needless_doctest_main)]
#[macro_use]
extern crate log;
#[cfg(feature = "flame-it")]
use vm::Settings;
mod interpreter;
mod settings;
mod shell;
use rustpython_vm::{AsObject, PyObjectRef, PyResult, VirtualMachine, scope::Scope};
use std::env;
use std::io::IsTerminal;
use std::process::ExitCode;
pub use interpreter::InterpreterConfig;
pub use rustpython_vm as vm;
pub use settings::{InstallPipMode, RunMode, parse_opts};
pub use shell::run_shell;
#[cfg(all(
feature = "ssl",
not(any(feature = "ssl-rustls", feature = "ssl-openssl"))
))]
compile_error!(
"Feature \"ssl\" is now enabled by either \"ssl-rustls\" or \"ssl-openssl\" to be enabled. Do not manually pass \"ssl\" feature. To enable ssl-openssl, use --no-default-features to disable ssl-rustls"
);
/// The main cli of the `rustpython` interpreter. This function will return `std::process::ExitCode`
/// based on the return code of the python code ran through the cli.
pub fn run(init: impl FnOnce(&mut VirtualMachine) + 'static) -> ExitCode {
env_logger::init();
// NOTE: This is not a WASI convention. But it will be convenient since POSIX shell always defines it.
#[cfg(target_os = "wasi")]
{
if let Ok(pwd) = env::var("PWD") {
let _ = env::set_current_dir(pwd);
};
}
let (settings, run_mode) = match parse_opts() {
Ok(x) => x,
Err(e) => {
println!("{e}");
return ExitCode::FAILURE;
}
};
// don't translate newlines (\r\n <=> \n)
#[cfg(windows)]
{
unsafe extern "C" {
fn _setmode(fd: i32, flags: i32) -> i32;
}
unsafe {
_setmode(0, libc::O_BINARY);
_setmode(1, libc::O_BINARY);
_setmode(2, libc::O_BINARY);
}
}
let mut config = InterpreterConfig::new().settings(settings);
#[cfg(feature = "stdlib")]
{
config = config.init_stdlib();
}
config = config.init_hook(Box::new(init));
let interp = config.interpreter();
let exitcode = interp.run(move |vm| run_rustpython(vm, run_mode));
rustpython_vm::common::os::exit_code(exitcode)
}
fn get_pip(scope: Scope, vm: &VirtualMachine) -> PyResult<()> {
let get_getpip = rustpython_vm::py_compile!(
source = r#"\
__import__("io").TextIOWrapper(
__import__("urllib.request").request.urlopen("https://bootstrap.pypa.io/get-pip.py")
).read()
"#,
mode = "eval"
);
eprintln!("downloading get-pip.py...");
let getpip_code = vm.run_code_obj(vm.ctx.new_code(get_getpip), vm.new_scope_with_builtins())?;
let getpip_code: rustpython_vm::builtins::PyStrRef = getpip_code
.downcast()
.expect("TextIOWrapper.read() should return str");
eprintln!("running get-pip.py...");
vm.run_string(scope, getpip_code.as_str(), "get-pip.py".to_owned())?;
Ok(())
}
fn install_pip(installer: InstallPipMode, scope: Scope, vm: &VirtualMachine) -> PyResult<()> {
if !cfg!(feature = "ssl") {
return Err(vm.new_exception_msg(
vm.ctx.exceptions.system_error.to_owned(),
"install-pip requires rustpython be build with '--features=ssl'".to_owned(),
));
}
match installer {
InstallPipMode::Ensurepip => vm.run_module("ensurepip"),
InstallPipMode::GetPip => get_pip(scope, vm),
}
}
// pymain_run_file_obj in Modules/main.c
fn run_file(vm: &VirtualMachine, scope: Scope, path: &str) -> PyResult<()> {
// Check if path is a package/directory with __main__.py
if let Some(_importer) = get_importer(path, vm)? {
vm.insert_sys_path(vm.new_pyobj(path))?;
let runpy = vm.import("runpy", 0)?;
let run_module_as_main = runpy.get_attr("_run_module_as_main", vm)?;
run_module_as_main.call((vm::identifier!(vm, __main__).to_owned(), false), vm)?;
return Ok(());
}
// Add script directory to sys.path[0]
if !vm.state.config.settings.safe_path {
let dir = std::path::Path::new(path)
.parent()
.and_then(|p| p.to_str())
.unwrap_or("");
vm.insert_sys_path(vm.new_pyobj(dir))?;
}
vm.run_any_file(scope, path)
}
fn get_importer(path: &str, vm: &VirtualMachine) -> PyResult<Option<PyObjectRef>> {
use rustpython_vm::builtins::PyDictRef;
use rustpython_vm::convert::TryFromObject;
let path_importer_cache = vm.sys_module.get_attr("path_importer_cache", vm)?;
let path_importer_cache = PyDictRef::try_from_object(vm, path_importer_cache)?;
if let Some(importer) = path_importer_cache.get_item_opt(path, vm)? {
return Ok(Some(importer));
}
let path_obj = vm.ctx.new_str(path);
let path_hooks = vm.sys_module.get_attr("path_hooks", vm)?;
let mut importer = None;
let path_hooks: Vec<PyObjectRef> = path_hooks.try_into_value(vm)?;
for path_hook in path_hooks {
match path_hook.call((path_obj.clone(),), vm) {
Ok(imp) => {
importer = Some(imp);
break;
}
Err(e) if e.fast_isinstance(vm.ctx.exceptions.import_error) => continue,
Err(e) => return Err(e),
}
}
Ok(if let Some(imp) = importer {
let imp = path_importer_cache.get_or_insert(vm, path_obj.into(), || imp.clone())?;
Some(imp)
} else {
None
})
}
// pymain_run_python
fn run_rustpython(vm: &VirtualMachine, run_mode: RunMode) -> PyResult<()> {
#[cfg(feature = "flame-it")]
let main_guard = flame::start_guard("RustPython main");
let scope = vm.new_scope_with_main()?;
// Import site first, before setting sys.path[0]
// This matches CPython's behavior where site.removeduppaths() runs
// before sys.path[0] is set, preventing '' from being converted to cwd
let site_result = vm.import("site", 0);
if site_result.is_err() {
warn!(
"Failed to import site, consider adding the Lib directory to your RUSTPYTHONPATH \
environment variable",
);
}
// _PyPathConfig_ComputeSysPath0 - set sys.path[0] after site import
if !vm.state.config.settings.safe_path {
let path0: Option<String> = match &run_mode {
RunMode::Command(_) => Some(String::new()),
RunMode::Module(_) => env::current_dir()
.ok()
.and_then(|p| p.to_str().map(|s| s.to_owned())),
RunMode::Script(_) | RunMode::InstallPip(_) => None, // handled by run_script
RunMode::Repl => Some(String::new()),
};
if let Some(path) = path0 {
vm.insert_sys_path(vm.new_pyobj(path))?;
}
}
// Enable faulthandler if -X faulthandler, PYTHONFAULTHANDLER or -X dev is set
// _PyFaulthandler_Init()
if vm.state.config.settings.faulthandler {
let _ = vm.run_simple_string("import faulthandler; faulthandler.enable()");
}
let is_repl = matches!(run_mode, RunMode::Repl);
if !vm.state.config.settings.quiet
&& (vm.state.config.settings.verbose > 0 || (is_repl && std::io::stdin().is_terminal()))
{
eprintln!(
"Welcome to the magnificent Rust Python {} interpreter \u{1f631} \u{1f596}",
env!("CARGO_PKG_VERSION")
);
eprintln!(
"RustPython {}.{}.{}",
vm::version::MAJOR,
vm::version::MINOR,
vm::version::MICRO,
);
eprintln!("Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.");
}
let res = match run_mode {
RunMode::Command(command) => {
debug!("Running command {command}");
vm.run_string(scope.clone(), &command, "<string>".to_owned())
.map(drop)
}
RunMode::Module(module) => {
debug!("Running module {module}");
vm.run_module(&module)
}
RunMode::InstallPip(installer) => install_pip(installer, scope.clone(), vm),
RunMode::Script(script_path) => {
// pymain_run_file_obj
debug!("Running script {}", &script_path);
run_file(vm, scope.clone(), &script_path)
}
RunMode::Repl => Ok(()),
};
if is_repl || vm.state.config.settings.inspect {
shell::run_shell(vm, scope)?;
} else {
res?;
}
#[cfg(feature = "flame-it")]
{
main_guard.end();
if let Err(e) = write_profile(&vm.state.as_ref().config.settings) {
error!("Error writing profile information: {}", e);
}
}
Ok(())
}
#[cfg(feature = "flame-it")]
fn write_profile(settings: &Settings) -> Result<(), Box<dyn core::error::Error>> {
use std::{fs, io};
enum ProfileFormat {
Html,
Text,
SpeedScope,
}
let profile_output = settings.profile_output.as_deref();
let profile_format = match settings.profile_format.as_deref() {
Some("html") => ProfileFormat::Html,
Some("text") => ProfileFormat::Text,
None if profile_output == Some("-".as_ref()) => ProfileFormat::Text,
// spell-checker:ignore speedscope
Some("speedscope") | None => ProfileFormat::SpeedScope,
Some(other) => {
error!("Unknown profile format {}", other);
// TODO: Need to change to ExitCode or Termination
std::process::exit(1);
}
};
let profile_output = profile_output.unwrap_or_else(|| match profile_format {
ProfileFormat::Html => "flame-graph.html".as_ref(),
ProfileFormat::Text => "flame.txt".as_ref(),
ProfileFormat::SpeedScope => "flamescope.json".as_ref(),
});
let profile_output: Box<dyn io::Write> = if profile_output == "-" {
Box::new(io::stdout())
} else {
Box::new(fs::File::create(profile_output)?)
};
let profile_output = io::BufWriter::new(profile_output);
match profile_format {
ProfileFormat::Html => flame::dump_html(profile_output)?,
ProfileFormat::Text => flame::dump_text_to_writer(profile_output)?,
ProfileFormat::SpeedScope => flamescope::dump(profile_output)?,
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use rustpython_vm::Interpreter;
fn interpreter() -> Interpreter {
InterpreterConfig::new().init_stdlib().interpreter()
}
#[test]
fn test_run_script() {
interpreter().enter(|vm| {
vm.unwrap_pyresult((|| {
let scope = vm.new_scope_with_main()?;
// test file run
vm.run_any_file(scope, "extra_tests/snippets/dir_main/__main__.py")?;
let scope = vm.new_scope_with_main()?;
// test module run (directory with __main__.py)
run_file(vm, scope, "extra_tests/snippets/dir_main")?;
Ok(())
})());
})
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/src/shell.rs | src/shell.rs | mod helper;
use rustpython_compiler::{
CompileError, ParseError, parser::InterpolatedStringErrorType, parser::LexicalErrorType,
parser::ParseErrorType,
};
use rustpython_vm::{
AsObject, PyResult, VirtualMachine,
builtins::PyBaseExceptionRef,
compiler::{self},
readline::{Readline, ReadlineResult},
scope::Scope,
};
enum ShellExecResult {
Ok,
PyErr(PyBaseExceptionRef),
ContinueBlock,
ContinueLine,
}
fn shell_exec(
vm: &VirtualMachine,
source: &str,
scope: Scope,
empty_line_given: bool,
continuing_block: bool,
) -> ShellExecResult {
// compiling expects only UNIX style line endings, and will replace windows line endings
// internally. Since we might need to analyze the source to determine if an error could be
// resolved by future input, we need the location from the error to match the source code that
// was actually compiled.
#[cfg(windows)]
let source = &source.replace("\r\n", "\n");
match vm.compile(source, compiler::Mode::Single, "<stdin>".to_owned()) {
Ok(code) => {
if empty_line_given || !continuing_block {
// We want to execute the full code
match vm.run_code_obj(code, scope) {
Ok(_val) => ShellExecResult::Ok,
Err(err) => ShellExecResult::PyErr(err),
}
} else {
// We can just return an ok result
ShellExecResult::Ok
}
}
Err(CompileError::Parse(ParseError {
error: ParseErrorType::Lexical(LexicalErrorType::Eof),
..
})) => ShellExecResult::ContinueLine,
Err(CompileError::Parse(ParseError {
error:
ParseErrorType::Lexical(LexicalErrorType::FStringError(
InterpolatedStringErrorType::UnterminatedTripleQuotedString,
)),
..
})) => ShellExecResult::ContinueLine,
Err(err) => {
// Check if the error is from an unclosed triple quoted string (which should always
// continue)
if let CompileError::Parse(ParseError {
error: ParseErrorType::Lexical(LexicalErrorType::UnclosedStringError),
raw_location,
..
}) = err
{
let loc = raw_location.start().to_usize();
let mut iter = source.chars();
if let Some(quote) = iter.nth(loc)
&& iter.next() == Some(quote)
&& iter.next() == Some(quote)
{
return ShellExecResult::ContinueLine;
}
};
// bad_error == true if we are handling an error that should be thrown even if we are continuing
// if its an indentation error, set to true if we are continuing and the error is on column 0,
// since indentations errors on columns other than 0 should be ignored.
// if its an unrecognized token for dedent, set to false
let bad_error = match err {
CompileError::Parse(ref p) => {
match &p.error {
ParseErrorType::Lexical(LexicalErrorType::IndentationError) => {
continuing_block
} // && p.location.is_some()
ParseErrorType::OtherError(msg) => {
!msg.starts_with("Expected an indented block")
}
_ => true, // !matches!(p, ParseErrorType::UnrecognizedToken(Tok::Dedent, _))
}
}
_ => true, // It is a bad error for everything else
};
// If we are handling an error on an empty line or an error worthy of throwing
if empty_line_given || bad_error {
ShellExecResult::PyErr(vm.new_syntax_error(&err, Some(source)))
} else {
ShellExecResult::ContinueBlock
}
}
}
}
/// Enter a repl loop
pub fn run_shell(vm: &VirtualMachine, scope: Scope) -> PyResult<()> {
let mut repl = Readline::new(helper::ShellHelper::new(vm, scope.globals.clone()));
let mut full_input = String::new();
// Retrieve a `history_path_str` dependent on the OS
let repl_history_path = match dirs::config_dir() {
Some(mut path) => {
path.push("rustpython");
path.push("repl_history.txt");
path
}
None => ".repl_history.txt".into(),
};
if repl.load_history(&repl_history_path).is_err() {
println!("No previous history.");
}
// We might either be waiting to know if a block is complete, or waiting to know if a multiline
// statement is complete. In the former case, we need to ensure that we read one extra new line
// to know that the block is complete. In the latter, we can execute as soon as the statement is
// valid.
let mut continuing_block = false;
let mut continuing_line = false;
loop {
let prompt_name = if continuing_block || continuing_line {
"ps2"
} else {
"ps1"
};
let prompt = vm
.sys_module
.get_attr(prompt_name, vm)
.and_then(|prompt| prompt.str(vm));
let prompt = match prompt {
Ok(ref s) => s.as_str(),
Err(_) => "",
};
continuing_line = false;
let result = match repl.readline(prompt) {
ReadlineResult::Line(line) => {
#[cfg(debug_assertions)]
debug!("You entered {line:?}");
repl.add_history_entry(line.trim_end()).unwrap();
let empty_line_given = line.is_empty();
if full_input.is_empty() {
full_input = line;
} else {
full_input.push_str(&line);
}
full_input.push('\n');
match shell_exec(
vm,
&full_input,
scope.clone(),
empty_line_given,
continuing_block,
) {
ShellExecResult::Ok => {
if continuing_block {
if empty_line_given {
// We should exit continue mode since the block successfully executed
continuing_block = false;
full_input.clear();
}
} else {
// We aren't in continue mode so proceed normally
full_input.clear();
}
Ok(())
}
// Continue, but don't change the mode
ShellExecResult::ContinueLine => {
continuing_line = true;
Ok(())
}
ShellExecResult::ContinueBlock => {
continuing_block = true;
Ok(())
}
ShellExecResult::PyErr(err) => {
continuing_block = false;
full_input.clear();
Err(err)
}
}
}
ReadlineResult::Interrupt => {
continuing_block = false;
full_input.clear();
let keyboard_interrupt =
vm.new_exception_empty(vm.ctx.exceptions.keyboard_interrupt.to_owned());
Err(keyboard_interrupt)
}
ReadlineResult::Eof => {
break;
}
#[cfg(unix)]
ReadlineResult::OsError(num) => {
let os_error =
vm.new_exception_msg(vm.ctx.exceptions.os_error.to_owned(), format!("{num:?}"));
vm.print_exception(os_error);
break;
}
ReadlineResult::Other(err) => {
eprintln!("Readline error: {err:?}");
break;
}
ReadlineResult::Io(err) => {
eprintln!("IO error: {err:?}");
break;
}
};
if let Err(exc) = result {
if exc.fast_isinstance(vm.ctx.exceptions.system_exit) {
repl.save_history(&repl_history_path).unwrap();
return Err(exc);
}
vm.print_exception(exc);
}
}
repl.save_history(&repl_history_path).unwrap();
Ok(())
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/src/interpreter.rs | src/interpreter.rs | use rustpython_vm::{Interpreter, PyRef, Settings, VirtualMachine, builtins::PyModule};
pub type InitHook = Box<dyn FnOnce(&mut VirtualMachine)>;
/// The convenient way to create [rustpython_vm::Interpreter] with stdlib and other stuffs.
///
/// Basic usage:
/// ```
/// let interpreter = rustpython::InterpreterConfig::new()
/// .init_stdlib()
/// .interpreter();
/// ```
///
/// To override [rustpython_vm::Settings]:
/// ```
/// use rustpython_vm::Settings;
/// // Override your settings here.
/// let mut settings = Settings::default();
/// settings.debug = 1;
/// // You may want to add paths to `rustpython_vm::Settings::path_list` to allow import python libraries.
/// settings.path_list.push("Lib".to_owned()); // add standard library directory
/// settings.path_list.push("".to_owned()); // add current working directory
/// let interpreter = rustpython::InterpreterConfig::new()
/// .settings(settings)
/// .interpreter();
/// ```
///
/// To add native modules:
/// ```
/// use rustpython_vm::pymodule;
///
/// #[pymodule]
/// mod your_module {}
///
/// let interpreter = rustpython::InterpreterConfig::new()
/// .init_stdlib()
/// .add_native_module(
/// "your_module_name".to_owned(),
/// your_module::make_module,
/// )
/// .interpreter();
/// ```
#[derive(Default)]
pub struct InterpreterConfig {
settings: Option<Settings>,
init_hooks: Vec<InitHook>,
}
impl InterpreterConfig {
/// Creates a new interpreter configuration with default settings.
pub fn new() -> Self {
Self::default()
}
/// Builds the interpreter with the current configuration.
pub fn interpreter(self) -> Interpreter {
let settings = self.settings.unwrap_or_default();
Interpreter::with_init(settings, |vm| {
for hook in self.init_hooks {
hook(vm);
}
})
}
/// Sets custom settings for the interpreter.
///
/// If called multiple times, only the last settings will be used.
pub fn settings(mut self, settings: Settings) -> Self {
self.settings = Some(settings);
self
}
/// Adds a custom initialization hook.
///
/// Hooks are executed in the order they are added during interpreter creation.
pub fn init_hook(mut self, hook: InitHook) -> Self {
self.init_hooks.push(hook);
self
}
/// Adds a native module to the interpreter.
pub fn add_native_module(
self,
name: String,
make_module: fn(&VirtualMachine) -> PyRef<PyModule>,
) -> Self {
self.init_hook(Box::new(move |vm| {
vm.add_native_module(name, Box::new(make_module))
}))
}
/// Initializes the Python standard library.
///
/// Requires the `stdlib` feature to be enabled.
#[cfg(feature = "stdlib")]
pub fn init_stdlib(self) -> Self {
self.init_hook(Box::new(init_stdlib))
}
}
/// Initializes all standard library modules for the given VM.
#[cfg(feature = "stdlib")]
pub fn init_stdlib(vm: &mut VirtualMachine) {
vm.add_native_modules(rustpython_stdlib::get_module_inits());
#[cfg(feature = "freeze-stdlib")]
setup_frozen_stdlib(vm);
#[cfg(not(feature = "freeze-stdlib"))]
setup_dynamic_stdlib(vm);
}
/// Setup frozen standard library (compiled into the binary)
#[cfg(all(feature = "stdlib", feature = "freeze-stdlib"))]
fn setup_frozen_stdlib(vm: &mut VirtualMachine) {
vm.add_frozen(rustpython_pylib::FROZEN_STDLIB);
// FIXME: Remove this hack once sys._stdlib_dir is properly implemented
// or _frozen_importlib doesn't depend on it anymore.
assert!(vm.sys_module.get_attr("_stdlib_dir", vm).is_err());
vm.sys_module
.set_attr(
"_stdlib_dir",
vm.new_pyobj(rustpython_pylib::LIB_PATH.to_owned()),
vm,
)
.unwrap();
}
/// Setup dynamic standard library loading from filesystem
#[cfg(all(feature = "stdlib", not(feature = "freeze-stdlib")))]
fn setup_dynamic_stdlib(vm: &mut VirtualMachine) {
use rustpython_vm::common::rc::PyRc;
let state = PyRc::get_mut(&mut vm.state).unwrap();
let paths = collect_stdlib_paths();
// Insert at the beginning so stdlib comes before user paths
for path in paths.into_iter().rev() {
state.config.paths.module_search_paths.insert(0, path);
}
}
/// Collect standard library paths from build-time configuration
#[cfg(all(feature = "stdlib", not(feature = "freeze-stdlib")))]
fn collect_stdlib_paths() -> Vec<String> {
// BUILDTIME_RUSTPYTHONPATH should be set when distributing
if let Some(paths) = option_env!("BUILDTIME_RUSTPYTHONPATH") {
crate::settings::split_paths(paths)
.map(|path| path.into_os_string().into_string().unwrap())
.collect()
} else {
#[cfg(feature = "rustpython-pylib")]
{
vec![rustpython_pylib::LIB_PATH.to_owned()]
}
#[cfg(not(feature = "rustpython-pylib"))]
{
vec![]
}
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/src/main.rs | src/main.rs | pub fn main() -> std::process::ExitCode {
rustpython::run(|_vm| {})
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/src/shell/helper.rs | src/shell/helper.rs | #![cfg_attr(target_arch = "wasm32", allow(dead_code))]
use rustpython_vm::{
AsObject, PyResult, TryFromObject, VirtualMachine,
builtins::{PyDictRef, PyStrRef},
function::ArgIterable,
identifier,
};
pub struct ShellHelper<'vm> {
vm: &'vm VirtualMachine,
globals: PyDictRef,
}
fn reverse_string(s: &mut String) {
let rev = s.chars().rev().collect();
*s = rev;
}
fn split_idents_on_dot(line: &str) -> Option<(usize, Vec<String>)> {
let mut words = vec![String::new()];
let mut startpos = 0;
for (i, c) in line.chars().rev().enumerate() {
match c {
'.' => {
// check for a double dot
if i != 0 && words.last().is_some_and(|s| s.is_empty()) {
return None;
}
reverse_string(words.last_mut().unwrap());
if words.len() == 1 {
startpos = line.len() - i;
}
words.push(String::new());
}
c if c.is_alphanumeric() || c == '_' => words.last_mut().unwrap().push(c),
_ => {
if words.len() == 1 {
if words.last().unwrap().is_empty() {
return None;
}
startpos = line.len() - i;
}
break;
}
}
}
if words == [String::new()] {
return None;
}
reverse_string(words.last_mut().unwrap());
words.reverse();
Some((startpos, words))
}
impl<'vm> ShellHelper<'vm> {
pub const fn new(vm: &'vm VirtualMachine, globals: PyDictRef) -> Self {
ShellHelper { vm, globals }
}
fn get_available_completions<'w>(
&self,
words: &'w [String],
) -> Option<(&'w str, impl Iterator<Item = PyResult<PyStrRef>> + 'vm)> {
// the very first word and then all the ones after the dot
let (first, rest) = words.split_first().unwrap();
let str_iter_method = |obj, name| {
let iter = self.vm.call_special_method(obj, name, ())?;
ArgIterable::<PyStrRef>::try_from_object(self.vm, iter)?.iter(self.vm)
};
let (word_start, iter1, iter2) = if let Some((last, parents)) = rest.split_last() {
// we need to get an attribute based off of the dir() of an object
// last: the last word, could be empty if it ends with a dot
// parents: the words before the dot
let mut current = self.globals.get_item_opt(first.as_str(), self.vm).ok()??;
for attr in parents {
let attr = self.vm.ctx.new_str(attr.as_str());
current = current.get_attr(&attr, self.vm).ok()?;
}
let current_iter = str_iter_method(¤t, identifier!(self.vm, __dir__)).ok()?;
(last, current_iter, None)
} else {
// we need to get a variable based off of globals/builtins
let globals =
str_iter_method(self.globals.as_object(), identifier!(self.vm, keys)).ok()?;
let builtins =
str_iter_method(self.vm.builtins.as_object(), identifier!(self.vm, __dir__))
.ok()?;
(first, globals, Some(builtins))
};
Some((word_start, iter1.chain(iter2.into_iter().flatten())))
}
fn complete_opt(&self, line: &str) -> Option<(usize, Vec<String>)> {
let (startpos, words) = split_idents_on_dot(line)?;
let (word_start, iter) = self.get_available_completions(&words)?;
let all_completions = iter
.filter(|res| {
res.as_ref()
.ok()
.is_none_or(|s| s.as_str().starts_with(word_start))
})
.collect::<Result<Vec<_>, _>>()
.ok()?;
let mut completions = if word_start.starts_with('_') {
// if they're already looking for something starting with a '_', just give
// them all the completions
all_completions
} else {
// only the completions that don't start with a '_'
let no_underscore = all_completions
.iter()
.filter(|&s| !s.as_str().starts_with('_'))
.cloned()
.collect::<Vec<_>>();
// if there are only completions that start with a '_', give them all of the
// completions, otherwise only the ones that don't start with '_'
if no_underscore.is_empty() {
all_completions
} else {
no_underscore
}
};
// sort the completions alphabetically
completions.sort_by(|a, b| std::cmp::Ord::cmp(a.as_str(), b.as_str()));
Some((
startpos,
completions
.into_iter()
.map(|s| s.as_str().to_owned())
.collect(),
))
}
}
cfg_if::cfg_if! {
if #[cfg(not(target_arch = "wasm32"))] {
use rustyline::{
completion::Completer, highlight::Highlighter, hint::Hinter, validate::Validator, Context,
Helper,
};
impl Completer for ShellHelper<'_> {
type Candidate = String;
fn complete(
&self,
line: &str,
pos: usize,
_ctx: &Context,
) -> rustyline::Result<(usize, Vec<String>)> {
Ok(self
.complete_opt(&line[0..pos])
// as far as I can tell, there's no better way to do both completion
// and indentation (or even just indentation)
.unwrap_or_else(|| (pos, vec!["\t".to_owned()])))
}
}
impl Hinter for ShellHelper<'_> {
type Hint = String;
}
impl Highlighter for ShellHelper<'_> {}
impl Validator for ShellHelper<'_> {}
impl Helper for ShellHelper<'_> {}
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/benches/microbenchmarks.rs | benches/microbenchmarks.rs | use criterion::{
BatchSize, BenchmarkGroup, BenchmarkId, Criterion, Throughput, criterion_group, criterion_main,
measurement::WallTime,
};
use pyo3::types::PyAnyMethods;
use rustpython_compiler::Mode;
use rustpython_vm::{AsObject, Interpreter, PyResult, Settings};
use std::{
fs, io,
path::{Path, PathBuf},
};
// List of microbenchmarks to skip.
//
// These result in excessive memory usage, some more so than others. For example, while
// exception_context.py consumes a lot of memory, it still finishes. On the other hand,
// call_kwargs.py seems like it performs an excessive amount of allocations and results in
// a system freeze.
// In addition, the fact that we don't yet have a GC means that benchmarks which might consume
// a bearable amount of memory accumulate. As such, best to skip them for now.
const SKIP_MICROBENCHMARKS: [&str; 8] = [
"call_simple.py",
"call_kwargs.py",
"construct_object.py",
"define_function.py",
"define_class.py",
"exception_nested.py",
"exception_simple.py",
"exception_context.py",
];
pub struct MicroBenchmark {
name: String,
setup: String,
code: String,
iterate: bool,
}
fn bench_cpython_code(group: &mut BenchmarkGroup<WallTime>, bench: &MicroBenchmark) {
pyo3::Python::attach(|py| {
let setup_name = format!("{}_setup", bench.name);
let setup_code = cpy_compile_code(py, &bench.setup, &setup_name).unwrap();
let code = cpy_compile_code(py, &bench.code, &bench.name).unwrap();
// Grab the exec function in advance so we don't have lookups in the hot code
let builtins =
pyo3::types::PyModule::import(py, "builtins").expect("Failed to import builtins");
let exec = builtins.getattr("exec").expect("no exec in builtins");
let bench_func = |(globals, locals): &mut (
pyo3::Bound<pyo3::types::PyDict>,
pyo3::Bound<pyo3::types::PyDict>,
)| {
let res = exec.call((&code, &*globals, &*locals), None);
if let Err(e) = res {
e.print(py);
panic!("Error running microbenchmark")
}
};
let bench_setup = |iterations| {
let globals = pyo3::types::PyDict::new(py);
let locals = pyo3::types::PyDict::new(py);
if let Some(idx) = iterations {
globals.set_item("ITERATIONS", idx).unwrap();
}
let res = exec.call((&setup_code, &globals, &locals), None);
if let Err(e) = res {
e.print(py);
panic!("Error running microbenchmark setup code")
}
(globals, locals)
};
if bench.iterate {
for idx in (100..=1_000).step_by(200) {
group.throughput(Throughput::Elements(idx as u64));
group.bench_with_input(BenchmarkId::new("cpython", &bench.name), &idx, |b, idx| {
b.iter_batched_ref(
|| bench_setup(Some(*idx)),
bench_func,
BatchSize::LargeInput,
);
});
}
} else {
group.bench_function(BenchmarkId::new("cpython", &bench.name), move |b| {
b.iter_batched_ref(|| bench_setup(None), bench_func, BatchSize::LargeInput);
});
}
})
}
fn cpy_compile_code<'a>(
py: pyo3::Python<'a>,
code: &str,
name: &str,
) -> pyo3::PyResult<pyo3::Bound<'a, pyo3::types::PyCode>> {
let builtins =
pyo3::types::PyModule::import(py, "builtins").expect("Failed to import builtins");
let compile = builtins.getattr("compile").expect("no compile in builtins");
Ok(compile
.call1((code, name, "exec"))?
.cast_into()
.expect("compile() should return a code object"))
}
fn bench_rustpython_code(group: &mut BenchmarkGroup<WallTime>, bench: &MicroBenchmark) {
let mut settings = Settings::default();
settings.path_list.push("Lib/".to_string());
settings.write_bytecode = false;
settings.user_site_directory = false;
Interpreter::with_init(settings, |vm| {
for (name, init) in rustpython_stdlib::get_module_inits() {
vm.add_native_module(name, init);
}
})
.enter(|vm| {
let setup_code = vm
.compile(&bench.setup, Mode::Exec, bench.name.to_owned())
.expect("Error compiling setup code");
let bench_code = vm
.compile(&bench.code, Mode::Exec, bench.name.to_owned())
.expect("Error compiling bench code");
let bench_func = |scope| {
let res: PyResult = vm.run_code_obj(bench_code.clone(), scope);
vm.unwrap_pyresult(res);
};
let bench_setup = |iterations| {
let scope = vm.new_scope_with_builtins();
if let Some(idx) = iterations {
scope
.locals
.as_object()
.set_item("ITERATIONS", vm.new_pyobj(idx), vm)
.expect("Error adding ITERATIONS local variable");
}
let setup_result = vm.run_code_obj(setup_code.clone(), scope.clone());
vm.unwrap_pyresult(setup_result);
scope
};
if bench.iterate {
for idx in (100..=1_000).step_by(200) {
group.throughput(Throughput::Elements(idx as u64));
group.bench_with_input(
BenchmarkId::new("rustpython", &bench.name),
&idx,
|b, idx| {
b.iter_batched(
|| bench_setup(Some(*idx)),
bench_func,
BatchSize::LargeInput,
);
},
);
}
} else {
group.bench_function(BenchmarkId::new("rustpython", &bench.name), move |b| {
b.iter_batched(|| bench_setup(None), bench_func, BatchSize::LargeInput);
});
}
})
}
pub fn run_micro_benchmark(c: &mut Criterion, benchmark: MicroBenchmark) {
let mut group = c.benchmark_group("microbenchmarks");
bench_cpython_code(&mut group, &benchmark);
bench_rustpython_code(&mut group, &benchmark);
group.finish();
}
pub fn criterion_benchmark(c: &mut Criterion) {
let benchmark_dir = Path::new("./benches/microbenchmarks/");
let dirs: Vec<fs::DirEntry> = benchmark_dir
.read_dir()
.unwrap()
.collect::<io::Result<_>>()
.unwrap();
let paths: Vec<PathBuf> = dirs.iter().map(|p| p.path()).collect();
let benchmarks: Vec<MicroBenchmark> = paths
.into_iter()
.map(|p| {
let name = p.file_name().unwrap().to_os_string();
let contents = fs::read_to_string(p).unwrap();
let iterate = contents.contains("ITERATIONS");
let (setup, code) = if contents.contains("# ---") {
let split: Vec<&str> = contents.splitn(2, "# ---").collect();
(split[0].to_string(), split[1].to_string())
} else {
("".to_string(), contents)
};
let name = name.into_string().unwrap();
MicroBenchmark {
name,
setup,
code,
iterate,
}
})
.collect();
for benchmark in benchmarks {
if SKIP_MICROBENCHMARKS.contains(&benchmark.name.as_str()) {
continue;
}
run_micro_benchmark(c, benchmark);
}
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/benches/execution.rs | benches/execution.rs | use criterion::{
Bencher, BenchmarkGroup, BenchmarkId, Criterion, Throughput, criterion_group, criterion_main,
measurement::WallTime,
};
use rustpython_compiler::Mode;
use rustpython_vm::{Interpreter, PyResult, Settings};
use std::{collections::HashMap, hint::black_box, path::Path};
fn bench_cpython_code(b: &mut Bencher, source: &str) {
let c_str_source_head = std::ffi::CString::new(source).unwrap();
let c_str_source = c_str_source_head.as_c_str();
pyo3::Python::attach(|py| {
b.iter(|| {
let module = pyo3::types::PyModule::from_code(py, c_str_source, c"", c"")
.expect("Error running source");
black_box(module);
})
})
}
fn bench_rustpython_code(b: &mut Bencher, name: &str, source: &str) {
// NOTE: Take long time.
let mut settings = Settings::default();
settings.path_list.push("Lib/".to_string());
settings.write_bytecode = false;
settings.user_site_directory = false;
Interpreter::without_stdlib(settings).enter(|vm| {
// Note: bench_cpython is both compiling and executing the code.
// As such we compile the code in the benchmark loop as well.
b.iter(|| {
let code = vm.compile(source, Mode::Exec, name.to_owned()).unwrap();
let scope = vm.new_scope_with_builtins();
let res: PyResult = vm.run_code_obj(code.clone(), scope);
vm.unwrap_pyresult(res);
})
})
}
pub fn benchmark_file_execution(group: &mut BenchmarkGroup<WallTime>, name: &str, contents: &str) {
group.bench_function(BenchmarkId::new(name, "cpython"), |b| {
bench_cpython_code(b, contents)
});
group.bench_function(BenchmarkId::new(name, "rustpython"), |b| {
bench_rustpython_code(b, name, contents)
});
}
pub fn benchmark_file_parsing(group: &mut BenchmarkGroup<WallTime>, name: &str, contents: &str) {
group.throughput(Throughput::Bytes(contents.len() as u64));
group.bench_function(BenchmarkId::new("rustpython", name), |b| {
b.iter(|| ruff_python_parser::parse_module(contents).unwrap())
});
group.bench_function(BenchmarkId::new("cpython", name), |b| {
use pyo3::types::PyAnyMethods;
pyo3::Python::attach(|py| {
let builtins =
pyo3::types::PyModule::import(py, "builtins").expect("Failed to import builtins");
let compile = builtins.getattr("compile").expect("no compile in builtins");
b.iter(|| {
let x = compile
.call1((contents, name, "exec"))
.expect("Failed to parse code");
black_box(x);
})
})
});
}
pub fn benchmark_pystone(group: &mut BenchmarkGroup<WallTime>, contents: String) {
// Default is 50_000. This takes a while, so reduce it to 30k.
for idx in (10_000..=30_000).step_by(10_000) {
let code_with_loops = format!("LOOPS = {idx}\n{contents}");
let code_str = code_with_loops.as_str();
group.throughput(Throughput::Elements(idx as u64));
group.bench_function(BenchmarkId::new("cpython", idx), |b| {
bench_cpython_code(b, code_str)
});
group.bench_function(BenchmarkId::new("rustpython", idx), |b| {
bench_rustpython_code(b, "pystone", code_str)
});
}
}
pub fn criterion_benchmark(c: &mut Criterion) {
let benchmark_dir = Path::new("./benches/benchmarks/");
let mut benches = benchmark_dir
.read_dir()
.unwrap()
.map(|entry| {
let path = entry.unwrap().path();
(
path.file_name().unwrap().to_str().unwrap().to_owned(),
std::fs::read_to_string(path).unwrap(),
)
})
.collect::<HashMap<_, _>>();
// Benchmark parsing
let mut parse_group = c.benchmark_group("parse_to_ast");
for (name, contents) in &benches {
benchmark_file_parsing(&mut parse_group, name, contents);
}
parse_group.finish();
// Benchmark PyStone
if let Some(pystone_contents) = benches.remove("pystone.py") {
let mut pystone_group = c.benchmark_group("pystone");
benchmark_pystone(&mut pystone_group, pystone_contents);
pystone_group.finish();
}
// Benchmark execution
let mut execution_group = c.benchmark_group("execution");
for (name, contents) in &benches {
benchmark_file_execution(&mut execution_group, name, contents);
}
execution_group.finish();
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/wtf8/src/lib.rs | crates/wtf8/src/lib.rs | // spell-checker:disable
//! An implementation of [WTF-8], a utf8-compatible encoding that allows for
//! unpaired surrogate codepoints. This implementation additionally allows for
//! paired surrogates that are nonetheless treated as two separate codepoints.
//!
//!
//! RustPython uses this because CPython internally uses a variant of UCS-1/2/4
//! as its string storage, which treats each `u8`/`u16`/`u32` value (depending
//! on the highest codepoint value in the string) as simply integers, unlike
//! UTF-8 or UTF-16 where some characters are encoded using multi-byte
//! sequences. CPython additionally doesn't disallow the use of surrogates in
//! `str`s (which in UTF-16 pair together to represent codepoints with a value
//! higher than `u16::MAX`) and in fact takes quite extensive advantage of the
//! fact that they're allowed. The `surrogateescape` codec-error handler uses
//! them to represent byte sequences which are invalid in the given codec (e.g.
//! bytes with their high bit set in ASCII or UTF-8) by mapping them into the
//! surrogate range. `surrogateescape` is the default error handler in Python
//! for interacting with the filesystem, and thus if RustPython is to properly
//! support `surrogateescape`, its `str`s must be able to represent surrogates.
//!
//! We use WTF-8 over something more similar to CPython's string implementation
//! because of its compatibility with UTF-8, meaning that in the case where a
//! string has no surrogates, it can be viewed as a UTF-8 Rust [`prim@str`] without
//! needing any copies or re-encoding.
//!
//! This implementation is mostly copied from the WTF-8 implementation in the
//! Rust 1.85 standard library, which is used as the backing for [`OsStr`] on
//! Windows targets. As previously mentioned, however, it is modified to not
//! join two surrogates into one codepoint when concatenating strings, in order
//! to match CPython's behavior.
//!
//! [WTF-8]: https://simonsapin.github.io/wtf-8
//! [`OsStr`]: std::ffi::OsStr
#![allow(clippy::precedence, clippy::match_overlapping_arm)]
use core::fmt;
use core::hash::{Hash, Hasher};
use core::iter::FusedIterator;
use core::mem;
use core::ops;
use core::slice;
use core::str;
use core_char::MAX_LEN_UTF8;
use core_char::{MAX_LEN_UTF16, encode_utf8_raw, encode_utf16_raw, len_utf8};
use core_str::{next_code_point, next_code_point_reverse};
use itertools::{Either, Itertools};
use std::borrow::{Borrow, Cow};
use std::collections::TryReserveError;
use std::string::String;
use std::vec::Vec;
use bstr::{ByteSlice, ByteVec};
mod core_char;
mod core_str;
mod core_str_count;
const UTF8_REPLACEMENT_CHARACTER: &str = "\u{FFFD}";
/// A Unicode code point: from U+0000 to U+10FFFF.
///
/// Compares with the `char` type,
/// which represents a Unicode scalar value:
/// a code point that is not a surrogate (U+D800 to U+DFFF).
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
pub struct CodePoint {
value: u32,
}
/// Format the code point as `U+` followed by four to six hexadecimal digits.
/// Example: `U+1F4A9`
impl fmt::Debug for CodePoint {
#[inline]
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "U+{:04X}", self.value)
}
}
impl fmt::Display for CodePoint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.to_char_lossy().fmt(f)
}
}
impl CodePoint {
/// Unsafely creates a new `CodePoint` without checking the value.
///
/// # Safety
///
/// `value` must be less than or equal to 0x10FFFF.
#[inline]
pub const unsafe fn from_u32_unchecked(value: u32) -> CodePoint {
CodePoint { value }
}
/// Creates a new `CodePoint` if the value is a valid code point.
///
/// Returns `None` if `value` is above 0x10FFFF.
#[inline]
pub const fn from_u32(value: u32) -> Option<CodePoint> {
match value {
0..=0x10FFFF => Some(CodePoint { value }),
_ => None,
}
}
/// Creates a new `CodePoint` from a `char`.
///
/// Since all Unicode scalar values are code points, this always succeeds.
#[inline]
pub const fn from_char(value: char) -> CodePoint {
CodePoint {
value: value as u32,
}
}
/// Returns the numeric value of the code point.
#[inline]
pub const fn to_u32(self) -> u32 {
self.value
}
/// Returns the numeric value of the code point if it is a leading surrogate.
#[inline]
pub const fn to_lead_surrogate(self) -> Option<LeadSurrogate> {
match self.value {
lead @ 0xD800..=0xDBFF => Some(LeadSurrogate(lead as u16)),
_ => None,
}
}
/// Returns the numeric value of the code point if it is a trailing surrogate.
#[inline]
pub const fn to_trail_surrogate(self) -> Option<TrailSurrogate> {
match self.value {
trail @ 0xDC00..=0xDFFF => Some(TrailSurrogate(trail as u16)),
_ => None,
}
}
/// Optionally returns a Unicode scalar value for the code point.
///
/// Returns `None` if the code point is a surrogate (from U+D800 to U+DFFF).
#[inline]
pub const fn to_char(self) -> Option<char> {
match self.value {
0xD800..=0xDFFF => None,
_ => Some(unsafe { char::from_u32_unchecked(self.value) }),
}
}
/// Returns a Unicode scalar value for the code point.
///
/// Returns `'\u{FFFD}'` (the replacement character “�”)
/// if the code point is a surrogate (from U+D800 to U+DFFF).
#[inline]
pub fn to_char_lossy(self) -> char {
self.to_char().unwrap_or('\u{FFFD}')
}
pub fn is_char_and(self, f: impl FnOnce(char) -> bool) -> bool {
self.to_char().is_some_and(f)
}
pub fn encode_wtf8(self, dst: &mut [u8]) -> &mut Wtf8 {
unsafe { Wtf8::from_mut_bytes_unchecked(encode_utf8_raw(self.value, dst)) }
}
pub const fn len_wtf8(&self) -> usize {
len_utf8(self.value)
}
pub fn is_ascii(&self) -> bool {
self.is_char_and(|c| c.is_ascii())
}
}
impl From<u16> for CodePoint {
fn from(value: u16) -> Self {
unsafe { Self::from_u32_unchecked(value.into()) }
}
}
impl From<u8> for CodePoint {
fn from(value: u8) -> Self {
char::from(value).into()
}
}
impl From<char> for CodePoint {
fn from(value: char) -> Self {
Self::from_char(value)
}
}
impl From<ascii::AsciiChar> for CodePoint {
fn from(value: ascii::AsciiChar) -> Self {
Self::from_char(value.into())
}
}
impl From<CodePoint> for Wtf8Buf {
fn from(ch: CodePoint) -> Self {
ch.encode_wtf8(&mut [0; MAX_LEN_UTF8]).to_owned()
}
}
impl PartialEq<char> for CodePoint {
fn eq(&self, other: &char) -> bool {
self.to_u32() == *other as u32
}
}
impl PartialEq<CodePoint> for char {
fn eq(&self, other: &CodePoint) -> bool {
*self as u32 == other.to_u32()
}
}
#[derive(Clone, Copy)]
pub struct LeadSurrogate(u16);
#[derive(Clone, Copy)]
pub struct TrailSurrogate(u16);
impl LeadSurrogate {
pub const fn merge(self, trail: TrailSurrogate) -> char {
decode_surrogate_pair(self.0, trail.0)
}
}
/// An owned, growable string of well-formed WTF-8 data.
///
/// Similar to `String`, but can additionally contain surrogate code points
/// if they’re not in a surrogate pair.
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Default)]
pub struct Wtf8Buf {
bytes: Vec<u8>,
}
impl ops::Deref for Wtf8Buf {
type Target = Wtf8;
fn deref(&self) -> &Wtf8 {
self.as_slice()
}
}
impl ops::DerefMut for Wtf8Buf {
fn deref_mut(&mut self) -> &mut Wtf8 {
self.as_mut_slice()
}
}
impl Borrow<Wtf8> for Wtf8Buf {
fn borrow(&self) -> &Wtf8 {
self
}
}
/// Formats the string in double quotes, with characters escaped according to
/// [`char::escape_debug`] and unpaired surrogates represented as `\u{xxxx}`,
/// where each `x` is a hexadecimal digit.
///
/// For example, the code units [U+0061, U+D800, U+000A] are formatted as
/// `"a\u{D800}\n"`.
impl fmt::Debug for Wtf8Buf {
#[inline]
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, formatter)
}
}
/// Formats the string with unpaired surrogates substituted with the replacement
/// character, U+FFFD.
impl fmt::Display for Wtf8Buf {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, formatter)
}
}
impl Wtf8Buf {
/// Creates a new, empty WTF-8 string.
#[inline]
pub fn new() -> Wtf8Buf {
Wtf8Buf::default()
}
/// Creates a new, empty WTF-8 string with pre-allocated capacity for `capacity` bytes.
#[inline]
pub fn with_capacity(capacity: usize) -> Wtf8Buf {
Wtf8Buf {
bytes: Vec::with_capacity(capacity),
}
}
/// Creates a WTF-8 string from a WTF-8 byte vec.
///
/// # Safety
///
/// `value` must contain valid WTF-8.
#[inline]
pub const unsafe fn from_bytes_unchecked(value: Vec<u8>) -> Wtf8Buf {
Wtf8Buf { bytes: value }
}
/// Create a WTF-8 string from a WTF-8 byte vec.
pub fn from_bytes(value: Vec<u8>) -> Result<Self, Vec<u8>> {
match Wtf8::from_bytes(&value) {
Some(_) => Ok(unsafe { Self::from_bytes_unchecked(value) }),
None => Err(value),
}
}
/// Creates a WTF-8 string from a UTF-8 `String`.
///
/// This takes ownership of the `String` and does not copy.
///
/// Since WTF-8 is a superset of UTF-8, this always succeeds.
#[inline]
pub fn from_string(string: String) -> Wtf8Buf {
Wtf8Buf {
bytes: string.into_bytes(),
}
}
pub fn clear(&mut self) {
self.bytes.clear();
}
/// Creates a WTF-8 string from a potentially ill-formed UTF-16 slice of 16-bit code units.
///
/// This is lossless: calling `.encode_wide()` on the resulting string
/// will always return the original code units.
pub fn from_wide(v: &[u16]) -> Wtf8Buf {
let mut string = Wtf8Buf::with_capacity(v.len());
for item in char::decode_utf16(v.iter().cloned()) {
match item {
Ok(ch) => string.push_char(ch),
Err(surrogate) => {
let surrogate = surrogate.unpaired_surrogate();
// Surrogates are known to be in the code point range.
let code_point = CodePoint::from(surrogate);
// Skip the WTF-8 concatenation check,
// surrogate pairs are already decoded by decode_utf16
string.push(code_point);
}
}
}
string
}
#[inline]
pub fn as_slice(&self) -> &Wtf8 {
unsafe { Wtf8::from_bytes_unchecked(&self.bytes) }
}
#[inline]
pub fn as_mut_slice(&mut self) -> &mut Wtf8 {
// Safety: `Wtf8` doesn't expose any way to mutate the bytes that would
// cause them to change from well-formed UTF-8 to ill-formed UTF-8,
// which would break the assumptions of the `is_known_utf8` field.
unsafe { Wtf8::from_mut_bytes_unchecked(&mut self.bytes) }
}
/// Reserves capacity for at least `additional` more bytes to be inserted
/// in the given `Wtf8Buf`.
/// The collection may reserve more space to avoid frequent reallocations.
///
/// # Panics
///
/// Panics if the new capacity exceeds `isize::MAX` bytes.
#[inline]
pub fn reserve(&mut self, additional: usize) {
self.bytes.reserve(additional)
}
/// Tries to reserve capacity for at least `additional` more bytes to be
/// inserted in the given `Wtf8Buf`. The `Wtf8Buf` may reserve more space to
/// avoid frequent reallocations. After calling `try_reserve`, capacity will
/// be greater than or equal to `self.len() + additional`. Does nothing if
/// capacity is already sufficient. This method preserves the contents even
/// if an error occurs.
///
/// # Errors
///
/// If the capacity overflows, or the allocator reports a failure, then an error
/// is returned.
#[inline]
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.bytes.try_reserve(additional)
}
#[inline]
pub fn reserve_exact(&mut self, additional: usize) {
self.bytes.reserve_exact(additional)
}
/// Tries to reserve the minimum capacity for exactly `additional` more
/// bytes to be inserted in the given `Wtf8Buf`. After calling
/// `try_reserve_exact`, capacity will be greater than or equal to
/// `self.len() + additional` if it returns `Ok(())`.
/// Does nothing if the capacity is already sufficient.
///
/// Note that the allocator may give the `Wtf8Buf` more space than it
/// requests. Therefore, capacity can not be relied upon to be precisely
/// minimal. Prefer [`try_reserve`] if future insertions are expected.
///
/// [`try_reserve`]: Wtf8Buf::try_reserve
///
/// # Errors
///
/// If the capacity overflows, or the allocator reports a failure, then an error
/// is returned.
#[inline]
pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.bytes.try_reserve_exact(additional)
}
#[inline]
pub fn shrink_to_fit(&mut self) {
self.bytes.shrink_to_fit()
}
#[inline]
pub fn shrink_to(&mut self, min_capacity: usize) {
self.bytes.shrink_to(min_capacity)
}
#[inline]
pub fn leak<'a>(self) -> &'a mut Wtf8 {
unsafe { Wtf8::from_mut_bytes_unchecked(self.bytes.leak()) }
}
/// Returns the number of bytes that this string buffer can hold without reallocating.
#[inline]
pub const fn capacity(&self) -> usize {
self.bytes.capacity()
}
/// Append a UTF-8 slice at the end of the string.
#[inline]
pub fn push_str(&mut self, other: &str) {
self.bytes.extend_from_slice(other.as_bytes())
}
/// Append a WTF-8 slice at the end of the string.
#[inline]
pub fn push_wtf8(&mut self, other: &Wtf8) {
self.bytes.extend_from_slice(&other.bytes);
}
/// Append a Unicode scalar value at the end of the string.
#[inline]
pub fn push_char(&mut self, c: char) {
self.push(CodePoint::from_char(c))
}
/// Append a code point at the end of the string.
#[inline]
pub fn push(&mut self, code_point: CodePoint) {
self.push_wtf8(code_point.encode_wtf8(&mut [0; MAX_LEN_UTF8]))
}
pub fn pop(&mut self) -> Option<CodePoint> {
let ch = self.code_points().next_back()?;
let new_len = self.len() - ch.len_wtf8();
self.bytes.truncate(new_len);
Some(ch)
}
/// Shortens a string to the specified length.
///
/// # Panics
///
/// Panics if `new_len` > current length,
/// or if `new_len` is not a code point boundary.
#[inline]
pub fn truncate(&mut self, new_len: usize) {
assert!(is_code_point_boundary(self, new_len));
self.bytes.truncate(new_len)
}
/// Inserts a codepoint into this `Wtf8Buf` at a byte position.
#[inline]
pub fn insert(&mut self, idx: usize, c: CodePoint) {
self.insert_wtf8(idx, c.encode_wtf8(&mut [0; MAX_LEN_UTF8]))
}
/// Inserts a WTF-8 slice into this `Wtf8Buf` at a byte position.
#[inline]
pub fn insert_wtf8(&mut self, idx: usize, w: &Wtf8) {
assert!(is_code_point_boundary(self, idx));
self.bytes.insert_str(idx, w)
}
/// Consumes the WTF-8 string and tries to convert it to a vec of bytes.
#[inline]
pub fn into_bytes(self) -> Vec<u8> {
self.bytes
}
/// Consumes the WTF-8 string and tries to convert it to UTF-8.
///
/// This does not copy the data.
///
/// If the contents are not well-formed UTF-8
/// (that is, if the string contains surrogates),
/// the original WTF-8 string is returned instead.
pub fn into_string(self) -> Result<String, Wtf8Buf> {
if self.is_utf8() {
Ok(unsafe { String::from_utf8_unchecked(self.bytes) })
} else {
Err(self)
}
}
/// Consumes the WTF-8 string and converts it lossily to UTF-8.
///
/// This does not copy the data (but may overwrite parts of it in place).
///
/// Surrogates are replaced with `"\u{FFFD}"` (the replacement character “�”)
pub fn into_string_lossy(mut self) -> String {
let mut pos = 0;
while let Some((surrogate_pos, _)) = self.next_surrogate(pos) {
pos = surrogate_pos + 3;
// Surrogates and the replacement character are all 3 bytes, so
// they can substituted in-place.
self.bytes[surrogate_pos..pos].copy_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes());
}
unsafe { String::from_utf8_unchecked(self.bytes) }
}
/// Converts this `Wtf8Buf` into a boxed `Wtf8`.
#[inline]
pub fn into_box(self) -> Box<Wtf8> {
// SAFETY: relies on `Wtf8` being `repr(transparent)`.
unsafe { mem::transmute(self.bytes.into_boxed_slice()) }
}
/// Converts a `Box<Wtf8>` into a `Wtf8Buf`.
pub fn from_box(boxed: Box<Wtf8>) -> Wtf8Buf {
let bytes: Box<[u8]> = unsafe { mem::transmute(boxed) };
Wtf8Buf {
bytes: bytes.into_vec(),
}
}
}
/// Creates a new WTF-8 string from an iterator of code points.
///
/// This replaces surrogate code point pairs with supplementary code points,
/// like concatenating ill-formed UTF-16 strings effectively would.
impl FromIterator<CodePoint> for Wtf8Buf {
fn from_iter<T: IntoIterator<Item = CodePoint>>(iter: T) -> Wtf8Buf {
let mut string = Wtf8Buf::new();
string.extend(iter);
string
}
}
/// Append code points from an iterator to the string.
///
/// This replaces surrogate code point pairs with supplementary code points,
/// like concatenating ill-formed UTF-16 strings effectively would.
impl Extend<CodePoint> for Wtf8Buf {
fn extend<T: IntoIterator<Item = CodePoint>>(&mut self, iter: T) {
let iterator = iter.into_iter();
let (low, _high) = iterator.size_hint();
// Lower bound of one byte per code point (ASCII only)
self.bytes.reserve(low);
iterator.for_each(move |code_point| self.push(code_point));
}
}
impl Extend<char> for Wtf8Buf {
fn extend<T: IntoIterator<Item = char>>(&mut self, iter: T) {
self.extend(iter.into_iter().map(CodePoint::from))
}
}
impl<W: AsRef<Wtf8>> Extend<W> for Wtf8Buf {
fn extend<T: IntoIterator<Item = W>>(&mut self, iter: T) {
iter.into_iter()
.for_each(move |w| self.push_wtf8(w.as_ref()));
}
}
impl<W: AsRef<Wtf8>> FromIterator<W> for Wtf8Buf {
fn from_iter<T: IntoIterator<Item = W>>(iter: T) -> Self {
let mut buf = Wtf8Buf::new();
iter.into_iter().for_each(|w| buf.push_wtf8(w.as_ref()));
buf
}
}
impl Hash for Wtf8Buf {
fn hash<H: Hasher>(&self, state: &mut H) {
Wtf8::hash(self, state)
}
}
impl AsRef<Wtf8> for Wtf8Buf {
fn as_ref(&self) -> &Wtf8 {
self
}
}
impl From<String> for Wtf8Buf {
fn from(s: String) -> Self {
Wtf8Buf::from_string(s)
}
}
impl From<&str> for Wtf8Buf {
fn from(s: &str) -> Self {
Wtf8Buf::from_string(s.to_owned())
}
}
impl From<ascii::AsciiString> for Wtf8Buf {
fn from(s: ascii::AsciiString) -> Self {
Wtf8Buf::from_string(s.into())
}
}
/// A borrowed slice of well-formed WTF-8 data.
///
/// Similar to `&str`, but can additionally contain surrogate code points
/// if they’re not in a surrogate pair.
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct Wtf8 {
bytes: [u8],
}
impl AsRef<Wtf8> for Wtf8 {
fn as_ref(&self) -> &Wtf8 {
self
}
}
impl ToOwned for Wtf8 {
type Owned = Wtf8Buf;
fn to_owned(&self) -> Self::Owned {
self.to_wtf8_buf()
}
fn clone_into(&self, buf: &mut Self::Owned) {
self.bytes.clone_into(&mut buf.bytes);
}
}
impl PartialEq<str> for Wtf8 {
fn eq(&self, other: &str) -> bool {
self.as_bytes().eq(other.as_bytes())
}
}
/// Formats the string in double quotes, with characters escaped according to
/// [`char::escape_debug`] and unpaired surrogates represented as `\u{xxxx}`,
/// where each `x` is a hexadecimal digit.
impl fmt::Debug for Wtf8 {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
fn write_str_escaped(f: &mut fmt::Formatter<'_>, s: &str) -> fmt::Result {
use std::fmt::Write;
for c in s.chars().flat_map(|c| c.escape_debug()) {
f.write_char(c)?
}
Ok(())
}
formatter.write_str("\"")?;
let mut pos = 0;
while let Some((surrogate_pos, surrogate)) = self.next_surrogate(pos) {
write_str_escaped(formatter, unsafe {
str::from_utf8_unchecked(&self.bytes[pos..surrogate_pos])
})?;
write!(formatter, "\\u{{{surrogate:x}}}")?;
pos = surrogate_pos + 3;
}
write_str_escaped(formatter, unsafe {
str::from_utf8_unchecked(&self.bytes[pos..])
})?;
formatter.write_str("\"")
}
}
/// Formats the string with unpaired surrogates substituted with the replacement
/// character, U+FFFD.
impl fmt::Display for Wtf8 {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let wtf8_bytes = &self.bytes;
let mut pos = 0;
loop {
match self.next_surrogate(pos) {
Some((surrogate_pos, _)) => {
formatter.write_str(unsafe {
str::from_utf8_unchecked(&wtf8_bytes[pos..surrogate_pos])
})?;
formatter.write_str(UTF8_REPLACEMENT_CHARACTER)?;
pos = surrogate_pos + 3;
}
None => {
let s = unsafe { str::from_utf8_unchecked(&wtf8_bytes[pos..]) };
if pos == 0 {
return s.fmt(formatter);
} else {
return formatter.write_str(s);
}
}
}
}
}
}
impl Default for &Wtf8 {
fn default() -> Self {
unsafe { Wtf8::from_bytes_unchecked(&[]) }
}
}
impl Hash for Wtf8 {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write(self.as_bytes());
state.write_u8(0xff);
}
}
impl Wtf8 {
/// Creates a WTF-8 slice from a UTF-8 `&str` slice.
///
/// Since WTF-8 is a superset of UTF-8, this always succeeds.
#[inline]
pub fn new<S: AsRef<Wtf8> + ?Sized>(value: &S) -> &Wtf8 {
value.as_ref()
}
/// Creates a WTF-8 slice from a WTF-8 byte slice.
///
/// # Safety
///
/// `value` must contain valid WTF-8.
#[inline]
pub const unsafe fn from_bytes_unchecked(value: &[u8]) -> &Wtf8 {
// SAFETY: start with &[u8], end with fancy &[u8]
unsafe { &*(value as *const [u8] as *const Wtf8) }
}
/// Creates a mutable WTF-8 slice from a mutable WTF-8 byte slice.
///
/// Since the byte slice is not checked for valid WTF-8, this functions is
/// marked unsafe.
#[inline]
const unsafe fn from_mut_bytes_unchecked(value: &mut [u8]) -> &mut Wtf8 {
// SAFETY: start with &mut [u8], end with fancy &mut [u8]
unsafe { &mut *(value as *mut [u8] as *mut Wtf8) }
}
/// Create a WTF-8 slice from a WTF-8 byte slice.
//
// whoops! using WTF-8 for interchange!
#[inline]
pub fn from_bytes(b: &[u8]) -> Option<&Self> {
let mut rest = b;
while let Err(e) = std::str::from_utf8(rest) {
rest = &rest[e.valid_up_to()..];
let _ = Self::decode_surrogate(rest)?;
rest = &rest[3..];
}
Some(unsafe { Wtf8::from_bytes_unchecked(b) })
}
fn decode_surrogate(b: &[u8]) -> Option<CodePoint> {
let [0xed, b2 @ (0xa0..), b3, ..] = *b else {
return None;
};
Some(decode_surrogate(b2, b3).into())
}
/// Returns the length, in WTF-8 bytes.
#[inline]
pub const fn len(&self) -> usize {
self.bytes.len()
}
#[inline]
pub const fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
/// Returns the code point at `position` if it is in the ASCII range,
/// or `b'\xFF'` otherwise.
///
/// # Panics
///
/// Panics if `position` is beyond the end of the string.
#[inline]
pub const fn ascii_byte_at(&self, position: usize) -> u8 {
match self.bytes[position] {
ascii_byte @ 0x00..=0x7F => ascii_byte,
_ => 0xFF,
}
}
/// Returns an iterator for the string’s code points.
#[inline]
pub fn code_points(&self) -> Wtf8CodePoints<'_> {
Wtf8CodePoints {
bytes: self.bytes.iter(),
}
}
/// Returns an iterator for the string’s code points and their indices.
#[inline]
pub fn code_point_indices(&self) -> Wtf8CodePointIndices<'_> {
Wtf8CodePointIndices {
front_offset: 0,
iter: self.code_points(),
}
}
/// Access raw bytes of WTF-8 data
#[inline]
pub const fn as_bytes(&self) -> &[u8] {
&self.bytes
}
/// Tries to convert the string to UTF-8 and return a `&str` slice.
///
/// Returns `None` if the string contains surrogates.
///
/// This does not copy the data.
#[inline]
pub const fn as_str(&self) -> Result<&str, str::Utf8Error> {
str::from_utf8(&self.bytes)
}
/// Creates an owned `Wtf8Buf` from a borrowed `Wtf8`.
pub fn to_wtf8_buf(&self) -> Wtf8Buf {
Wtf8Buf {
bytes: self.bytes.to_vec(),
}
}
/// Lossily converts the string to UTF-8.
/// Returns a UTF-8 `&str` slice if the contents are well-formed in UTF-8.
///
/// Surrogates are replaced with `"\u{FFFD}"` (the replacement character “�”).
///
/// This only copies the data if necessary (if it contains any surrogate).
pub fn to_string_lossy(&self) -> Cow<'_, str> {
let Some((surrogate_pos, _)) = self.next_surrogate(0) else {
return Cow::Borrowed(unsafe { str::from_utf8_unchecked(&self.bytes) });
};
let wtf8_bytes = &self.bytes;
let mut utf8_bytes = Vec::with_capacity(self.len());
utf8_bytes.extend_from_slice(&wtf8_bytes[..surrogate_pos]);
utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes());
let mut pos = surrogate_pos + 3;
loop {
match self.next_surrogate(pos) {
Some((surrogate_pos, _)) => {
utf8_bytes.extend_from_slice(&wtf8_bytes[pos..surrogate_pos]);
utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes());
pos = surrogate_pos + 3;
}
None => {
utf8_bytes.extend_from_slice(&wtf8_bytes[pos..]);
return Cow::Owned(unsafe { String::from_utf8_unchecked(utf8_bytes) });
}
}
}
}
/// Converts the WTF-8 string to potentially ill-formed UTF-16
/// and return an iterator of 16-bit code units.
///
/// This is lossless:
/// calling `Wtf8Buf::from_ill_formed_utf16` on the resulting code units
/// would always return the original WTF-8 string.
#[inline]
pub fn encode_wide(&self) -> EncodeWide<'_> {
EncodeWide {
code_points: self.code_points(),
extra: 0,
}
}
pub const fn chunks(&self) -> Wtf8Chunks<'_> {
Wtf8Chunks { wtf8: self }
}
pub fn map_utf8<'a, I>(&'a self, f: impl Fn(&'a str) -> I) -> impl Iterator<Item = CodePoint>
where
I: Iterator<Item = char>,
{
self.chunks().flat_map(move |chunk| match chunk {
Wtf8Chunk::Utf8(s) => Either::Left(f(s).map_into()),
Wtf8Chunk::Surrogate(c) => Either::Right(std::iter::once(c)),
})
}
#[inline]
fn next_surrogate(&self, mut pos: usize) -> Option<(usize, u16)> {
let mut iter = self.bytes[pos..].iter();
loop {
let b = *iter.next()?;
if b < 0x80 {
pos += 1;
} else if b < 0xE0 {
iter.next();
pos += 2;
} else if b == 0xED {
match (iter.next(), iter.next()) {
(Some(&b2), Some(&b3)) if b2 >= 0xA0 => {
return Some((pos, decode_surrogate(b2, b3)));
}
_ => pos += 3,
}
} else if b < 0xF0 {
iter.next();
iter.next();
pos += 3;
} else {
iter.next();
iter.next();
iter.next();
pos += 4;
}
}
}
pub fn is_code_point_boundary(&self, index: usize) -> bool {
is_code_point_boundary(self, index)
}
/// Boxes this `Wtf8`.
#[inline]
pub fn into_box(&self) -> Box<Wtf8> {
let boxed: Box<[u8]> = self.bytes.into();
unsafe { mem::transmute(boxed) }
}
/// Creates a boxed, empty `Wtf8`.
pub fn empty_box() -> Box<Wtf8> {
let boxed: Box<[u8]> = Default::default();
unsafe { mem::transmute(boxed) }
}
#[inline]
pub fn make_ascii_lowercase(&mut self) {
self.bytes.make_ascii_lowercase()
}
#[inline]
pub fn make_ascii_uppercase(&mut self) {
self.bytes.make_ascii_uppercase()
}
#[inline]
pub fn to_ascii_lowercase(&self) -> Wtf8Buf {
Wtf8Buf {
bytes: self.bytes.to_ascii_lowercase(),
}
}
#[inline]
pub fn to_ascii_uppercase(&self) -> Wtf8Buf {
Wtf8Buf {
bytes: self.bytes.to_ascii_uppercase(),
}
}
#[inline]
pub const fn is_ascii(&self) -> bool {
self.bytes.is_ascii()
}
#[inline]
pub fn is_utf8(&self) -> bool {
self.next_surrogate(0).is_none()
}
#[inline]
pub fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
self.bytes.eq_ignore_ascii_case(&other.bytes)
}
pub fn split(&self, pat: &Wtf8) -> impl Iterator<Item = &Self> {
self.as_bytes()
.split_str(pat)
.map(|w| unsafe { Wtf8::from_bytes_unchecked(w) })
}
pub fn splitn(&self, n: usize, pat: &Wtf8) -> impl Iterator<Item = &Self> {
self.as_bytes()
.splitn_str(n, pat)
.map(|w| unsafe { Wtf8::from_bytes_unchecked(w) })
}
pub fn rsplit(&self, pat: &Wtf8) -> impl Iterator<Item = &Self> {
self.as_bytes()
.rsplit_str(pat)
.map(|w| unsafe { Wtf8::from_bytes_unchecked(w) })
}
pub fn rsplitn(&self, n: usize, pat: &Wtf8) -> impl Iterator<Item = &Self> {
self.as_bytes()
.rsplitn_str(n, pat)
.map(|w| unsafe { Wtf8::from_bytes_unchecked(w) })
}
pub fn trim(&self) -> &Self {
let w = self.bytes.trim();
unsafe { Wtf8::from_bytes_unchecked(w) }
}
pub fn trim_start(&self) -> &Self {
let w = self.bytes.trim_start();
unsafe { Wtf8::from_bytes_unchecked(w) }
}
pub fn trim_end(&self) -> &Self {
let w = self.bytes.trim_end();
unsafe { Wtf8::from_bytes_unchecked(w) }
}
pub fn trim_start_matches(&self, f: impl Fn(CodePoint) -> bool) -> &Self {
let mut iter = self.code_points();
loop {
let old = iter.clone();
match iter.next().map(&f) {
Some(true) => continue,
Some(false) => {
iter = old;
break;
}
None => return iter.as_wtf8(),
}
}
iter.as_wtf8()
}
pub fn trim_end_matches(&self, f: impl Fn(CodePoint) -> bool) -> &Self {
let mut iter = self.code_points();
loop {
let old = iter.clone();
match iter.next_back().map(&f) {
Some(true) => continue,
Some(false) => {
iter = old;
break;
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | true |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/wtf8/src/core_char.rs | crates/wtf8/src/core_char.rs | // spell-checker:disable
//! Unstable functions from [`core::char`]
use core::slice;
pub const MAX_LEN_UTF8: usize = 4;
pub const MAX_LEN_UTF16: usize = 2;
// UTF-8 ranges and tags for encoding characters
const TAG_CONT: u8 = 0b1000_0000;
const TAG_TWO_B: u8 = 0b1100_0000;
const TAG_THREE_B: u8 = 0b1110_0000;
const TAG_FOUR_B: u8 = 0b1111_0000;
const MAX_ONE_B: u32 = 0x80;
const MAX_TWO_B: u32 = 0x800;
const MAX_THREE_B: u32 = 0x10000;
#[inline]
#[must_use]
pub const fn len_utf8(code: u32) -> usize {
match code {
..MAX_ONE_B => 1,
..MAX_TWO_B => 2,
..MAX_THREE_B => 3,
_ => 4,
}
}
#[inline]
#[must_use]
const fn len_utf16(code: u32) -> usize {
if (code & 0xFFFF) == code { 1 } else { 2 }
}
/// Encodes a raw `u32` value as UTF-8 into the provided byte buffer,
/// and then returns the subslice of the buffer that contains the encoded character.
///
/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
/// (Creating a `char` in the surrogate range is UB.)
/// The result is valid [generalized UTF-8] but not valid UTF-8.
///
/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
///
/// # Panics
///
/// Panics if the buffer is not large enough.
/// A buffer of length four is large enough to encode any `char`.
#[doc(hidden)]
#[inline]
pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
let len = len_utf8(code);
match (len, &mut *dst) {
(1, [a, ..]) => {
*a = code as u8;
}
(2, [a, b, ..]) => {
*a = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
*b = (code & 0x3F) as u8 | TAG_CONT;
}
(3, [a, b, c, ..]) => {
*a = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
*b = (code >> 6 & 0x3F) as u8 | TAG_CONT;
*c = (code & 0x3F) as u8 | TAG_CONT;
}
(4, [a, b, c, d, ..]) => {
*a = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
*b = (code >> 12 & 0x3F) as u8 | TAG_CONT;
*c = (code >> 6 & 0x3F) as u8 | TAG_CONT;
*d = (code & 0x3F) as u8 | TAG_CONT;
}
_ => {
panic!(
"encode_utf8: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
dst_len = dst.len(),
)
}
};
// SAFETY: `<&mut [u8]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
}
/// Encodes a raw `u32` value as UTF-16 into the provided `u16` buffer,
/// and then returns the subslice of the buffer that contains the encoded character.
///
/// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
/// (Creating a `char` in the surrogate range is UB.)
///
/// # Panics
///
/// Panics if the buffer is not large enough.
/// A buffer of length 2 is large enough to encode any `char`.
#[doc(hidden)]
#[inline]
pub fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
let len = len_utf16(code);
match (len, &mut *dst) {
(1, [a, ..]) => {
*a = code as u16;
}
(2, [a, b, ..]) => {
code -= 0x1_0000;
*a = (code >> 10) as u16 | 0xD800;
*b = (code & 0x3FF) as u16 | 0xDC00;
}
_ => {
panic!(
"encode_utf16: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
dst_len = dst.len(),
)
}
};
// SAFETY: `<&mut [u16]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/wtf8/src/core_str_count.rs | crates/wtf8/src/core_str_count.rs | // spell-checker:disable
//! Modified from core::str::count
use super::Wtf8;
const USIZE_SIZE: usize = core::mem::size_of::<usize>();
const UNROLL_INNER: usize = 4;
#[inline]
pub(super) fn count_chars(s: &Wtf8) -> usize {
if s.len() < USIZE_SIZE * UNROLL_INNER {
// Avoid entering the optimized implementation for strings where the
// difference is not likely to matter, or where it might even be slower.
// That said, a ton of thought was not spent on the particular threshold
// here, beyond "this value seems to make sense".
char_count_general_case(s.as_bytes())
} else {
do_count_chars(s)
}
}
fn do_count_chars(s: &Wtf8) -> usize {
// For correctness, `CHUNK_SIZE` must be:
//
// - Less than or equal to 255, otherwise we'll overflow bytes in `counts`.
// - A multiple of `UNROLL_INNER`, otherwise our `break` inside the
// `body.chunks(CHUNK_SIZE)` loop is incorrect.
//
// For performance, `CHUNK_SIZE` should be:
// - Relatively cheap to `/` against (so some simple sum of powers of two).
// - Large enough to avoid paying for the cost of the `sum_bytes_in_usize`
// too often.
const CHUNK_SIZE: usize = 192;
// Check the properties of `CHUNK_SIZE` and `UNROLL_INNER` that are required
// for correctness.
const _: () = assert!(CHUNK_SIZE < 256);
const _: () = assert!(CHUNK_SIZE.is_multiple_of(UNROLL_INNER));
// SAFETY: transmuting `[u8]` to `[usize]` is safe except for size
// differences which are handled by `align_to`.
let (head, body, tail) = unsafe { s.as_bytes().align_to::<usize>() };
// This should be quite rare, and basically exists to handle the degenerate
// cases where align_to fails (as well as miri under symbolic alignment
// mode).
//
// The `unlikely` helps discourage LLVM from inlining the body, which is
// nice, as we would rather not mark the `char_count_general_case` function
// as cold.
if unlikely(body.is_empty() || head.len() > USIZE_SIZE || tail.len() > USIZE_SIZE) {
return char_count_general_case(s.as_bytes());
}
let mut total = char_count_general_case(head) + char_count_general_case(tail);
// Split `body` into `CHUNK_SIZE` chunks to reduce the frequency with which
// we call `sum_bytes_in_usize`.
for chunk in body.chunks(CHUNK_SIZE) {
// We accumulate intermediate sums in `counts`, where each byte contains
// a subset of the sum of this chunk, like a `[u8; size_of::<usize>()]`.
let mut counts = 0;
let (unrolled_chunks, remainder) = slice_as_chunks::<_, UNROLL_INNER>(chunk);
for unrolled in unrolled_chunks {
for &word in unrolled {
// Because `CHUNK_SIZE` is < 256, this addition can't cause the
// count in any of the bytes to overflow into a subsequent byte.
counts += contains_non_continuation_byte(word);
}
}
// Sum the values in `counts` (which, again, is conceptually a `[u8;
// size_of::<usize>()]`), and accumulate the result into `total`.
total += sum_bytes_in_usize(counts);
// If there's any data in `remainder`, then handle it. This will only
// happen for the last `chunk` in `body.chunks()` (because `CHUNK_SIZE`
// is divisible by `UNROLL_INNER`), so we explicitly break at the end
// (which seems to help LLVM out).
if !remainder.is_empty() {
// Accumulate all the data in the remainder.
let mut counts = 0;
for &word in remainder {
counts += contains_non_continuation_byte(word);
}
total += sum_bytes_in_usize(counts);
break;
}
}
total
}
// Checks each byte of `w` to see if it contains the first byte in a UTF-8
// sequence. Bytes in `w` which are continuation bytes are left as `0x00` (e.g.
// false), and bytes which are non-continuation bytes are left as `0x01` (e.g.
// true)
#[inline]
fn contains_non_continuation_byte(w: usize) -> usize {
const LSB: usize = usize_repeat_u8(0x01);
((!w >> 7) | (w >> 6)) & LSB
}
// Morally equivalent to `values.to_ne_bytes().into_iter().sum::<usize>()`, but
// more efficient.
#[inline]
fn sum_bytes_in_usize(values: usize) -> usize {
const LSB_SHORTS: usize = usize_repeat_u16(0x0001);
const SKIP_BYTES: usize = usize_repeat_u16(0x00ff);
let pair_sum: usize = (values & SKIP_BYTES) + ((values >> 8) & SKIP_BYTES);
pair_sum.wrapping_mul(LSB_SHORTS) >> ((USIZE_SIZE - 2) * 8)
}
// This is the most direct implementation of the concept of "count the number of
// bytes in the string which are not continuation bytes", and is used for the
// head and tail of the input string (the first and last item in the tuple
// returned by `slice::align_to`).
fn char_count_general_case(s: &[u8]) -> usize {
s.iter()
.filter(|&&byte| !super::core_str::utf8_is_cont_byte(byte))
.count()
}
// polyfills of unstable library features
const fn usize_repeat_u8(x: u8) -> usize {
usize::from_ne_bytes([x; size_of::<usize>()])
}
const fn usize_repeat_u16(x: u16) -> usize {
let mut r = 0usize;
let mut i = 0;
while i < size_of::<usize>() {
// Use `wrapping_shl` to make it work on targets with 16-bit `usize`
r = r.wrapping_shl(16) | (x as usize);
i += 2;
}
r
}
fn slice_as_chunks<T, const N: usize>(slice: &[T]) -> (&[[T; N]], &[T]) {
assert!(N != 0, "chunk size must be non-zero");
let len_rounded_down = slice.len() / N * N;
// SAFETY: The rounded-down value is always the same or smaller than the
// original length, and thus must be in-bounds of the slice.
let (multiple_of_n, remainder) = unsafe { slice.split_at_unchecked(len_rounded_down) };
// SAFETY: We already panicked for zero, and ensured by construction
// that the length of the subslice is a multiple of N.
let array_slice = unsafe { slice_as_chunks_unchecked(multiple_of_n) };
(array_slice, remainder)
}
unsafe fn slice_as_chunks_unchecked<T, const N: usize>(slice: &[T]) -> &[[T; N]] {
let new_len = slice.len() / N;
// SAFETY: We cast a slice of `new_len * N` elements into
// a slice of `new_len` many `N` elements chunks.
unsafe { std::slice::from_raw_parts(slice.as_ptr().cast(), new_len) }
}
const fn unlikely(x: bool) -> bool {
x
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/wtf8/src/core_str.rs | crates/wtf8/src/core_str.rs | //! Operations related to UTF-8 validation.
//!
//! Copied from `core::str::validations`
/// Returns the initial codepoint accumulator for the first byte.
/// The first byte is special, only want bottom 5 bits for width 2, 4 bits
/// for width 3, and 3 bits for width 4.
#[inline]
const fn utf8_first_byte(byte: u8, width: u32) -> u32 {
(byte & (0x7F >> width)) as u32
}
/// Returns the value of `ch` updated with continuation byte `byte`.
#[inline]
const fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 {
(ch << 6) | (byte & CONT_MASK) as u32
}
/// Checks whether the byte is a UTF-8 continuation byte (i.e., starts with the
/// bits `10`).
#[inline]
pub(super) const fn utf8_is_cont_byte(byte: u8) -> bool {
(byte as i8) < -64
}
/// Reads the next code point out of a byte iterator (assuming a
/// UTF-8-like encoding).
///
/// # Safety
///
/// `bytes` must produce a valid UTF-8-like (UTF-8 or WTF-8) string
#[inline]
pub unsafe fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
// Decode UTF-8
let x = *bytes.next()?;
if x < 128 {
return Some(x as u32);
}
// Multibyte case follows
// Decode from a byte combination out of: [[[x y] z] w]
// NOTE: Performance is sensitive to the exact formulation here
let init = utf8_first_byte(x, 2);
// SAFETY: `bytes` produces an UTF-8-like string,
// so the iterator must produce a value here.
let y = unsafe { *bytes.next().unwrap_unchecked() };
let mut ch = utf8_acc_cont_byte(init, y);
if x >= 0xE0 {
// [[x y z] w] case
// 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid
// SAFETY: `bytes` produces an UTF-8-like string,
// so the iterator must produce a value here.
let z = unsafe { *bytes.next().unwrap_unchecked() };
let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z);
ch = init << 12 | y_z;
if x >= 0xF0 {
// [x y z w] case
// use only the lower 3 bits of `init`
// SAFETY: `bytes` produces an UTF-8-like string,
// so the iterator must produce a value here.
let w = unsafe { *bytes.next().unwrap_unchecked() };
ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w);
}
}
Some(ch)
}
/// Reads the last code point out of a byte iterator (assuming a
/// UTF-8-like encoding).
///
/// # Safety
///
/// `bytes` must produce a valid UTF-8-like (UTF-8 or WTF-8) string
#[inline]
pub unsafe fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32>
where
I: DoubleEndedIterator<Item = &'a u8>,
{
// Decode UTF-8
let w = match *bytes.next_back()? {
next_byte if next_byte < 128 => return Some(next_byte as u32),
back_byte => back_byte,
};
// Multibyte case follows
// Decode from a byte combination out of: [x [y [z w]]]
let mut ch;
// SAFETY: `bytes` produces an UTF-8-like string,
// so the iterator must produce a value here.
let z = unsafe { *bytes.next_back().unwrap_unchecked() };
ch = utf8_first_byte(z, 2);
if utf8_is_cont_byte(z) {
// SAFETY: `bytes` produces an UTF-8-like string,
// so the iterator must produce a value here.
let y = unsafe { *bytes.next_back().unwrap_unchecked() };
ch = utf8_first_byte(y, 3);
if utf8_is_cont_byte(y) {
// SAFETY: `bytes` produces an UTF-8-like string,
// so the iterator must produce a value here.
let x = unsafe { *bytes.next_back().unwrap_unchecked() };
ch = utf8_first_byte(x, 4);
ch = utf8_acc_cont_byte(ch, y);
}
ch = utf8_acc_cont_byte(ch, z);
}
ch = utf8_acc_cont_byte(ch, w);
Some(ch)
}
/// Mask of the value bits of a continuation byte.
const CONT_MASK: u8 = 0b0011_1111;
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/jit/src/lib.rs | crates/jit/src/lib.rs | mod instructions;
extern crate alloc;
use alloc::fmt;
use core::mem::ManuallyDrop;
use cranelift::prelude::*;
use cranelift_jit::{JITBuilder, JITModule};
use cranelift_module::{FuncId, Linkage, Module, ModuleError};
use instructions::FunctionCompiler;
use rustpython_compiler_core::bytecode;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum JitCompileError {
#[error("function can't be jitted")]
NotSupported,
#[error("bad bytecode")]
BadBytecode,
#[error("error while compiling to machine code: {0}")]
CraneliftError(Box<ModuleError>),
}
impl From<ModuleError> for JitCompileError {
fn from(err: ModuleError) -> Self {
Self::CraneliftError(Box::new(err))
}
}
#[derive(Debug, thiserror::Error, Eq, PartialEq)]
#[non_exhaustive]
pub enum JitArgumentError {
#[error("argument is of wrong type")]
ArgumentTypeMismatch,
#[error("wrong number of arguments")]
WrongNumberOfArguments,
}
struct Jit {
builder_context: FunctionBuilderContext,
ctx: codegen::Context,
module: JITModule,
}
impl Jit {
fn new() -> Self {
let builder = JITBuilder::new(cranelift_module::default_libcall_names())
.expect("Failed to build JITBuilder");
let module = JITModule::new(builder);
Self {
builder_context: FunctionBuilderContext::new(),
ctx: module.make_context(),
module,
}
}
fn build_function<C: bytecode::Constant>(
&mut self,
bytecode: &bytecode::CodeObject<C>,
args: &[JitType],
ret: Option<JitType>,
) -> Result<(FuncId, JitSig), JitCompileError> {
for arg in args {
self.ctx
.func
.signature
.params
.push(AbiParam::new(arg.to_cranelift()));
}
if ret.is_some() {
self.ctx
.func
.signature
.returns
.push(AbiParam::new(ret.clone().unwrap().to_cranelift()));
}
let id = self.module.declare_function(
&format!("jit_{}", bytecode.obj_name.as_ref()),
Linkage::Export,
&self.ctx.func.signature,
)?;
let func_ref = self.module.declare_func_in_func(id, &mut self.ctx.func);
let mut builder = FunctionBuilder::new(&mut self.ctx.func, &mut self.builder_context);
let entry_block = builder.create_block();
builder.append_block_params_for_function_params(entry_block);
builder.switch_to_block(entry_block);
let sig = {
let mut compiler = FunctionCompiler::new(
&mut builder,
bytecode.varnames.len(),
args,
ret,
entry_block,
);
compiler.compile(func_ref, bytecode)?;
compiler.sig
};
builder.seal_all_blocks();
builder.finalize();
self.module.define_function(id, &mut self.ctx)?;
self.module.clear_context(&mut self.ctx);
Ok((id, sig))
}
}
pub fn compile<C: bytecode::Constant>(
bytecode: &bytecode::CodeObject<C>,
args: &[JitType],
ret: Option<JitType>,
) -> Result<CompiledCode, JitCompileError> {
let mut jit = Jit::new();
let (id, sig) = jit.build_function(bytecode, args, ret)?;
jit.module.finalize_definitions()?;
let code = jit.module.get_finalized_function(id);
Ok(CompiledCode {
sig,
code,
module: ManuallyDrop::new(jit.module),
})
}
pub struct CompiledCode {
sig: JitSig,
code: *const u8,
module: ManuallyDrop<JITModule>,
}
impl CompiledCode {
pub fn args_builder(&self) -> ArgsBuilder<'_> {
ArgsBuilder::new(self)
}
pub fn invoke(&self, args: &[AbiValue]) -> Result<Option<AbiValue>, JitArgumentError> {
if self.sig.args.len() != args.len() {
return Err(JitArgumentError::WrongNumberOfArguments);
}
let cif_args = self
.sig
.args
.iter()
.zip(args.iter())
.map(|(ty, val)| type_check(ty, val).map(|_| val))
.map(|v| v.map(AbiValue::to_libffi_arg))
.collect::<Result<Vec<_>, _>>()?;
Ok(unsafe { self.invoke_raw(&cif_args) })
}
unsafe fn invoke_raw(&self, cif_args: &[libffi::middle::Arg<'_>]) -> Option<AbiValue> {
unsafe {
let cif = self.sig.to_cif();
let value = cif.call::<UnTypedAbiValue>(
libffi::middle::CodePtr::from_ptr(self.code as *const _),
cif_args,
);
self.sig.ret.as_ref().map(|ty| value.to_typed(ty))
}
}
}
struct JitSig {
args: Vec<JitType>,
ret: Option<JitType>,
}
impl JitSig {
fn to_cif(&self) -> libffi::middle::Cif {
let ret = match self.ret {
Some(ref ty) => ty.to_libffi(),
None => libffi::middle::Type::void(),
};
libffi::middle::Cif::new(self.args.iter().map(JitType::to_libffi), ret)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum JitType {
Int,
Float,
Bool,
}
impl JitType {
fn to_cranelift(&self) -> types::Type {
match self {
Self::Int => types::I64,
Self::Float => types::F64,
Self::Bool => types::I8,
}
}
fn to_libffi(&self) -> libffi::middle::Type {
match self {
Self::Int => libffi::middle::Type::i64(),
Self::Float => libffi::middle::Type::f64(),
Self::Bool => libffi::middle::Type::u8(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum AbiValue {
Float(f64),
Int(i64),
Bool(bool),
}
impl AbiValue {
fn to_libffi_arg(&self) -> libffi::middle::Arg<'_> {
match self {
AbiValue::Int(i) => libffi::middle::Arg::new(i),
AbiValue::Float(f) => libffi::middle::Arg::new(f),
AbiValue::Bool(b) => libffi::middle::Arg::new(b),
}
}
}
impl From<i64> for AbiValue {
fn from(i: i64) -> Self {
AbiValue::Int(i)
}
}
impl From<f64> for AbiValue {
fn from(f: f64) -> Self {
AbiValue::Float(f)
}
}
impl From<bool> for AbiValue {
fn from(b: bool) -> Self {
AbiValue::Bool(b)
}
}
impl TryFrom<AbiValue> for i64 {
type Error = ();
fn try_from(value: AbiValue) -> Result<Self, Self::Error> {
match value {
AbiValue::Int(i) => Ok(i),
_ => Err(()),
}
}
}
impl TryFrom<AbiValue> for f64 {
type Error = ();
fn try_from(value: AbiValue) -> Result<Self, Self::Error> {
match value {
AbiValue::Float(f) => Ok(f),
_ => Err(()),
}
}
}
impl TryFrom<AbiValue> for bool {
type Error = ();
fn try_from(value: AbiValue) -> Result<Self, Self::Error> {
match value {
AbiValue::Bool(b) => Ok(b),
_ => Err(()),
}
}
}
fn type_check(ty: &JitType, val: &AbiValue) -> Result<(), JitArgumentError> {
match (ty, val) {
(JitType::Int, AbiValue::Int(_))
| (JitType::Float, AbiValue::Float(_))
| (JitType::Bool, AbiValue::Bool(_)) => Ok(()),
_ => Err(JitArgumentError::ArgumentTypeMismatch),
}
}
#[derive(Copy, Clone)]
union UnTypedAbiValue {
float: f64,
int: i64,
boolean: u8,
_void: (),
}
impl UnTypedAbiValue {
unsafe fn to_typed(self, ty: &JitType) -> AbiValue {
unsafe {
match ty {
JitType::Int => AbiValue::Int(self.int),
JitType::Float => AbiValue::Float(self.float),
JitType::Bool => AbiValue::Bool(self.boolean != 0),
}
}
}
}
// we don't actually ever touch CompiledCode til we drop it, it should be safe.
// TODO: confirm with wasmtime ppl that it's not unsound?
unsafe impl Send for CompiledCode {}
unsafe impl Sync for CompiledCode {}
impl Drop for CompiledCode {
fn drop(&mut self) {
// SAFETY: The only pointer that this memory will also be dropped now
unsafe { ManuallyDrop::take(&mut self.module).free_memory() }
}
}
impl fmt::Debug for CompiledCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[compiled code]")
}
}
pub struct ArgsBuilder<'a> {
values: Vec<Option<AbiValue>>,
code: &'a CompiledCode,
}
impl<'a> ArgsBuilder<'a> {
fn new(code: &'a CompiledCode) -> ArgsBuilder<'a> {
ArgsBuilder {
values: vec![None; code.sig.args.len()],
code,
}
}
pub fn set(&mut self, idx: usize, value: AbiValue) -> Result<(), JitArgumentError> {
type_check(&self.code.sig.args[idx], &value).map(|_| {
self.values[idx] = Some(value);
})
}
pub fn is_set(&self, idx: usize) -> bool {
self.values[idx].is_some()
}
pub fn into_args(self) -> Option<Args<'a>> {
// Ensure all values are set
if self.values.iter().any(|v| v.is_none()) {
return None;
}
Some(Args {
values: self.values.into_iter().map(|v| v.unwrap()).collect(),
code: self.code,
})
}
}
pub struct Args<'a> {
values: Vec<AbiValue>,
code: &'a CompiledCode,
}
impl Args<'_> {
pub fn invoke(&self) -> Option<AbiValue> {
let cif_args: Vec<_> = self.values.iter().map(AbiValue::to_libffi_arg).collect();
unsafe { self.code.invoke_raw(&cif_args) }
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/jit/src/instructions.rs | crates/jit/src/instructions.rs | // spell-checker: disable
use super::{JitCompileError, JitSig, JitType};
use cranelift::codegen::ir::FuncRef;
use cranelift::prelude::*;
use num_traits::cast::ToPrimitive;
use rustpython_compiler_core::bytecode::{
self, BinaryOperator, BorrowedConstant, CodeObject, ComparisonOperator, Instruction, Label,
OpArg, OpArgState, UnaryOperator,
};
use std::collections::HashMap;
#[repr(u16)]
enum CustomTrapCode {
/// Raised when shifting by a negative number
NegativeShiftCount = 1,
}
#[derive(Clone)]
struct Local {
var: Variable,
ty: JitType,
}
#[derive(Debug)]
enum JitValue {
Int(Value),
Float(Value),
Bool(Value),
None,
Tuple(Vec<JitValue>),
FuncRef(FuncRef),
}
impl JitValue {
fn from_type_and_value(ty: JitType, val: Value) -> JitValue {
match ty {
JitType::Int => JitValue::Int(val),
JitType::Float => JitValue::Float(val),
JitType::Bool => JitValue::Bool(val),
}
}
fn to_jit_type(&self) -> Option<JitType> {
match self {
JitValue::Int(_) => Some(JitType::Int),
JitValue::Float(_) => Some(JitType::Float),
JitValue::Bool(_) => Some(JitType::Bool),
JitValue::None | JitValue::Tuple(_) | JitValue::FuncRef(_) => None,
}
}
fn into_value(self) -> Option<Value> {
match self {
JitValue::Int(val) | JitValue::Float(val) | JitValue::Bool(val) => Some(val),
JitValue::None | JitValue::Tuple(_) | JitValue::FuncRef(_) => None,
}
}
}
#[derive(Clone)]
struct DDValue {
hi: Value,
lo: Value,
}
pub struct FunctionCompiler<'a, 'b> {
builder: &'a mut FunctionBuilder<'b>,
stack: Vec<JitValue>,
variables: Box<[Option<Local>]>,
label_to_block: HashMap<Label, Block>,
pub(crate) sig: JitSig,
}
impl<'a, 'b> FunctionCompiler<'a, 'b> {
pub fn new(
builder: &'a mut FunctionBuilder<'b>,
num_variables: usize,
arg_types: &[JitType],
ret_type: Option<JitType>,
entry_block: Block,
) -> FunctionCompiler<'a, 'b> {
let mut compiler = FunctionCompiler {
builder,
stack: Vec::new(),
variables: vec![None; num_variables].into_boxed_slice(),
label_to_block: HashMap::new(),
sig: JitSig {
args: arg_types.to_vec(),
ret: ret_type,
},
};
let params = compiler.builder.func.dfg.block_params(entry_block).to_vec();
for (i, (ty, val)) in arg_types.iter().zip(params).enumerate() {
compiler
.store_variable(i as u32, JitValue::from_type_and_value(ty.clone(), val))
.unwrap();
}
compiler
}
fn pop_multiple(&mut self, count: usize) -> Vec<JitValue> {
let stack_len = self.stack.len();
self.stack.drain(stack_len - count..).collect()
}
fn store_variable(
&mut self,
idx: bytecode::NameIdx,
val: JitValue,
) -> Result<(), JitCompileError> {
let builder = &mut self.builder;
let ty = val.to_jit_type().ok_or(JitCompileError::NotSupported)?;
let local = self.variables[idx as usize].get_or_insert_with(|| {
let var = builder.declare_var(ty.to_cranelift());
Local {
var,
ty: ty.clone(),
}
});
if ty != local.ty {
Err(JitCompileError::NotSupported)
} else {
self.builder.def_var(local.var, val.into_value().unwrap());
Ok(())
}
}
fn boolean_val(&mut self, val: JitValue) -> Result<Value, JitCompileError> {
match val {
JitValue::Float(val) => {
let zero = self.builder.ins().f64const(0.0);
let val = self.builder.ins().fcmp(FloatCC::NotEqual, val, zero);
Ok(val)
}
JitValue::Int(val) => {
let zero = self.builder.ins().iconst(types::I64, 0);
let val = self.builder.ins().icmp(IntCC::NotEqual, val, zero);
Ok(val)
}
JitValue::Bool(val) => Ok(val),
JitValue::None => Ok(self.builder.ins().iconst(types::I8, 0)),
JitValue::Tuple(_) | JitValue::FuncRef(_) => Err(JitCompileError::NotSupported),
}
}
fn get_or_create_block(&mut self, label: Label) -> Block {
let builder = &mut self.builder;
*self
.label_to_block
.entry(label)
.or_insert_with(|| builder.create_block())
}
pub fn compile<C: bytecode::Constant>(
&mut self,
func_ref: FuncRef,
bytecode: &CodeObject<C>,
) -> Result<(), JitCompileError> {
let label_targets = bytecode.label_targets();
let mut arg_state = OpArgState::default();
// Track whether we have "returned" in the current block
let mut in_unreachable_code = false;
for (offset, &raw_instr) in bytecode.instructions.iter().enumerate() {
let label = Label(offset as u32);
let (instruction, arg) = arg_state.get(raw_instr);
// If this is a label that some earlier jump can target,
// treat it as the start of a new reachable block:
if label_targets.contains(&label) {
// Create or get the block for this label:
let target_block = self.get_or_create_block(label);
// If the current block isn't terminated, add a fallthrough jump
if let Some(cur) = self.builder.current_block()
&& cur != target_block
{
// Check if the block needs a terminator by examining the last instruction
let needs_terminator = match self.builder.func.layout.last_inst(cur) {
None => true, // Empty block needs terminator
Some(inst) => {
// Check if the last instruction is a terminator
!self.builder.func.dfg.insts[inst].opcode().is_terminator()
}
};
if needs_terminator {
self.builder.ins().jump(target_block, &[]);
}
}
// Switch to the target block
if self.builder.current_block() != Some(target_block) {
self.builder.switch_to_block(target_block);
}
// We are definitely reachable again at this label
in_unreachable_code = false;
}
// If we're in unreachable code, skip this instruction unless the label re-entered above.
if in_unreachable_code {
continue;
}
// Actually compile this instruction:
self.add_instruction(func_ref, bytecode, instruction, arg)?;
// If that was an unconditional branch or return, mark future instructions unreachable
match instruction {
Instruction::ReturnValue
| Instruction::ReturnConst { .. }
| Instruction::Jump { .. } => {
in_unreachable_code = true;
}
_ => {}
}
}
// After processing, if the current block is unterminated, insert a trap
if let Some(cur) = self.builder.current_block() {
let needs_terminator = match self.builder.func.layout.last_inst(cur) {
None => true,
Some(inst) => !self.builder.func.dfg.insts[inst].opcode().is_terminator(),
};
if needs_terminator {
self.builder.ins().trap(TrapCode::user(0).unwrap());
}
}
Ok(())
}
fn prepare_const<C: bytecode::Constant>(
&mut self,
constant: BorrowedConstant<'_, C>,
) -> Result<JitValue, JitCompileError> {
let value = match constant {
BorrowedConstant::Integer { value } => {
let val = self.builder.ins().iconst(
types::I64,
value.to_i64().ok_or(JitCompileError::NotSupported)?,
);
JitValue::Int(val)
}
BorrowedConstant::Float { value } => {
let val = self.builder.ins().f64const(value);
JitValue::Float(val)
}
BorrowedConstant::Boolean { value } => {
let val = self.builder.ins().iconst(types::I8, value as i64);
JitValue::Bool(val)
}
BorrowedConstant::None => JitValue::None,
_ => return Err(JitCompileError::NotSupported),
};
Ok(value)
}
fn return_value(&mut self, val: JitValue) -> Result<(), JitCompileError> {
if let Some(ref ty) = self.sig.ret {
// If the signature has a return type, enforce it
if val.to_jit_type().as_ref() != Some(ty) {
return Err(JitCompileError::NotSupported);
}
} else {
// First time we see a return, define it in the signature
let ty = val.to_jit_type().ok_or(JitCompileError::NotSupported)?;
self.sig.ret = Some(ty.clone());
self.builder
.func
.signature
.returns
.push(AbiParam::new(ty.to_cranelift()));
}
// If this is e.g. an Int, Float, or Bool we have a Cranelift `Value`.
// If we have JitValue::None or .Tuple(...) but can't handle that, error out (or handle differently).
let cr_val = val.into_value().ok_or(JitCompileError::NotSupported)?;
self.builder.ins().return_(&[cr_val]);
Ok(())
}
pub fn add_instruction<C: bytecode::Constant>(
&mut self,
func_ref: FuncRef,
bytecode: &CodeObject<C>,
instruction: Instruction,
arg: OpArg,
) -> Result<(), JitCompileError> {
match instruction {
Instruction::BinaryOp { op } => {
let op = op.get(arg);
// the rhs is popped off first
let b = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
let a = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
let a_type = a.to_jit_type();
let b_type = b.to_jit_type();
let val = match (op, a, b) {
(
BinaryOperator::Add | BinaryOperator::InplaceAdd,
JitValue::Int(a),
JitValue::Int(b),
) => {
let (out, carry) = self.builder.ins().sadd_overflow(a, b);
self.builder.ins().trapnz(carry, TrapCode::INTEGER_OVERFLOW);
JitValue::Int(out)
}
(
BinaryOperator::Subtract | BinaryOperator::InplaceSubtract,
JitValue::Int(a),
JitValue::Int(b),
) => JitValue::Int(self.compile_sub(a, b)),
(
BinaryOperator::FloorDivide | BinaryOperator::InplaceFloorDivide,
JitValue::Int(a),
JitValue::Int(b),
) => JitValue::Int(self.builder.ins().sdiv(a, b)),
(
BinaryOperator::TrueDivide | BinaryOperator::InplaceTrueDivide,
JitValue::Int(a),
JitValue::Int(b),
) => {
// Check if b == 0, If so trap with a division by zero error
self.builder
.ins()
.trapz(b, TrapCode::INTEGER_DIVISION_BY_ZERO);
// Else convert to float and divide
let a_float = self.builder.ins().fcvt_from_sint(types::F64, a);
let b_float = self.builder.ins().fcvt_from_sint(types::F64, b);
JitValue::Float(self.builder.ins().fdiv(a_float, b_float))
}
(
BinaryOperator::Multiply | BinaryOperator::InplaceMultiply,
JitValue::Int(a),
JitValue::Int(b),
) => JitValue::Int(self.builder.ins().imul(a, b)),
(
BinaryOperator::Remainder | BinaryOperator::InplaceRemainder,
JitValue::Int(a),
JitValue::Int(b),
) => JitValue::Int(self.builder.ins().srem(a, b)),
(
BinaryOperator::Power | BinaryOperator::InplacePower,
JitValue::Int(a),
JitValue::Int(b),
) => JitValue::Int(self.compile_ipow(a, b)),
(
BinaryOperator::Lshift | BinaryOperator::Rshift,
JitValue::Int(a),
JitValue::Int(b),
) => {
// Shifts throw an exception if we have a negative shift count
// Remove all bits except the sign bit, and trap if its 1 (i.e. negative).
let sign = self.builder.ins().ushr_imm(b, 63);
self.builder.ins().trapnz(
sign,
TrapCode::user(CustomTrapCode::NegativeShiftCount as u8).unwrap(),
);
let out =
if matches!(op, BinaryOperator::Lshift | BinaryOperator::InplaceLshift)
{
self.builder.ins().ishl(a, b)
} else {
self.builder.ins().sshr(a, b)
};
JitValue::Int(out)
}
(
BinaryOperator::And | BinaryOperator::InplaceAnd,
JitValue::Int(a),
JitValue::Int(b),
) => JitValue::Int(self.builder.ins().band(a, b)),
(
BinaryOperator::Or | BinaryOperator::InplaceOr,
JitValue::Int(a),
JitValue::Int(b),
) => JitValue::Int(self.builder.ins().bor(a, b)),
(
BinaryOperator::Xor | BinaryOperator::InplaceXor,
JitValue::Int(a),
JitValue::Int(b),
) => JitValue::Int(self.builder.ins().bxor(a, b)),
// Floats
(
BinaryOperator::Add | BinaryOperator::InplaceAdd,
JitValue::Float(a),
JitValue::Float(b),
) => JitValue::Float(self.builder.ins().fadd(a, b)),
(
BinaryOperator::Subtract | BinaryOperator::InplaceSubtract,
JitValue::Float(a),
JitValue::Float(b),
) => JitValue::Float(self.builder.ins().fsub(a, b)),
(
BinaryOperator::Multiply | BinaryOperator::InplaceMultiply,
JitValue::Float(a),
JitValue::Float(b),
) => JitValue::Float(self.builder.ins().fmul(a, b)),
(
BinaryOperator::TrueDivide | BinaryOperator::InplaceTrueDivide,
JitValue::Float(a),
JitValue::Float(b),
) => JitValue::Float(self.builder.ins().fdiv(a, b)),
(
BinaryOperator::Power | BinaryOperator::InplacePower,
JitValue::Float(a),
JitValue::Float(b),
) => JitValue::Float(self.compile_fpow(a, b)),
// Floats and Integers
(_, JitValue::Int(a), JitValue::Float(b))
| (_, JitValue::Float(a), JitValue::Int(b)) => {
let operand_one = match a_type.unwrap() {
JitType::Int => self.builder.ins().fcvt_from_sint(types::F64, a),
_ => a,
};
let operand_two = match b_type.unwrap() {
JitType::Int => self.builder.ins().fcvt_from_sint(types::F64, b),
_ => b,
};
match op {
BinaryOperator::Add | BinaryOperator::InplaceAdd => {
JitValue::Float(self.builder.ins().fadd(operand_one, operand_two))
}
BinaryOperator::Subtract | BinaryOperator::InplaceSubtract => {
JitValue::Float(self.builder.ins().fsub(operand_one, operand_two))
}
BinaryOperator::Multiply | BinaryOperator::InplaceMultiply => {
JitValue::Float(self.builder.ins().fmul(operand_one, operand_two))
}
BinaryOperator::TrueDivide | BinaryOperator::InplaceTrueDivide => {
JitValue::Float(self.builder.ins().fdiv(operand_one, operand_two))
}
BinaryOperator::Power | BinaryOperator::InplacePower => {
JitValue::Float(self.compile_fpow(operand_one, operand_two))
}
_ => return Err(JitCompileError::NotSupported),
}
}
_ => return Err(JitCompileError::NotSupported),
};
self.stack.push(val);
Ok(())
}
Instruction::BuildTuple { size } => {
let elements = self.pop_multiple(size.get(arg) as usize);
self.stack.push(JitValue::Tuple(elements));
Ok(())
}
Instruction::CallFunctionPositional { nargs } => {
let nargs = nargs.get(arg);
let mut args = Vec::new();
for _ in 0..nargs {
let arg = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
args.push(arg.into_value().unwrap());
}
match self.stack.pop().ok_or(JitCompileError::BadBytecode)? {
JitValue::FuncRef(reference) => {
let call = self.builder.ins().call(reference, &args);
let returns = self.builder.inst_results(call);
self.stack.push(JitValue::Int(returns[0]));
Ok(())
}
_ => Err(JitCompileError::BadBytecode),
}
}
Instruction::CompareOperation { op, .. } => {
let op = op.get(arg);
// the rhs is popped off first
let b = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
let a = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
let a_type: Option<JitType> = a.to_jit_type();
let b_type: Option<JitType> = b.to_jit_type();
match (a, b) {
(JitValue::Int(a), JitValue::Int(b))
| (JitValue::Bool(a), JitValue::Bool(b))
| (JitValue::Bool(a), JitValue::Int(b))
| (JitValue::Int(a), JitValue::Bool(b)) => {
let operand_one = match a_type.unwrap() {
JitType::Bool => self.builder.ins().uextend(types::I64, a),
_ => a,
};
let operand_two = match b_type.unwrap() {
JitType::Bool => self.builder.ins().uextend(types::I64, b),
_ => b,
};
let cond = match op {
ComparisonOperator::Equal => IntCC::Equal,
ComparisonOperator::NotEqual => IntCC::NotEqual,
ComparisonOperator::Less => IntCC::SignedLessThan,
ComparisonOperator::LessOrEqual => IntCC::SignedLessThanOrEqual,
ComparisonOperator::Greater => IntCC::SignedGreaterThan,
ComparisonOperator::GreaterOrEqual => IntCC::SignedGreaterThanOrEqual,
};
let val = self.builder.ins().icmp(cond, operand_one, operand_two);
self.stack.push(JitValue::Bool(val));
Ok(())
}
(JitValue::Float(a), JitValue::Float(b)) => {
let cond = match op {
ComparisonOperator::Equal => FloatCC::Equal,
ComparisonOperator::NotEqual => FloatCC::NotEqual,
ComparisonOperator::Less => FloatCC::LessThan,
ComparisonOperator::LessOrEqual => FloatCC::LessThanOrEqual,
ComparisonOperator::Greater => FloatCC::GreaterThan,
ComparisonOperator::GreaterOrEqual => FloatCC::GreaterThanOrEqual,
};
let val = self.builder.ins().fcmp(cond, a, b);
self.stack.push(JitValue::Bool(val));
Ok(())
}
_ => Err(JitCompileError::NotSupported),
}
}
Instruction::ExtendedArg => Ok(()),
Instruction::Jump { target } => {
let target_block = self.get_or_create_block(target.get(arg));
self.builder.ins().jump(target_block, &[]);
Ok(())
}
Instruction::LoadConst { idx } => {
let val = self
.prepare_const(bytecode.constants[idx.get(arg) as usize].borrow_constant())?;
self.stack.push(val);
Ok(())
}
Instruction::LoadFast(idx) => {
let local = self.variables[idx.get(arg) as usize]
.as_ref()
.ok_or(JitCompileError::BadBytecode)?;
self.stack.push(JitValue::from_type_and_value(
local.ty.clone(),
self.builder.use_var(local.var),
));
Ok(())
}
Instruction::LoadGlobal(idx) => {
let name = &bytecode.names[idx.get(arg) as usize];
if name.as_ref() != bytecode.obj_name.as_ref() {
Err(JitCompileError::NotSupported)
} else {
self.stack.push(JitValue::FuncRef(func_ref));
Ok(())
}
}
Instruction::Nop => Ok(()),
Instruction::PopBlock => {
// TODO: block support
Ok(())
}
Instruction::PopJumpIfFalse { target } => {
let cond = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
let val = self.boolean_val(cond)?;
let then_block = self.get_or_create_block(target.get(arg));
let else_block = self.builder.create_block();
self.builder
.ins()
.brif(val, else_block, &[], then_block, &[]);
self.builder.switch_to_block(else_block);
Ok(())
}
Instruction::PopJumpIfTrue { target } => {
let cond = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
let val = self.boolean_val(cond)?;
let then_block = self.get_or_create_block(target.get(arg));
let else_block = self.builder.create_block();
self.builder
.ins()
.brif(val, then_block, &[], else_block, &[]);
self.builder.switch_to_block(else_block);
Ok(())
}
Instruction::PopTop => {
self.stack.pop();
Ok(())
}
Instruction::Resume { arg: _resume_arg } => {
// TODO: Implement the resume instruction
Ok(())
}
Instruction::ReturnConst { idx } => {
let val = self
.prepare_const(bytecode.constants[idx.get(arg) as usize].borrow_constant())?;
self.return_value(val)
}
Instruction::ReturnValue => {
let val = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
self.return_value(val)
}
Instruction::StoreFast(idx) => {
let val = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
self.store_variable(idx.get(arg), val)
}
Instruction::Swap { index } => {
let len = self.stack.len();
let i = len - 1;
let j = len - 1 - index.get(arg) as usize;
self.stack.swap(i, j);
Ok(())
}
Instruction::UnaryOperation { op, .. } => {
let op = op.get(arg);
let a = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
match (op, a) {
(UnaryOperator::Minus, JitValue::Int(val)) => {
// Compile minus as 0 - a.
let zero = self.builder.ins().iconst(types::I64, 0);
let out = self.compile_sub(zero, val);
self.stack.push(JitValue::Int(out));
Ok(())
}
(UnaryOperator::Plus, JitValue::Int(val)) => {
// Nothing to do
self.stack.push(JitValue::Int(val));
Ok(())
}
(UnaryOperator::Not, a) => {
let boolean = self.boolean_val(a)?;
let not_boolean = self.builder.ins().bxor_imm(boolean, 1);
self.stack.push(JitValue::Bool(not_boolean));
Ok(())
}
_ => Err(JitCompileError::NotSupported),
}
}
Instruction::UnpackSequence { size } => {
let val = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
let elements = match val {
JitValue::Tuple(elements) => elements,
_ => return Err(JitCompileError::NotSupported),
};
if elements.len() != size.get(arg) as usize {
return Err(JitCompileError::NotSupported);
}
self.stack.extend(elements.into_iter().rev());
Ok(())
}
_ => Err(JitCompileError::NotSupported),
}
}
fn compile_sub(&mut self, a: Value, b: Value) -> Value {
let (out, carry) = self.builder.ins().ssub_overflow(a, b);
self.builder.ins().trapnz(carry, TrapCode::INTEGER_OVERFLOW);
out
}
/// Creates a double–double (DDValue) from a regular f64 constant.
/// The high part is set to x and the low part is set to 0.0.
fn dd_from_f64(&mut self, x: f64) -> DDValue {
DDValue {
hi: self.builder.ins().f64const(x),
lo: self.builder.ins().f64const(0.0),
}
}
/// Creates a DDValue from a Value (assumed to represent an f64).
/// This function initializes the high part with x and the low part to 0.0.
fn dd_from_value(&mut self, x: Value) -> DDValue {
DDValue {
hi: x,
lo: self.builder.ins().f64const(0.0),
}
}
/// Creates a DDValue from two f64 parts.
/// The 'hi' parameter sets the high part and 'lo' sets the low part.
fn dd_from_parts(&mut self, hi: f64, lo: f64) -> DDValue {
DDValue {
hi: self.builder.ins().f64const(hi),
lo: self.builder.ins().f64const(lo),
}
}
/// Converts a DDValue back to a single f64 value by adding the high and low parts.
fn dd_to_f64(&mut self, dd: DDValue) -> Value {
self.builder.ins().fadd(dd.hi, dd.lo)
}
/// Computes the negation of a DDValue.
/// It subtracts both the high and low parts from zero.
fn dd_neg(&mut self, dd: DDValue) -> DDValue {
let zero = self.builder.ins().f64const(0.0);
DDValue {
hi: self.builder.ins().fsub(zero, dd.hi),
lo: self.builder.ins().fsub(zero, dd.lo),
}
}
/// Adds two DDValue numbers using error-free transformations to maintain extra precision.
/// It carefully adds the high parts, computes the rounding error, adds the low parts along with the error,
/// and then normalizes the result.
fn dd_add(&mut self, a: DDValue, b: DDValue) -> DDValue {
// Compute the sum of the high parts.
let s = self.builder.ins().fadd(a.hi, b.hi);
// Compute t = s - a.hi to capture part of the rounding error.
let t = self.builder.ins().fsub(s, a.hi);
// Compute the error e from the high part additions.
let s_minus_t = self.builder.ins().fsub(s, t);
let part1 = self.builder.ins().fsub(a.hi, s_minus_t);
let part2 = self.builder.ins().fsub(b.hi, t);
let e = self.builder.ins().fadd(part1, part2);
// Sum the low parts along with the error.
let lo = self.builder.ins().fadd(a.lo, b.lo);
let lo_sum = self.builder.ins().fadd(lo, e);
// Renormalize: add the low sum to s and compute a new low component.
let hi_new = self.builder.ins().fadd(s, lo_sum);
let hi_new_minus_s = self.builder.ins().fsub(hi_new, s);
let lo_new = self.builder.ins().fsub(lo_sum, hi_new_minus_s);
DDValue {
hi: hi_new,
lo: lo_new,
}
}
/// Subtracts DDValue b from DDValue a by negating b and then using the addition function.
fn dd_sub(&mut self, a: DDValue, b: DDValue) -> DDValue {
let neg_b = self.dd_neg(b);
self.dd_add(a, neg_b)
}
/// Multiplies two DDValue numbers using double–double arithmetic.
/// It calculates the high product, uses a fused multiply–add (FMA) to capture rounding error,
/// computes the cross products, and then normalizes the result.
fn dd_mul(&mut self, a: DDValue, b: DDValue) -> DDValue {
// p = a.hi * b.hi (primary product)
let p = self.builder.ins().fmul(a.hi, b.hi);
// err = fma(a.hi, b.hi, -p) recovers the rounding error.
let zero = self.builder.ins().f64const(0.0);
let neg_p = self.builder.ins().fsub(zero, p);
let err = self.builder.ins().fma(a.hi, b.hi, neg_p);
// Compute cross terms: a.hi*b.lo + a.lo*b.hi.
let a_hi_b_lo = self.builder.ins().fmul(a.hi, b.lo);
let a_lo_b_hi = self.builder.ins().fmul(a.lo, b.hi);
let cross = self.builder.ins().fadd(a_hi_b_lo, a_lo_b_hi);
// Sum p and the cross terms.
let s = self.builder.ins().fadd(p, cross);
// Isolate rounding error from the addition.
let t = self.builder.ins().fsub(s, p);
let s_minus_t = self.builder.ins().fsub(s, t);
let part1 = self.builder.ins().fsub(p, s_minus_t);
let part2 = self.builder.ins().fsub(cross, t);
let e = self.builder.ins().fadd(part1, part2);
// Include the error from the low parts multiplication.
let a_lo_b_lo = self.builder.ins().fmul(a.lo, b.lo);
let err_plus_e = self.builder.ins().fadd(err, e);
let lo_sum = self.builder.ins().fadd(err_plus_e, a_lo_b_lo);
// Renormalize the sum.
let hi_new = self.builder.ins().fadd(s, lo_sum);
let hi_new_minus_s = self.builder.ins().fsub(hi_new, s);
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | true |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/jit/tests/float_tests.rs | crates/jit/tests/float_tests.rs | macro_rules! assert_approx_eq {
($left:expr, $right:expr) => {
match ($left, $right) {
(Ok(lhs), Ok(rhs)) => approx::assert_relative_eq!(lhs, rhs),
(lhs, rhs) => assert_eq!(lhs, rhs),
}
};
}
macro_rules! assert_bits_eq {
($left:expr, $right:expr) => {
match ($left, $right) {
(Ok(lhs), Ok(rhs)) => assert!(lhs.to_bits() == rhs.to_bits()),
(lhs, rhs) => assert_eq!(lhs, rhs),
}
};
}
#[test]
fn test_add() {
let add = jit_function! { add(a:f64, b:f64) -> f64 => r##"
def add(a: float, b: float):
return a + b
"## };
assert_approx_eq!(add(5.5, 10.2), Ok(15.7));
assert_approx_eq!(add(-4.5, 7.6), Ok(3.1));
assert_approx_eq!(add(-5.2, -3.9), Ok(-9.1));
assert_bits_eq!(add(-5.2, f64::NAN), Ok(f64::NAN));
assert_eq!(add(2.0, f64::INFINITY), Ok(f64::INFINITY));
assert_eq!(add(-2.0, f64::NEG_INFINITY), Ok(f64::NEG_INFINITY));
assert_eq!(add(1.0, f64::NEG_INFINITY), Ok(f64::NEG_INFINITY));
}
#[test]
fn test_add_with_integer() {
let add = jit_function! { add(a:f64, b:i64) -> f64 => r##"
def add(a: float, b: int):
return a + b
"## };
assert_approx_eq!(add(5.5, 10), Ok(15.5));
assert_approx_eq!(add(-4.6, 7), Ok(2.4));
assert_approx_eq!(add(-5.2, -3), Ok(-8.2));
}
#[test]
fn test_sub() {
let sub = jit_function! { sub(a:f64, b:f64) -> f64 => r##"
def sub(a: float, b: float):
return a - b
"## };
assert_approx_eq!(sub(5.2, 3.6), Ok(1.6));
assert_approx_eq!(sub(3.4, 4.2), Ok(-0.8));
assert_approx_eq!(sub(-2.1, 1.3), Ok(-3.4));
assert_approx_eq!(sub(3.1, -1.3), Ok(4.4));
assert_bits_eq!(sub(-5.2, f64::NAN), Ok(f64::NAN));
assert_eq!(sub(f64::INFINITY, 2.0), Ok(f64::INFINITY));
assert_eq!(sub(-2.0, f64::NEG_INFINITY), Ok(f64::INFINITY));
assert_eq!(sub(1.0, f64::INFINITY), Ok(f64::NEG_INFINITY));
}
#[test]
fn test_sub_with_integer() {
let sub = jit_function! { sub(a:i64, b:f64) -> f64 => r##"
def sub(a: int, b: float):
return a - b
"## };
assert_approx_eq!(sub(5, 3.6), Ok(1.4));
assert_approx_eq!(sub(3, -4.2), Ok(7.2));
assert_approx_eq!(sub(-2, 1.3), Ok(-3.3));
assert_approx_eq!(sub(-3, -1.3), Ok(-1.7));
}
#[test]
fn test_mul() {
let mul = jit_function! { mul(a:f64, b:f64) -> f64 => r##"
def mul(a: float, b: float):
return a * b
"## };
assert_approx_eq!(mul(5.2, 2.0), Ok(10.4));
assert_approx_eq!(mul(3.4, -1.7), Ok(-5.779999999999999));
assert_bits_eq!(mul(1.0, 0.0), Ok(0.0f64));
assert_bits_eq!(mul(1.0, -0.0), Ok(-0.0f64));
assert_bits_eq!(mul(-1.0, 0.0), Ok(-0.0f64));
assert_bits_eq!(mul(-1.0, -0.0), Ok(0.0f64));
assert_bits_eq!(mul(-5.2, f64::NAN), Ok(f64::NAN));
assert_eq!(mul(1.0, f64::INFINITY), Ok(f64::INFINITY));
assert_eq!(mul(1.0, f64::NEG_INFINITY), Ok(f64::NEG_INFINITY));
assert_eq!(mul(-1.0, f64::INFINITY), Ok(f64::NEG_INFINITY));
assert!(mul(0.0, f64::INFINITY).unwrap().is_nan());
assert_eq!(mul(f64::NEG_INFINITY, f64::INFINITY), Ok(f64::NEG_INFINITY));
}
#[test]
fn test_mul_with_integer() {
let mul = jit_function! { mul(a:f64, b:i64) -> f64 => r##"
def mul(a: float, b: int):
return a * b
"## };
assert_approx_eq!(mul(5.2, 2), Ok(10.4));
assert_approx_eq!(mul(3.4, -1), Ok(-3.4));
assert_bits_eq!(mul(1.0, 0), Ok(0.0f64));
assert_bits_eq!(mul(-0.0, 1), Ok(-0.0f64));
assert_bits_eq!(mul(0.0, -1), Ok(-0.0f64));
assert_bits_eq!(mul(-0.0, -1), Ok(0.0f64));
}
#[test]
fn test_power() {
let pow = jit_function! { pow(a:f64, b:f64) -> f64 => r##"
def pow(a:float, b: float):
return a**b
"##};
// Test base cases
assert_approx_eq!(pow(0.0, 0.0), Ok(1.0));
assert_approx_eq!(pow(0.0, 1.0), Ok(0.0));
assert_approx_eq!(pow(1.0, 0.0), Ok(1.0));
assert_approx_eq!(pow(1.0, 1.0), Ok(1.0));
assert_approx_eq!(pow(1.0, -1.0), Ok(1.0));
assert_approx_eq!(pow(-1.0, 0.0), Ok(1.0));
assert_approx_eq!(pow(-1.0, 1.0), Ok(-1.0));
assert_approx_eq!(pow(-1.0, -1.0), Ok(-1.0));
// NaN and Infinity cases
assert_approx_eq!(pow(f64::NAN, 0.0), Ok(1.0));
//assert_approx_eq!(pow(f64::NAN, 1.0), Ok(f64::NAN)); // Return the correct answer but fails compare
//assert_approx_eq!(pow(0.0, f64::NAN), Ok(f64::NAN)); // Return the correct answer but fails compare
assert_approx_eq!(pow(f64::INFINITY, 0.0), Ok(1.0));
assert_approx_eq!(pow(f64::INFINITY, 1.0), Ok(f64::INFINITY));
assert_approx_eq!(pow(f64::INFINITY, f64::INFINITY), Ok(f64::INFINITY));
// Negative infinity cases:
// For any exponent of 0.0, the result is 1.0.
assert_approx_eq!(pow(f64::NEG_INFINITY, 0.0), Ok(1.0));
// For negative infinity base, when b is an odd integer, result is -infinity;
// when b is even, result is +infinity.
assert_approx_eq!(pow(f64::NEG_INFINITY, 1.0), Ok(f64::NEG_INFINITY));
assert_approx_eq!(pow(f64::NEG_INFINITY, 2.0), Ok(f64::INFINITY));
assert_approx_eq!(pow(f64::NEG_INFINITY, 3.0), Ok(f64::NEG_INFINITY));
// Exponent -infinity gives 0.0.
assert_approx_eq!(pow(f64::NEG_INFINITY, f64::NEG_INFINITY), Ok(0.0));
// Test positive float base, positive float exponent
assert_approx_eq!(pow(2.0, 2.0), Ok(4.0));
assert_approx_eq!(pow(3.0, 3.0), Ok(27.0));
assert_approx_eq!(pow(4.0, 4.0), Ok(256.0));
assert_approx_eq!(pow(2.0, 3.0), Ok(8.0));
assert_approx_eq!(pow(2.0, 4.0), Ok(16.0));
// Test negative float base, positive float exponent (integral exponents only)
assert_approx_eq!(pow(-2.0, 2.0), Ok(4.0));
assert_approx_eq!(pow(-3.0, 3.0), Ok(-27.0));
assert_approx_eq!(pow(-4.0, 4.0), Ok(256.0));
assert_approx_eq!(pow(-2.0, 3.0), Ok(-8.0));
assert_approx_eq!(pow(-2.0, 4.0), Ok(16.0));
// Test positive float base, positive float exponent
assert_approx_eq!(pow(2.5, 2.0), Ok(6.25));
assert_approx_eq!(pow(3.5, 3.0), Ok(42.875));
assert_approx_eq!(pow(4.5, 4.0), Ok(410.0625));
assert_approx_eq!(pow(2.5, 3.0), Ok(15.625));
assert_approx_eq!(pow(2.5, 4.0), Ok(39.0625));
// Test negative float base, positive float exponent (integral exponents only)
assert_approx_eq!(pow(-2.5, 2.0), Ok(6.25));
assert_approx_eq!(pow(-3.5, 3.0), Ok(-42.875));
assert_approx_eq!(pow(-4.5, 4.0), Ok(410.0625));
assert_approx_eq!(pow(-2.5, 3.0), Ok(-15.625));
assert_approx_eq!(pow(-2.5, 4.0), Ok(39.0625));
// Test positive float base, positive float exponent with non-integral exponents
assert_approx_eq!(pow(2.0, 2.5), Ok(5.656854249492381));
assert_approx_eq!(pow(3.0, 3.5), Ok(46.76537180435969));
assert_approx_eq!(pow(4.0, 4.5), Ok(512.0));
assert_approx_eq!(pow(2.0, 3.5), Ok(11.313708498984761));
assert_approx_eq!(pow(2.0, 4.5), Ok(22.627416997969522));
// Test positive float base, negative float exponent
assert_approx_eq!(pow(2.0, -2.5), Ok(0.1767766952966369));
assert_approx_eq!(pow(3.0, -3.5), Ok(0.021383343303319473));
assert_approx_eq!(pow(4.0, -4.5), Ok(0.001953125));
assert_approx_eq!(pow(2.0, -3.5), Ok(0.08838834764831845));
assert_approx_eq!(pow(2.0, -4.5), Ok(0.04419417382415922));
// Test negative float base, negative float exponent (integral exponents only)
assert_approx_eq!(pow(-2.0, -2.0), Ok(0.25));
assert_approx_eq!(pow(-3.0, -3.0), Ok(-0.037037037037037035));
assert_approx_eq!(pow(-4.0, -4.0), Ok(0.00390625));
assert_approx_eq!(pow(-2.0, -3.0), Ok(-0.125));
assert_approx_eq!(pow(-2.0, -4.0), Ok(0.0625));
// Currently negative float base with non-integral exponent is not supported:
// assert_approx_eq!(pow(-2.0, 2.5), Ok(5.656854249492381));
// assert_approx_eq!(pow(-3.0, 3.5), Ok(-46.76537180435969));
// assert_approx_eq!(pow(-4.0, 4.5), Ok(512.0));
// assert_approx_eq!(pow(-2.0, -2.5), Ok(0.1767766952966369));
// assert_approx_eq!(pow(-3.0, -3.5), Ok(0.021383343303319473));
// assert_approx_eq!(pow(-4.0, -4.5), Ok(0.001953125));
// Extra cases **NOTE** these are not all working:
// * If they are commented in then they work
// * If they are commented out with a number that is the current return value it throws vs the expected value
// * If they are commented out with a "fail to run" that means I couldn't get them to work, could add a case for really big or small values
// 1e308^2.0
assert_approx_eq!(pow(1e308, 2.0), Ok(f64::INFINITY));
// 1e308^(1e-2)
assert_approx_eq!(pow(1e308, 1e-2), Ok(1202.2644346174131));
// 1e-308^2.0
//assert_approx_eq!(pow(1e-308, 2.0), Ok(0.0)); // --8.403311421507407
// 1e-308^-2.0
assert_approx_eq!(pow(1e-308, -2.0), Ok(f64::INFINITY));
// 1e100^(1e50)
//assert_approx_eq!(pow(1e100, 1e50), Ok(1.0000000000000002e+150)); // fail to run (Crashes as "illegal hardware instruction")
// 1e50^(1e-100)
assert_approx_eq!(pow(1e50, 1e-100), Ok(1.0));
// 1e308^(-1e2)
//assert_approx_eq!(pow(1e308, -1e2), Ok(0.0)); // 2.961801792837933e25
// 1e-308^(1e2)
//assert_approx_eq!(pow(1e-308, 1e2), Ok(f64::INFINITY)); // 1.6692559244043896e46
// 1e308^(-1e308)
// assert_approx_eq!(pow(1e308, -1e308), Ok(0.0)); // fail to run (Crashes as "illegal hardware instruction")
// 1e-308^(1e308)
// assert_approx_eq!(pow(1e-308, 1e308), Ok(0.0)); // fail to run (Crashes as "illegal hardware instruction")
}
#[test]
fn test_div() {
let div = jit_function! { div(a:f64, b:f64) -> f64 => r##"
def div(a: float, b: float):
return a / b
"## };
assert_approx_eq!(div(5.2, 2.0), Ok(2.6));
assert_approx_eq!(div(3.4, -1.7), Ok(-2.0));
assert_eq!(div(1.0, 0.0), Ok(f64::INFINITY));
assert_eq!(div(1.0, -0.0), Ok(f64::NEG_INFINITY));
assert_eq!(div(-1.0, 0.0), Ok(f64::NEG_INFINITY));
assert_eq!(div(-1.0, -0.0), Ok(f64::INFINITY));
assert_bits_eq!(div(-5.2, f64::NAN), Ok(f64::NAN));
assert_eq!(div(f64::INFINITY, 2.0), Ok(f64::INFINITY));
assert_bits_eq!(div(-2.0, f64::NEG_INFINITY), Ok(0.0f64));
assert_bits_eq!(div(1.0, f64::INFINITY), Ok(0.0f64));
assert_bits_eq!(div(2.0, f64::NEG_INFINITY), Ok(-0.0f64));
assert_bits_eq!(div(-1.0, f64::INFINITY), Ok(-0.0f64));
}
#[test]
fn test_div_with_integer() {
let div = jit_function! { div(a:f64, b:i64) -> f64 => r##"
def div(a: float, b: int):
return a / b
"## };
assert_approx_eq!(div(5.2, 2), Ok(2.6));
assert_approx_eq!(div(3.4, -1), Ok(-3.4));
assert_eq!(div(1.0, 0), Ok(f64::INFINITY));
assert_eq!(div(1.0, -0), Ok(f64::INFINITY));
assert_eq!(div(-1.0, 0), Ok(f64::NEG_INFINITY));
assert_eq!(div(-1.0, -0), Ok(f64::NEG_INFINITY));
assert_eq!(div(f64::INFINITY, 2), Ok(f64::INFINITY));
assert_eq!(div(f64::NEG_INFINITY, 3), Ok(f64::NEG_INFINITY));
}
#[test]
fn test_if_bool() {
let if_bool = jit_function! { if_bool(a:f64) -> i64 => r##"
def if_bool(a: float):
if a:
return 1
return 0
"## };
assert_eq!(if_bool(5.2), Ok(1));
assert_eq!(if_bool(-3.4), Ok(1));
assert_eq!(if_bool(f64::NAN), Ok(1));
assert_eq!(if_bool(f64::INFINITY), Ok(1));
assert_eq!(if_bool(0.0), Ok(0));
}
#[test]
fn test_float_eq() {
let float_eq = jit_function! { float_eq(a: f64, b: f64) -> bool => r##"
def float_eq(a: float, b: float):
return a == b
"## };
assert_eq!(float_eq(2.0, 2.0), Ok(true));
assert_eq!(float_eq(3.4, -1.7), Ok(false));
assert_eq!(float_eq(0.0, 0.0), Ok(true));
assert_eq!(float_eq(-0.0, -0.0), Ok(true));
assert_eq!(float_eq(-0.0, 0.0), Ok(true));
assert_eq!(float_eq(-5.2, f64::NAN), Ok(false));
assert_eq!(float_eq(f64::NAN, f64::NAN), Ok(false));
assert_eq!(float_eq(f64::INFINITY, f64::NEG_INFINITY), Ok(false));
}
#[test]
fn test_float_ne() {
let float_ne = jit_function! { float_ne(a: f64, b: f64) -> bool => r##"
def float_ne(a: float, b: float):
return a != b
"## };
assert_eq!(float_ne(2.0, 2.0), Ok(false));
assert_eq!(float_ne(3.4, -1.7), Ok(true));
assert_eq!(float_ne(0.0, 0.0), Ok(false));
assert_eq!(float_ne(-0.0, -0.0), Ok(false));
assert_eq!(float_ne(-0.0, 0.0), Ok(false));
assert_eq!(float_ne(-5.2, f64::NAN), Ok(true));
assert_eq!(float_ne(f64::NAN, f64::NAN), Ok(true));
assert_eq!(float_ne(f64::INFINITY, f64::NEG_INFINITY), Ok(true));
}
#[test]
fn test_float_gt() {
let float_gt = jit_function! { float_gt(a: f64, b: f64) -> bool => r##"
def float_gt(a: float, b: float):
return a > b
"## };
assert_eq!(float_gt(2.0, 2.0), Ok(false));
assert_eq!(float_gt(3.4, -1.7), Ok(true));
assert_eq!(float_gt(0.0, 0.0), Ok(false));
assert_eq!(float_gt(-0.0, -0.0), Ok(false));
assert_eq!(float_gt(-0.0, 0.0), Ok(false));
assert_eq!(float_gt(-5.2, f64::NAN), Ok(false));
assert_eq!(float_gt(f64::NAN, f64::NAN), Ok(false));
assert_eq!(float_gt(f64::INFINITY, f64::NEG_INFINITY), Ok(true));
}
#[test]
fn test_float_gte() {
let float_gte = jit_function! { float_gte(a: f64, b: f64) -> bool => r##"
def float_gte(a: float, b: float):
return a >= b
"## };
assert_eq!(float_gte(2.0, 2.0), Ok(true));
assert_eq!(float_gte(3.4, -1.7), Ok(true));
assert_eq!(float_gte(0.0, 0.0), Ok(true));
assert_eq!(float_gte(-0.0, -0.0), Ok(true));
assert_eq!(float_gte(-0.0, 0.0), Ok(true));
assert_eq!(float_gte(-5.2, f64::NAN), Ok(false));
assert_eq!(float_gte(f64::NAN, f64::NAN), Ok(false));
assert_eq!(float_gte(f64::INFINITY, f64::NEG_INFINITY), Ok(true));
}
#[test]
fn test_float_lt() {
let float_lt = jit_function! { float_lt(a: f64, b: f64) -> bool => r##"
def float_lt(a: float, b: float):
return a < b
"## };
assert_eq!(float_lt(2.0, 2.0), Ok(false));
assert_eq!(float_lt(3.4, -1.7), Ok(false));
assert_eq!(float_lt(0.0, 0.0), Ok(false));
assert_eq!(float_lt(-0.0, -0.0), Ok(false));
assert_eq!(float_lt(-0.0, 0.0), Ok(false));
assert_eq!(float_lt(-5.2, f64::NAN), Ok(false));
assert_eq!(float_lt(f64::NAN, f64::NAN), Ok(false));
assert_eq!(float_lt(f64::INFINITY, f64::NEG_INFINITY), Ok(false));
}
#[test]
fn test_float_lte() {
let float_lte = jit_function! { float_lte(a: f64, b: f64) -> bool => r##"
def float_lte(a: float, b: float):
return a <= b
"## };
assert_eq!(float_lte(2.0, 2.0), Ok(true));
assert_eq!(float_lte(3.4, -1.7), Ok(false));
assert_eq!(float_lte(0.0, 0.0), Ok(true));
assert_eq!(float_lte(-0.0, -0.0), Ok(true));
assert_eq!(float_lte(-0.0, 0.0), Ok(true));
assert_eq!(float_lte(-5.2, f64::NAN), Ok(false));
assert_eq!(float_lte(f64::NAN, f64::NAN), Ok(false));
assert_eq!(float_lte(f64::INFINITY, f64::NEG_INFINITY), Ok(false));
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/jit/tests/lib.rs | crates/jit/tests/lib.rs | #[macro_use]
mod common;
mod bool_tests;
mod float_tests;
mod int_tests;
mod misc_tests;
mod none_tests;
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/jit/tests/none_tests.rs | crates/jit/tests/none_tests.rs | #[test]
fn test_not() {
let not_ = jit_function! { not_(x: i64) -> bool => r##"
def not_(x: int):
return not None
"## };
assert_eq!(not_(0), Ok(true));
}
#[test]
fn test_if_not() {
let if_not = jit_function! { if_not(x: i64) -> i64 => r##"
def if_not(x: int):
if not None:
return 1
else:
return 0
return -1
"## };
assert_eq!(if_not(0), Ok(1));
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/jit/tests/common.rs | crates/jit/tests/common.rs | use core::ops::ControlFlow;
use rustpython_compiler_core::bytecode::{
CodeObject, ConstantData, Instruction, OpArg, OpArgState,
};
use rustpython_jit::{CompiledCode, JitType};
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub struct Function {
code: Box<CodeObject>,
annotations: HashMap<String, StackValue>,
}
impl Function {
pub fn compile(self) -> CompiledCode {
let mut arg_types = Vec::new();
for arg in self.code.arg_names().args {
let arg_type = match self.annotations.get(arg) {
Some(StackValue::String(annotation)) => match annotation.as_str() {
"int" => JitType::Int,
"float" => JitType::Float,
"bool" => JitType::Bool,
_ => panic!("Unrecognised jit type"),
},
_ => panic!("Argument have annotation"),
};
arg_types.push(arg_type);
}
let ret_type = match self.annotations.get("return") {
Some(StackValue::String(annotation)) => match annotation.as_str() {
"int" => Some(JitType::Int),
"float" => Some(JitType::Float),
"bool" => Some(JitType::Bool),
_ => panic!("Unrecognised jit type"),
},
_ => None,
};
rustpython_jit::compile(&self.code, &arg_types, ret_type).expect("Compile failure")
}
}
#[derive(Debug, Clone)]
enum StackValue {
String(String),
None,
Map(HashMap<String, StackValue>),
Code(Box<CodeObject>),
Function(Function),
}
impl From<ConstantData> for StackValue {
fn from(value: ConstantData) -> Self {
match value {
ConstantData::Str { value } => {
StackValue::String(value.into_string().expect("surrogate in test code"))
}
ConstantData::None => StackValue::None,
ConstantData::Code { code } => StackValue::Code(code),
c => unimplemented!("constant {:?} isn't yet supported in py_function!", c),
}
}
}
pub struct StackMachine {
stack: Vec<StackValue>,
locals: HashMap<String, StackValue>,
}
impl StackMachine {
pub fn new() -> StackMachine {
StackMachine {
stack: Vec::new(),
locals: HashMap::new(),
}
}
pub fn run(&mut self, code: CodeObject) {
let mut op_arg_state = OpArgState::default();
let _ = code.instructions.iter().try_for_each(|&word| {
let (instruction, arg) = op_arg_state.get(word);
self.process_instruction(instruction, arg, &code.constants, &code.names)
});
}
fn process_instruction(
&mut self,
instruction: Instruction,
arg: OpArg,
constants: &[ConstantData],
names: &[String],
) -> ControlFlow<()> {
match instruction {
Instruction::LoadConst { idx } => {
let idx = idx.get(arg);
self.stack.push(constants[idx as usize].clone().into())
}
Instruction::LoadNameAny(idx) => self
.stack
.push(StackValue::String(names[idx.get(arg) as usize].clone())),
Instruction::StoreLocal(idx) => {
let idx = idx.get(arg);
self.locals
.insert(names[idx as usize].clone(), self.stack.pop().unwrap());
}
Instruction::StoreAttr { .. } => {
// Do nothing except throw away the stack values
self.stack.pop().unwrap();
self.stack.pop().unwrap();
}
Instruction::BuildMap { size, .. } => {
let mut map = HashMap::new();
for _ in 0..size.get(arg) {
let value = self.stack.pop().unwrap();
let name = if let Some(StackValue::String(name)) = self.stack.pop() {
name
} else {
unimplemented!("no string keys isn't yet supported in py_function!")
};
map.insert(name, value);
}
self.stack.push(StackValue::Map(map));
}
Instruction::MakeFunction => {
let code = if let Some(StackValue::Code(code)) = self.stack.pop() {
code
} else {
panic!("Expected function code")
};
// Other attributes will be set by SET_FUNCTION_ATTRIBUTE
self.stack.push(StackValue::Function(Function {
code,
annotations: HashMap::new(), // empty annotations, will be set later if needed
}));
}
Instruction::SetFunctionAttribute { attr } => {
// Stack: [..., attr_value, func] -> [..., func]
let func = if let Some(StackValue::Function(func)) = self.stack.pop() {
func
} else {
panic!("Expected function on stack for SET_FUNCTION_ATTRIBUTE")
};
let attr_value = self.stack.pop().expect("Expected attribute value on stack");
// For now, we only handle ANNOTATIONS flag in JIT tests
if attr
.get(arg)
.contains(rustpython_compiler_core::bytecode::MakeFunctionFlags::ANNOTATIONS)
{
if let StackValue::Map(annotations) = attr_value {
// Update function's annotations
let updated_func = Function {
code: func.code,
annotations,
};
self.stack.push(StackValue::Function(updated_func));
} else {
panic!("Expected annotations to be a map");
}
} else {
// For other attributes, just push the function back unchanged
// (since JIT tests mainly care about type annotations)
self.stack.push(StackValue::Function(func));
}
}
Instruction::ReturnConst { idx } => {
let idx = idx.get(arg);
self.stack.push(constants[idx as usize].clone().into());
return ControlFlow::Break(());
}
Instruction::ReturnValue => return ControlFlow::Break(()),
Instruction::ExtendedArg => {}
_ => unimplemented!(
"instruction {:?} isn't yet supported in py_function!",
instruction
),
}
ControlFlow::Continue(())
}
pub fn get_function(&self, name: &str) -> Function {
if let Some(StackValue::Function(function)) = self.locals.get(name) {
function.clone()
} else {
panic!("There was no function named {name}")
}
}
}
macro_rules! jit_function {
($func_name:ident => $($t:tt)*) => {
{
let code = rustpython_derive::py_compile!(
crate_name = "rustpython_compiler_core",
source = $($t)*
);
let code = code.decode(rustpython_compiler_core::bytecode::BasicBag);
let mut machine = $crate::common::StackMachine::new();
machine.run(code);
machine.get_function(stringify!($func_name)).compile()
}
};
($func_name:ident($($arg_name:ident:$arg_type:ty),*) -> $ret_type:ty => $($t:tt)*) => {
{
let jit_code = jit_function!($func_name => $($t)*);
move |$($arg_name:$arg_type),*| -> Result<$ret_type, rustpython_jit::JitArgumentError> {
jit_code
.invoke(&[$($arg_name.into()),*])
.map(|ret| match ret {
Some(ret) => ret.try_into().expect("jit function returned unexpected type"),
None => panic!("jit function unexpectedly returned None")
})
}
}
};
($func_name:ident($($arg_name:ident:$arg_type:ty),*) => $($t:tt)*) => {
{
let jit_code = jit_function!($func_name => $($t)*);
move |$($arg_name:$arg_type),*| -> Result<(), rustpython_jit::JitArgumentError> {
jit_code
.invoke(&[$($arg_name.into()),*])
.map(|ret| match ret {
Some(ret) => panic!("jit function unexpectedly returned a value {:?}", ret),
None => ()
})
}
}
};
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/jit/tests/misc_tests.rs | crates/jit/tests/misc_tests.rs | use rustpython_jit::{AbiValue, JitArgumentError};
// TODO currently broken
// #[test]
// fn test_no_return_value() {
// let func = jit_function! { func() => r##"
// def func():
// pass
// "## };
//
// assert_eq!(func(), Ok(()));
// }
#[test]
fn test_invoke() {
let func = jit_function! { func => r##"
def func(a: int, b: float):
return 1
"## };
assert_eq!(
func.invoke(&[AbiValue::Int(1)]),
Err(JitArgumentError::WrongNumberOfArguments)
);
assert_eq!(
func.invoke(&[AbiValue::Int(1), AbiValue::Float(2.0), AbiValue::Int(0)]),
Err(JitArgumentError::WrongNumberOfArguments)
);
assert_eq!(
func.invoke(&[AbiValue::Int(1), AbiValue::Int(1)]),
Err(JitArgumentError::ArgumentTypeMismatch)
);
assert_eq!(
func.invoke(&[AbiValue::Int(1), AbiValue::Float(2.0)]),
Ok(Some(AbiValue::Int(1)))
);
}
#[test]
fn test_args_builder() {
let func = jit_function! { func=> r##"
def func(a: int, b: float):
return 1
"## };
let mut args_builder = func.args_builder();
assert_eq!(args_builder.set(0, AbiValue::Int(1)), Ok(()));
assert!(args_builder.is_set(0));
assert!(!args_builder.is_set(1));
assert_eq!(
args_builder.set(1, AbiValue::Int(1)),
Err(JitArgumentError::ArgumentTypeMismatch)
);
assert!(args_builder.is_set(0));
assert!(!args_builder.is_set(1));
assert!(args_builder.into_args().is_none());
let mut args_builder = func.args_builder();
assert_eq!(args_builder.set(0, AbiValue::Int(1)), Ok(()));
assert_eq!(args_builder.set(1, AbiValue::Float(1.0)), Ok(()));
assert!(args_builder.is_set(0));
assert!(args_builder.is_set(1));
let args = args_builder.into_args();
assert!(args.is_some());
assert_eq!(args.unwrap().invoke(), Some(AbiValue::Int(1)));
}
#[test]
fn test_if_else() {
let if_else = jit_function! { if_else(a:i64) -> i64 => r##"
def if_else(a: int):
if a:
return 42
else:
return 0
# Prevent type failure from implicit `return None`
return 0
"## };
assert_eq!(if_else(0), Ok(0));
assert_eq!(if_else(1), Ok(42));
assert_eq!(if_else(-1), Ok(42));
assert_eq!(if_else(100), Ok(42));
}
#[test]
fn test_while_loop() {
let while_loop = jit_function! { while_loop(a:i64) -> i64 => r##"
def while_loop(a: int):
b = 0
while a > 0:
b += 1
a -= 1
return b
"## };
assert_eq!(while_loop(0), Ok(0));
assert_eq!(while_loop(-1), Ok(0));
assert_eq!(while_loop(1), Ok(1));
assert_eq!(while_loop(10), Ok(10));
}
#[test]
fn test_unpack_tuple() {
let unpack_tuple = jit_function! { unpack_tuple(a:i64, b:i64) -> i64 => r##"
def unpack_tuple(a: int, b: int):
a, b = b, a
return a
"## };
assert_eq!(unpack_tuple(0, 1), Ok(1));
assert_eq!(unpack_tuple(1, 2), Ok(2));
}
#[test]
fn test_recursive_fib() {
let fib = jit_function! { fib(n: i64) -> i64 => r##"
def fib(n: int) -> int:
if n == 0 or n == 1:
return 1
return fib(n-1) + fib(n-2)
"## };
assert_eq!(fib(10), Ok(89));
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/jit/tests/bool_tests.rs | crates/jit/tests/bool_tests.rs | #[test]
fn test_return() {
let return_ = jit_function! { return_(a: bool) -> bool => r##"
def return_(a: bool):
return a
"## };
assert_eq!(return_(true), Ok(true));
assert_eq!(return_(false), Ok(false));
}
#[test]
fn test_const() {
let const_true = jit_function! { const_true(a: i64) -> bool => r##"
def const_true(a: int):
return True
"## };
assert_eq!(const_true(0), Ok(true));
let const_false = jit_function! { const_false(a: i64) -> bool => r##"
def const_false(a: int):
return False
"## };
assert_eq!(const_false(0), Ok(false));
}
#[test]
fn test_not() {
let not_ = jit_function! { not_(a: bool) -> bool => r##"
def not_(a: bool):
return not a
"## };
assert_eq!(not_(true), Ok(false));
assert_eq!(not_(false), Ok(true));
}
#[test]
fn test_if_not() {
let if_not = jit_function! { if_not(a: bool) -> i64 => r##"
def if_not(a: bool):
if not a:
return 0
else:
return 1
return -1
"## };
assert_eq!(if_not(true), Ok(1));
assert_eq!(if_not(false), Ok(0));
}
#[test]
fn test_eq() {
let eq = jit_function! { eq(a:bool, b:bool) -> i64 => r##"
def eq(a: bool, b: bool):
if a == b:
return 1
return 0
"## };
assert_eq!(eq(false, false), Ok(1));
assert_eq!(eq(true, true), Ok(1));
assert_eq!(eq(false, true), Ok(0));
assert_eq!(eq(true, false), Ok(0));
}
#[test]
fn test_eq_with_integers() {
let eq = jit_function! { eq(a:bool, b:i64) -> i64 => r##"
def eq(a: bool, b: int):
if a == b:
return 1
return 0
"## };
assert_eq!(eq(false, 0), Ok(1));
assert_eq!(eq(true, 1), Ok(1));
assert_eq!(eq(false, 1), Ok(0));
assert_eq!(eq(true, 0), Ok(0));
}
#[test]
fn test_gt() {
let gt = jit_function! { gt(a:bool, b:bool) -> i64 => r##"
def gt(a: bool, b: bool):
if a > b:
return 1
return 0
"## };
assert_eq!(gt(false, false), Ok(0));
assert_eq!(gt(true, true), Ok(0));
assert_eq!(gt(false, true), Ok(0));
assert_eq!(gt(true, false), Ok(1));
}
#[test]
fn test_gt_with_integers() {
let gt = jit_function! { gt(a:i64, b:bool) -> i64 => r##"
def gt(a: int, b: bool):
if a > b:
return 1
return 0
"## };
assert_eq!(gt(0, false), Ok(0));
assert_eq!(gt(1, true), Ok(0));
assert_eq!(gt(0, true), Ok(0));
assert_eq!(gt(1, false), Ok(1));
}
#[test]
fn test_lt() {
let lt = jit_function! { lt(a:bool, b:bool) -> i64 => r##"
def lt(a: bool, b: bool):
if a < b:
return 1
return 0
"## };
assert_eq!(lt(false, false), Ok(0));
assert_eq!(lt(true, true), Ok(0));
assert_eq!(lt(false, true), Ok(1));
assert_eq!(lt(true, false), Ok(0));
}
#[test]
fn test_lt_with_integers() {
let lt = jit_function! { lt(a:i64, b:bool) -> i64 => r##"
def lt(a: int, b: bool):
if a < b:
return 1
return 0
"## };
assert_eq!(lt(0, false), Ok(0));
assert_eq!(lt(1, true), Ok(0));
assert_eq!(lt(0, true), Ok(1));
assert_eq!(lt(1, false), Ok(0));
}
#[test]
fn test_gte() {
let gte = jit_function! { gte(a:bool, b:bool) -> i64 => r##"
def gte(a: bool, b: bool):
if a >= b:
return 1
return 0
"## };
assert_eq!(gte(false, false), Ok(1));
assert_eq!(gte(true, true), Ok(1));
assert_eq!(gte(false, true), Ok(0));
assert_eq!(gte(true, false), Ok(1));
}
#[test]
fn test_gte_with_integers() {
let gte = jit_function! { gte(a:bool, b:i64) -> i64 => r##"
def gte(a: bool, b: int):
if a >= b:
return 1
return 0
"## };
assert_eq!(gte(false, 0), Ok(1));
assert_eq!(gte(true, 1), Ok(1));
assert_eq!(gte(false, 1), Ok(0));
assert_eq!(gte(true, 0), Ok(1));
}
#[test]
fn test_lte() {
let lte = jit_function! { lte(a:bool, b:bool) -> i64 => r##"
def lte(a: bool, b: bool):
if a <= b:
return 1
return 0
"## };
assert_eq!(lte(false, false), Ok(1));
assert_eq!(lte(true, true), Ok(1));
assert_eq!(lte(false, true), Ok(1));
assert_eq!(lte(true, false), Ok(0));
}
#[test]
fn test_lte_with_integers() {
let lte = jit_function! { lte(a:bool, b:i64) -> i64 => r##"
def lte(a: bool, b: int):
if a <= b:
return 1
return 0
"## };
assert_eq!(lte(false, 0), Ok(1));
assert_eq!(lte(true, 1), Ok(1));
assert_eq!(lte(false, 1), Ok(1));
assert_eq!(lte(true, 0), Ok(0));
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/jit/tests/int_tests.rs | crates/jit/tests/int_tests.rs | use core::f64;
#[test]
fn test_add() {
let add = jit_function! { add(a:i64, b:i64) -> i64 => r##"
def add(a: int, b: int):
return a + b
"## };
assert_eq!(add(5, 10), Ok(15));
assert_eq!(add(-5, 12), Ok(7));
assert_eq!(add(-5, -3), Ok(-8));
}
#[test]
fn test_sub() {
let sub = jit_function! { sub(a:i64, b:i64) -> i64 => r##"
def sub(a: int, b: int):
return a - b
"## };
assert_eq!(sub(5, 10), Ok(-5));
assert_eq!(sub(12, 10), Ok(2));
assert_eq!(sub(7, 10), Ok(-3));
assert_eq!(sub(-3, -10), Ok(7));
}
#[test]
fn test_mul() {
let mul = jit_function! { mul(a:i64, b:i64) -> i64 => r##"
def mul(a: int, b: int):
return a * b
"## };
assert_eq!(mul(5, 10), Ok(50));
assert_eq!(mul(0, 5), Ok(0));
assert_eq!(mul(5, 0), Ok(0));
assert_eq!(mul(0, 0), Ok(0));
assert_eq!(mul(-5, 10), Ok(-50));
assert_eq!(mul(5, -10), Ok(-50));
assert_eq!(mul(-5, -10), Ok(50));
assert_eq!(mul(999999, 999999), Ok(999998000001));
assert_eq!(mul(i64::MAX, 1), Ok(i64::MAX));
assert_eq!(mul(1, i64::MAX), Ok(i64::MAX));
}
#[test]
fn test_div() {
let div = jit_function! { div(a:i64, b:i64) -> f64 => r##"
def div(a: int, b: int):
return a / b
"## };
assert_eq!(div(0, 1), Ok(0.0));
assert_eq!(div(5, 1), Ok(5.0));
assert_eq!(div(5, 10), Ok(0.5));
assert_eq!(div(5, 2), Ok(2.5));
assert_eq!(div(12, 10), Ok(1.2));
assert_eq!(div(7, 10), Ok(0.7));
assert_eq!(div(-3, -1), Ok(3.0));
assert_eq!(div(-3, 1), Ok(-3.0));
assert_eq!(div(1, 1000), Ok(0.001));
assert_eq!(div(1, 100000), Ok(0.00001));
assert_eq!(div(2, 3), Ok(0.6666666666666666));
assert_eq!(div(1, 3), Ok(0.3333333333333333));
assert_eq!(div(i64::MAX, 2), Ok(4611686018427387904.0));
assert_eq!(div(i64::MIN, 2), Ok(-4611686018427387904.0));
assert_eq!(div(i64::MIN, -1), Ok(9223372036854775808.0)); // Overflow case
assert_eq!(div(i64::MIN, i64::MAX), Ok(-1.0));
}
#[test]
fn test_floor_div() {
let floor_div = jit_function! { floor_div(a:i64, b:i64) -> i64 => r##"
def floor_div(a: int, b: int):
return a // b
"## };
assert_eq!(floor_div(5, 10), Ok(0));
assert_eq!(floor_div(5, 2), Ok(2));
assert_eq!(floor_div(12, 10), Ok(1));
assert_eq!(floor_div(7, 10), Ok(0));
assert_eq!(floor_div(-3, -1), Ok(3));
}
#[test]
fn test_exp() {
let exp = jit_function! { exp(a: i64, b: i64) -> i64 => r##"
def exp(a: int, b: int):
return a ** b
"## };
assert_eq!(exp(2, 3), Ok(8));
assert_eq!(exp(3, 2), Ok(9));
assert_eq!(exp(5, 0), Ok(1));
assert_eq!(exp(0, 0), Ok(1));
assert_eq!(exp(-5, 0), Ok(1));
assert_eq!(exp(0, 1), Ok(0));
assert_eq!(exp(0, 5), Ok(0));
assert_eq!(exp(-2, 2), Ok(4));
assert_eq!(exp(-3, 4), Ok(81));
assert_eq!(exp(-2, 3), Ok(-8));
assert_eq!(exp(-3, 3), Ok(-27));
assert_eq!(exp(1000, 2), Ok(1000000));
}
#[test]
fn test_mod() {
let modulo = jit_function! { modulo(a:i64, b:i64) -> i64 => r##"
def modulo(a: int, b: int):
return a % b
"## };
assert_eq!(modulo(5, 10), Ok(5));
assert_eq!(modulo(5, 2), Ok(1));
assert_eq!(modulo(12, 10), Ok(2));
assert_eq!(modulo(7, 10), Ok(7));
assert_eq!(modulo(-3, 1), Ok(0));
assert_eq!(modulo(-5, 10), Ok(-5));
}
#[test]
fn test_power() {
let power = jit_function! { power(a:i64, b:i64) -> i64 => r##"
def power(a: int, b: int):
return a ** b
"##
};
assert_eq!(power(10, 2), Ok(100));
assert_eq!(power(5, 1), Ok(5));
assert_eq!(power(1, 0), Ok(1));
}
#[test]
fn test_lshift() {
let lshift = jit_function! { lshift(a:i64, b:i64) -> i64 => r##"
def lshift(a: int, b: int):
return a << b
"## };
assert_eq!(lshift(5, 10), Ok(5120));
assert_eq!(lshift(5, 2), Ok(20));
assert_eq!(lshift(12, 10), Ok(12288));
assert_eq!(lshift(7, 10), Ok(7168));
assert_eq!(lshift(-3, 1), Ok(-6));
assert_eq!(lshift(-10, 2), Ok(-40));
}
#[test]
fn test_rshift() {
let rshift = jit_function! { rshift(a:i64, b:i64) -> i64 => r##"
def rshift(a: int, b: int):
return a >> b
"## };
assert_eq!(rshift(5120, 10), Ok(5));
assert_eq!(rshift(20, 2), Ok(5));
assert_eq!(rshift(12288, 10), Ok(12));
assert_eq!(rshift(7168, 10), Ok(7));
assert_eq!(rshift(-3, 1), Ok(-2));
assert_eq!(rshift(-10, 2), Ok(-3));
}
#[test]
fn test_and() {
let bitand = jit_function! { bitand(a:i64, b:i64) -> i64 => r##"
def bitand(a: int, b: int):
return a & b
"## };
assert_eq!(bitand(5120, 10), Ok(0));
assert_eq!(bitand(20, 16), Ok(16));
assert_eq!(bitand(12488, 4249), Ok(4232));
assert_eq!(bitand(7168, 2), Ok(0));
assert_eq!(bitand(-3, 1), Ok(1));
assert_eq!(bitand(-10, 2), Ok(2));
}
#[test]
fn test_or() {
let bitor = jit_function! { bitor(a:i64, b:i64) -> i64 => r##"
def bitor(a: int, b: int):
return a | b
"## };
assert_eq!(bitor(5120, 10), Ok(5130));
assert_eq!(bitor(20, 16), Ok(20));
assert_eq!(bitor(12488, 4249), Ok(12505));
assert_eq!(bitor(7168, 2), Ok(7170));
assert_eq!(bitor(-3, 1), Ok(-3));
assert_eq!(bitor(-10, 2), Ok(-10));
}
#[test]
fn test_xor() {
let bitxor = jit_function! { bitxor(a:i64, b:i64) -> i64 => r##"
def bitxor(a: int, b: int):
return a ^ b
"## };
assert_eq!(bitxor(5120, 10), Ok(5130));
assert_eq!(bitxor(20, 16), Ok(4));
assert_eq!(bitxor(12488, 4249), Ok(8273));
assert_eq!(bitxor(7168, 2), Ok(7170));
assert_eq!(bitxor(-3, 1), Ok(-4));
assert_eq!(bitxor(-10, 2), Ok(-12));
}
#[test]
fn test_eq() {
let eq = jit_function! { eq(a:i64, b:i64) -> i64 => r##"
def eq(a: int, b: int):
if a == b:
return 1
return 0
"## };
assert_eq!(eq(0, 0), Ok(1));
assert_eq!(eq(1, 1), Ok(1));
assert_eq!(eq(0, 1), Ok(0));
assert_eq!(eq(-200, 200), Ok(0));
}
#[test]
fn test_gt() {
let gt = jit_function! { gt(a:i64, b:i64) -> i64 => r##"
def gt(a: int, b: int):
if a > b:
return 1
return 0
"## };
assert_eq!(gt(5, 2), Ok(1));
assert_eq!(gt(2, 5), Ok(0));
assert_eq!(gt(2, 2), Ok(0));
assert_eq!(gt(5, 5), Ok(0));
assert_eq!(gt(-1, -10), Ok(1));
assert_eq!(gt(1, -1), Ok(1));
}
#[test]
fn test_lt() {
let lt = jit_function! { lt(a:i64, b:i64) -> i64 => r##"
def lt(a: int, b: int):
if a < b:
return 1
return 0
"## };
assert_eq!(lt(-1, -5), Ok(0));
assert_eq!(lt(10, 0), Ok(0));
assert_eq!(lt(0, 1), Ok(1));
assert_eq!(lt(-10, -1), Ok(1));
assert_eq!(lt(100, 100), Ok(0));
}
#[test]
fn test_gte() {
let gte = jit_function! { gte(a:i64, b:i64) -> i64 => r##"
def gte(a: int, b: int):
if a >= b:
return 1
return 0
"## };
assert_eq!(gte(-64, -64), Ok(1));
assert_eq!(gte(100, -1), Ok(1));
assert_eq!(gte(1, 2), Ok(0));
assert_eq!(gte(1, 0), Ok(1));
}
#[test]
fn test_lte() {
let lte = jit_function! { lte(a:i64, b:i64) -> i64 => r##"
def lte(a: int, b: int):
if a <= b:
return 1
return 0
"## };
assert_eq!(lte(-100, -100), Ok(1));
assert_eq!(lte(-100, 100), Ok(1));
assert_eq!(lte(10, 1), Ok(0));
assert_eq!(lte(0, -2), Ok(0));
}
#[test]
fn test_minus() {
let minus = jit_function! { minus(a:i64) -> i64 => r##"
def minus(a: int):
return -a
"## };
assert_eq!(minus(5), Ok(-5));
assert_eq!(minus(12), Ok(-12));
assert_eq!(minus(-7), Ok(7));
assert_eq!(minus(-3), Ok(3));
assert_eq!(minus(0), Ok(0));
}
#[test]
fn test_plus() {
let plus = jit_function! { plus(a:i64) -> i64 => r##"
def plus(a: int):
return +a
"## };
assert_eq!(plus(5), Ok(5));
assert_eq!(plus(12), Ok(12));
assert_eq!(plus(-7), Ok(-7));
assert_eq!(plus(-3), Ok(-3));
assert_eq!(plus(0), Ok(0));
}
#[test]
fn test_not() {
let not_ = jit_function! { not_(a: i64) -> bool => r##"
def not_(a: int):
return not a
"## };
assert_eq!(not_(0), Ok(true));
assert_eq!(not_(1), Ok(false));
assert_eq!(not_(-1), Ok(false));
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/codegen/src/lib.rs | crates/codegen/src/lib.rs | //! Compile a Python AST or source code into bytecode consumable by RustPython.
#![doc(html_logo_url = "https://raw.githubusercontent.com/RustPython/RustPython/main/logo.png")]
#![doc(html_root_url = "https://docs.rs/rustpython-compiler/")]
#[macro_use]
extern crate log;
extern crate alloc;
type IndexMap<K, V> = indexmap::IndexMap<K, V, ahash::RandomState>;
type IndexSet<T> = indexmap::IndexSet<T, ahash::RandomState>;
pub mod compile;
pub mod error;
pub mod ir;
mod string_parser;
pub mod symboltable;
mod unparse;
pub use compile::CompileOpts;
use ruff_python_ast::Expr;
pub(crate) use compile::InternalResult;
pub trait ToPythonName {
/// Returns a short name for the node suitable for use in error messages.
fn python_name(&self) -> &'static str;
}
impl ToPythonName for Expr {
fn python_name(&self) -> &'static str {
match self {
Self::BoolOp { .. } | Self::BinOp { .. } | Self::UnaryOp { .. } => "operator",
Self::Subscript { .. } => "subscript",
Self::Await { .. } => "await expression",
Self::Yield { .. } | Self::YieldFrom { .. } => "yield expression",
Self::Compare { .. } => "comparison",
Self::Attribute { .. } => "attribute",
Self::Call { .. } => "function call",
Self::BooleanLiteral(b) => {
if b.value {
"True"
} else {
"False"
}
}
Self::EllipsisLiteral(_) => "ellipsis",
Self::NoneLiteral(_) => "None",
Self::NumberLiteral(_) | Self::BytesLiteral(_) | Self::StringLiteral(_) => "literal",
Self::Tuple(_) => "tuple",
Self::List { .. } => "list",
Self::Dict { .. } => "dict display",
Self::Set { .. } => "set display",
Self::ListComp { .. } => "list comprehension",
Self::DictComp { .. } => "dict comprehension",
Self::SetComp { .. } => "set comprehension",
Self::Generator { .. } => "generator expression",
Self::Starred { .. } => "starred",
Self::Slice { .. } => "slice",
Self::FString { .. } => "f-string expression",
Self::TString { .. } => "t-string expression",
Self::Name { .. } => "name",
Self::Lambda { .. } => "lambda",
Self::If { .. } => "conditional expression",
Self::Named { .. } => "named expression",
Self::IpyEscapeCommand(_) => todo!(),
}
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/codegen/src/symboltable.rs | crates/codegen/src/symboltable.rs | /* Python code is pre-scanned for symbols in the ast.
This ensures that global and nonlocal keywords are picked up.
Then the compiler can use the symbol table to generate proper
load and store instructions for names.
Inspirational file: https://github.com/python/cpython/blob/main/Python/symtable.c
*/
use crate::{
IndexMap,
error::{CodegenError, CodegenErrorType},
};
use alloc::{borrow::Cow, fmt};
use bitflags::bitflags;
use ruff_python_ast::{
self as ast, Comprehension, Decorator, Expr, Identifier, ModExpression, ModModule, Parameter,
ParameterWithDefault, Parameters, Pattern, PatternMatchAs, PatternMatchClass,
PatternMatchMapping, PatternMatchOr, PatternMatchSequence, PatternMatchStar, PatternMatchValue,
Stmt, TypeParam, TypeParamParamSpec, TypeParamTypeVar, TypeParamTypeVarTuple, TypeParams,
};
use ruff_text_size::{Ranged, TextRange};
use rustpython_compiler_core::{PositionEncoding, SourceFile, SourceLocation};
/// Captures all symbols in the current scope, and has a list of sub-scopes in this scope.
#[derive(Clone)]
pub struct SymbolTable {
/// The name of this symbol table. Often the name of the class or function.
pub name: String,
/// The type of symbol table
pub typ: CompilerScope,
/// The line number in the source code where this symboltable begins.
pub line_number: u32,
// Return True if the block is a nested class or function
pub is_nested: bool,
/// A set of symbols present on this scope level.
pub symbols: IndexMap<String, Symbol>,
/// A list of sub-scopes in the order as found in the
/// AST nodes.
pub sub_tables: Vec<SymbolTable>,
/// Variable names in definition order (parameters first, then locals)
pub varnames: Vec<String>,
/// Whether this class scope needs an implicit __class__ cell
pub needs_class_closure: bool,
/// Whether this class scope needs an implicit __classdict__ cell
pub needs_classdict: bool,
/// Whether this type param scope can see the parent class scope
pub can_see_class_scope: bool,
/// Whether this comprehension scope should be inlined (PEP 709)
/// True for list/set/dict comprehensions in non-generator expressions
pub comp_inlined: bool,
}
impl SymbolTable {
fn new(name: String, typ: CompilerScope, line_number: u32, is_nested: bool) -> Self {
Self {
name,
typ,
line_number,
is_nested,
symbols: IndexMap::default(),
sub_tables: vec![],
varnames: Vec::new(),
needs_class_closure: false,
needs_classdict: false,
can_see_class_scope: false,
comp_inlined: false,
}
}
pub fn scan_program(program: &ModModule, source_file: SourceFile) -> SymbolTableResult<Self> {
let mut builder = SymbolTableBuilder::new(source_file);
builder.scan_statements(program.body.as_ref())?;
builder.finish()
}
pub fn scan_expr(expr: &ModExpression, source_file: SourceFile) -> SymbolTableResult<Self> {
let mut builder = SymbolTableBuilder::new(source_file);
builder.scan_expression(expr.body.as_ref(), ExpressionContext::Load)?;
builder.finish()
}
pub fn lookup(&self, name: &str) -> Option<&Symbol> {
self.symbols.get(name)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompilerScope {
Module,
Class,
Function,
AsyncFunction,
Lambda,
Comprehension,
TypeParams,
}
impl fmt::Display for CompilerScope {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Module => write!(f, "module"),
Self::Class => write!(f, "class"),
Self::Function => write!(f, "function"),
Self::AsyncFunction => write!(f, "async function"),
Self::Lambda => write!(f, "lambda"),
Self::Comprehension => write!(f, "comprehension"),
Self::TypeParams => write!(f, "type parameter"),
// TODO missing types from the C implementation
// if self._table.type == _symtable.TYPE_ANNOTATION:
// return "annotation"
// if self._table.type == _symtable.TYPE_TYPE_VAR_BOUND:
// return "TypeVar bound"
// if self._table.type == _symtable.TYPE_TYPE_ALIAS:
// return "type alias"
}
}
}
/// Indicator for a single symbol what the scope of this symbol is.
/// The scope can be unknown, which is unfortunate, but not impossible.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolScope {
Unknown,
Local,
GlobalExplicit,
GlobalImplicit,
Free,
Cell,
}
bitflags! {
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct SymbolFlags: u16 {
const REFERENCED = 0x001; // USE
const ASSIGNED = 0x002; // DEF_LOCAL
const PARAMETER = 0x004; // DEF_PARAM
const ANNOTATED = 0x008; // DEF_ANNOT
const IMPORTED = 0x010; // DEF_IMPORT
const NONLOCAL = 0x020; // DEF_NONLOCAL
// indicates if the symbol gets a value assigned by a named expression in a comprehension
// this is required to correct the scope in the analysis.
const ASSIGNED_IN_COMPREHENSION = 0x040;
// indicates that the symbol is used a bound iterator variable. We distinguish this case
// from normal assignment to detect disallowed re-assignment to iterator variables.
const ITER = 0x080;
/// indicates that the symbol is a free variable in a class method from the scope that the
/// class is defined in, e.g.:
/// ```python
/// def foo(x):
/// class A:
/// def method(self):
/// return x // is_free_class
/// ```
const FREE_CLASS = 0x100; // DEF_FREE_CLASS
const GLOBAL = 0x200; // DEF_GLOBAL
const COMP_ITER = 0x400; // DEF_COMP_ITER
const COMP_CELL = 0x800; // DEF_COMP_CELL
const TYPE_PARAM = 0x1000; // DEF_TYPE_PARAM
const BOUND = Self::ASSIGNED.bits() | Self::PARAMETER.bits() | Self::IMPORTED.bits() | Self::ITER.bits() | Self::TYPE_PARAM.bits();
}
}
/// A single symbol in a table. Has various properties such as the scope
/// of the symbol, and also the various uses of the symbol.
#[derive(Debug, Clone)]
pub struct Symbol {
pub name: String,
pub scope: SymbolScope,
pub flags: SymbolFlags,
}
impl Symbol {
fn new(name: &str) -> Self {
Self {
name: name.to_owned(),
// table,
scope: SymbolScope::Unknown,
flags: SymbolFlags::empty(),
}
}
pub const fn is_global(&self) -> bool {
matches!(
self.scope,
SymbolScope::GlobalExplicit | SymbolScope::GlobalImplicit
)
}
pub const fn is_local(&self) -> bool {
matches!(self.scope, SymbolScope::Local | SymbolScope::Cell)
}
pub const fn is_bound(&self) -> bool {
self.flags.intersects(SymbolFlags::BOUND)
}
}
#[derive(Debug)]
pub struct SymbolTableError {
error: String,
location: Option<SourceLocation>,
}
impl SymbolTableError {
pub fn into_codegen_error(self, source_path: String) -> CodegenError {
CodegenError {
location: self.location,
error: CodegenErrorType::SyntaxError(self.error),
source_path,
}
}
}
type SymbolTableResult<T = ()> = Result<T, SymbolTableError>;
impl core::fmt::Debug for SymbolTable {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"SymbolTable({:?} symbols, {:?} sub scopes)",
self.symbols.len(),
self.sub_tables.len()
)
}
}
/* Perform some sort of analysis on nonlocals, globals etc..
See also: https://github.com/python/cpython/blob/main/Python/symtable.c#L410
*/
fn analyze_symbol_table(symbol_table: &mut SymbolTable) -> SymbolTableResult {
let mut analyzer = SymbolTableAnalyzer::default();
analyzer.analyze_symbol_table(symbol_table)
}
/* Drop __class__ and __classdict__ from free variables in class scope
and set the appropriate flags. Equivalent to CPython's drop_class_free().
See: https://github.com/python/cpython/blob/main/Python/symtable.c#L884
*/
fn drop_class_free(symbol_table: &mut SymbolTable) {
// Check if __class__ is used as a free variable
if let Some(class_symbol) = symbol_table.symbols.get("__class__")
&& class_symbol.scope == SymbolScope::Free
{
symbol_table.needs_class_closure = true;
// Note: In CPython, the symbol is removed from the free set,
// but in RustPython we handle this differently during code generation
}
// Check if __classdict__ is used as a free variable
if let Some(classdict_symbol) = symbol_table.symbols.get("__classdict__")
&& classdict_symbol.scope == SymbolScope::Free
{
symbol_table.needs_classdict = true;
// Note: In CPython, the symbol is removed from the free set,
// but in RustPython we handle this differently during code generation
}
}
type SymbolMap = IndexMap<String, Symbol>;
mod stack {
use core::ptr::NonNull;
use std::panic;
pub struct StackStack<T> {
v: Vec<NonNull<T>>,
}
impl<T> Default for StackStack<T> {
fn default() -> Self {
Self { v: Vec::new() }
}
}
impl<T> StackStack<T> {
/// Appends a reference to this stack for the duration of the function `f`. When `f`
/// returns, the reference will be popped off the stack.
pub fn with_append<F, R>(&mut self, x: &mut T, f: F) -> R
where
F: FnOnce(&mut Self) -> R,
{
self.v.push(x.into());
let res = panic::catch_unwind(panic::AssertUnwindSafe(|| f(self)));
self.v.pop();
res.unwrap_or_else(|x| panic::resume_unwind(x))
}
pub fn iter(&self) -> impl DoubleEndedIterator<Item = &T> + '_ {
self.as_ref().iter().copied()
}
pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> + '_ {
self.as_mut().iter_mut().map(|x| &mut **x)
}
// pub fn top(&self) -> Option<&T> {
// self.as_ref().last().copied()
// }
// pub fn top_mut(&mut self) -> Option<&mut T> {
// self.as_mut().last_mut().map(|x| &mut **x)
// }
pub fn len(&self) -> usize {
self.v.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn as_ref(&self) -> &[&T] {
unsafe { &*(self.v.as_slice() as *const [NonNull<T>] as *const [&T]) }
}
pub fn as_mut(&mut self) -> &mut [&mut T] {
unsafe { &mut *(self.v.as_mut_slice() as *mut [NonNull<T>] as *mut [&mut T]) }
}
}
}
use stack::StackStack;
/// Symbol table analysis. Can be used to analyze a fully
/// build symbol table structure. It will mark variables
/// as local variables for example.
#[derive(Default)]
#[repr(transparent)]
struct SymbolTableAnalyzer {
tables: StackStack<(SymbolMap, CompilerScope)>,
}
impl SymbolTableAnalyzer {
fn analyze_symbol_table(&mut self, symbol_table: &mut SymbolTable) -> SymbolTableResult {
let symbols = core::mem::take(&mut symbol_table.symbols);
let sub_tables = &mut *symbol_table.sub_tables;
let mut info = (symbols, symbol_table.typ);
self.tables.with_append(&mut info, |list| {
let inner_scope = unsafe { &mut *(list as *mut _ as *mut Self) };
// Analyze sub scopes:
for sub_table in sub_tables.iter_mut() {
inner_scope.analyze_symbol_table(sub_table)?;
}
Ok(())
})?;
symbol_table.symbols = info.0;
// PEP 709: Merge symbols from inlined comprehensions into parent scope
// Only merge symbols that are actually bound in the comprehension,
// not references to outer scope variables (Free symbols).
const BOUND_FLAGS: SymbolFlags = SymbolFlags::ASSIGNED
.union(SymbolFlags::PARAMETER)
.union(SymbolFlags::ITER)
.union(SymbolFlags::ASSIGNED_IN_COMPREHENSION);
for sub_table in sub_tables.iter() {
if sub_table.comp_inlined {
for (name, sub_symbol) in &sub_table.symbols {
// Skip the .0 parameter - it's internal to the comprehension
if name == ".0" {
continue;
}
// Only merge symbols that are bound in the comprehension
// Skip Free references to outer scope variables
if !sub_symbol.flags.intersects(BOUND_FLAGS) {
continue;
}
// If the symbol doesn't exist in parent, add it
if !symbol_table.symbols.contains_key(name) {
let mut symbol = sub_symbol.clone();
// Mark as local in parent scope
symbol.scope = SymbolScope::Local;
symbol_table.symbols.insert(name.clone(), symbol);
}
}
}
}
// Analyze symbols:
for symbol in symbol_table.symbols.values_mut() {
self.analyze_symbol(symbol, symbol_table.typ, sub_tables)?;
}
// Handle class-specific implicit cells (like CPython)
if symbol_table.typ == CompilerScope::Class {
drop_class_free(symbol_table);
}
Ok(())
}
fn analyze_symbol(
&mut self,
symbol: &mut Symbol,
st_typ: CompilerScope,
sub_tables: &[SymbolTable],
) -> SymbolTableResult {
if symbol
.flags
.contains(SymbolFlags::ASSIGNED_IN_COMPREHENSION)
&& st_typ == CompilerScope::Comprehension
{
// propagate symbol to next higher level that can hold it,
// i.e., function or module. Comprehension is skipped and
// Class is not allowed and detected as error.
//symbol.scope = SymbolScope::Nonlocal;
self.analyze_symbol_comprehension(symbol, 0)?
} else {
match symbol.scope {
SymbolScope::Free => {
if !self.tables.as_ref().is_empty() {
let scope_depth = self.tables.as_ref().len();
// check if the name is already defined in any outer scope
// therefore
if scope_depth < 2
|| self.found_in_outer_scope(&symbol.name) != Some(SymbolScope::Free)
{
return Err(SymbolTableError {
error: format!("no binding for nonlocal '{}' found", symbol.name),
// TODO: accurate location info, somehow
location: None,
});
}
} else {
return Err(SymbolTableError {
error: format!(
"nonlocal {} defined at place without an enclosing scope",
symbol.name
),
// TODO: accurate location info, somehow
location: None,
});
}
}
SymbolScope::GlobalExplicit | SymbolScope::GlobalImplicit => {
// TODO: add more checks for globals?
}
SymbolScope::Local | SymbolScope::Cell => {
// all is well
}
SymbolScope::Unknown => {
// Try hard to figure out what the scope of this symbol is.
let scope = if symbol.is_bound() {
self.found_in_inner_scope(sub_tables, &symbol.name, st_typ)
.unwrap_or(SymbolScope::Local)
} else if let Some(scope) = self.found_in_outer_scope(&symbol.name) {
scope
} else if self.tables.is_empty() {
// Don't make assumptions when we don't know.
SymbolScope::Unknown
} else {
// If there are scopes above we assume global.
SymbolScope::GlobalImplicit
};
symbol.scope = scope;
}
}
}
Ok(())
}
fn found_in_outer_scope(&mut self, name: &str) -> Option<SymbolScope> {
let mut decl_depth = None;
for (i, (symbols, typ)) in self.tables.iter().rev().enumerate() {
if matches!(typ, CompilerScope::Module)
|| matches!(typ, CompilerScope::Class if name != "__class__")
{
continue;
}
if let Some(sym) = symbols.get(name) {
match sym.scope {
SymbolScope::GlobalExplicit => return Some(SymbolScope::GlobalExplicit),
SymbolScope::GlobalImplicit => {}
_ => {
if sym.is_bound() {
decl_depth = Some(i);
break;
}
}
}
}
}
if let Some(decl_depth) = decl_depth {
// decl_depth is the number of tables between the current one and
// the one that declared the cell var
for (table, typ) in self.tables.iter_mut().rev().take(decl_depth) {
if let CompilerScope::Class = typ {
if let Some(free_class) = table.get_mut(name) {
free_class.flags.insert(SymbolFlags::FREE_CLASS)
} else {
let mut symbol = Symbol::new(name);
symbol.flags.insert(SymbolFlags::FREE_CLASS);
symbol.scope = SymbolScope::Free;
table.insert(name.to_owned(), symbol);
}
} else if !table.contains_key(name) {
let mut symbol = Symbol::new(name);
symbol.scope = SymbolScope::Free;
// symbol.is_referenced = true;
table.insert(name.to_owned(), symbol);
}
}
}
decl_depth.map(|_| SymbolScope::Free)
}
fn found_in_inner_scope(
&self,
sub_tables: &[SymbolTable],
name: &str,
st_typ: CompilerScope,
) -> Option<SymbolScope> {
sub_tables.iter().find_map(|st| {
let sym = st.symbols.get(name)?;
if sym.scope == SymbolScope::Free || sym.flags.contains(SymbolFlags::FREE_CLASS) {
if st_typ == CompilerScope::Class && name != "__class__" {
None
} else {
Some(SymbolScope::Cell)
}
} else if sym.scope == SymbolScope::GlobalExplicit && self.tables.is_empty() {
// the symbol is defined on the module level, and an inner scope declares
// a global that points to it
Some(SymbolScope::GlobalExplicit)
} else {
None
}
})
}
// Implements the symbol analysis and scope extension for names
// assigned by a named expression in a comprehension. See:
// https://github.com/python/cpython/blob/7b78e7f9fd77bb3280ee39fb74b86772a7d46a70/Python/symtable.c#L1435
fn analyze_symbol_comprehension(
&mut self,
symbol: &mut Symbol,
parent_offset: usize,
) -> SymbolTableResult {
// when this is called, we expect to be in the direct parent scope of the scope that contains 'symbol'
let last = self.tables.iter_mut().rev().nth(parent_offset).unwrap();
let symbols = &mut last.0;
let table_type = last.1;
// it is not allowed to use an iterator variable as assignee in a named expression
if symbol.flags.contains(SymbolFlags::ITER) {
return Err(SymbolTableError {
error: format!(
"assignment expression cannot rebind comprehension iteration variable {}",
symbol.name
),
// TODO: accurate location info, somehow
location: None,
});
}
match table_type {
CompilerScope::Module => {
symbol.scope = SymbolScope::GlobalImplicit;
}
CompilerScope::Class => {
// named expressions are forbidden in comprehensions on class scope
return Err(SymbolTableError {
error: "assignment expression within a comprehension cannot be used in a class body".to_string(),
// TODO: accurate location info, somehow
location: None,
});
}
CompilerScope::Function | CompilerScope::AsyncFunction | CompilerScope::Lambda => {
if let Some(parent_symbol) = symbols.get_mut(&symbol.name) {
if let SymbolScope::Unknown = parent_symbol.scope {
// this information is new, as the assignment is done in inner scope
parent_symbol.flags.insert(SymbolFlags::ASSIGNED);
}
symbol.scope = if parent_symbol.is_global() {
parent_symbol.scope
} else {
SymbolScope::Free
};
} else {
let mut cloned_sym = symbol.clone();
cloned_sym.scope = SymbolScope::Cell;
last.0.insert(cloned_sym.name.to_owned(), cloned_sym);
}
}
CompilerScope::Comprehension => {
// TODO check for conflicts - requires more context information about variables
match symbols.get_mut(&symbol.name) {
Some(parent_symbol) => {
// check if assignee is an iterator in top scope
if parent_symbol.flags.contains(SymbolFlags::ITER) {
return Err(SymbolTableError {
error: format!(
"assignment expression cannot rebind comprehension iteration variable {}",
symbol.name
),
location: None,
});
}
// we synthesize the assignment to the symbol from inner scope
parent_symbol.flags.insert(SymbolFlags::ASSIGNED); // more checks are required
}
None => {
// extend the scope of the inner symbol
// as we are in a nested comprehension, we expect that the symbol is needed
// outside, too, and set it therefore to non-local scope. I.e., we expect to
// find a definition on a higher level
let mut cloned_sym = symbol.clone();
cloned_sym.scope = SymbolScope::Free;
last.0.insert(cloned_sym.name.to_owned(), cloned_sym);
}
}
self.analyze_symbol_comprehension(symbol, parent_offset + 1)?;
}
CompilerScope::TypeParams => {
// Named expression in comprehension cannot be used in type params
return Err(SymbolTableError {
error: "assignment expression within a comprehension cannot be used within the definition of a generic".to_string(),
location: None,
});
}
}
Ok(())
}
}
#[derive(Debug, Clone)]
enum SymbolUsage {
Global,
Nonlocal,
Used,
Assigned,
Imported,
AnnotationAssigned,
Parameter,
AnnotationParameter,
AssignedNamedExprInComprehension,
Iter,
TypeParam,
}
struct SymbolTableBuilder {
class_name: Option<String>,
// Scope stack.
tables: Vec<SymbolTable>,
future_annotations: bool,
source_file: SourceFile,
// Current scope's varnames being collected (temporary storage)
current_varnames: Vec<String>,
// Track if we're inside an iterable definition expression (for nested comprehensions)
in_iter_def_exp: bool,
// Track if we're inside an annotation (yield/await/named expr not allowed)
in_annotation: bool,
// Track if we're inside a type alias (yield/await/named expr not allowed)
in_type_alias: bool,
// Track if we're scanning an inner loop iteration target (not the first generator)
in_comp_inner_loop_target: bool,
// Scope info for error messages (e.g., "a TypeVar bound")
scope_info: Option<&'static str>,
}
/// Enum to indicate in what mode an expression
/// was used.
/// In cpython this is stored in the AST, but I think this
/// is not logical, since it is not context free.
#[derive(Copy, Clone, PartialEq)]
enum ExpressionContext {
Load,
Store,
Delete,
Iter,
IterDefinitionExp,
}
impl SymbolTableBuilder {
fn new(source_file: SourceFile) -> Self {
let mut this = Self {
class_name: None,
tables: vec![],
future_annotations: false,
source_file,
current_varnames: Vec::new(),
in_iter_def_exp: false,
in_annotation: false,
in_type_alias: false,
in_comp_inner_loop_target: false,
scope_info: None,
};
this.enter_scope("top", CompilerScope::Module, 0);
this
}
fn finish(mut self) -> Result<SymbolTable, SymbolTableError> {
assert_eq!(self.tables.len(), 1);
let mut symbol_table = self.tables.pop().unwrap();
// Save varnames for the top-level module scope
symbol_table.varnames = self.current_varnames;
analyze_symbol_table(&mut symbol_table)?;
Ok(symbol_table)
}
fn enter_scope(&mut self, name: &str, typ: CompilerScope, line_number: u32) {
let is_nested = self
.tables
.last()
.map(|table| table.is_nested || table.typ == CompilerScope::Function)
.unwrap_or(false);
let table = SymbolTable::new(name.to_owned(), typ, line_number, is_nested);
self.tables.push(table);
// Clear current_varnames for the new scope
self.current_varnames.clear();
}
fn enter_type_param_block(&mut self, name: &str, line_number: u32) -> SymbolTableResult {
// Check if we're in a class scope
let in_class = self
.tables
.last()
.is_some_and(|t| t.typ == CompilerScope::Class);
self.enter_scope(name, CompilerScope::TypeParams, line_number);
// If we're in a class, mark that this type param scope can see the class scope
if let Some(table) = self.tables.last_mut() {
table.can_see_class_scope = in_class;
// Add __classdict__ as a USE symbol in type param scope if in class
if in_class {
self.register_name("__classdict__", SymbolUsage::Used, TextRange::default())?;
}
}
// Register .type_params as a SET symbol (it will be converted to cell variable later)
self.register_name(".type_params", SymbolUsage::Assigned, TextRange::default())?;
Ok(())
}
/// Pop symbol table and add to sub table of parent table.
fn leave_scope(&mut self) {
let mut table = self.tables.pop().unwrap();
// Save the collected varnames to the symbol table
table.varnames = core::mem::take(&mut self.current_varnames);
self.tables.last_mut().unwrap().sub_tables.push(table);
}
fn line_index_start(&self, range: TextRange) -> u32 {
self.source_file
.to_source_code()
.line_index(range.start())
.get() as _
}
fn scan_statements(&mut self, statements: &[Stmt]) -> SymbolTableResult {
for statement in statements {
self.scan_statement(statement)?;
}
Ok(())
}
fn scan_parameters(&mut self, parameters: &[ParameterWithDefault]) -> SymbolTableResult {
for parameter in parameters {
self.scan_parameter(¶meter.parameter)?;
}
Ok(())
}
fn scan_parameter(&mut self, parameter: &Parameter) -> SymbolTableResult {
let usage = if parameter.annotation.is_some() {
SymbolUsage::AnnotationParameter
} else {
SymbolUsage::Parameter
};
// Check for duplicate parameter names
let table = self.tables.last().unwrap();
if table.symbols.contains_key(parameter.name.as_str()) {
return Err(SymbolTableError {
error: format!(
"duplicate parameter '{}' in function definition",
parameter.name
),
location: Some(
self.source_file
.to_source_code()
.source_location(parameter.name.range.start(), PositionEncoding::Utf8),
),
});
}
self.register_ident(¶meter.name, usage)
}
fn scan_annotation(&mut self, annotation: &Expr) -> SymbolTableResult {
if self.future_annotations {
Ok(())
} else {
let was_in_annotation = self.in_annotation;
self.in_annotation = true;
let result = self.scan_expression(annotation, ExpressionContext::Load);
self.in_annotation = was_in_annotation;
result
}
}
fn scan_statement(&mut self, statement: &Stmt) -> SymbolTableResult {
use ruff_python_ast::*;
if let Stmt::ImportFrom(StmtImportFrom { module, names, .. }) = &statement
&& module.as_ref().map(|id| id.as_str()) == Some("__future__")
{
self.future_annotations =
self.future_annotations || names.iter().any(|future| &future.name == "annotations");
}
match &statement {
Stmt::Global(StmtGlobal { names, .. }) => {
for name in names {
self.register_ident(name, SymbolUsage::Global)?;
}
}
Stmt::Nonlocal(StmtNonlocal { names, .. }) => {
for name in names {
self.register_ident(name, SymbolUsage::Nonlocal)?;
}
}
Stmt::FunctionDef(StmtFunctionDef {
name,
body,
parameters,
decorator_list,
type_params,
returns,
range,
..
}) => {
self.scan_decorators(decorator_list, ExpressionContext::Load)?;
self.register_ident(name, SymbolUsage::Assigned)?;
if let Some(expression) = returns {
self.scan_annotation(expression)?;
}
if let Some(type_params) = type_params {
self.enter_type_param_block(
&format!("<generic parameters of {}>", name.as_str()),
self.line_index_start(type_params.range),
)?;
self.scan_type_params(type_params)?;
}
self.enter_scope_with_parameters(
name.as_str(),
parameters,
self.line_index_start(*range),
)?;
self.scan_statements(body)?;
self.leave_scope();
if type_params.is_some() {
self.leave_scope();
}
}
Stmt::ClassDef(StmtClassDef {
name,
body,
arguments,
decorator_list,
type_params,
range,
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | true |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/codegen/src/compile.rs | crates/codegen/src/compile.rs | //!
//! Take an AST and transform it into bytecode
//!
//! Inspirational code:
//! <https://github.com/python/cpython/blob/main/Python/compile.c>
//! <https://github.com/micropython/micropython/blob/master/py/compile.c>
// spell-checker:ignore starunpack subscripter
#![deny(clippy::cast_possible_truncation)]
use crate::{
IndexMap, IndexSet, ToPythonName,
error::{CodegenError, CodegenErrorType, InternalError, PatternUnreachableReason},
ir::{self, BlockIdx},
symboltable::{self, CompilerScope, SymbolFlags, SymbolScope, SymbolTable},
unparse::UnparseExpr,
};
use alloc::borrow::Cow;
use itertools::Itertools;
use malachite_bigint::BigInt;
use num_complex::Complex;
use num_traits::{Num, ToPrimitive};
use ruff_python_ast::{
Alias, Arguments, BoolOp, CmpOp, Comprehension, ConversionFlag, DebugText, Decorator, DictItem,
ExceptHandler, ExceptHandlerExceptHandler, Expr, ExprAttribute, ExprBoolOp, ExprContext,
ExprFString, ExprList, ExprName, ExprSlice, ExprStarred, ExprSubscript, ExprTuple, ExprUnaryOp,
FString, FStringFlags, FStringPart, Identifier, Int, InterpolatedStringElement,
InterpolatedStringElements, Keyword, MatchCase, ModExpression, ModModule, Operator, Parameters,
Pattern, PatternMatchAs, PatternMatchClass, PatternMatchMapping, PatternMatchOr,
PatternMatchSequence, PatternMatchSingleton, PatternMatchStar, PatternMatchValue, Singleton,
Stmt, StmtExpr, TypeParam, TypeParamParamSpec, TypeParamTypeVar, TypeParamTypeVarTuple,
TypeParams, UnaryOp, WithItem,
visitor::{Visitor, walk_expr},
};
use ruff_text_size::{Ranged, TextRange};
use rustpython_compiler_core::{
Mode, OneIndexed, PositionEncoding, SourceFile, SourceLocation,
bytecode::{
self, Arg as OpArgMarker, BinaryOperator, BuildSliceArgCount, CodeObject,
ComparisonOperator, ConstantData, ConvertValueOparg, Instruction, Invert, OpArg, OpArgType,
UnpackExArgs,
},
};
use rustpython_wtf8::Wtf8Buf;
use std::collections::HashSet;
const MAXBLOCKS: usize = 20;
#[derive(Debug, Clone, Copy)]
pub enum FBlockType {
WhileLoop,
ForLoop,
TryExcept,
FinallyTry,
FinallyEnd,
With,
AsyncWith,
HandlerCleanup,
PopValue,
ExceptionHandler,
ExceptionGroupHandler,
AsyncComprehensionGenerator,
StopIteration,
}
/// Stores additional data for fblock unwinding
// fb_datum
#[derive(Debug, Clone)]
pub enum FBlockDatum {
None,
/// For FinallyTry: stores the finally body statements to compile during unwind
FinallyBody(Vec<Stmt>),
/// For HandlerCleanup: stores the exception variable name (e.g., "e" in "except X as e")
ExceptionName(String),
}
#[derive(Debug, Clone)]
pub struct FBlockInfo {
pub fb_type: FBlockType,
pub fb_block: BlockIdx,
pub fb_exit: BlockIdx,
// For Python 3.11+ exception table generation
pub fb_handler: Option<BlockIdx>, // Exception handler block
pub fb_stack_depth: u32, // Stack depth at block entry
pub fb_preserve_lasti: bool, // Whether to preserve lasti (for SETUP_CLEANUP)
// additional data for fblock unwinding
pub fb_datum: FBlockDatum,
}
pub(crate) type InternalResult<T> = Result<T, InternalError>;
type CompileResult<T> = Result<T, CodegenError>;
#[derive(PartialEq, Eq, Clone, Copy)]
enum NameUsage {
Load,
Store,
Delete,
}
enum CallType {
Positional { nargs: u32 },
Keyword { nargs: u32 },
Ex { has_kwargs: bool },
}
fn is_forbidden_name(name: &str) -> bool {
// See https://docs.python.org/3/library/constants.html#built-in-constants
const BUILTIN_CONSTANTS: &[&str] = &["__debug__"];
BUILTIN_CONSTANTS.contains(&name)
}
/// Main structure holding the state of compilation.
struct Compiler {
code_stack: Vec<ir::CodeInfo>,
symbol_table_stack: Vec<SymbolTable>,
source_file: SourceFile,
// current_source_location: SourceLocation,
current_source_range: TextRange,
done_with_future_stmts: DoneWithFuture,
future_annotations: bool,
ctx: CompileContext,
opts: CompileOpts,
in_annotation: bool,
}
enum DoneWithFuture {
No,
DoneWithDoc,
Yes,
}
#[derive(Debug, Clone)]
pub struct CompileOpts {
/// How optimized the bytecode output should be; any optimize > 0 does
/// not emit assert statements
pub optimize: u8,
/// Include column info in bytecode (-X no_debug_ranges disables)
pub debug_ranges: bool,
}
impl Default for CompileOpts {
fn default() -> Self {
Self {
optimize: 0,
debug_ranges: true,
}
}
}
#[derive(Debug, Clone, Copy)]
struct CompileContext {
loop_data: Option<(BlockIdx, BlockIdx)>,
in_class: bool,
func: FunctionContext,
/// True if we're anywhere inside an async function (even inside nested comprehensions)
in_async_scope: bool,
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum FunctionContext {
NoFunction,
Function,
AsyncFunction,
}
impl CompileContext {
fn in_func(self) -> bool {
self.func != FunctionContext::NoFunction
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum ComprehensionType {
Generator,
List,
Set,
Dict,
}
fn validate_duplicate_params(params: &Parameters) -> Result<(), CodegenErrorType> {
let mut seen_params = HashSet::new();
for param in params {
let param_name = param.name().as_str();
if !seen_params.insert(param_name) {
return Err(CodegenErrorType::SyntaxError(format!(
r#"Duplicate parameter "{param_name}""#
)));
}
}
Ok(())
}
/// Compile an Mod produced from ruff parser
pub fn compile_top(
ast: ruff_python_ast::Mod,
source_file: SourceFile,
mode: Mode,
opts: CompileOpts,
) -> CompileResult<CodeObject> {
match ast {
ruff_python_ast::Mod::Module(module) => match mode {
Mode::Exec | Mode::Eval => compile_program(&module, source_file, opts),
Mode::Single => compile_program_single(&module, source_file, opts),
Mode::BlockExpr => compile_block_expression(&module, source_file, opts),
},
ruff_python_ast::Mod::Expression(expr) => compile_expression(&expr, source_file, opts),
}
}
/// Compile a standard Python program to bytecode
pub fn compile_program(
ast: &ModModule,
source_file: SourceFile,
opts: CompileOpts,
) -> CompileResult<CodeObject> {
let symbol_table = SymbolTable::scan_program(ast, source_file.clone())
.map_err(|e| e.into_codegen_error(source_file.name().to_owned()))?;
let mut compiler = Compiler::new(opts, source_file, "<module>".to_owned());
compiler.compile_program(ast, symbol_table)?;
let code = compiler.exit_scope();
trace!("Compilation completed: {code:?}");
Ok(code)
}
/// Compile a Python program to bytecode for the context of a REPL
pub fn compile_program_single(
ast: &ModModule,
source_file: SourceFile,
opts: CompileOpts,
) -> CompileResult<CodeObject> {
let symbol_table = SymbolTable::scan_program(ast, source_file.clone())
.map_err(|e| e.into_codegen_error(source_file.name().to_owned()))?;
let mut compiler = Compiler::new(opts, source_file, "<module>".to_owned());
compiler.compile_program_single(&ast.body, symbol_table)?;
let code = compiler.exit_scope();
trace!("Compilation completed: {code:?}");
Ok(code)
}
pub fn compile_block_expression(
ast: &ModModule,
source_file: SourceFile,
opts: CompileOpts,
) -> CompileResult<CodeObject> {
let symbol_table = SymbolTable::scan_program(ast, source_file.clone())
.map_err(|e| e.into_codegen_error(source_file.name().to_owned()))?;
let mut compiler = Compiler::new(opts, source_file, "<module>".to_owned());
compiler.compile_block_expr(&ast.body, symbol_table)?;
let code = compiler.exit_scope();
trace!("Compilation completed: {code:?}");
Ok(code)
}
pub fn compile_expression(
ast: &ModExpression,
source_file: SourceFile,
opts: CompileOpts,
) -> CompileResult<CodeObject> {
let symbol_table = SymbolTable::scan_expr(ast, source_file.clone())
.map_err(|e| e.into_codegen_error(source_file.name().to_owned()))?;
let mut compiler = Compiler::new(opts, source_file, "<module>".to_owned());
compiler.compile_eval(ast, symbol_table)?;
let code = compiler.exit_scope();
Ok(code)
}
macro_rules! emit {
($c:expr, Instruction::$op:ident { $arg:ident$(,)? }$(,)?) => {
$c.emit_arg($arg, |x| Instruction::$op { $arg: x })
};
($c:expr, Instruction::$op:ident { $arg:ident : $arg_val:expr $(,)? }$(,)?) => {
$c.emit_arg($arg_val, |x| Instruction::$op { $arg: x })
};
($c:expr, Instruction::$op:ident( $arg_val:expr $(,)? )$(,)?) => {
$c.emit_arg($arg_val, Instruction::$op)
};
($c:expr, Instruction::$op:ident$(,)?) => {
$c.emit_no_arg(Instruction::$op)
};
}
fn eprint_location(zelf: &Compiler) {
let start = zelf
.source_file
.to_source_code()
.source_location(zelf.current_source_range.start(), PositionEncoding::Utf8);
let end = zelf
.source_file
.to_source_code()
.source_location(zelf.current_source_range.end(), PositionEncoding::Utf8);
eprintln!(
"LOCATION: {} from {}:{} to {}:{}",
zelf.source_file.name(),
start.line,
start.character_offset,
end.line,
end.character_offset
);
}
/// Better traceback for internal error
#[track_caller]
fn unwrap_internal<T>(zelf: &Compiler, r: InternalResult<T>) -> T {
if let Err(ref r_err) = r {
eprintln!("=== CODEGEN PANIC INFO ===");
eprintln!("This IS an internal error: {r_err}");
eprint_location(zelf);
eprintln!("=== END PANIC INFO ===");
}
r.unwrap()
}
fn compiler_unwrap_option<T>(zelf: &Compiler, o: Option<T>) -> T {
if o.is_none() {
eprintln!("=== CODEGEN PANIC INFO ===");
eprintln!("This IS an internal error, an option was unwrapped during codegen");
eprint_location(zelf);
eprintln!("=== END PANIC INFO ===");
}
o.unwrap()
}
// fn compiler_result_unwrap<T, E: core::fmt::Debug>(zelf: &Compiler, result: Result<T, E>) -> T {
// if result.is_err() {
// eprintln!("=== CODEGEN PANIC INFO ===");
// eprintln!("This IS an internal error, an result was unwrapped during codegen");
// eprint_location(zelf);
// eprintln!("=== END PANIC INFO ===");
// }
// result.unwrap()
// }
/// The pattern context holds information about captured names and jump targets.
#[derive(Clone)]
pub struct PatternContext {
/// A list of names captured by the pattern.
pub stores: Vec<String>,
/// If false, then any name captures against our subject will raise.
pub allow_irrefutable: bool,
/// A list of jump target labels used on pattern failure.
pub fail_pop: Vec<BlockIdx>,
/// The number of items on top of the stack that should remain.
pub on_top: usize,
}
impl Default for PatternContext {
fn default() -> Self {
Self::new()
}
}
impl PatternContext {
pub const fn new() -> Self {
Self {
stores: Vec::new(),
allow_irrefutable: false,
fail_pop: Vec::new(),
on_top: 0,
}
}
pub fn fail_pop_size(&self) -> usize {
self.fail_pop.len()
}
}
enum JumpOp {
Jump,
PopJumpIfFalse,
}
/// Type of collection to build in starunpack_helper
#[derive(Debug, Clone, Copy, PartialEq)]
enum CollectionType {
Tuple,
List,
Set,
}
impl Compiler {
fn new(opts: CompileOpts, source_file: SourceFile, code_name: String) -> Self {
let module_code = ir::CodeInfo {
flags: bytecode::CodeFlags::NEW_LOCALS,
source_path: source_file.name().to_owned(),
private: None,
blocks: vec![ir::Block::default()],
current_block: BlockIdx::new(0),
metadata: ir::CodeUnitMetadata {
name: code_name.clone(),
qualname: Some(code_name),
consts: IndexSet::default(),
names: IndexSet::default(),
varnames: IndexSet::default(),
cellvars: IndexSet::default(),
freevars: IndexSet::default(),
fast_hidden: IndexMap::default(),
argcount: 0,
posonlyargcount: 0,
kwonlyargcount: 0,
firstlineno: OneIndexed::MIN,
},
static_attributes: None,
in_inlined_comp: false,
fblock: Vec::with_capacity(MAXBLOCKS),
symbol_table_index: 0, // Module is always the first symbol table
};
Self {
code_stack: vec![module_code],
symbol_table_stack: Vec::new(),
source_file,
// current_source_location: SourceLocation::default(),
current_source_range: TextRange::default(),
done_with_future_stmts: DoneWithFuture::No,
future_annotations: false,
ctx: CompileContext {
loop_data: None,
in_class: false,
func: FunctionContext::NoFunction,
in_async_scope: false,
},
opts,
in_annotation: false,
}
}
/// Check if the slice is a two-element slice (no step)
// = is_two_element_slice
const fn is_two_element_slice(slice: &Expr) -> bool {
matches!(slice, Expr::Slice(s) if s.step.is_none())
}
/// Compile a slice expression
// = compiler_slice
fn compile_slice(&mut self, s: &ExprSlice) -> CompileResult<BuildSliceArgCount> {
// Compile lower
if let Some(lower) = &s.lower {
self.compile_expression(lower)?;
} else {
self.emit_load_const(ConstantData::None);
}
// Compile upper
if let Some(upper) = &s.upper {
self.compile_expression(upper)?;
} else {
self.emit_load_const(ConstantData::None);
}
Ok(match &s.step {
Some(step) => {
// Compile step if present
self.compile_expression(step)?;
BuildSliceArgCount::Three
}
None => BuildSliceArgCount::Two,
})
}
/// Compile a subscript expression
// = compiler_subscript
fn compile_subscript(
&mut self,
value: &Expr,
slice: &Expr,
ctx: ExprContext,
) -> CompileResult<()> {
// 1. Check subscripter and index for Load context
// 2. VISIT value
// 3. Handle two-element slice specially
// 4. Otherwise VISIT slice and emit appropriate instruction
// For Load context, some checks are skipped for now
// if ctx == ExprContext::Load {
// check_subscripter(value);
// check_index(value, slice);
// }
// VISIT(c, expr, e->v.Subscript.value)
self.compile_expression(value)?;
// Handle two-element slice (for Load/Store, not Del)
if Self::is_two_element_slice(slice) && !matches!(ctx, ExprContext::Del) {
let argc = match slice {
Expr::Slice(s) => self.compile_slice(s)?,
_ => unreachable!("is_two_element_slice should only return true for Expr::Slice"),
};
match ctx {
ExprContext::Load => {
emit!(self, Instruction::BuildSlice { argc });
emit!(self, Instruction::Subscript);
}
ExprContext::Store => {
emit!(self, Instruction::BuildSlice { argc });
emit!(self, Instruction::StoreSubscript);
}
_ => unreachable!(),
}
} else {
// VISIT(c, expr, e->v.Subscript.slice)
self.compile_expression(slice)?;
// Emit appropriate instruction based on context
match ctx {
ExprContext::Load => emit!(self, Instruction::Subscript),
ExprContext::Store => emit!(self, Instruction::StoreSubscript),
ExprContext::Del => emit!(self, Instruction::DeleteSubscript),
ExprContext::Invalid => {
return Err(self.error(CodegenErrorType::SyntaxError(
"Invalid expression context".to_owned(),
)));
}
}
}
Ok(())
}
/// Helper function for compiling tuples/lists/sets with starred expressions
///
/// Parameters:
/// - elts: The elements to compile
/// - pushed: Number of items already on the stack
/// - collection_type: What type of collection to build (tuple, list, set)
///
// = starunpack_helper in compile.c
fn starunpack_helper(
&mut self,
elts: &[Expr],
pushed: u32,
collection_type: CollectionType,
) -> CompileResult<()> {
// Use RustPython's existing approach with BuildXFromTuples
let (size, unpack) = self.gather_elements(pushed, elts)?;
if unpack {
// Has starred elements
match collection_type {
CollectionType::Tuple => {
if size > 1 || pushed > 0 {
emit!(self, Instruction::BuildTupleFromTuples { size });
}
// If size == 1 and pushed == 0, the single tuple is already on the stack
}
CollectionType::List => {
emit!(self, Instruction::BuildListFromTuples { size });
}
CollectionType::Set => {
emit!(self, Instruction::BuildSetFromTuples { size });
}
}
} else {
// No starred elements
match collection_type {
CollectionType::Tuple => {
emit!(self, Instruction::BuildTuple { size });
}
CollectionType::List => {
emit!(self, Instruction::BuildList { size });
}
CollectionType::Set => {
emit!(self, Instruction::BuildSet { size });
}
}
}
Ok(())
}
fn error(&mut self, error: CodegenErrorType) -> CodegenError {
self.error_ranged(error, self.current_source_range)
}
fn error_ranged(&mut self, error: CodegenErrorType, range: TextRange) -> CodegenError {
let location = self
.source_file
.to_source_code()
.source_location(range.start(), PositionEncoding::Utf8);
CodegenError {
error,
location: Some(location),
source_path: self.source_file.name().to_owned(),
}
}
/// Get the SymbolTable for the current scope.
fn current_symbol_table(&self) -> &SymbolTable {
self.symbol_table_stack
.last()
.expect("symbol_table_stack is empty! This is a compiler bug.")
}
/// Get the index of a free variable.
fn get_free_var_index(&mut self, name: &str) -> CompileResult<u32> {
let info = self.code_stack.last_mut().unwrap();
let idx = info
.metadata
.freevars
.get_index_of(name)
.unwrap_or_else(|| info.metadata.freevars.insert_full(name.to_owned()).0);
Ok((idx + info.metadata.cellvars.len()).to_u32())
}
/// Get the index of a cell variable.
fn get_cell_var_index(&mut self, name: &str) -> CompileResult<u32> {
let info = self.code_stack.last_mut().unwrap();
let idx = info
.metadata
.cellvars
.get_index_of(name)
.unwrap_or_else(|| info.metadata.cellvars.insert_full(name.to_owned()).0);
Ok(idx.to_u32())
}
/// Get the index of a local variable.
fn get_local_var_index(&mut self, name: &str) -> CompileResult<u32> {
let info = self.code_stack.last_mut().unwrap();
let idx = info
.metadata
.varnames
.get_index_of(name)
.unwrap_or_else(|| info.metadata.varnames.insert_full(name.to_owned()).0);
Ok(idx.to_u32())
}
/// Get the index of a global name.
fn get_global_name_index(&mut self, name: &str) -> u32 {
let info = self.code_stack.last_mut().unwrap();
let idx = info
.metadata
.names
.get_index_of(name)
.unwrap_or_else(|| info.metadata.names.insert_full(name.to_owned()).0);
idx.to_u32()
}
/// Push the next symbol table on to the stack
fn push_symbol_table(&mut self) -> &SymbolTable {
// Look up the next table contained in the scope of the current table
let current_table = self
.symbol_table_stack
.last_mut()
.expect("no current symbol table");
if current_table.sub_tables.is_empty() {
panic!(
"push_symbol_table: no sub_tables available in {} (type: {:?})",
current_table.name, current_table.typ
);
}
let table = current_table.sub_tables.remove(0);
// Push the next table onto the stack
self.symbol_table_stack.push(table);
self.current_symbol_table()
}
/// Pop the current symbol table off the stack
fn pop_symbol_table(&mut self) -> SymbolTable {
self.symbol_table_stack.pop().expect("compiler bug")
}
/// Check if this is an inlined comprehension context (PEP 709)
/// Currently disabled - always returns false to avoid stack issues
fn is_inlined_comprehension_context(&self, _comprehension_type: ComprehensionType) -> bool {
// TODO: Implement PEP 709 inlined comprehensions properly
// For now, disabled to avoid stack underflow issues
false
}
/// Enter a new scope
// = compiler_enter_scope
fn enter_scope(
&mut self,
name: &str,
scope_type: CompilerScope,
key: usize, // In RustPython, we use the index in symbol_table_stack as key
lineno: u32,
) -> CompileResult<()> {
// Create location
let location = SourceLocation {
line: OneIndexed::new(lineno as usize).unwrap_or(OneIndexed::MIN),
character_offset: OneIndexed::MIN,
};
// Allocate a new compiler unit
// In Rust, we'll create the structure directly
let source_path = self.source_file.name().to_owned();
// Lookup symbol table entry using key (_PySymtable_Lookup)
let ste = match self.symbol_table_stack.get(key) {
Some(v) => v,
None => {
return Err(self.error(CodegenErrorType::SyntaxError(
"unknown symbol table entry".to_owned(),
)));
}
};
// Use varnames from symbol table (already collected in definition order)
let varname_cache: IndexSet<String> = ste.varnames.iter().cloned().collect();
// Build cellvars using dictbytype (CELL scope, sorted)
let mut cellvar_cache = IndexSet::default();
let mut cell_names: Vec<_> = ste
.symbols
.iter()
.filter(|(_, s)| s.scope == SymbolScope::Cell)
.map(|(name, _)| name.clone())
.collect();
cell_names.sort();
for name in cell_names {
cellvar_cache.insert(name);
}
// Handle implicit __class__ cell if needed
if ste.needs_class_closure {
// Cook up an implicit __class__ cell
debug_assert_eq!(scope_type, CompilerScope::Class);
cellvar_cache.insert("__class__".to_string());
}
// Handle implicit __classdict__ cell if needed
if ste.needs_classdict {
// Cook up an implicit __classdict__ cell
debug_assert_eq!(scope_type, CompilerScope::Class);
cellvar_cache.insert("__classdict__".to_string());
}
// Build freevars using dictbytype (FREE scope, offset by cellvars size)
let mut freevar_cache = IndexSet::default();
let mut free_names: Vec<_> = ste
.symbols
.iter()
.filter(|(_, s)| {
s.scope == SymbolScope::Free || s.flags.contains(SymbolFlags::FREE_CLASS)
})
.map(|(name, _)| name.clone())
.collect();
free_names.sort();
for name in free_names {
freevar_cache.insert(name);
}
// Initialize u_metadata fields
let (flags, posonlyarg_count, arg_count, kwonlyarg_count) = match scope_type {
CompilerScope::Module => (bytecode::CodeFlags::empty(), 0, 0, 0),
CompilerScope::Class => (bytecode::CodeFlags::empty(), 0, 0, 0),
CompilerScope::Function | CompilerScope::AsyncFunction | CompilerScope::Lambda => (
bytecode::CodeFlags::NEW_LOCALS | bytecode::CodeFlags::IS_OPTIMIZED,
0, // Will be set later in enter_function
0, // Will be set later in enter_function
0, // Will be set later in enter_function
),
CompilerScope::Comprehension => (
bytecode::CodeFlags::NEW_LOCALS | bytecode::CodeFlags::IS_OPTIMIZED,
0,
1, // comprehensions take one argument (.0)
0,
),
CompilerScope::TypeParams => (
bytecode::CodeFlags::NEW_LOCALS | bytecode::CodeFlags::IS_OPTIMIZED,
0,
0,
0,
),
};
// Get private name from parent scope
let private = if !self.code_stack.is_empty() {
self.code_stack.last().unwrap().private.clone()
} else {
None
};
// Create the new compilation unit
let code_info = ir::CodeInfo {
flags,
source_path: source_path.clone(),
private,
blocks: vec![ir::Block::default()],
current_block: BlockIdx::new(0),
metadata: ir::CodeUnitMetadata {
name: name.to_owned(),
qualname: None, // Will be set below
consts: IndexSet::default(),
names: IndexSet::default(),
varnames: varname_cache,
cellvars: cellvar_cache,
freevars: freevar_cache,
fast_hidden: IndexMap::default(),
argcount: arg_count,
posonlyargcount: posonlyarg_count,
kwonlyargcount: kwonlyarg_count,
firstlineno: OneIndexed::new(lineno as usize).unwrap_or(OneIndexed::MIN),
},
static_attributes: if scope_type == CompilerScope::Class {
Some(IndexSet::default())
} else {
None
},
in_inlined_comp: false,
fblock: Vec::with_capacity(MAXBLOCKS),
symbol_table_index: key,
};
// Push the old compiler unit on the stack (like PyCapsule)
// This happens before setting qualname
self.code_stack.push(code_info);
// Set qualname after pushing (uses compiler_set_qualname logic)
if scope_type != CompilerScope::Module {
self.set_qualname();
}
// Emit RESUME instruction
let _resume_loc = if scope_type == CompilerScope::Module {
// Module scope starts with lineno 0
SourceLocation {
line: OneIndexed::MIN,
character_offset: OneIndexed::MIN,
}
} else {
location
};
// Set the source range for the RESUME instruction
// For now, just use an empty range at the beginning
self.current_source_range = TextRange::default();
emit!(
self,
Instruction::Resume {
arg: bytecode::ResumeType::AtFuncStart as u32
}
);
if scope_type == CompilerScope::Module {
// This would be loc.lineno = -1 in CPython
// We handle this differently in RustPython
}
Ok(())
}
fn push_output(
&mut self,
flags: bytecode::CodeFlags,
posonlyarg_count: u32,
arg_count: u32,
kwonlyarg_count: u32,
obj_name: String,
) {
// First push the symbol table
let table = self.push_symbol_table();
let scope_type = table.typ;
// The key is the current position in the symbol table stack
let key = self.symbol_table_stack.len() - 1;
// Get the line number
let lineno = self.get_source_line_number().get();
// Call enter_scope which does most of the work
if let Err(e) = self.enter_scope(&obj_name, scope_type, key, lineno.to_u32()) {
// In the current implementation, push_output doesn't return an error,
// so we panic here. This maintains the same behavior.
panic!("enter_scope failed: {e:?}");
}
// Override the values that push_output sets explicitly
// enter_scope sets default values based on scope_type, but push_output
// allows callers to specify exact values
if let Some(info) = self.code_stack.last_mut() {
info.flags = flags;
info.metadata.argcount = arg_count;
info.metadata.posonlyargcount = posonlyarg_count;
info.metadata.kwonlyargcount = kwonlyarg_count;
}
}
// compiler_exit_scope
fn exit_scope(&mut self) -> CodeObject {
let _table = self.pop_symbol_table();
// Various scopes can have sub_tables:
// - TypeParams scope can have sub_tables (the function body's symbol table)
// - Module scope can have sub_tables (for TypeAlias scopes, nested functions, classes)
// - Function scope can have sub_tables (for nested functions, classes)
// - Class scope can have sub_tables (for nested classes, methods)
let pop = self.code_stack.pop();
let stack_top = compiler_unwrap_option(self, pop);
// No parent scope stack to maintain
unwrap_internal(self, stack_top.finalize_code(&self.opts))
}
/// Push a new fblock
// = compiler_push_fblock
fn push_fblock(
&mut self,
fb_type: FBlockType,
fb_block: BlockIdx,
fb_exit: BlockIdx,
) -> CompileResult<()> {
self.push_fblock_full(
fb_type,
fb_block,
fb_exit,
None,
0,
false,
FBlockDatum::None,
)
}
/// Push an fblock with exception handler info
fn push_fblock_with_handler(
&mut self,
fb_type: FBlockType,
fb_block: BlockIdx,
fb_exit: BlockIdx,
fb_handler: Option<BlockIdx>,
fb_stack_depth: u32,
fb_preserve_lasti: bool,
) -> CompileResult<()> {
self.push_fblock_full(
fb_type,
fb_block,
fb_exit,
fb_handler,
fb_stack_depth,
fb_preserve_lasti,
FBlockDatum::None,
)
}
/// Push an fblock with all parameters including fb_datum
#[allow(clippy::too_many_arguments)]
fn push_fblock_full(
&mut self,
fb_type: FBlockType,
fb_block: BlockIdx,
fb_exit: BlockIdx,
fb_handler: Option<BlockIdx>,
fb_stack_depth: u32,
fb_preserve_lasti: bool,
fb_datum: FBlockDatum,
) -> CompileResult<()> {
let code = self.current_code_info();
if code.fblock.len() >= MAXBLOCKS {
return Err(self.error(CodegenErrorType::SyntaxError(
"too many statically nested blocks".to_owned(),
)));
}
code.fblock.push(FBlockInfo {
fb_type,
fb_block,
fb_exit,
fb_handler,
fb_stack_depth,
fb_preserve_lasti,
fb_datum,
});
Ok(())
}
/// Pop an fblock
// = compiler_pop_fblock
fn pop_fblock(&mut self, _expected_type: FBlockType) -> FBlockInfo {
let code = self.current_code_info();
// TODO: Add assertion to check expected type matches
// assert!(matches!(fblock.fb_type, expected_type));
code.fblock.pop().expect("fblock stack underflow")
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | true |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/codegen/src/string_parser.rs | crates/codegen/src/string_parser.rs | //! A stripped-down version of ruff's string literal parser, modified to
//! handle surrogates in string literals and output WTF-8.
//!
//! Any `unreachable!()` statements in this file are because we only get here
//! after ruff has already successfully parsed the string literal, meaning
//! we don't need to do any validation or error handling.
use core::convert::Infallible;
use ruff_python_ast::{AnyStringFlags, StringFlags};
use rustpython_wtf8::{CodePoint, Wtf8, Wtf8Buf};
// use ruff_python_parser::{LexicalError, LexicalErrorType};
type LexicalError = Infallible;
enum EscapedChar {
Literal(CodePoint),
Escape(char),
}
struct StringParser {
/// The raw content of the string e.g., the `foo` part in `"foo"`.
source: Box<str>,
/// Current position of the parser in the source.
cursor: usize,
/// Flags that can be used to query information about the string.
flags: AnyStringFlags,
}
impl StringParser {
const fn new(source: Box<str>, flags: AnyStringFlags) -> Self {
Self {
source,
cursor: 0,
flags,
}
}
#[inline]
fn skip_bytes(&mut self, bytes: usize) -> &str {
let skipped_str = &self.source[self.cursor..self.cursor + bytes];
self.cursor += bytes;
skipped_str
}
/// Returns the next byte in the string, if there is one.
///
/// # Panics
///
/// When the next byte is a part of a multi-byte character.
#[inline]
fn next_byte(&mut self) -> Option<u8> {
self.source[self.cursor..].as_bytes().first().map(|&byte| {
self.cursor += 1;
byte
})
}
#[inline]
fn next_char(&mut self) -> Option<char> {
self.source[self.cursor..].chars().next().inspect(|c| {
self.cursor += c.len_utf8();
})
}
#[inline]
fn peek_byte(&self) -> Option<u8> {
self.source[self.cursor..].as_bytes().first().copied()
}
fn parse_unicode_literal(&mut self, literal_number: usize) -> Result<CodePoint, LexicalError> {
let mut p: u32 = 0u32;
for i in 1..=literal_number {
match self.next_char() {
Some(c) => match c.to_digit(16) {
Some(d) => p += d << ((literal_number - i) * 4),
None => unreachable!(),
},
None => unreachable!(),
}
}
Ok(CodePoint::from_u32(p).unwrap())
}
fn parse_octet(&mut self, o: u8) -> char {
let mut radix_bytes = [o, 0, 0];
let mut len = 1;
while len < 3 {
let Some(b'0'..=b'7') = self.peek_byte() else {
break;
};
radix_bytes[len] = self.next_byte().unwrap();
len += 1;
}
// OK because radix_bytes is always going to be in the ASCII range.
let radix_str = core::str::from_utf8(&radix_bytes[..len]).expect("ASCII bytes");
let value = u32::from_str_radix(radix_str, 8).unwrap();
char::from_u32(value).unwrap()
}
fn parse_unicode_name(&mut self) -> Result<char, LexicalError> {
let Some('{') = self.next_char() else {
unreachable!()
};
let Some(close_idx) = self.source[self.cursor..].find('}') else {
unreachable!()
};
let name_and_ending = self.skip_bytes(close_idx + 1);
let name = &name_and_ending[..name_and_ending.len() - 1];
unicode_names2::character(name).ok_or_else(|| unreachable!())
}
/// Parse an escaped character, returning the new character.
fn parse_escaped_char(&mut self) -> Result<Option<EscapedChar>, LexicalError> {
let Some(first_char) = self.next_char() else {
unreachable!()
};
let new_char = match first_char {
'\\' => '\\'.into(),
'\'' => '\''.into(),
'\"' => '"'.into(),
'a' => '\x07'.into(),
'b' => '\x08'.into(),
'f' => '\x0c'.into(),
'n' => '\n'.into(),
'r' => '\r'.into(),
't' => '\t'.into(),
'v' => '\x0b'.into(),
o @ '0'..='7' => self.parse_octet(o as u8).into(),
'x' => self.parse_unicode_literal(2)?,
'u' if !self.flags.is_byte_string() => self.parse_unicode_literal(4)?,
'U' if !self.flags.is_byte_string() => self.parse_unicode_literal(8)?,
'N' if !self.flags.is_byte_string() => self.parse_unicode_name()?.into(),
// Special cases where the escape sequence is not a single character
'\n' => return Ok(None),
'\r' => {
if self.peek_byte() == Some(b'\n') {
self.next_byte();
}
return Ok(None);
}
_ => return Ok(Some(EscapedChar::Escape(first_char))),
};
Ok(Some(EscapedChar::Literal(new_char)))
}
fn parse_fstring_middle(mut self) -> Result<Box<Wtf8>, LexicalError> {
// Fast-path: if the f-string doesn't contain any escape sequences, return the literal.
let Some(mut index) = memchr::memchr3(b'{', b'}', b'\\', self.source.as_bytes()) else {
return Ok(self.source.into());
};
let mut value = Wtf8Buf::with_capacity(self.source.len());
loop {
// Add the characters before the escape sequence (or curly brace) to the string.
let before_with_slash_or_brace = self.skip_bytes(index + 1);
let before = &before_with_slash_or_brace[..before_with_slash_or_brace.len() - 1];
value.push_str(before);
// Add the escaped character to the string.
match &self.source.as_bytes()[self.cursor - 1] {
// If there are any curly braces inside a `FStringMiddle` token,
// then they were escaped (i.e. `{{` or `}}`). This means that
// we need increase the location by 2 instead of 1.
b'{' => value.push_char('{'),
b'}' => value.push_char('}'),
// We can encounter a `\` as the last character in a `FStringMiddle`
// token which is valid in this context. For example,
//
// ```python
// f"\{foo} \{bar:\}"
// # ^ ^^ ^
// ```
//
// Here, the `FStringMiddle` token content will be "\" and " \"
// which is invalid if we look at the content in isolation:
//
// ```python
// "\"
// ```
//
// However, the content is syntactically valid in the context of
// the f-string because it's a substring of the entire f-string.
// This is still an invalid escape sequence, but we don't want to
// raise a syntax error as is done by the CPython parser. It might
// be supported in the future, refer to point 3: https://peps.python.org/pep-0701/#rejected-ideas
b'\\' => {
if !self.flags.is_raw_string() && self.peek_byte().is_some() {
match self.parse_escaped_char()? {
None => {}
Some(EscapedChar::Literal(c)) => value.push(c),
Some(EscapedChar::Escape(c)) => {
value.push_char('\\');
value.push_char(c);
}
}
} else {
value.push_char('\\');
}
}
ch => {
unreachable!("Expected '{{', '}}', or '\\' but got {:?}", ch);
}
}
let Some(next_index) =
memchr::memchr3(b'{', b'}', b'\\', self.source[self.cursor..].as_bytes())
else {
// Add the rest of the string to the value.
let rest = &self.source[self.cursor..];
value.push_str(rest);
break;
};
index = next_index;
}
Ok(value.into())
}
fn parse_string(mut self) -> Result<Box<Wtf8>, LexicalError> {
if self.flags.is_raw_string() {
// For raw strings, no escaping is necessary.
return Ok(self.source.into());
}
let Some(mut escape) = memchr::memchr(b'\\', self.source.as_bytes()) else {
// If the string doesn't contain any escape sequences, return the owned string.
return Ok(self.source.into());
};
// If the string contains escape sequences, we need to parse them.
let mut value = Wtf8Buf::with_capacity(self.source.len());
loop {
// Add the characters before the escape sequence to the string.
let before_with_slash = self.skip_bytes(escape + 1);
let before = &before_with_slash[..before_with_slash.len() - 1];
value.push_str(before);
// Add the escaped character to the string.
match self.parse_escaped_char()? {
None => {}
Some(EscapedChar::Literal(c)) => value.push(c),
Some(EscapedChar::Escape(c)) => {
value.push_char('\\');
value.push_char(c);
}
}
let Some(next_escape) = self.source[self.cursor..].find('\\') else {
// Add the rest of the string to the value.
let rest = &self.source[self.cursor..];
value.push_str(rest);
break;
};
// Update the position of the next escape sequence.
escape = next_escape;
}
Ok(value.into())
}
}
pub(crate) fn parse_string_literal(source: &str, flags: AnyStringFlags) -> Box<Wtf8> {
let source = &source[flags.opener_len().to_usize()..];
let source = &source[..source.len() - flags.quote_len().to_usize()];
StringParser::new(source.into(), flags)
.parse_string()
.unwrap_or_else(|x| match x {})
}
pub(crate) fn parse_fstring_literal_element(source: Box<str>, flags: AnyStringFlags) -> Box<Wtf8> {
StringParser::new(source, flags)
.parse_fstring_middle()
.unwrap_or_else(|x| match x {})
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/codegen/src/error.rs | crates/codegen/src/error.rs | use alloc::fmt;
use core::fmt::Display;
use rustpython_compiler_core::SourceLocation;
use thiserror::Error;
#[derive(Debug)]
pub enum PatternUnreachableReason {
NameCapture,
Wildcard,
}
impl Display for PatternUnreachableReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NameCapture => write!(f, "name capture"),
Self::Wildcard => write!(f, "wildcard"),
}
}
}
// pub type CodegenError = rustpython_parser_core::source_code::LocatedError<CodegenErrorType>;
#[derive(Error, Debug)]
pub struct CodegenError {
pub location: Option<SourceLocation>,
#[source]
pub error: CodegenErrorType,
pub source_path: String,
}
impl fmt::Display for CodegenError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// TODO:
self.error.fmt(f)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum InternalError {
StackOverflow,
StackUnderflow,
MissingSymbol(String),
}
impl Display for InternalError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::StackOverflow => write!(f, "stack overflow"),
Self::StackUnderflow => write!(f, "stack underflow"),
Self::MissingSymbol(s) => write!(
f,
"The symbol '{s}' must be present in the symbol table, even when it is undefined in python."
),
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum CodegenErrorType {
/// Invalid assignment, cannot store value in target.
Assign(&'static str),
/// Invalid delete
Delete(&'static str),
SyntaxError(String),
/// Multiple `*` detected
MultipleStarArgs,
/// Misplaced `*` expression
InvalidStarExpr,
/// Break statement outside of loop.
InvalidBreak,
/// Continue statement outside of loop.
InvalidContinue,
InvalidReturn,
InvalidYield,
InvalidYieldFrom,
InvalidAwait,
InvalidAsyncFor,
InvalidAsyncWith,
InvalidAsyncComprehension,
AsyncYieldFrom,
AsyncReturnValue,
InvalidFuturePlacement,
InvalidFutureFeature(String),
FunctionImportStar,
TooManyStarUnpack,
EmptyWithItems,
EmptyWithBody,
ForbiddenName,
DuplicateStore(String),
UnreachablePattern(PatternUnreachableReason),
RepeatedAttributePattern,
ConflictingNameBindPattern,
/// break/continue/return inside except* block
BreakContinueReturnInExceptStar,
NotImplementedYet, // RustPython marker for unimplemented features
}
impl core::error::Error for CodegenErrorType {}
impl fmt::Display for CodegenErrorType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use CodegenErrorType::*;
match self {
Assign(target) => write!(f, "cannot assign to {target}"),
Delete(target) => write!(f, "cannot delete {target}"),
SyntaxError(err) => write!(f, "{}", err.as_str()),
MultipleStarArgs => {
write!(f, "two starred expressions in assignment")
}
InvalidStarExpr => write!(f, "cannot use starred expression here"),
InvalidBreak => write!(f, "'break' outside loop"),
InvalidContinue => write!(f, "'continue' outside loop"),
InvalidReturn => write!(f, "'return' outside function"),
InvalidYield => write!(f, "'yield' outside function"),
InvalidYieldFrom => write!(f, "'yield from' outside function"),
InvalidAwait => write!(f, "'await' outside async function"),
InvalidAsyncFor => write!(f, "'async for' outside async function"),
InvalidAsyncWith => write!(f, "'async with' outside async function"),
InvalidAsyncComprehension => {
write!(
f,
"asynchronous comprehension outside of an asynchronous function"
)
}
AsyncYieldFrom => write!(f, "'yield from' inside async function"),
AsyncReturnValue => {
write!(f, "'return' with value inside async generator")
}
InvalidFuturePlacement => write!(
f,
"from __future__ imports must occur at the beginning of the file"
),
InvalidFutureFeature(feat) => {
write!(f, "future feature {feat} is not defined")
}
FunctionImportStar => {
write!(f, "import * only allowed at module level")
}
TooManyStarUnpack => {
write!(f, "too many expressions in star-unpacking assignment")
}
EmptyWithItems => {
write!(f, "empty items on With")
}
EmptyWithBody => {
write!(f, "empty body on With")
}
ForbiddenName => {
write!(f, "forbidden attribute name")
}
DuplicateStore(s) => {
write!(f, "duplicate store {s}")
}
UnreachablePattern(reason) => {
write!(f, "{reason} makes remaining patterns unreachable")
}
RepeatedAttributePattern => {
write!(f, "attribute name repeated in class pattern")
}
ConflictingNameBindPattern => {
write!(f, "alternative patterns bind different names")
}
BreakContinueReturnInExceptStar => {
write!(
f,
"'break', 'continue' and 'return' cannot appear in an except* block"
)
}
NotImplementedYet => {
write!(f, "RustPython does not implement this feature yet")
}
}
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/codegen/src/unparse.rs | crates/codegen/src/unparse.rs | use alloc::fmt;
use core::fmt::Display as _;
use ruff_python_ast::{
self as ruff, Arguments, BoolOp, Comprehension, ConversionFlag, Expr, Identifier, Operator,
Parameter, ParameterWithDefault, Parameters,
};
use ruff_text_size::Ranged;
use rustpython_compiler_core::SourceFile;
use rustpython_literal::escape::{AsciiEscape, UnicodeEscape};
mod precedence {
macro_rules! precedence {
($($op:ident,)*) => {
precedence!(@0, $($op,)*);
};
(@$i:expr, $op1:ident, $($op:ident,)*) => {
pub const $op1: u8 = $i;
precedence!(@$i + 1, $($op,)*);
};
(@$i:expr,) => {};
}
precedence!(
TUPLE, TEST, OR, AND, NOT, CMP, // "EXPR" =
BOR, BXOR, BAND, SHIFT, ARITH, TERM, FACTOR, POWER, AWAIT, ATOM,
);
pub const EXPR: u8 = BOR;
}
struct Unparser<'a, 'b, 'c> {
f: &'b mut fmt::Formatter<'a>,
source: &'c SourceFile,
}
impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> {
const fn new(f: &'b mut fmt::Formatter<'a>, source: &'c SourceFile) -> Self {
Self { f, source }
}
fn p(&mut self, s: &str) -> fmt::Result {
self.f.write_str(s)
}
fn p_id(&mut self, s: &Identifier) -> fmt::Result {
self.f.write_str(s.as_str())
}
fn p_if(&mut self, cond: bool, s: &str) -> fmt::Result {
if cond {
self.f.write_str(s)?;
}
Ok(())
}
fn p_delim(&mut self, first: &mut bool, s: &str) -> fmt::Result {
self.p_if(!core::mem::take(first), s)
}
fn write_fmt(&mut self, f: fmt::Arguments<'_>) -> fmt::Result {
self.f.write_fmt(f)
}
fn unparse_expr(&mut self, ast: &Expr, level: u8) -> fmt::Result {
macro_rules! op_prec {
($op_ty:ident, $x:expr, $enu:path, $($var:ident($op:literal, $prec:ident)),*$(,)?) => {
match $x {
$(<$enu>::$var => (op_prec!(@space $op_ty, $op), precedence::$prec),)*
}
};
(@space bin, $op:literal) => {
concat!(" ", $op, " ")
};
(@space un, $op:literal) => {
$op
};
}
macro_rules! group_if {
($lvl:expr, $body:block) => {{
let group = level > $lvl;
self.p_if(group, "(")?;
let ret = $body;
self.p_if(group, ")")?;
ret
}};
}
match &ast {
Expr::BoolOp(ruff::ExprBoolOp {
op,
values,
node_index: _,
range: _range,
}) => {
let (op, prec) = op_prec!(bin, op, BoolOp, And("and", AND), Or("or", OR));
group_if!(prec, {
let mut first = true;
for val in values {
self.p_delim(&mut first, op)?;
self.unparse_expr(val, prec + 1)?;
}
})
}
Expr::Named(ruff::ExprNamed {
target,
value,
node_index: _,
range: _range,
}) => {
group_if!(precedence::TUPLE, {
self.unparse_expr(target, precedence::ATOM)?;
self.p(" := ")?;
self.unparse_expr(value, precedence::ATOM)?;
})
}
Expr::BinOp(ruff::ExprBinOp {
left,
op,
right,
node_index: _,
range: _range,
}) => {
let right_associative = matches!(op, Operator::Pow);
let (op, prec) = op_prec!(
bin,
op,
Operator,
Add("+", ARITH),
Sub("-", ARITH),
Mult("*", TERM),
MatMult("@", TERM),
Div("/", TERM),
Mod("%", TERM),
Pow("**", POWER),
LShift("<<", SHIFT),
RShift(">>", SHIFT),
BitOr("|", BOR),
BitXor("^", BXOR),
BitAnd("&", BAND),
FloorDiv("//", TERM),
);
group_if!(prec, {
self.unparse_expr(left, prec + right_associative as u8)?;
self.p(op)?;
self.unparse_expr(right, prec + !right_associative as u8)?;
})
}
Expr::UnaryOp(ruff::ExprUnaryOp {
op,
operand,
node_index: _,
range: _range,
}) => {
let (op, prec) = op_prec!(
un,
op,
ruff::UnaryOp,
Invert("~", FACTOR),
Not("not ", NOT),
UAdd("+", FACTOR),
USub("-", FACTOR)
);
group_if!(prec, {
self.p(op)?;
self.unparse_expr(operand, prec)?;
})
}
Expr::Lambda(ruff::ExprLambda {
parameters,
body,
node_index: _,
range: _range,
}) => {
group_if!(precedence::TEST, {
if let Some(parameters) = parameters {
self.p("lambda ")?;
self.unparse_arguments(parameters)?;
} else {
self.p("lambda")?;
}
write!(self, ": {}", UnparseExpr::new(body, self.source))?;
})
}
Expr::If(ruff::ExprIf {
test,
body,
orelse,
node_index: _,
range: _range,
}) => {
group_if!(precedence::TEST, {
self.unparse_expr(body, precedence::TEST + 1)?;
self.p(" if ")?;
self.unparse_expr(test, precedence::TEST + 1)?;
self.p(" else ")?;
self.unparse_expr(orelse, precedence::TEST)?;
})
}
Expr::Dict(ruff::ExprDict {
items,
node_index: _,
range: _range,
}) => {
self.p("{")?;
let mut first = true;
for item in items {
self.p_delim(&mut first, ", ")?;
if let Some(k) = &item.key {
write!(self, "{}: ", UnparseExpr::new(k, self.source))?;
} else {
self.p("**")?;
}
self.unparse_expr(&item.value, level)?;
}
self.p("}")?;
}
Expr::Set(ruff::ExprSet {
elts,
node_index: _,
range: _range,
}) => {
self.p("{")?;
let mut first = true;
for v in elts {
self.p_delim(&mut first, ", ")?;
self.unparse_expr(v, precedence::TEST)?;
}
self.p("}")?;
}
Expr::ListComp(ruff::ExprListComp {
elt,
generators,
node_index: _,
range: _range,
}) => {
self.p("[")?;
self.unparse_expr(elt, precedence::TEST)?;
self.unparse_comp(generators)?;
self.p("]")?;
}
Expr::SetComp(ruff::ExprSetComp {
elt,
generators,
node_index: _,
range: _range,
}) => {
self.p("{")?;
self.unparse_expr(elt, precedence::TEST)?;
self.unparse_comp(generators)?;
self.p("}")?;
}
Expr::DictComp(ruff::ExprDictComp {
key,
value,
generators,
node_index: _,
range: _range,
}) => {
self.p("{")?;
self.unparse_expr(key, precedence::TEST)?;
self.p(": ")?;
self.unparse_expr(value, precedence::TEST)?;
self.unparse_comp(generators)?;
self.p("}")?;
}
Expr::Generator(ruff::ExprGenerator {
parenthesized: _,
elt,
generators,
node_index: _,
range: _range,
}) => {
self.p("(")?;
self.unparse_expr(elt, precedence::TEST)?;
self.unparse_comp(generators)?;
self.p(")")?;
}
Expr::Await(ruff::ExprAwait {
value,
node_index: _,
range: _range,
}) => {
group_if!(precedence::AWAIT, {
self.p("await ")?;
self.unparse_expr(value, precedence::ATOM)?;
})
}
Expr::Yield(ruff::ExprYield {
value,
node_index: _,
range: _range,
}) => {
if let Some(value) = value {
write!(self, "(yield {})", UnparseExpr::new(value, self.source))?;
} else {
self.p("(yield)")?;
}
}
Expr::YieldFrom(ruff::ExprYieldFrom {
value,
node_index: _,
range: _range,
}) => {
write!(
self,
"(yield from {})",
UnparseExpr::new(value, self.source)
)?;
}
Expr::Compare(ruff::ExprCompare {
left,
ops,
comparators,
node_index: _,
range: _range,
}) => {
group_if!(precedence::CMP, {
let new_lvl = precedence::CMP + 1;
self.unparse_expr(left, new_lvl)?;
for (op, cmp) in ops.iter().zip(comparators) {
self.p(" ")?;
self.p(op.as_str())?;
self.p(" ")?;
self.unparse_expr(cmp, new_lvl)?;
}
})
}
Expr::Call(ruff::ExprCall {
func,
arguments: Arguments { args, keywords, .. },
node_index: _,
range: _range,
}) => {
self.unparse_expr(func, precedence::ATOM)?;
self.p("(")?;
if let (
[
Expr::Generator(ruff::ExprGenerator {
elt,
generators,
node_index: _,
range: _range,
..
}),
],
[],
) = (&**args, &**keywords)
{
// make sure a single genexpr doesn't get double parens
self.unparse_expr(elt, precedence::TEST)?;
self.unparse_comp(generators)?;
} else {
let mut first = true;
for arg in args {
self.p_delim(&mut first, ", ")?;
self.unparse_expr(arg, precedence::TEST)?;
}
for kw in keywords {
self.p_delim(&mut first, ", ")?;
if let Some(arg) = &kw.arg {
self.p_id(arg)?;
self.p("=")?;
} else {
self.p("**")?;
}
self.unparse_expr(&kw.value, precedence::TEST)?;
}
}
self.p(")")?;
}
Expr::FString(ruff::ExprFString { value, .. }) => self.unparse_fstring(value)?,
Expr::TString(_) => self.p("t\"\"")?,
Expr::StringLiteral(ruff::ExprStringLiteral { value, .. }) => {
if value.is_unicode() {
self.p("u")?
}
UnicodeEscape::new_repr(value.to_str().as_ref())
.str_repr()
.fmt(self.f)?
}
Expr::BytesLiteral(ruff::ExprBytesLiteral { value, .. }) => {
AsciiEscape::new_repr(&value.bytes().collect::<Vec<_>>())
.bytes_repr()
.fmt(self.f)?
}
Expr::NumberLiteral(ruff::ExprNumberLiteral { value, .. }) => {
#[allow(clippy::correctness, clippy::assertions_on_constants)]
const {
assert!(f64::MAX_10_EXP == 308)
};
let inf_str = "1e309";
match value {
ruff::Number::Int(int) => int.fmt(self.f)?,
&ruff::Number::Float(fp) => {
if fp.is_infinite() {
self.p(inf_str)?
} else {
self.p(&rustpython_literal::float::to_string(fp))?
}
}
&ruff::Number::Complex { real, imag } => self
.p(&rustpython_literal::complex::to_string(real, imag)
.replace("inf", inf_str))?,
}
}
Expr::BooleanLiteral(ruff::ExprBooleanLiteral { value, .. }) => {
self.p(if *value { "True" } else { "False" })?
}
Expr::NoneLiteral(ruff::ExprNoneLiteral { .. }) => self.p("None")?,
Expr::EllipsisLiteral(ruff::ExprEllipsisLiteral { .. }) => self.p("...")?,
Expr::Attribute(ruff::ExprAttribute { value, attr, .. }) => {
self.unparse_expr(value, precedence::ATOM)?;
let period = if let Expr::NumberLiteral(ruff::ExprNumberLiteral {
value: ruff::Number::Int(_),
..
}) = value.as_ref()
{
" ."
} else {
"."
};
self.p(period)?;
self.p_id(attr)?;
}
Expr::Subscript(ruff::ExprSubscript { value, slice, .. }) => {
self.unparse_expr(value, precedence::ATOM)?;
let lvl = precedence::TUPLE;
self.p("[")?;
self.unparse_expr(slice, lvl)?;
self.p("]")?;
}
Expr::Starred(ruff::ExprStarred { value, .. }) => {
self.p("*")?;
self.unparse_expr(value, precedence::EXPR)?;
}
Expr::Name(ruff::ExprName { id, .. }) => self.p(id.as_str())?,
Expr::List(ruff::ExprList { elts, .. }) => {
self.p("[")?;
let mut first = true;
for elt in elts {
self.p_delim(&mut first, ", ")?;
self.unparse_expr(elt, precedence::TEST)?;
}
self.p("]")?;
}
Expr::Tuple(ruff::ExprTuple { elts, .. }) => {
if elts.is_empty() {
self.p("()")?;
} else {
group_if!(precedence::TUPLE, {
let mut first = true;
for elt in elts {
self.p_delim(&mut first, ", ")?;
self.unparse_expr(elt, precedence::TEST)?;
}
self.p_if(elts.len() == 1, ",")?;
})
}
}
Expr::Slice(ruff::ExprSlice {
lower,
upper,
step,
node_index: _,
range: _range,
}) => {
if let Some(lower) = lower {
self.unparse_expr(lower, precedence::TEST)?;
}
self.p(":")?;
if let Some(upper) = upper {
self.unparse_expr(upper, precedence::TEST)?;
}
if let Some(step) = step {
self.p(":")?;
self.unparse_expr(step, precedence::TEST)?;
}
}
Expr::IpyEscapeCommand(_) => {}
}
Ok(())
}
fn unparse_arguments(&mut self, args: &Parameters) -> fmt::Result {
let mut first = true;
for (i, arg) in args.posonlyargs.iter().chain(&args.args).enumerate() {
self.p_delim(&mut first, ", ")?;
self.unparse_function_arg(arg)?;
self.p_if(i + 1 == args.posonlyargs.len(), ", /")?;
}
if args.vararg.is_some() || !args.kwonlyargs.is_empty() {
self.p_delim(&mut first, ", ")?;
self.p("*")?;
}
if let Some(vararg) = &args.vararg {
self.unparse_arg(vararg)?;
}
for kwarg in &args.kwonlyargs {
self.p_delim(&mut first, ", ")?;
self.unparse_function_arg(kwarg)?;
}
if let Some(kwarg) = &args.kwarg {
self.p_delim(&mut first, ", ")?;
self.p("**")?;
self.unparse_arg(kwarg)?;
}
Ok(())
}
fn unparse_function_arg(&mut self, arg: &ParameterWithDefault) -> fmt::Result {
self.unparse_arg(&arg.parameter)?;
if let Some(default) = &arg.default {
write!(self, "={}", UnparseExpr::new(default, self.source))?;
}
Ok(())
}
fn unparse_arg(&mut self, arg: &Parameter) -> fmt::Result {
self.p_id(&arg.name)?;
if let Some(ann) = &arg.annotation {
write!(self, ": {}", UnparseExpr::new(ann, self.source))?;
}
Ok(())
}
fn unparse_comp(&mut self, generators: &[Comprehension]) -> fmt::Result {
for comp in generators {
self.p(if comp.is_async {
" async for "
} else {
" for "
})?;
self.unparse_expr(&comp.target, precedence::TUPLE)?;
self.p(" in ")?;
self.unparse_expr(&comp.iter, precedence::TEST + 1)?;
for cond in &comp.ifs {
self.p(" if ")?;
self.unparse_expr(cond, precedence::TEST + 1)?;
}
}
Ok(())
}
fn unparse_fstring_body(
&mut self,
elements: &[ruff::InterpolatedStringElement],
) -> fmt::Result {
for elem in elements {
self.unparse_fstring_elem(elem)?;
}
Ok(())
}
fn unparse_formatted(
&mut self,
val: &Expr,
debug_text: Option<&ruff::DebugText>,
conversion: ConversionFlag,
spec: Option<&ruff::InterpolatedStringFormatSpec>,
) -> fmt::Result {
let buffered = to_string_fmt(|f| {
Unparser::new(f, self.source).unparse_expr(val, precedence::TEST + 1)
});
if let Some(ruff::DebugText { leading, trailing }) = debug_text {
self.p(leading)?;
self.p(self.source.slice(val.range()))?;
self.p(trailing)?;
}
let brace = if buffered.starts_with('{') {
// put a space to avoid escaping the bracket
"{ "
} else {
"{"
};
self.p(brace)?;
self.p(&buffered)?;
drop(buffered);
if conversion != ConversionFlag::None {
self.p("!")?;
let buf = &[conversion as u8];
let c = core::str::from_utf8(buf).unwrap();
self.p(c)?;
}
if let Some(spec) = spec {
self.p(":")?;
self.unparse_fstring_body(&spec.elements)?;
}
self.p("}")?;
Ok(())
}
fn unparse_fstring_elem(&mut self, elem: &ruff::InterpolatedStringElement) -> fmt::Result {
match elem {
ruff::InterpolatedStringElement::Interpolation(ruff::InterpolatedElement {
expression,
debug_text,
conversion,
format_spec,
..
}) => self.unparse_formatted(
expression,
debug_text.as_ref(),
*conversion,
format_spec.as_deref(),
),
ruff::InterpolatedStringElement::Literal(ruff::InterpolatedStringLiteralElement {
value,
..
}) => self.unparse_fstring_str(value),
}
}
fn unparse_fstring_str(&mut self, s: &str) -> fmt::Result {
let s = s.replace('{', "{{").replace('}', "}}");
self.p(&s)
}
fn unparse_fstring(&mut self, value: &ruff::FStringValue) -> fmt::Result {
self.p("f")?;
let body = to_string_fmt(|f| {
value.iter().try_for_each(|part| match part {
ruff::FStringPart::Literal(lit) => f.write_str(lit),
ruff::FStringPart::FString(ruff::FString { elements, .. }) => {
Unparser::new(f, self.source).unparse_fstring_body(elements)
}
})
});
// .unparse_fstring_body(elements));
UnicodeEscape::new_repr(body.as_str().as_ref())
.str_repr()
.write(self.f)
}
}
pub struct UnparseExpr<'a> {
expr: &'a Expr,
source: &'a SourceFile,
}
impl<'a> UnparseExpr<'a> {
pub const fn new(expr: &'a Expr, source: &'a SourceFile) -> Self {
Self { expr, source }
}
}
impl fmt::Display for UnparseExpr<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Unparser::new(f, self.source).unparse_expr(self.expr, precedence::TEST)
}
}
fn to_string_fmt(f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) -> String {
use core::cell::Cell;
struct Fmt<F>(Cell<Option<F>>);
impl<F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result> fmt::Display for Fmt<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.take().unwrap()(f)
}
}
Fmt(Cell::new(Some(f))).to_string()
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/codegen/src/ir.rs | crates/codegen/src/ir.rs | use core::ops;
use crate::{IndexMap, IndexSet, error::InternalError};
use rustpython_compiler_core::{
OneIndexed, SourceLocation,
bytecode::{
CodeFlags, CodeObject, CodeUnit, CodeUnits, ConstantData, ExceptionTableEntry,
InstrDisplayContext, Instruction, Label, OpArg, PyCodeLocationInfoKind,
encode_exception_table,
},
varint::{write_signed_varint, write_varint},
};
/// Metadata for a code unit
// = _PyCompile_CodeUnitMetadata
#[derive(Clone, Debug)]
pub struct CodeUnitMetadata {
pub name: String, // u_name (obj_name)
pub qualname: Option<String>, // u_qualname
pub consts: IndexSet<ConstantData>, // u_consts
pub names: IndexSet<String>, // u_names
pub varnames: IndexSet<String>, // u_varnames
pub cellvars: IndexSet<String>, // u_cellvars
pub freevars: IndexSet<String>, // u_freevars
pub fast_hidden: IndexMap<String, bool>, // u_fast_hidden
pub argcount: u32, // u_argcount
pub posonlyargcount: u32, // u_posonlyargcount
pub kwonlyargcount: u32, // u_kwonlyargcount
pub firstlineno: OneIndexed, // u_firstlineno
}
// use rustpython_parser_core::source_code::{LineNumber, SourceLocation};
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct BlockIdx(u32);
impl BlockIdx {
pub const NULL: Self = Self::new(u32::MAX);
/// Creates a new instance of [`BlockIdx`] from a [`u32`].
#[must_use]
pub const fn new(value: u32) -> Self {
Self(value)
}
/// Returns the inner value as a [`usize`].
#[must_use]
pub const fn idx(self) -> usize {
self.0 as usize
}
}
impl From<BlockIdx> for u32 {
fn from(block_idx: BlockIdx) -> Self {
block_idx.0
}
}
impl ops::Index<BlockIdx> for [Block] {
type Output = Block;
fn index(&self, idx: BlockIdx) -> &Block {
&self[idx.idx()]
}
}
impl ops::IndexMut<BlockIdx> for [Block] {
fn index_mut(&mut self, idx: BlockIdx) -> &mut Block {
&mut self[idx.idx()]
}
}
impl ops::Index<BlockIdx> for Vec<Block> {
type Output = Block;
fn index(&self, idx: BlockIdx) -> &Block {
&self[idx.idx()]
}
}
impl ops::IndexMut<BlockIdx> for Vec<Block> {
fn index_mut(&mut self, idx: BlockIdx) -> &mut Block {
&mut self[idx.idx()]
}
}
#[derive(Debug, Clone)]
pub struct InstructionInfo {
pub instr: Instruction,
pub arg: OpArg,
pub target: BlockIdx,
pub location: SourceLocation,
pub end_location: SourceLocation,
pub except_handler: Option<ExceptHandlerInfo>,
}
/// Exception handler information for an instruction
#[derive(Debug, Clone)]
pub struct ExceptHandlerInfo {
/// Block to jump to when exception occurs
pub handler_block: BlockIdx,
/// Stack depth at handler entry
pub stack_depth: u32,
/// Whether to push lasti before exception
pub preserve_lasti: bool,
}
// spell-checker:ignore petgraph
// TODO: look into using petgraph for handling blocks and stuff? it's heavier than this, but it
// might enable more analysis/optimizations
#[derive(Debug)]
pub struct Block {
pub instructions: Vec<InstructionInfo>,
pub next: BlockIdx,
}
impl Default for Block {
fn default() -> Self {
Self {
instructions: Vec::new(),
next: BlockIdx::NULL,
}
}
}
pub struct CodeInfo {
pub flags: CodeFlags,
pub source_path: String,
pub private: Option<String>, // For private name mangling, mostly for class
pub blocks: Vec<Block>,
pub current_block: BlockIdx,
pub metadata: CodeUnitMetadata,
// For class scopes: attributes accessed via self.X
pub static_attributes: Option<IndexSet<String>>,
// True if compiling an inlined comprehension
pub in_inlined_comp: bool,
// Block stack for tracking nested control structures
pub fblock: Vec<crate::compile::FBlockInfo>,
// Reference to the symbol table for this scope
pub symbol_table_index: usize,
}
impl CodeInfo {
pub fn finalize_code(
mut self,
opts: &crate::compile::CompileOpts,
) -> crate::InternalResult<CodeObject> {
if opts.optimize > 0 {
self.dce();
}
let max_stackdepth = self.max_stackdepth()?;
let cell2arg = self.cell2arg();
let Self {
flags,
source_path,
private: _, // private is only used during compilation
mut blocks,
current_block: _,
metadata,
static_attributes: _,
in_inlined_comp: _,
fblock: _,
symbol_table_index: _,
} = self;
let CodeUnitMetadata {
name: obj_name,
qualname,
consts: constants,
names: name_cache,
varnames: varname_cache,
cellvars: cellvar_cache,
freevars: freevar_cache,
fast_hidden: _,
argcount: arg_count,
posonlyargcount: posonlyarg_count,
kwonlyargcount: kwonlyarg_count,
firstlineno: first_line_number,
} = metadata;
let mut instructions = Vec::new();
let mut locations = Vec::new();
let mut block_to_offset = vec![Label(0); blocks.len()];
// block_to_index: maps block idx to instruction index (for exception table)
// This is the index into the final instructions array, including EXTENDED_ARG
let mut block_to_index = vec![0u32; blocks.len()];
loop {
let mut num_instructions = 0;
for (idx, block) in iter_blocks(&blocks) {
block_to_offset[idx.idx()] = Label(num_instructions as u32);
// block_to_index uses the same value as block_to_offset but as u32
// because lasti in frame.rs is the index into instructions array
// and instructions array index == byte offset (each instruction is 1 CodeUnit)
block_to_index[idx.idx()] = num_instructions as u32;
for instr in &block.instructions {
num_instructions += instr.arg.instr_size();
}
}
instructions.reserve_exact(num_instructions);
locations.reserve_exact(num_instructions);
let mut recompile_extended_arg = false;
let mut next_block = BlockIdx(0);
while next_block != BlockIdx::NULL {
let block = &mut blocks[next_block];
for info in &mut block.instructions {
let (op, arg, target) = (info.instr, &mut info.arg, info.target);
if target != BlockIdx::NULL {
let new_arg = OpArg(block_to_offset[target.idx()].0);
recompile_extended_arg |= new_arg.instr_size() != arg.instr_size();
*arg = new_arg;
}
let (extras, lo_arg) = arg.split();
locations.extend(core::iter::repeat_n(
(info.location, info.end_location),
arg.instr_size(),
));
instructions.extend(
extras
.map(|byte| CodeUnit::new(Instruction::ExtendedArg, byte))
.chain([CodeUnit { op, arg: lo_arg }]),
);
}
next_block = block.next;
}
if !recompile_extended_arg {
break;
}
instructions.clear();
locations.clear()
}
// Generate linetable from locations
let linetable = generate_linetable(
&locations,
first_line_number.get() as i32,
opts.debug_ranges,
);
// Generate exception table before moving source_path
let exceptiontable = generate_exception_table(&blocks, &block_to_index);
Ok(CodeObject {
flags,
posonlyarg_count,
arg_count,
kwonlyarg_count,
source_path,
first_line_number: Some(first_line_number),
obj_name: obj_name.clone(),
qualname: qualname.unwrap_or(obj_name),
max_stackdepth,
instructions: CodeUnits::from(instructions),
locations: locations.into_boxed_slice(),
constants: constants.into_iter().collect(),
names: name_cache.into_iter().collect(),
varnames: varname_cache.into_iter().collect(),
cellvars: cellvar_cache.into_iter().collect(),
freevars: freevar_cache.into_iter().collect(),
cell2arg,
linetable,
exceptiontable,
})
}
fn cell2arg(&self) -> Option<Box<[i32]>> {
if self.metadata.cellvars.is_empty() {
return None;
}
let total_args = self.metadata.argcount
+ self.metadata.kwonlyargcount
+ self.flags.contains(CodeFlags::HAS_VARARGS) as u32
+ self.flags.contains(CodeFlags::HAS_VARKEYWORDS) as u32;
let mut found_cellarg = false;
let cell2arg = self
.metadata
.cellvars
.iter()
.map(|var| {
self.metadata
.varnames
.get_index_of(var)
// check that it's actually an arg
.filter(|i| *i < total_args as usize)
.map_or(-1, |i| {
found_cellarg = true;
i as i32
})
})
.collect::<Box<[_]>>();
if found_cellarg { Some(cell2arg) } else { None }
}
fn dce(&mut self) {
for block in &mut self.blocks {
let mut last_instr = None;
for (i, ins) in block.instructions.iter().enumerate() {
if ins.instr.unconditional_branch() {
last_instr = Some(i);
break;
}
}
if let Some(i) = last_instr {
block.instructions.truncate(i + 1);
}
}
}
fn max_stackdepth(&self) -> crate::InternalResult<u32> {
let mut maxdepth = 0u32;
let mut stack = Vec::with_capacity(self.blocks.len());
let mut start_depths = vec![u32::MAX; self.blocks.len()];
start_depths[0] = 0;
stack.push(BlockIdx(0));
const DEBUG: bool = false;
// Global iteration limit as safety guard
// The algorithm is monotonic (depths only increase), so it should converge quickly.
// Max iterations = blocks * max_possible_depth_increases per block
let max_iterations = self.blocks.len() * 100;
let mut iterations = 0usize;
'process_blocks: while let Some(block_idx) = stack.pop() {
iterations += 1;
if iterations > max_iterations {
// Safety guard: should never happen in valid code
// Return error instead of silently breaking to avoid underestimated stack depth
return Err(InternalError::StackOverflow);
}
let idx = block_idx.idx();
let mut depth = start_depths[idx];
if DEBUG {
eprintln!("===BLOCK {}===", block_idx.0);
}
let block = &self.blocks[block_idx];
for ins in &block.instructions {
let instr = &ins.instr;
let effect = instr.stack_effect(ins.arg, false);
if DEBUG {
let display_arg = if ins.target == BlockIdx::NULL {
ins.arg
} else {
OpArg(ins.target.0)
};
let instr_display = instr.display(display_arg, self);
eprint!("{instr_display}: {depth} {effect:+} => ");
}
let new_depth = depth.checked_add_signed(effect).ok_or({
if effect < 0 {
InternalError::StackUnderflow
} else {
InternalError::StackOverflow
}
})?;
if DEBUG {
eprintln!("{new_depth}");
}
if new_depth > maxdepth {
maxdepth = new_depth
}
// Process target blocks for branching instructions
if ins.target != BlockIdx::NULL {
let effect = instr.stack_effect(ins.arg, true);
let target_depth = depth.checked_add_signed(effect).ok_or({
if effect < 0 {
InternalError::StackUnderflow
} else {
InternalError::StackOverflow
}
})?;
if target_depth > maxdepth {
maxdepth = target_depth
}
stackdepth_push(&mut stack, &mut start_depths, ins.target, target_depth);
}
// Process exception handler blocks
// When exception occurs, stack is unwound to handler.stack_depth, then:
// - If preserve_lasti: push lasti (+1)
// - Push exception (+1)
// - Handler block starts with PUSH_EXC_INFO as its first instruction
// So the starting depth for the handler block (BEFORE PUSH_EXC_INFO) is:
// handler.stack_depth + preserve_lasti + 1 (exc)
// PUSH_EXC_INFO will then add +1 when the block is processed
if let Some(ref handler) = ins.except_handler {
let handler_depth = handler.stack_depth + 1 + (handler.preserve_lasti as u32); // +1 for exception, +1 for lasti if preserve_lasti
if DEBUG {
eprintln!(
" HANDLER: block={} depth={} (base={} lasti={})",
handler.handler_block.0,
handler_depth,
handler.stack_depth,
handler.preserve_lasti
);
}
if handler_depth > maxdepth {
maxdepth = handler_depth;
}
stackdepth_push(
&mut stack,
&mut start_depths,
handler.handler_block,
handler_depth,
);
}
depth = new_depth;
if instr.unconditional_branch() {
continue 'process_blocks;
}
}
// Only push next block if it's not NULL
if block.next != BlockIdx::NULL {
stackdepth_push(&mut stack, &mut start_depths, block.next, depth);
}
}
if DEBUG {
eprintln!("DONE: {maxdepth}");
}
Ok(maxdepth)
}
}
impl InstrDisplayContext for CodeInfo {
type Constant = ConstantData;
fn get_constant(&self, i: usize) -> &ConstantData {
&self.metadata.consts[i]
}
fn get_name(&self, i: usize) -> &str {
self.metadata.names[i].as_ref()
}
fn get_varname(&self, i: usize) -> &str {
self.metadata.varnames[i].as_ref()
}
fn get_cell_name(&self, i: usize) -> &str {
self.metadata
.cellvars
.get_index(i)
.unwrap_or_else(|| &self.metadata.freevars[i - self.metadata.cellvars.len()])
.as_ref()
}
}
fn stackdepth_push(
stack: &mut Vec<BlockIdx>,
start_depths: &mut [u32],
target: BlockIdx,
depth: u32,
) {
let idx = target.idx();
let block_depth = &mut start_depths[idx];
if depth > *block_depth || *block_depth == u32::MAX {
// Found a path with higher depth (or first visit): update max and queue
*block_depth = depth;
stack.push(target);
}
}
fn iter_blocks(blocks: &[Block]) -> impl Iterator<Item = (BlockIdx, &Block)> + '_ {
let mut next = BlockIdx(0);
core::iter::from_fn(move || {
if next == BlockIdx::NULL {
return None;
}
let (idx, b) = (next, &blocks[next]);
next = b.next;
Some((idx, b))
})
}
/// Generate Python 3.11+ format linetable from source locations
fn generate_linetable(
locations: &[(SourceLocation, SourceLocation)],
first_line: i32,
debug_ranges: bool,
) -> Box<[u8]> {
if locations.is_empty() {
return Box::new([]);
}
let mut linetable = Vec::new();
// Initialize prev_line to first_line
// The first entry's delta is relative to co_firstlineno
let mut prev_line = first_line;
let mut i = 0;
while i < locations.len() {
let (loc, end_loc) = &locations[i];
// Count consecutive instructions with the same location
let mut length = 1;
while i + length < locations.len() && locations[i + length] == locations[i] {
length += 1;
}
// Process in chunks of up to 8 instructions
while length > 0 {
let entry_length = length.min(8);
// Get line information
let line = loc.line.get() as i32;
let end_line = end_loc.line.get() as i32;
let line_delta = line - prev_line;
let end_line_delta = end_line - line;
// When debug_ranges is disabled, only emit line info (NoColumns format)
if !debug_ranges {
// NoColumns format (code 13): line info only, no column data
linetable.push(
0x80 | ((PyCodeLocationInfoKind::NoColumns as u8) << 3)
| ((entry_length - 1) as u8),
);
write_signed_varint(&mut linetable, line_delta);
prev_line = line;
length -= entry_length;
i += entry_length;
continue;
}
// Get column information (only when debug_ranges is enabled)
let col = loc.character_offset.to_zero_indexed() as i32;
let end_col = end_loc.character_offset.to_zero_indexed() as i32;
// Choose the appropriate encoding based on line delta and column info
if line_delta == 0 && end_line_delta == 0 {
if col < 80 && end_col - col < 16 && end_col >= col {
// Short form (codes 0-9) for common cases
let code = (col / 8).min(9) as u8; // Short0 to Short9
linetable.push(0x80 | (code << 3) | ((entry_length - 1) as u8));
let col_byte = (((col % 8) as u8) << 4) | ((end_col - col) as u8 & 0xf);
linetable.push(col_byte);
} else if col < 128 && end_col < 128 {
// One-line form (code 10) for same line
linetable.push(
0x80 | ((PyCodeLocationInfoKind::OneLine0 as u8) << 3)
| ((entry_length - 1) as u8),
);
linetable.push(col as u8);
linetable.push(end_col as u8);
} else {
// Long form for columns >= 128
linetable.push(
0x80 | ((PyCodeLocationInfoKind::Long as u8) << 3)
| ((entry_length - 1) as u8),
);
write_signed_varint(&mut linetable, 0); // line_delta = 0
write_varint(&mut linetable, 0); // end_line delta = 0
write_varint(&mut linetable, (col as u32) + 1);
write_varint(&mut linetable, (end_col as u32) + 1);
}
} else if line_delta > 0 && line_delta < 3 && end_line_delta == 0 {
// One-line form (codes 11-12) for line deltas 1-2
if col < 128 && end_col < 128 {
let code = (PyCodeLocationInfoKind::OneLine0 as u8) + (line_delta as u8);
linetable.push(0x80 | (code << 3) | ((entry_length - 1) as u8));
linetable.push(col as u8);
linetable.push(end_col as u8);
} else {
// Long form for columns >= 128
linetable.push(
0x80 | ((PyCodeLocationInfoKind::Long as u8) << 3)
| ((entry_length - 1) as u8),
);
write_signed_varint(&mut linetable, line_delta);
write_varint(&mut linetable, 0); // end_line delta = 0
write_varint(&mut linetable, (col as u32) + 1);
write_varint(&mut linetable, (end_col as u32) + 1);
}
} else {
// Long form (code 14) for all other cases
// Handles: line_delta < 0, line_delta >= 3, multi-line spans, or columns >= 128
linetable.push(
0x80 | ((PyCodeLocationInfoKind::Long as u8) << 3) | ((entry_length - 1) as u8),
);
write_signed_varint(&mut linetable, line_delta);
write_varint(&mut linetable, end_line_delta as u32);
write_varint(&mut linetable, (col as u32) + 1);
write_varint(&mut linetable, (end_col as u32) + 1);
}
prev_line = line;
length -= entry_length;
i += entry_length;
}
}
linetable.into_boxed_slice()
}
/// Generate Python 3.11+ exception table from instruction handler info
fn generate_exception_table(blocks: &[Block], block_to_index: &[u32]) -> Box<[u8]> {
let mut entries: Vec<ExceptionTableEntry> = Vec::new();
let mut current_entry: Option<(ExceptHandlerInfo, u32)> = None; // (handler_info, start_index)
let mut instr_index = 0u32;
// Iterate through all instructions in block order
// instr_index is the index into the final instructions array (including EXTENDED_ARG)
// This matches how frame.rs uses lasti
for (_, block) in iter_blocks(blocks) {
for instr in &block.instructions {
// instr_size includes EXTENDED_ARG instructions
let instr_size = instr.arg.instr_size() as u32;
match (¤t_entry, &instr.except_handler) {
// No current entry, no handler - nothing to do
(None, None) => {}
// No current entry, handler starts - begin new entry
(None, Some(handler)) => {
current_entry = Some((handler.clone(), instr_index));
}
// Current entry exists, same handler - continue
(Some((curr_handler, _)), Some(handler))
if curr_handler.handler_block == handler.handler_block
&& curr_handler.stack_depth == handler.stack_depth
&& curr_handler.preserve_lasti == handler.preserve_lasti => {}
// Current entry exists, different handler - finish current, start new
(Some((curr_handler, start)), Some(handler)) => {
let target_index = block_to_index[curr_handler.handler_block.idx()];
entries.push(ExceptionTableEntry::new(
*start,
instr_index,
target_index,
curr_handler.stack_depth as u16,
curr_handler.preserve_lasti,
));
current_entry = Some((handler.clone(), instr_index));
}
// Current entry exists, no handler - finish current entry
(Some((curr_handler, start)), None) => {
let target_index = block_to_index[curr_handler.handler_block.idx()];
entries.push(ExceptionTableEntry::new(
*start,
instr_index,
target_index,
curr_handler.stack_depth as u16,
curr_handler.preserve_lasti,
));
current_entry = None;
}
}
instr_index += instr_size; // Account for EXTENDED_ARG instructions
}
}
// Finish any remaining entry
if let Some((curr_handler, start)) = current_entry {
let target_index = block_to_index[curr_handler.handler_block.idx()];
entries.push(ExceptionTableEntry::new(
start,
instr_index,
target_index,
curr_handler.stack_depth as u16,
curr_handler.preserve_lasti,
));
}
encode_exception_table(&entries)
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/pylib/build.rs | crates/pylib/build.rs | const CRATE_ROOT: &str = "../..";
fn main() {
process_python_libs(format!("{CRATE_ROOT}/vm/Lib/python_builtins/*").as_str());
process_python_libs(format!("{CRATE_ROOT}/vm/Lib/core_modules/*").as_str());
#[cfg(feature = "freeze-stdlib")]
if cfg!(windows) {
process_python_libs(format!("{CRATE_ROOT}/Lib/**/*").as_str());
} else {
process_python_libs("./Lib/**/*");
}
if cfg!(windows)
&& let Ok(real_path) = std::fs::read_to_string("Lib")
{
let canonicalized_path = std::fs::canonicalize(real_path)
.expect("failed to resolve RUSTPYTHONPATH during build time");
// Strip the extended path prefix (\\?\) that canonicalize adds on Windows
let path_str = canonicalized_path.to_str().unwrap();
let path_str = path_str.strip_prefix(r"\\?\").unwrap_or(path_str);
println!("cargo:rustc-env=win_lib_path={path_str}");
}
}
// remove *.pyc files and add *.py to watch list
fn process_python_libs(pattern: &str) {
let glob = glob::glob(pattern).unwrap_or_else(|e| panic!("failed to glob {pattern:?}: {e}"));
for entry in glob.flatten() {
if entry.is_dir() {
continue;
}
let display = entry.display();
if display.to_string().ends_with(".pyc") {
if std::fs::remove_file(&entry).is_err() {
println!("cargo:warning=failed to remove {display}")
}
continue;
}
println!("cargo:rerun-if-changed={display}");
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/pylib/src/lib.rs | crates/pylib/src/lib.rs | //! This crate includes the compiled python bytecode of the RustPython standard library. The most
//! common way to use this crate is to just add the `"freeze-stdlib"` feature to `rustpython-vm`,
//! in order to automatically include the python part of the standard library into the binary.
// windows needs to read the symlink out of `Lib` as git turns it into a text file,
// so build.rs sets this env var
pub const LIB_PATH: &str = match option_env!("win_lib_path") {
Some(s) => s,
None => concat!(env!("CARGO_MANIFEST_DIR"), "/Lib"),
};
#[cfg(feature = "freeze-stdlib")]
pub const FROZEN_STDLIB: &rustpython_compiler_core::frozen::FrozenLib =
rustpython_derive::py_freeze!(dir = "./Lib", crate_name = "rustpython_compiler_core");
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/wasm/src/browser_module.rs | crates/wasm/src/browser_module.rs | use rustpython_vm::VirtualMachine;
pub(crate) use _browser::make_module;
#[pymodule]
mod _browser {
use crate::{convert, js_module::PyPromise, vm_class::weak_vm, wasm_builtins::window};
use js_sys::Promise;
use rustpython_vm::{
PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
builtins::{PyDictRef, PyStrRef},
class::PyClassImpl,
convert::ToPyObject,
function::{ArgCallable, OptionalArg},
import::import_source,
};
use wasm_bindgen::{JsCast, prelude::*};
use wasm_bindgen_futures::JsFuture;
enum FetchResponseFormat {
Json,
Text,
ArrayBuffer,
}
impl FetchResponseFormat {
fn from_str(vm: &VirtualMachine, s: &str) -> PyResult<Self> {
match s {
"json" => Ok(FetchResponseFormat::Json),
"text" => Ok(FetchResponseFormat::Text),
"array_buffer" => Ok(FetchResponseFormat::ArrayBuffer),
_ => Err(vm.new_type_error("Unknown fetch response_format")),
}
}
fn get_response(&self, response: &web_sys::Response) -> Result<Promise, JsValue> {
match self {
FetchResponseFormat::Json => response.json(),
FetchResponseFormat::Text => response.text(),
FetchResponseFormat::ArrayBuffer => response.array_buffer(),
}
}
}
#[derive(FromArgs)]
struct FetchArgs {
#[pyarg(named, default)]
response_format: Option<PyStrRef>,
#[pyarg(named, default)]
method: Option<PyStrRef>,
#[pyarg(named, default)]
headers: Option<PyDictRef>,
#[pyarg(named, default)]
body: Option<PyObjectRef>,
#[pyarg(named, default)]
content_type: Option<PyStrRef>,
}
#[pyfunction]
fn fetch(url: PyStrRef, args: FetchArgs, vm: &VirtualMachine) -> PyResult {
let FetchArgs {
response_format,
method,
headers,
body,
content_type,
} = args;
let response_format = match response_format {
Some(s) => FetchResponseFormat::from_str(vm, s.as_str())?,
None => FetchResponseFormat::Text,
};
let opts = web_sys::RequestInit::new();
match method {
Some(s) => opts.set_method(s.as_str()),
None => opts.set_method("GET"),
};
if let Some(body) = body {
opts.set_body(&convert::py_to_js(vm, body));
}
let request = web_sys::Request::new_with_str_and_init(url.as_str(), &opts)
.map_err(|err| convert::js_py_typeerror(vm, err))?;
if let Some(headers) = headers {
let h = request.headers();
for (key, value) in headers {
let key = key.str(vm)?;
let value = value.str(vm)?;
h.set(key.as_str(), value.as_str())
.map_err(|err| convert::js_py_typeerror(vm, err))?;
}
}
if let Some(content_type) = content_type {
request
.headers()
.set("Content-Type", content_type.as_str())
.map_err(|err| convert::js_py_typeerror(vm, err))?;
}
let window = window();
let request_prom = window.fetch_with_request(&request);
let future = async move {
let val = JsFuture::from(request_prom).await?;
let response = val
.dyn_into::<web_sys::Response>()
.expect("val to be of type Response");
JsFuture::from(response_format.get_response(&response)?).await
};
Ok(PyPromise::from_future(future).into_pyobject(vm))
}
#[pyfunction]
fn request_animation_frame(func: ArgCallable, vm: &VirtualMachine) -> PyResult {
use alloc::rc::Rc;
use core::cell::RefCell;
// this basic setup for request_animation_frame taken from:
// https://rustwasm.github.io/wasm-bindgen/examples/request-animation-frame.html
let f = Rc::new(RefCell::new(None));
let g = f.clone();
let weak_vm = weak_vm(vm);
*g.borrow_mut() = Some(Closure::wrap(Box::new(move |time: f64| {
let stored_vm = weak_vm
.upgrade()
.expect("that the vm is valid from inside of request_animation_frame");
stored_vm.interp.enter(|vm| {
let func = func.clone();
let args = vec![vm.ctx.new_float(time).into()];
let _ = func.invoke(args, vm);
let closure = f.borrow_mut().take();
drop(closure);
})
}) as Box<dyn Fn(f64)>));
let id = window()
.request_animation_frame(&js_sys::Function::from(
g.borrow().as_ref().unwrap().as_ref().clone(),
))
.map_err(|err| convert::js_py_typeerror(vm, err))?;
Ok(vm.ctx.new_int(id).into())
}
#[pyfunction]
fn cancel_animation_frame(id: i32, vm: &VirtualMachine) -> PyResult<()> {
window()
.cancel_animation_frame(id)
.map_err(|err| convert::js_py_typeerror(vm, err))?;
Ok(())
}
#[pyattr]
#[pyclass(module = "browser", name)]
#[derive(Debug, PyPayload)]
struct Document {
doc: web_sys::Document,
}
#[pyclass]
impl Document {
#[pymethod]
fn query(&self, query: PyStrRef, vm: &VirtualMachine) -> PyResult {
let elem = self
.doc
.query_selector(query.as_str())
.map_err(|err| convert::js_py_typeerror(vm, err))?
.map(|elem| Element { elem })
.to_pyobject(vm);
Ok(elem)
}
}
#[pyattr]
fn document(vm: &VirtualMachine) -> PyRef<Document> {
PyRef::new_ref(
Document {
doc: window().document().expect("Document missing from window"),
},
Document::make_class(&vm.ctx),
None,
)
}
#[pyattr]
#[pyclass(module = "browser", name)]
#[derive(Debug, PyPayload)]
struct Element {
elem: web_sys::Element,
}
#[pyclass]
impl Element {
#[pymethod]
fn get_attr(
&self,
attr: PyStrRef,
default: OptionalArg<PyObjectRef>,
vm: &VirtualMachine,
) -> PyObjectRef {
match self.elem.get_attribute(attr.as_str()) {
Some(s) => vm.ctx.new_str(s).into(),
None => default.unwrap_or_none(vm),
}
}
#[pymethod]
fn set_attr(&self, attr: PyStrRef, value: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
self.elem
.set_attribute(attr.as_str(), value.as_str())
.map_err(|err| convert::js_py_typeerror(vm, err))
}
}
#[pyfunction]
fn load_module(module: PyStrRef, path: PyStrRef, vm: &VirtualMachine) -> PyResult {
let weak_vm = weak_vm(vm);
let opts = web_sys::RequestInit::new();
opts.set_method("GET");
let request = web_sys::Request::new_with_str_and_init(path.as_str(), &opts)
.map_err(|err| convert::js_py_typeerror(vm, err))?;
let window = window();
let request_prom = window.fetch_with_request(&request);
let future = async move {
let val = JsFuture::from(request_prom).await?;
let response = val
.dyn_into::<web_sys::Response>()
.expect("val to be of type Response");
let text = JsFuture::from(response.text()?).await?;
let stored_vm = &weak_vm
.upgrade()
.expect("that the vm is valid when the promise resolves");
stored_vm.interp.enter(move |vm| {
let resp_text = text.as_string().unwrap();
let res = import_source(vm, module.as_str(), &resp_text);
match res {
Ok(_) => Ok(JsValue::null()),
Err(err) => Err(convert::py_err_to_js_err(vm, &err)),
}
})
};
Ok(PyPromise::from_future(future).into_pyobject(vm))
}
}
pub fn setup_browser_module(vm: &mut VirtualMachine) {
vm.add_native_module("_browser".to_owned(), Box::new(make_module));
vm.add_frozen(py_freeze!(dir = "Lib"));
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/wasm/src/lib.rs | crates/wasm/src/lib.rs | extern crate alloc;
pub mod browser_module;
pub mod convert;
pub mod js_module;
pub mod vm_class;
pub mod wasm_builtins;
#[macro_use]
extern crate rustpython_vm;
use js_sys::{Reflect, WebAssembly::RuntimeError};
use std::panic;
pub use vm_class::add_init_func;
pub(crate) use vm_class::weak_vm;
use wasm_bindgen::prelude::*;
/// Sets error info on the window object, and prints the backtrace to console
pub fn panic_hook(info: &panic::PanicHookInfo<'_>) {
// If something errors, just ignore it; we don't want to panic in the panic hook
let try_set_info = || {
let msg = &info.to_string();
let window = match web_sys::window() {
Some(win) => win,
None => return,
};
let _ = Reflect::set(&window, &"__RUSTPYTHON_ERROR_MSG".into(), &msg.into());
let error = RuntimeError::new(msg);
let _ = Reflect::set(&window, &"__RUSTPYTHON_ERROR".into(), &error);
let stack = match Reflect::get(&error, &"stack".into()) {
Ok(stack) => stack,
Err(_) => return,
};
let _ = Reflect::set(&window, &"__RUSTPYTHON_ERROR_STACK".into(), &stack);
};
try_set_info();
console_error_panic_hook::hook(info);
}
#[doc(hidden)]
#[cfg(not(feature = "no-start-func"))]
#[wasm_bindgen(start)]
pub fn _setup_console_error() {
std::panic::set_hook(Box::new(panic_hook));
}
pub mod eval {
use crate::vm_class::VMStore;
use js_sys::{Object, Reflect, TypeError};
use rustpython_vm::compiler::Mode;
use wasm_bindgen::prelude::*;
const PY_EVAL_VM_ID: &str = "__py_eval_vm";
fn run_py(source: &str, options: Option<Object>, mode: Mode) -> Result<JsValue, JsValue> {
let vm = VMStore::init(PY_EVAL_VM_ID.into(), Some(true));
let options = options.unwrap_or_default();
let js_vars = {
let prop = Reflect::get(&options, &"vars".into())?;
if prop.is_undefined() {
None
} else if prop.is_object() {
Some(Object::from(prop))
} else {
return Err(TypeError::new("vars must be an object").into());
}
};
vm.set_stdout(Reflect::get(&options, &"stdout".into())?)?;
if let Some(js_vars) = js_vars {
vm.add_to_scope("js_vars".into(), js_vars.into())?;
}
vm.run(source, mode, None)
}
/// Evaluate Python code
///
/// ```js
/// var result = pyEval(code, options?);
/// ```
///
/// `code`: `string`: The Python code to run in eval mode
///
/// `options`:
///
/// - `vars?`: `{ [key: string]: any }`: Variables passed to the VM that can be
/// accessed in Python with the variable `js_vars`. Functions do work, and
/// receive the Python kwargs as the `this` argument.
/// - `stdout?`: `"console" | ((out: string) => void) | null`: A function to replace the
/// native print native print function, and it will be `console.log` when giving
/// `undefined` or "console", and it will be a dumb function when giving null.
#[wasm_bindgen(js_name = pyEval)]
pub fn eval_py(source: &str, options: Option<Object>) -> Result<JsValue, JsValue> {
run_py(source, options, Mode::Eval)
}
/// Evaluate Python code
///
/// ```js
/// pyExec(code, options?);
/// ```
///
/// `code`: `string`: The Python code to run in exec mode
///
/// `options`: The options are the same as eval mode
#[wasm_bindgen(js_name = pyExec)]
pub fn exec_py(source: &str, options: Option<Object>) -> Result<(), JsValue> {
run_py(source, options, Mode::Exec).map(drop)
}
/// Evaluate Python code
///
/// ```js
/// var result = pyExecSingle(code, options?);
/// ```
///
/// `code`: `string`: The Python code to run in exec single mode
///
/// `options`: The options are the same as eval mode
#[wasm_bindgen(js_name = pyExecSingle)]
pub fn exec_single_py(source: &str, options: Option<Object>) -> Result<JsValue, JsValue> {
run_py(source, options, Mode::Single)
}
}
/// A module containing all the wasm-bindgen exports that rustpython_wasm has
/// Re-export as `pub use rustpython_wasm::exports::*;` in the root of your crate if you want your
/// wasm module to mimic rustpython_wasm's API
pub mod exports {
pub use crate::convert::PyError;
pub use crate::eval::{eval_py, exec_py, exec_single_py};
pub use crate::vm_class::{VMStore, WASMVirtualMachine};
}
#[doc(hidden)]
pub use exports::*;
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/wasm/src/convert.rs | crates/wasm/src/convert.rs | #![allow(clippy::empty_docs)] // TODO: remove it later. false positive by wasm-bindgen generated code
use crate::js_module;
use crate::vm_class::{WASMVirtualMachine, stored_vm_from_wasm};
use js_sys::{Array, ArrayBuffer, Object, Promise, Reflect, SyntaxError, Uint8Array};
use rustpython_vm::{
AsObject, Py, PyObjectRef, PyPayload, PyResult, TryFromBorrowedObject, VirtualMachine,
builtins::{PyBaseException, PyBaseExceptionRef},
compiler::{CompileError, ParseError, parser::LexicalErrorType, parser::ParseErrorType},
exceptions,
function::{ArgBytesLike, FuncArgs},
py_serde,
};
use wasm_bindgen::{JsCast, closure::Closure, prelude::*};
#[wasm_bindgen(inline_js = r"
export class PyError extends Error {
constructor(info) {
const msg = info.args[0];
if (typeof msg === 'string') super(msg);
else super();
this.info = info;
}
get name() { return this.info.exc_type; }
get traceback() { return this.info.traceback; }
toString() { return this.info.rendered; }
}
")]
extern "C" {
pub type PyError;
#[wasm_bindgen(constructor)]
fn new(info: JsValue) -> PyError;
}
pub fn py_err_to_js_err(vm: &VirtualMachine, py_err: &Py<PyBaseException>) -> JsValue {
let js_err = vm.try_class("_js", "JSError").ok();
let js_arg = if js_err.is_some_and(|js_err| py_err.fast_isinstance(&js_err)) {
py_err.get_arg(0)
} else {
None
};
let js_arg = js_arg
.as_ref()
.and_then(|x| x.downcast_ref::<js_module::PyJsValue>());
match js_arg {
Some(val) => val.value.clone(),
None => {
let res =
serde_wasm_bindgen::to_value(&exceptions::SerializeException::new(vm, py_err));
match res {
Ok(err_info) => PyError::new(err_info).into(),
Err(e) => e.into(),
}
}
}
}
pub fn js_py_typeerror(vm: &VirtualMachine, js_err: JsValue) -> PyBaseExceptionRef {
let msg = js_err.unchecked_into::<js_sys::Error>().to_string();
vm.new_type_error(msg)
}
pub fn js_err_to_py_err(vm: &VirtualMachine, js_err: &JsValue) -> PyBaseExceptionRef {
match js_err.dyn_ref::<js_sys::Error>() {
Some(err) => {
let exc_type = match String::from(err.name()).as_str() {
"TypeError" => vm.ctx.exceptions.type_error,
"ReferenceError" => vm.ctx.exceptions.name_error,
"SyntaxError" => vm.ctx.exceptions.syntax_error,
_ => vm.ctx.exceptions.exception_type,
}
.to_owned();
vm.new_exception_msg(exc_type, err.message().into())
}
None => vm.new_exception_msg(
vm.ctx.exceptions.exception_type.to_owned(),
format!("{js_err:?}"),
),
}
}
pub fn py_to_js(vm: &VirtualMachine, py_obj: PyObjectRef) -> JsValue {
if let Some(ref wasm_id) = vm.wasm_id
&& py_obj.fast_isinstance(vm.ctx.types.function_type)
{
let wasm_vm = WASMVirtualMachine {
id: wasm_id.clone(),
};
let weak_py_obj = wasm_vm.push_held_rc(py_obj).unwrap().unwrap();
let closure = move |args: Option<Box<[JsValue]>>,
kwargs: Option<Object>|
-> Result<JsValue, JsValue> {
let py_obj = match wasm_vm.assert_valid() {
Ok(_) => weak_py_obj
.upgrade()
.expect("weak_py_obj to be valid if VM is valid"),
Err(err) => {
return Err(err);
}
};
stored_vm_from_wasm(&wasm_vm).interp.enter(move |vm| {
let args = match args {
Some(args) => Vec::from(args)
.into_iter()
.map(|arg| js_to_py(vm, arg))
.collect::<Vec<_>>(),
None => Vec::new(),
};
let mut py_func_args = FuncArgs::from(args);
if let Some(ref kwargs) = kwargs {
for pair in object_entries(kwargs) {
let (key, val) = pair?;
py_func_args
.kwargs
.insert(js_sys::JsString::from(key).into(), js_to_py(vm, val));
}
}
let result = py_obj.call(py_func_args, vm);
pyresult_to_js_result(vm, result)
})
};
let closure = Closure::wrap(Box::new(closure)
as Box<
dyn FnMut(Option<Box<[JsValue]>>, Option<Object>) -> Result<JsValue, JsValue>,
>);
let func = closure.as_ref().clone();
// stores pretty much nothing, it's fine to leak this because if it gets dropped
// the error message is worse
closure.forget();
return func;
}
// the browser module might not be injected
if vm.try_class("_js", "Promise").is_ok()
&& let Some(py_prom) = py_obj.downcast_ref::<js_module::PyPromise>()
{
return py_prom.as_js(vm).into();
}
if let Ok(bytes) = ArgBytesLike::try_from_borrowed_object(vm, &py_obj) {
bytes.with_ref(|bytes| unsafe {
// `Uint8Array::view` is an `unsafe fn` because it provides
// a direct view into the WASM linear memory; if you were to allocate
// something with Rust that view would probably become invalid. It's safe
// because we then copy the array using `Uint8Array::slice`.
let view = Uint8Array::view(bytes);
view.slice(0, bytes.len() as u32).into()
})
} else {
py_serde::serialize(vm, &py_obj, &serde_wasm_bindgen::Serializer::new())
.unwrap_or(JsValue::UNDEFINED)
}
}
pub fn object_entries(obj: &Object) -> impl Iterator<Item = Result<(JsValue, JsValue), JsValue>> {
Object::entries(obj).values().into_iter().map(|pair| {
pair.map(|pair| {
let key = Reflect::get(&pair, &"0".into()).unwrap();
let val = Reflect::get(&pair, &"1".into()).unwrap();
(key, val)
})
})
}
pub fn pyresult_to_js_result(vm: &VirtualMachine, result: PyResult) -> Result<JsValue, JsValue> {
result
.map(|value| py_to_js(vm, value))
.map_err(|err| py_err_to_js_err(vm, &err))
}
pub fn js_to_py(vm: &VirtualMachine, js_val: JsValue) -> PyObjectRef {
if js_val.is_object() {
if let Some(promise) = js_val.dyn_ref::<Promise>() {
// the browser module might not be injected
if vm.try_class("browser", "Promise").is_ok() {
return js_module::PyPromise::new(promise.clone())
.into_ref(&vm.ctx)
.into();
}
}
if Array::is_array(&js_val) {
let js_arr: Array = js_val.into();
let elems = js_arr
.values()
.into_iter()
.map(|val| js_to_py(vm, val.expect("Iteration over array failed")))
.collect();
vm.ctx.new_list(elems).into()
} else if ArrayBuffer::is_view(&js_val) || js_val.is_instance_of::<ArrayBuffer>() {
// unchecked_ref because if it's not an ArrayBuffer it could either be a TypedArray
// or a DataView, but they all have a `buffer` property
let u8_array = js_sys::Uint8Array::new(
&js_val
.dyn_ref::<ArrayBuffer>()
.cloned()
.unwrap_or_else(|| js_val.unchecked_ref::<Uint8Array>().buffer()),
);
let mut vec = vec![0; u8_array.length() as usize];
u8_array.copy_to(&mut vec);
vm.ctx.new_bytes(vec).into()
} else {
let dict = vm.ctx.new_dict();
for pair in object_entries(&Object::from(js_val)) {
let (key, val) = pair.expect("iteration over object to not fail");
let py_val = js_to_py(vm, val);
dict.set_item(
String::from(js_sys::JsString::from(key)).as_str(),
py_val,
vm,
)
.unwrap();
}
dict.into()
}
} else if js_val.is_function() {
let func = js_sys::Function::from(js_val);
vm.new_function(
vm.ctx.intern_str(String::from(func.name())).as_str(),
move |args: FuncArgs, vm: &VirtualMachine| -> PyResult {
let this = Object::new();
for (k, v) in args.kwargs {
Reflect::set(&this, &k.into(), &py_to_js(vm, v))
.expect("property to be settable");
}
let js_args = args
.args
.into_iter()
.map(|v| py_to_js(vm, v))
.collect::<Array>();
func.apply(&this, &js_args)
.map(|val| js_to_py(vm, val))
.map_err(|err| js_err_to_py_err(vm, &err))
},
)
.into()
} else if let Some(err) = js_val.dyn_ref::<js_sys::Error>() {
js_err_to_py_err(vm, err).into()
} else if js_val.is_undefined() {
// Because `JSON.stringify(undefined)` returns undefined
vm.ctx.none()
} else {
py_serde::deserialize(vm, serde_wasm_bindgen::Deserializer::from(js_val))
.unwrap_or_else(|_| vm.ctx.none())
}
}
pub fn syntax_err(err: CompileError) -> SyntaxError {
let js_err = SyntaxError::new(&format!("Error parsing Python code: {err}"));
let _ = Reflect::set(
&js_err,
&"row".into(),
&(err.location().unwrap().line.get()).into(),
);
let _ = Reflect::set(
&js_err,
&"col".into(),
&(err.location().unwrap().character_offset.get()).into(),
);
// | ParseErrorType::UnrecognizedToken(Token::Dedent, _)
let can_continue = matches!(
&err,
CompileError::Parse(ParseError {
error: ParseErrorType::Lexical(LexicalErrorType::Eof)
| ParseErrorType::Lexical(LexicalErrorType::IndentationError),
..
})
);
let _ = Reflect::set(&js_err, &"canContinue".into(), &can_continue.into());
js_err
}
pub trait PyResultExt<T> {
fn into_js(self, vm: &VirtualMachine) -> Result<T, JsValue>;
}
impl<T> PyResultExt<T> for PyResult<T> {
fn into_js(self, vm: &VirtualMachine) -> Result<T, JsValue> {
self.map_err(|err| py_err_to_js_err(vm, &err))
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/wasm/src/wasm_builtins.rs | crates/wasm/src/wasm_builtins.rs | //! Builtin function specific to WASM build.
//!
//! This is required because some feature like I/O works differently in the browser comparing to
//! desktop.
//! Implements functions listed here: https://docs.python.org/3/library/builtins.html.
use rustpython_vm::{PyObjectRef, PyRef, PyResult, VirtualMachine, builtins::PyStrRef};
use web_sys::{self, console};
pub(crate) fn window() -> web_sys::Window {
web_sys::window().expect("Window to be available")
}
pub fn sys_stdout_write_console(data: &str, _vm: &VirtualMachine) -> PyResult<()> {
console::log_1(&data.into());
Ok(())
}
pub fn make_stdout_object(
vm: &VirtualMachine,
write_f: impl Fn(&str, &VirtualMachine) -> PyResult<()> + 'static,
) -> PyObjectRef {
let ctx = &vm.ctx;
// there's not really any point to storing this class so that there's a consistent type object,
// we just want a half-decent repr() output
let cls = PyRef::leak(py_class!(
ctx,
"JSStdout",
vm.ctx.types.object_type.to_owned(),
{}
));
let write_method = vm.new_method(
"write",
cls,
move |_self: PyObjectRef, data: PyStrRef, vm: &VirtualMachine| -> PyResult<()> {
write_f(data.as_str(), vm)
},
);
let flush_method = vm.new_method("flush", cls, |_self: PyObjectRef| {});
extend_class!(ctx, cls, {
"write" => write_method,
"flush" => flush_method,
});
ctx.new_base_object(cls.to_owned(), None)
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/wasm/src/js_module.rs | crates/wasm/src/js_module.rs | pub(crate) use _js::{PyJsValue, PyPromise};
use rustpython_vm::VirtualMachine;
#[pymodule]
mod _js {
use crate::{
convert,
vm_class::{WASMVirtualMachine, stored_vm_from_wasm},
weak_vm,
};
use core::{cell, fmt, future};
use js_sys::{Array, Object, Promise, Reflect};
use rustpython_vm::{
Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
builtins::{PyBaseExceptionRef, PyFloat, PyStrRef, PyType, PyTypeRef},
convert::{IntoObject, ToPyObject},
function::{ArgCallable, OptionalArg, OptionalOption, PosArgs},
protocol::PyIterReturn,
types::{IterNext, Representable, SelfIter},
};
use wasm_bindgen::{JsCast, closure::Closure, prelude::*};
use wasm_bindgen_futures::{JsFuture, future_to_promise};
#[wasm_bindgen(inline_js = "
export function has_prop(target, prop) { return prop in Object(target); }
export function get_prop(target, prop) { return target[prop]; }
export function set_prop(target, prop, value) { target[prop] = value; }
export function type_of(a) { return typeof a; }
export function instance_of(lhs, rhs) { return lhs instanceof rhs; }
export function call_func(func, args) { return func(...args); }
export function call_method(obj, method, args) { return obj[method](...args) }
export function wrap_closure(closure) {
return function pyfunction(...args) {
closure(this, args)
}
}
")]
extern "C" {
#[wasm_bindgen(catch)]
fn has_prop(target: &JsValue, prop: &JsValue) -> Result<bool, JsValue>;
#[wasm_bindgen(catch)]
fn get_prop(target: &JsValue, prop: &JsValue) -> Result<JsValue, JsValue>;
#[wasm_bindgen(catch)]
fn set_prop(target: &JsValue, prop: &JsValue, value: &JsValue) -> Result<(), JsValue>;
#[wasm_bindgen]
fn type_of(a: &JsValue) -> String;
#[wasm_bindgen(catch)]
fn instance_of(lhs: &JsValue, rhs: &JsValue) -> Result<bool, JsValue>;
#[wasm_bindgen(catch)]
fn call_func(func: &JsValue, args: &Array) -> Result<JsValue, JsValue>;
#[wasm_bindgen(catch)]
fn call_method(obj: &JsValue, method: &JsValue, args: &Array) -> Result<JsValue, JsValue>;
#[wasm_bindgen]
fn wrap_closure(closure: &JsValue) -> JsValue;
}
#[pyattr]
#[pyclass(module = "_js", name = "JSValue")]
#[derive(Debug, PyPayload)]
pub struct PyJsValue {
pub(crate) value: JsValue,
}
type PyJsValueRef = PyRef<PyJsValue>;
impl AsRef<JsValue> for PyJsValue {
fn as_ref(&self) -> &JsValue {
&self.value
}
}
enum JsProperty {
Str(PyStrRef),
Js(PyJsValueRef),
}
impl TryFromObject for JsProperty {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
PyStrRef::try_from_object(vm, obj.clone())
.map(JsProperty::Str)
.or_else(|_| PyJsValueRef::try_from_object(vm, obj).map(JsProperty::Js))
}
}
impl JsProperty {
fn into_js_value(self) -> JsValue {
match self {
JsProperty::Str(s) => s.as_str().into(),
JsProperty::Js(value) => value.value.clone(),
}
}
}
#[pyclass(with(Representable))]
impl PyJsValue {
#[inline]
pub fn new(value: impl Into<JsValue>) -> PyJsValue {
let value = value.into();
PyJsValue { value }
}
#[pymethod]
fn null(&self) -> PyJsValue {
PyJsValue::new(JsValue::NULL)
}
#[pymethod]
fn undefined(&self) -> PyJsValue {
PyJsValue::new(JsValue::UNDEFINED)
}
#[pymethod]
fn new_from_str(&self, s: PyStrRef) -> PyJsValue {
PyJsValue::new(s.as_str())
}
#[pymethod]
fn new_from_float(&self, n: PyRef<PyFloat>) -> PyJsValue {
PyJsValue::new(n.to_f64())
}
#[pymethod]
fn new_closure(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<JsClosure> {
JsClosure::new(obj, false, vm)
}
#[pymethod]
fn new_closure_once(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<JsClosure> {
JsClosure::new(obj, true, vm)
}
#[pymethod]
fn new_object(&self, opts: NewObjectOptions, vm: &VirtualMachine) -> PyResult<PyJsValue> {
let value = if let Some(proto) = opts.prototype {
if let Some(proto) = proto.value.dyn_ref::<Object>() {
Object::create(proto)
} else if proto.value.is_null() {
Object::create(proto.value.unchecked_ref())
} else {
return Err(vm.new_value_error("prototype must be an Object or null"));
}
} else {
Object::new()
};
Ok(PyJsValue::new(value))
}
#[pymethod]
fn has_prop(&self, name: JsProperty, vm: &VirtualMachine) -> PyResult<bool> {
has_prop(&self.value, &name.into_js_value()).map_err(|err| new_js_error(vm, err))
}
#[pymethod]
fn get_prop(&self, name: JsProperty, vm: &VirtualMachine) -> PyResult<PyJsValue> {
let name = &name.into_js_value();
if has_prop(&self.value, name).map_err(|err| new_js_error(vm, err))? {
get_prop(&self.value, name)
.map(PyJsValue::new)
.map_err(|err| new_js_error(vm, err))
} else {
Err(vm.new_attribute_error(format!("No attribute {name:?} on JS value")))
}
}
#[pymethod]
fn set_prop(
&self,
name: JsProperty,
value: PyJsValueRef,
vm: &VirtualMachine,
) -> PyResult<()> {
set_prop(&self.value, &name.into_js_value(), &value.value)
.map_err(|err| new_js_error(vm, err))
}
#[pymethod]
fn call(
&self,
args: PosArgs<PyJsValueRef>,
opts: CallOptions,
vm: &VirtualMachine,
) -> PyResult<PyJsValue> {
let func = self
.value
.dyn_ref::<js_sys::Function>()
.ok_or_else(|| vm.new_type_error("JS value is not callable"))?;
let js_args = args.iter().map(|x| -> &PyJsValue { x }).collect::<Array>();
let res = match opts.this {
Some(this) => Reflect::apply(func, &this.value, &js_args),
None => call_func(func, &js_args),
};
res.map(PyJsValue::new).map_err(|err| new_js_error(vm, err))
}
#[pymethod]
fn call_method(
&self,
name: JsProperty,
args: PosArgs<PyJsValueRef>,
vm: &VirtualMachine,
) -> PyResult<PyJsValue> {
let js_args = args.iter().map(|x| -> &PyJsValue { x }).collect::<Array>();
call_method(&self.value, &name.into_js_value(), &js_args)
.map(PyJsValue::new)
.map_err(|err| new_js_error(vm, err))
}
#[pymethod]
fn construct(
&self,
args: PosArgs<PyJsValueRef>,
opts: NewObjectOptions,
vm: &VirtualMachine,
) -> PyResult<PyJsValue> {
let ctor = self
.value
.dyn_ref::<js_sys::Function>()
.ok_or_else(|| vm.new_type_error("JS value is not callable"))?;
let proto = opts
.prototype
.as_ref()
.and_then(|proto| proto.value.dyn_ref::<js_sys::Function>());
let js_args = args.iter().map(|x| -> &PyJsValue { x }).collect::<Array>();
let constructed_result = if let Some(proto) = proto {
Reflect::construct_with_new_target(ctor, &js_args, proto)
} else {
Reflect::construct(ctor, &js_args)
};
constructed_result
.map(PyJsValue::new)
.map_err(|err| new_js_error(vm, err))
}
#[pymethod]
fn as_str(&self) -> Option<String> {
self.value.as_string()
}
#[pymethod]
fn as_float(&self) -> Option<f64> {
self.value.as_f64()
}
#[pymethod]
fn as_bool(&self) -> Option<bool> {
self.value.as_bool()
}
#[pymethod(name = "typeof")]
fn type_of(&self) -> String {
type_of(&self.value)
}
/// Checks that `typeof self == "object" && self !== null`. Use instead
/// of `value.typeof() == "object"`
#[pymethod]
fn is_object(&self) -> bool {
self.value.is_object()
}
#[pymethod]
fn instanceof(&self, rhs: PyJsValueRef, vm: &VirtualMachine) -> PyResult<bool> {
instance_of(&self.value, &rhs.value).map_err(|err| new_js_error(vm, err))
}
}
impl Representable for PyJsValue {
#[inline]
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
Ok(format!("{:?}", zelf.value))
}
}
#[derive(FromArgs)]
struct CallOptions {
#[pyarg(named, default)]
this: Option<PyJsValueRef>,
}
#[derive(FromArgs)]
struct NewObjectOptions {
#[pyarg(named, default)]
prototype: Option<PyJsValueRef>,
}
type ClosureType = Closure<dyn FnMut(JsValue, Box<[JsValue]>) -> Result<JsValue, JsValue>>;
#[pyattr]
#[pyclass(module = "_js", name = "JSClosure")]
#[derive(PyPayload)]
struct JsClosure {
closure: cell::RefCell<Option<(ClosureType, PyJsValueRef)>>,
destroyed: cell::Cell<bool>,
detached: cell::Cell<bool>,
}
impl fmt::Debug for JsClosure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("JsClosure")
}
}
#[pyclass]
impl JsClosure {
fn new(obj: PyObjectRef, once: bool, vm: &VirtualMachine) -> PyResult<Self> {
let wasm_vm = WASMVirtualMachine {
id: vm.wasm_id.clone().unwrap(),
};
let weak_py_obj = wasm_vm.push_held_rc(obj).unwrap()?;
let f = move |this: JsValue, args: Box<[JsValue]>| {
let py_obj = match wasm_vm.assert_valid() {
Ok(_) => weak_py_obj
.upgrade()
.expect("weak_py_obj to be valid if VM is valid"),
Err(err) => {
return Err(err);
}
};
stored_vm_from_wasm(&wasm_vm).interp.enter(move |vm| {
let mut pyargs = vec![PyJsValue::new(this).into_pyobject(vm)];
pyargs.extend(
Vec::from(args)
.into_iter()
.map(|arg| PyJsValue::new(arg).into_pyobject(vm)),
);
let res = py_obj.call(pyargs, vm);
convert::pyresult_to_js_result(vm, res)
})
};
let closure: ClosureType = if once {
Closure::wrap(Box::new(f))
} else {
Closure::once(Box::new(f))
};
let wrapped = PyJsValue::new(wrap_closure(closure.as_ref())).into_ref(&vm.ctx);
Ok(JsClosure {
closure: Some((closure, wrapped)).into(),
destroyed: false.into(),
detached: false.into(),
})
}
#[pygetset]
fn value(&self) -> Option<PyJsValueRef> {
self.closure
.borrow()
.as_ref()
.map(|(_, js_val)| js_val.clone())
}
#[pygetset]
fn destroyed(&self) -> bool {
self.destroyed.get()
}
#[pygetset]
fn detached(&self) -> bool {
self.detached.get()
}
#[pymethod]
fn destroy(&self, vm: &VirtualMachine) -> PyResult<()> {
let (closure, _) = self.closure.replace(None).ok_or_else(|| {
vm.new_value_error("can't destroy closure has already been destroyed or detached")
})?;
drop(closure);
self.destroyed.set(true);
Ok(())
}
#[pymethod]
fn detach(&self, vm: &VirtualMachine) -> PyResult<PyJsValueRef> {
let (closure, js_val) = self.closure.replace(None).ok_or_else(|| {
vm.new_value_error("can't detach closure has already been detached or destroyed")
})?;
closure.forget();
self.detached.set(true);
Ok(js_val)
}
}
#[pyattr]
#[pyclass(module = "_js", name = "Promise")]
#[derive(Debug, Clone, PyPayload)]
pub struct PyPromise {
value: PromiseKind,
}
#[derive(Debug, Clone)]
enum PromiseKind {
Js(Promise),
PyProm { then: PyObjectRef },
PyResolved(PyObjectRef),
PyRejected(PyBaseExceptionRef),
}
#[pyclass]
impl PyPromise {
pub fn new(value: Promise) -> PyPromise {
PyPromise {
value: PromiseKind::Js(value),
}
}
pub fn from_future<F>(future: F) -> PyPromise
where
F: future::Future<Output = Result<JsValue, JsValue>> + 'static,
{
PyPromise::new(future_to_promise(future))
}
pub fn as_js(&self, vm: &VirtualMachine) -> Promise {
match &self.value {
PromiseKind::Js(prom) => prom.clone(),
PromiseKind::PyProm { then } => Promise::new(&mut |js_resolve, js_reject| {
let resolve = move |res: PyObjectRef, vm: &VirtualMachine| {
let _ = js_resolve.call1(&JsValue::UNDEFINED, &convert::py_to_js(vm, res));
};
let reject = move |err: PyBaseExceptionRef, vm: &VirtualMachine| {
let _ = js_reject
.call1(&JsValue::UNDEFINED, &convert::py_err_to_js_err(vm, &err));
};
let _ = then.call(
(
vm.new_function("resolve", resolve),
vm.new_function("reject", reject),
),
vm,
);
}),
PromiseKind::PyResolved(obj) => {
Promise::resolve(&convert::py_to_js(vm, obj.clone()))
}
PromiseKind::PyRejected(err) => {
Promise::reject(&convert::py_err_to_js_err(vm, err))
}
}
}
fn cast(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {
let then = vm.get_attribute_opt(obj.clone(), "then")?;
let value = if let Some(then) = then.filter(|obj| obj.is_callable()) {
PromiseKind::PyProm { then }
} else {
PromiseKind::PyResolved(obj)
};
Ok(Self { value })
}
fn cast_result(res: PyResult, vm: &VirtualMachine) -> PyResult<Self> {
match res {
Ok(res) => Self::cast(res, vm),
Err(e) => Ok(Self {
value: PromiseKind::PyRejected(e),
}),
}
}
#[pyclassmethod]
fn resolve(cls: PyTypeRef, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
Self::cast(obj, vm)?.into_ref_with_type(vm, cls)
}
#[pyclassmethod]
fn reject(
cls: PyTypeRef,
err: PyBaseExceptionRef,
vm: &VirtualMachine,
) -> PyResult<PyRef<Self>> {
Self {
value: PromiseKind::PyRejected(err),
}
.into_ref_with_type(vm, cls)
}
#[pymethod]
fn then(
&self,
on_fulfill: OptionalOption<ArgCallable>,
on_reject: OptionalOption<ArgCallable>,
vm: &VirtualMachine,
) -> PyResult<PyPromise> {
let (on_fulfill, on_reject) = (on_fulfill.flatten(), on_reject.flatten());
if on_fulfill.is_none() && on_reject.is_none() {
return Ok(self.clone());
}
match &self.value {
PromiseKind::Js(prom) => {
let weak_vm = weak_vm(vm);
let prom = JsFuture::from(prom.clone());
let ret_future = async move {
let stored_vm = &weak_vm
.upgrade()
.expect("that the vm is valid when the promise resolves");
let res = prom.await;
match res {
Ok(val) => match on_fulfill {
Some(on_fulfill) => stored_vm.interp.enter(move |vm| {
let val = convert::js_to_py(vm, val);
let res = on_fulfill.invoke((val,), vm);
convert::pyresult_to_js_result(vm, res)
}),
None => Ok(val),
},
Err(err) => match on_reject {
Some(on_reject) => stored_vm.interp.enter(move |vm| {
let err = new_js_error(vm, err);
let res = on_reject.invoke((err,), vm);
convert::pyresult_to_js_result(vm, res)
}),
None => Err(err),
},
}
};
Ok(PyPromise::from_future(ret_future))
}
PromiseKind::PyProm { then } => Self::cast_result(
then.call(
(
on_fulfill.map(IntoObject::into_object),
on_reject.map(IntoObject::into_object),
),
vm,
),
vm,
),
PromiseKind::PyResolved(res) => match on_fulfill {
Some(resolve) => Self::cast_result(resolve.invoke((res.clone(),), vm), vm),
None => Ok(self.clone()),
},
PromiseKind::PyRejected(err) => match on_reject {
Some(reject) => Self::cast_result(reject.invoke((err.clone(),), vm), vm),
None => Ok(self.clone()),
},
}
}
#[pymethod]
fn catch(
&self,
on_reject: OptionalOption<ArgCallable>,
vm: &VirtualMachine,
) -> PyResult<PyPromise> {
self.then(OptionalArg::Present(None), on_reject, vm)
}
#[pymethod(name = "__await__")]
fn r#await(zelf: PyRef<Self>) -> AwaitPromise {
AwaitPromise {
obj: Some(zelf.into()).into(),
}
}
}
#[pyclass(no_attr, module = "_js", name = "AwaitPromise")]
#[derive(PyPayload)]
struct AwaitPromise {
obj: cell::Cell<Option<PyObjectRef>>,
}
impl fmt::Debug for AwaitPromise {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AwaitPromise").finish()
}
}
#[pyclass(with(IterNext))]
impl AwaitPromise {
#[pymethod]
fn send(&self, val: Option<PyObjectRef>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
match self.obj.take() {
Some(prom) => {
if val.is_some() {
Err(vm.new_type_error("can't send non-None value to an AwaitPromise"))
} else {
Ok(PyIterReturn::Return(prom))
}
}
None => Ok(PyIterReturn::StopIteration(val)),
}
}
#[pymethod]
fn throw(
&self,
exc_type: PyObjectRef,
exc_val: OptionalArg,
exc_tb: OptionalArg,
vm: &VirtualMachine,
) -> PyResult {
let err = vm.normalize_exception(
exc_type,
exc_val.unwrap_or_none(vm),
exc_tb.unwrap_or_none(vm),
)?;
Err(err)
}
}
impl SelfIter for AwaitPromise {}
impl IterNext for AwaitPromise {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
zelf.send(None, vm)
}
}
fn new_js_error(vm: &VirtualMachine, err: JsValue) -> PyBaseExceptionRef {
vm.new_exception(
vm.class("_js", "JSError"),
vec![PyJsValue::new(err).to_pyobject(vm)],
)
}
#[pyattr(name = "JSError", once)]
fn js_error(vm: &VirtualMachine) -> PyTypeRef {
let ctx = &vm.ctx;
let js_error = PyRef::leak(
PyType::new_simple_heap("JSError", vm.ctx.exceptions.exception_type, ctx).unwrap(),
);
extend_class!(ctx, js_error, {
"value" => ctx.new_readonly_getset("value", js_error, |exc: PyBaseExceptionRef| exc.get_arg(0)),
});
js_error.to_owned()
}
}
pub(crate) use _js::make_module;
pub fn setup_js_module(vm: &mut VirtualMachine) {
vm.add_native_module("_js".to_owned(), Box::new(make_module));
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/wasm/src/vm_class.rs | crates/wasm/src/vm_class.rs | use crate::{
browser_module::setup_browser_module,
convert::{self, PyResultExt},
js_module, wasm_builtins,
};
use alloc::rc::{Rc, Weak};
use core::cell::RefCell;
use js_sys::{Object, TypeError};
use rustpython_vm::{
Interpreter, PyObjectRef, PyPayload, PyRef, PyResult, Settings, VirtualMachine,
builtins::{PyModule, PyWeak},
compiler::Mode,
scope::Scope,
};
use std::collections::HashMap;
use wasm_bindgen::prelude::*;
pub(crate) struct StoredVirtualMachine {
pub interp: Interpreter,
pub scope: Scope,
/// you can put a Rc in here, keep it as a Weak, and it'll be held only for
/// as long as the StoredVM is alive
held_objects: RefCell<Vec<PyObjectRef>>,
}
#[pymodule]
mod _window {}
fn init_window_module(vm: &VirtualMachine) -> PyRef<PyModule> {
let module = _window::make_module(vm);
extend_module!(vm, &module, {
"window" => js_module::PyJsValue::new(wasm_builtins::window()).into_ref(&vm.ctx),
});
module
}
impl StoredVirtualMachine {
fn new(id: String, inject_browser_module: bool) -> StoredVirtualMachine {
let mut scope = None;
let mut settings = Settings::default();
settings.allow_external_library = false;
let interp = Interpreter::with_init(settings, |vm| {
#[cfg(feature = "freeze-stdlib")]
vm.add_native_modules(rustpython_stdlib::get_module_inits());
#[cfg(feature = "freeze-stdlib")]
vm.add_frozen(rustpython_pylib::FROZEN_STDLIB);
vm.wasm_id = Some(id);
js_module::setup_js_module(vm);
if inject_browser_module {
vm.add_native_module("_window".to_owned(), Box::new(init_window_module));
setup_browser_module(vm);
}
VM_INIT_FUNCS.with_borrow(|funcs| {
for f in funcs {
f(vm)
}
});
scope = Some(vm.new_scope_with_builtins());
});
StoredVirtualMachine {
interp,
scope: scope.unwrap(),
held_objects: RefCell::new(Vec::new()),
}
}
}
/// Add a hook to add builtins or frozen modules to the RustPython VirtualMachine while it's
/// initializing.
pub fn add_init_func(f: fn(&mut VirtualMachine)) {
VM_INIT_FUNCS.with_borrow_mut(|funcs| funcs.push(f))
}
// It's fine that it's thread local, since WASM doesn't even have threads yet. thread_local!
// probably gets compiled down to a normal-ish static variable, like Atomic* types do:
// https://rustwasm.github.io/2018/10/24/multithreading-rust-and-wasm.html#atomic-instructions
thread_local! {
static STORED_VMS: RefCell<HashMap<String, Rc<StoredVirtualMachine>>> = RefCell::default();
static VM_INIT_FUNCS: RefCell<Vec<fn(&mut VirtualMachine)>> = const {
RefCell::new(Vec::new())
};
}
pub fn get_vm_id(vm: &VirtualMachine) -> &str {
vm.wasm_id
.as_ref()
.expect("VirtualMachine inside of WASM crate should have wasm_id set")
}
pub(crate) fn stored_vm_from_wasm(wasm_vm: &WASMVirtualMachine) -> Rc<StoredVirtualMachine> {
STORED_VMS.with_borrow(|vms| {
vms.get(&wasm_vm.id)
.expect("VirtualMachine is not valid")
.clone()
})
}
pub(crate) fn weak_vm(vm: &VirtualMachine) -> Weak<StoredVirtualMachine> {
let id = get_vm_id(vm);
STORED_VMS.with_borrow(|vms| Rc::downgrade(vms.get(id).expect("VirtualMachine is not valid")))
}
#[wasm_bindgen(js_name = vmStore)]
pub struct VMStore;
#[wasm_bindgen(js_class = vmStore)]
impl VMStore {
pub fn init(id: String, inject_browser_module: Option<bool>) -> WASMVirtualMachine {
STORED_VMS.with_borrow_mut(|vms| {
if !vms.contains_key(&id) {
let stored_vm =
StoredVirtualMachine::new(id.clone(), inject_browser_module.unwrap_or(true));
vms.insert(id.clone(), Rc::new(stored_vm));
}
});
WASMVirtualMachine { id }
}
pub(crate) fn _get(id: String) -> Option<WASMVirtualMachine> {
STORED_VMS.with_borrow(|vms| vms.contains_key(&id).then_some(WASMVirtualMachine { id }))
}
pub fn get(id: String) -> JsValue {
match Self::_get(id) {
Some(wasm_vm) => wasm_vm.into(),
None => JsValue::UNDEFINED,
}
}
pub fn destroy(id: String) {
STORED_VMS.with_borrow_mut(|vms| {
if let Some(stored_vm) = vms.remove(&id) {
// for f in stored_vm.drop_handlers.iter() {
// f();
// }
// deallocate the VM
drop(stored_vm);
}
});
}
pub fn ids() -> Vec<JsValue> {
STORED_VMS.with_borrow(|vms| vms.keys().map(|k| k.into()).collect())
}
}
#[wasm_bindgen(js_name = VirtualMachine)]
#[derive(Clone)]
pub struct WASMVirtualMachine {
pub(crate) id: String,
}
#[wasm_bindgen(js_class = VirtualMachine)]
impl WASMVirtualMachine {
pub(crate) fn with_unchecked<F, R>(&self, f: F) -> R
where
F: FnOnce(&StoredVirtualMachine) -> R,
{
let stored_vm = STORED_VMS.with_borrow_mut(|vms| vms.get_mut(&self.id).unwrap().clone());
f(&stored_vm)
}
pub(crate) fn with<F, R>(&self, f: F) -> Result<R, JsValue>
where
F: FnOnce(&StoredVirtualMachine) -> R,
{
self.assert_valid()?;
Ok(self.with_unchecked(f))
}
pub(crate) fn with_vm<F, R>(&self, f: F) -> Result<R, JsValue>
where
F: FnOnce(&VirtualMachine, &StoredVirtualMachine) -> R,
{
self.with(|stored| stored.interp.enter(|vm| f(vm, stored)))
}
pub fn valid(&self) -> bool {
STORED_VMS.with_borrow(|vms| vms.contains_key(&self.id))
}
pub(crate) fn push_held_rc(
&self,
obj: PyObjectRef,
) -> Result<PyResult<PyRef<PyWeak>>, JsValue> {
self.with_vm(|vm, stored_vm| {
let weak = obj.downgrade(None, vm)?;
stored_vm.held_objects.borrow_mut().push(obj);
Ok(weak)
})
}
pub fn assert_valid(&self) -> Result<(), JsValue> {
if self.valid() {
Ok(())
} else {
Err(TypeError::new(
"Invalid VirtualMachine, this VM was destroyed while this reference was still held",
)
.into())
}
}
pub fn destroy(&self) -> Result<(), JsValue> {
self.assert_valid()?;
VMStore::destroy(self.id.clone());
Ok(())
}
#[wasm_bindgen(js_name = addToScope)]
pub fn add_to_scope(&self, name: String, value: JsValue) -> Result<(), JsValue> {
self.with_vm(move |vm, StoredVirtualMachine { scope, .. }| {
let value = convert::js_to_py(vm, value);
scope.globals.set_item(&name, value, vm).into_js(vm)
})?
}
#[wasm_bindgen(js_name = setStdout)]
pub fn set_stdout(&self, stdout: JsValue) -> Result<(), JsValue> {
self.with_vm(|vm, _| {
fn error() -> JsValue {
TypeError::new("Unknown stdout option, please pass a function or 'console'").into()
}
use wasm_builtins::make_stdout_object;
let stdout: PyObjectRef = if let Some(s) = stdout.as_string() {
match s.as_str() {
"console" => make_stdout_object(vm, wasm_builtins::sys_stdout_write_console),
_ => return Err(error()),
}
} else if stdout.is_function() {
let func = js_sys::Function::from(stdout);
make_stdout_object(vm, move |data, vm| {
func.call1(&JsValue::UNDEFINED, &data.into())
.map_err(|err| convert::js_py_typeerror(vm, err))?;
Ok(())
})
} else if stdout.is_null() {
make_stdout_object(vm, |_, _| Ok(()))
} else if stdout.is_undefined() {
make_stdout_object(vm, wasm_builtins::sys_stdout_write_console)
} else {
return Err(error());
};
vm.sys_module.set_attr("stdout", stdout, vm).unwrap();
Ok(())
})?
}
#[wasm_bindgen(js_name = injectModule)]
pub fn inject_module(
&self,
name: String,
source: &str,
imports: Option<Object>,
) -> Result<(), JsValue> {
self.with_vm(|vm, _| {
let code = vm
.compile(source, Mode::Exec, name.clone())
.map_err(convert::syntax_err)?;
let attrs = vm.ctx.new_dict();
attrs
.set_item("__name__", vm.new_pyobj(name.as_str()), vm)
.into_js(vm)?;
if let Some(imports) = imports {
for entry in convert::object_entries(&imports) {
let (key, value) = entry?;
let key: String = Object::from(key).to_string().into();
attrs
.set_item(key.as_str(), convert::js_to_py(vm, value), vm)
.into_js(vm)?;
}
}
vm.run_code_obj(code, Scope::new(None, attrs.clone()))
.into_js(vm)?;
let module = vm.new_module(&name, attrs, None);
let sys_modules = vm.sys_module.get_attr("modules", vm).into_js(vm)?;
sys_modules.set_item(&name, module.into(), vm).into_js(vm)?;
Ok(())
})?
}
#[wasm_bindgen(js_name = injectJSModule)]
pub fn inject_js_module(&self, name: String, module: Object) -> Result<(), JsValue> {
self.with_vm(|vm, _| {
let py_module = vm.new_module(&name, vm.ctx.new_dict(), None);
for entry in convert::object_entries(&module) {
let (key, value) = entry?;
let key = Object::from(key).to_string();
extend_module!(vm, &py_module, {
String::from(key) => convert::js_to_py(vm, value),
});
}
let sys_modules = vm.sys_module.get_attr("modules", vm).into_js(vm)?;
sys_modules
.set_item(&name, py_module.into(), vm)
.into_js(vm)?;
Ok(())
})?
}
pub(crate) fn run(
&self,
source: &str,
mode: Mode,
source_path: Option<String>,
) -> Result<JsValue, JsValue> {
self.with_vm(|vm, StoredVirtualMachine { scope, .. }| {
let source_path = source_path.unwrap_or_else(|| "<wasm>".to_owned());
let code = vm.compile(source, mode, source_path);
let code = code.map_err(convert::syntax_err)?;
let result = vm.run_code_obj(code, scope.clone());
convert::pyresult_to_js_result(vm, result)
})?
}
pub fn exec(&self, source: &str, source_path: Option<String>) -> Result<JsValue, JsValue> {
self.run(source, Mode::Exec, source_path)
}
pub fn eval(&self, source: &str, source_path: Option<String>) -> Result<JsValue, JsValue> {
self.run(source, Mode::Eval, source_path)
}
#[wasm_bindgen(js_name = execSingle)]
pub fn exec_single(
&self,
source: &str,
source_path: Option<String>,
) -> Result<JsValue, JsValue> {
self.run(source, Mode::Single, source_path)
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/static_cell.rs | crates/common/src/static_cell.rs | #[cfg(not(feature = "threading"))]
mod non_threading {
use crate::lock::OnceCell;
use std::thread::LocalKey;
pub struct StaticCell<T: 'static> {
inner: &'static LocalKey<OnceCell<&'static T>>,
}
fn leak<T>(x: T) -> &'static T {
Box::leak(Box::new(x))
}
impl<T> StaticCell<T> {
#[doc(hidden)]
pub const fn _from_local_key(inner: &'static LocalKey<OnceCell<&'static T>>) -> Self {
Self { inner }
}
pub fn get(&'static self) -> Option<&'static T> {
self.inner.with(|x| x.get().copied())
}
pub fn set(&'static self, value: T) -> Result<(), T> {
// thread-safe because it's a unsync::OnceCell
self.inner.with(|x| {
if x.get().is_some() {
Err(value)
} else {
// will never fail
let _ = x.set(leak(value));
Ok(())
}
})
}
pub fn get_or_init<F>(&'static self, f: F) -> &'static T
where
F: FnOnce() -> T,
{
self.inner.with(|x| *x.get_or_init(|| leak(f())))
}
pub fn get_or_try_init<F, E>(&'static self, f: F) -> Result<&'static T, E>
where
F: FnOnce() -> Result<T, E>,
{
self.inner
.with(|x| x.get_or_try_init(|| f().map(leak)).copied())
}
}
#[macro_export]
macro_rules! static_cell {
($($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty;)+) => {
$($(#[$attr])*
$vis static $name: $crate::static_cell::StaticCell<$t> = {
::std::thread_local! {
$vis static $name: $crate::lock::OnceCell<&'static $t> = const {
$crate::lock::OnceCell::new()
};
}
$crate::static_cell::StaticCell::_from_local_key(&$name)
};)+
};
}
}
#[cfg(not(feature = "threading"))]
pub use non_threading::*;
#[cfg(feature = "threading")]
mod threading {
use crate::lock::OnceCell;
pub struct StaticCell<T: 'static> {
inner: OnceCell<T>,
}
impl<T> StaticCell<T> {
#[doc(hidden)]
pub const fn _from_once_cell(inner: OnceCell<T>) -> Self {
Self { inner }
}
pub fn get(&'static self) -> Option<&'static T> {
self.inner.get()
}
pub fn set(&'static self, value: T) -> Result<(), T> {
self.inner.set(value)
}
pub fn get_or_init<F>(&'static self, f: F) -> &'static T
where
F: FnOnce() -> T,
{
self.inner.get_or_init(f)
}
pub fn get_or_try_init<F, E>(&'static self, f: F) -> Result<&'static T, E>
where
F: FnOnce() -> Result<T, E>,
{
self.inner.get_or_try_init(f)
}
}
#[macro_export]
macro_rules! static_cell {
($($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty;)+) => {
$($(#[$attr])*
$vis static $name: $crate::static_cell::StaticCell<$t> =
$crate::static_cell::StaticCell::_from_once_cell($crate::lock::OnceCell::new());)+
};
}
}
#[cfg(feature = "threading")]
pub use threading::*;
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/cformat.rs | crates/common/src/cformat.rs | //! Implementation of Printf-Style string formatting
//! as per the [Python Docs](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting).
use alloc::fmt;
use bitflags::bitflags;
use core::{
cmp,
iter::{Enumerate, Peekable},
str::FromStr,
};
use itertools::Itertools;
use malachite_bigint::{BigInt, Sign};
use num_traits::Signed;
use rustpython_literal::{float, format::Case};
use crate::wtf8::{CodePoint, Wtf8, Wtf8Buf};
#[derive(Debug, PartialEq)]
pub enum CFormatErrorType {
UnmatchedKeyParentheses,
MissingModuloSign,
UnsupportedFormatChar(CodePoint),
IncompleteFormat,
IntTooBig,
// Unimplemented,
}
// also contains how many chars the parsing function consumed
pub type ParsingError = (CFormatErrorType, usize);
#[derive(Debug, PartialEq)]
pub struct CFormatError {
pub typ: CFormatErrorType, // FIXME
pub index: usize,
}
impl fmt::Display for CFormatError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use CFormatErrorType::*;
match self.typ {
UnmatchedKeyParentheses => write!(f, "incomplete format key"),
IncompleteFormat => write!(f, "incomplete format"),
UnsupportedFormatChar(c) => write!(
f,
"unsupported format character '{}' ({:#x}) at index {}",
c,
c.to_u32(),
self.index
),
IntTooBig => write!(f, "width/precision too big"),
_ => write!(f, "unexpected error parsing format string"),
}
}
}
pub type CFormatConversion = super::format::FormatConversion;
#[derive(Debug, PartialEq, Clone, Copy)]
#[repr(u8)]
pub enum CNumberType {
DecimalD = b'd',
DecimalI = b'i',
DecimalU = b'u',
Octal = b'o',
HexLower = b'x',
HexUpper = b'X',
}
#[derive(Debug, PartialEq, Clone, Copy)]
#[repr(u8)]
pub enum CFloatType {
ExponentLower = b'e',
ExponentUpper = b'E',
PointDecimalLower = b'f',
PointDecimalUpper = b'F',
GeneralLower = b'g',
GeneralUpper = b'G',
}
impl CFloatType {
const fn case(self) -> Case {
use CFloatType::*;
match self {
ExponentLower | PointDecimalLower | GeneralLower => Case::Lower,
ExponentUpper | PointDecimalUpper | GeneralUpper => Case::Upper,
}
}
}
#[derive(Debug, PartialEq, Clone, Copy)]
#[repr(u8)]
pub enum CCharacterType {
Character = b'c',
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum CFormatType {
Number(CNumberType),
Float(CFloatType),
Character(CCharacterType),
String(CFormatConversion),
}
impl CFormatType {
pub const fn to_char(self) -> char {
match self {
Self::Number(x) => x as u8 as char,
Self::Float(x) => x as u8 as char,
Self::Character(x) => x as u8 as char,
Self::String(x) => x as u8 as char,
}
}
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum CFormatPrecision {
Quantity(CFormatQuantity),
Dot,
}
impl From<CFormatQuantity> for CFormatPrecision {
fn from(quantity: CFormatQuantity) -> Self {
Self::Quantity(quantity)
}
}
bitflags! {
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct CConversionFlags: u32 {
const ALTERNATE_FORM = 0b0000_0001;
const ZERO_PAD = 0b0000_0010;
const LEFT_ADJUST = 0b0000_0100;
const BLANK_SIGN = 0b0000_1000;
const SIGN_CHAR = 0b0001_0000;
}
}
impl CConversionFlags {
#[inline]
pub const fn sign_string(&self) -> &'static str {
if self.contains(Self::SIGN_CHAR) {
"+"
} else if self.contains(Self::BLANK_SIGN) {
" "
} else {
""
}
}
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum CFormatQuantity {
Amount(usize),
FromValuesTuple,
}
pub trait FormatBuf:
Extend<Self::Char> + Default + FromIterator<Self::Char> + From<String>
{
type Char: FormatChar;
fn chars(&self) -> impl Iterator<Item = Self::Char>;
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn concat(self, other: Self) -> Self;
}
pub trait FormatChar: Copy + Into<CodePoint> + From<u8> {
fn to_char_lossy(self) -> char;
fn eq_char(self, c: char) -> bool;
}
impl FormatBuf for String {
type Char = char;
fn chars(&self) -> impl Iterator<Item = Self::Char> {
(**self).chars()
}
fn len(&self) -> usize {
self.len()
}
fn concat(mut self, other: Self) -> Self {
self.extend([other]);
self
}
}
impl FormatChar for char {
fn to_char_lossy(self) -> char {
self
}
fn eq_char(self, c: char) -> bool {
self == c
}
}
impl FormatBuf for Wtf8Buf {
type Char = CodePoint;
fn chars(&self) -> impl Iterator<Item = Self::Char> {
self.code_points()
}
fn len(&self) -> usize {
(**self).len()
}
fn concat(mut self, other: Self) -> Self {
self.extend([other]);
self
}
}
impl FormatChar for CodePoint {
fn to_char_lossy(self) -> char {
self.to_char_lossy()
}
fn eq_char(self, c: char) -> bool {
self == c
}
}
impl FormatBuf for Vec<u8> {
type Char = u8;
fn chars(&self) -> impl Iterator<Item = Self::Char> {
self.iter().copied()
}
fn len(&self) -> usize {
self.len()
}
fn concat(mut self, other: Self) -> Self {
self.extend(other);
self
}
}
impl FormatChar for u8 {
fn to_char_lossy(self) -> char {
self.into()
}
fn eq_char(self, c: char) -> bool {
char::from(self) == c
}
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct CFormatSpec {
pub flags: CConversionFlags,
pub min_field_width: Option<CFormatQuantity>,
pub precision: Option<CFormatPrecision>,
pub format_type: CFormatType,
// chars_consumed: usize,
}
#[derive(Debug, PartialEq)]
pub struct CFormatSpecKeyed<T> {
pub mapping_key: Option<T>,
pub spec: CFormatSpec,
}
#[cfg(test)]
impl FromStr for CFormatSpec {
type Err = ParsingError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
text.parse::<CFormatSpecKeyed<String>>()
.map(|CFormatSpecKeyed { mapping_key, spec }| {
assert!(mapping_key.is_none());
spec
})
}
}
impl FromStr for CFormatSpecKeyed<String> {
type Err = ParsingError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let mut chars = text.chars().enumerate().peekable();
if chars.next().map(|x| x.1) != Some('%') {
return Err((CFormatErrorType::MissingModuloSign, 1));
}
Self::parse(&mut chars)
}
}
pub type ParseIter<I> = Peekable<Enumerate<I>>;
impl<T: FormatBuf> CFormatSpecKeyed<T> {
pub fn parse<I>(iter: &mut ParseIter<I>) -> Result<Self, ParsingError>
where
I: Iterator<Item = T::Char>,
{
let mapping_key = parse_spec_mapping_key(iter)?;
let flags = parse_flags(iter);
let min_field_width = parse_quantity(iter)?;
let precision = parse_precision(iter)?;
consume_length(iter);
let format_type = parse_format_type(iter)?;
let spec = CFormatSpec {
flags,
min_field_width,
precision,
format_type,
};
Ok(Self { mapping_key, spec })
}
}
impl CFormatSpec {
fn compute_fill_string<T: FormatBuf>(fill_char: T::Char, fill_chars_needed: usize) -> T {
(0..fill_chars_needed).map(|_| fill_char).collect()
}
fn fill_string<T: FormatBuf>(
&self,
string: T,
fill_char: T::Char,
num_prefix_chars: Option<usize>,
) -> T {
let mut num_chars = string.chars().count();
if let Some(num_prefix_chars) = num_prefix_chars {
num_chars += num_prefix_chars;
}
let num_chars = num_chars;
let width = match &self.min_field_width {
Some(CFormatQuantity::Amount(width)) => cmp::max(width, &num_chars),
_ => &num_chars,
};
let fill_chars_needed = width.saturating_sub(num_chars);
let fill_string: T = Self::compute_fill_string(fill_char, fill_chars_needed);
if !fill_string.is_empty() {
if self.flags.contains(CConversionFlags::LEFT_ADJUST) {
string.concat(fill_string)
} else {
fill_string.concat(string)
}
} else {
string
}
}
fn fill_string_with_precision<T: FormatBuf>(&self, string: T, fill_char: T::Char) -> T {
let num_chars = string.chars().count();
let width = match &self.precision {
Some(CFormatPrecision::Quantity(CFormatQuantity::Amount(width))) => {
cmp::max(width, &num_chars)
}
_ => &num_chars,
};
let fill_chars_needed = width.saturating_sub(num_chars);
let fill_string: T = Self::compute_fill_string(fill_char, fill_chars_needed);
if !fill_string.is_empty() {
// Don't left-adjust if precision-filling: that will always be prepending 0s to %d
// arguments, the LEFT_ADJUST flag will be used by a later call to fill_string with
// the 0-filled string as the string param.
fill_string.concat(string)
} else {
string
}
}
fn format_string_with_precision<T: FormatBuf>(
&self,
string: T,
precision: Option<&CFormatPrecision>,
) -> T {
// truncate if needed
let string = match precision {
Some(CFormatPrecision::Quantity(CFormatQuantity::Amount(precision)))
if string.chars().count() > *precision =>
{
string.chars().take(*precision).collect::<T>()
}
Some(CFormatPrecision::Dot) => {
// truncate to 0
T::default()
}
_ => string,
};
self.fill_string(string, b' '.into(), None)
}
#[inline]
pub fn format_string<T: FormatBuf>(&self, string: T) -> T {
self.format_string_with_precision(string, self.precision.as_ref())
}
#[inline]
pub fn format_char<T: FormatBuf>(&self, ch: T::Char) -> T {
self.format_string_with_precision(
T::from_iter([ch]),
Some(&(CFormatQuantity::Amount(1).into())),
)
}
pub fn format_bytes(&self, bytes: &[u8]) -> Vec<u8> {
let bytes = if let Some(CFormatPrecision::Quantity(CFormatQuantity::Amount(precision))) =
self.precision
{
&bytes[..cmp::min(bytes.len(), precision)]
} else {
bytes
};
if let Some(CFormatQuantity::Amount(width)) = self.min_field_width {
let fill = cmp::max(0, width - bytes.len());
let mut v = Vec::with_capacity(bytes.len() + fill);
if self.flags.contains(CConversionFlags::LEFT_ADJUST) {
v.extend_from_slice(bytes);
v.append(&mut vec![b' '; fill]);
} else {
v.append(&mut vec![b' '; fill]);
v.extend_from_slice(bytes);
}
v
} else {
bytes.to_vec()
}
}
pub fn format_number(&self, num: &BigInt) -> String {
use CNumberType::*;
let CFormatType::Number(format_type) = self.format_type else {
unreachable!()
};
let magnitude = num.abs();
let prefix = if self.flags.contains(CConversionFlags::ALTERNATE_FORM) {
match format_type {
Octal => "0o",
HexLower => "0x",
HexUpper => "0X",
_ => "",
}
} else {
""
};
let magnitude_string: String = match format_type {
DecimalD | DecimalI | DecimalU => magnitude.to_str_radix(10),
Octal => magnitude.to_str_radix(8),
HexLower => magnitude.to_str_radix(16),
HexUpper => {
let mut result = magnitude.to_str_radix(16);
result.make_ascii_uppercase();
result
}
};
let sign_string = match num.sign() {
Sign::Minus => "-",
_ => self.flags.sign_string(),
};
let padded_magnitude_string = self.fill_string_with_precision(magnitude_string, '0');
if self.flags.contains(CConversionFlags::ZERO_PAD) {
let fill_char = if !self.flags.contains(CConversionFlags::LEFT_ADJUST) {
'0'
} else {
' ' // '-' overrides the '0' conversion if both are given
};
let signed_prefix = format!("{sign_string}{prefix}");
format!(
"{}{}",
signed_prefix,
self.fill_string(
padded_magnitude_string,
fill_char,
Some(signed_prefix.chars().count()),
),
)
} else {
self.fill_string(
format!("{sign_string}{prefix}{padded_magnitude_string}"),
' ',
None,
)
}
}
pub fn format_float(&self, num: f64) -> String {
let sign_string = if num.is_sign_negative() && !num.is_nan() {
"-"
} else {
self.flags.sign_string()
};
let precision = match &self.precision {
Some(CFormatPrecision::Quantity(quantity)) => match quantity {
CFormatQuantity::Amount(amount) => *amount,
CFormatQuantity::FromValuesTuple => 6,
},
Some(CFormatPrecision::Dot) => 0,
None => 6,
};
let CFormatType::Float(format_type) = self.format_type else {
unreachable!()
};
let magnitude = num.abs();
let case = format_type.case();
let magnitude_string = match format_type {
CFloatType::PointDecimalLower | CFloatType::PointDecimalUpper => float::format_fixed(
precision,
magnitude,
case,
self.flags.contains(CConversionFlags::ALTERNATE_FORM),
),
CFloatType::ExponentLower | CFloatType::ExponentUpper => float::format_exponent(
precision,
magnitude,
case,
self.flags.contains(CConversionFlags::ALTERNATE_FORM),
),
CFloatType::GeneralLower | CFloatType::GeneralUpper => {
let precision = if precision == 0 { 1 } else { precision };
float::format_general(
precision,
magnitude,
case,
self.flags.contains(CConversionFlags::ALTERNATE_FORM),
false,
)
}
};
if self.flags.contains(CConversionFlags::ZERO_PAD) {
let fill_char = if !self.flags.contains(CConversionFlags::LEFT_ADJUST) {
'0'
} else {
' '
};
format!(
"{}{}",
sign_string,
self.fill_string(
magnitude_string,
fill_char,
Some(sign_string.chars().count()),
)
)
} else {
self.fill_string(format!("{sign_string}{magnitude_string}"), ' ', None)
}
}
}
fn parse_spec_mapping_key<T, I>(iter: &mut ParseIter<I>) -> Result<Option<T>, ParsingError>
where
T: FormatBuf,
I: Iterator<Item = T::Char>,
{
if let Some((index, _)) = iter.next_if(|(_, c)| c.eq_char('(')) {
return match parse_text_inside_parentheses(iter) {
Some(key) => Ok(Some(key)),
None => Err((CFormatErrorType::UnmatchedKeyParentheses, index)),
};
}
Ok(None)
}
fn parse_flags<C, I>(iter: &mut ParseIter<I>) -> CConversionFlags
where
C: FormatChar,
I: Iterator<Item = C>,
{
let mut flags = CConversionFlags::empty();
iter.peeking_take_while(|(_, c)| {
let flag = match c.to_char_lossy() {
'#' => CConversionFlags::ALTERNATE_FORM,
'0' => CConversionFlags::ZERO_PAD,
'-' => CConversionFlags::LEFT_ADJUST,
' ' => CConversionFlags::BLANK_SIGN,
'+' => CConversionFlags::SIGN_CHAR,
_ => return false,
};
flags |= flag;
true
})
.for_each(drop);
flags
}
fn consume_length<C, I>(iter: &mut ParseIter<I>)
where
C: FormatChar,
I: Iterator<Item = C>,
{
iter.next_if(|(_, c)| matches!(c.to_char_lossy(), 'h' | 'l' | 'L'));
}
fn parse_format_type<C, I>(iter: &mut ParseIter<I>) -> Result<CFormatType, ParsingError>
where
C: FormatChar,
I: Iterator<Item = C>,
{
use CFloatType::*;
use CNumberType::*;
let (index, c) = iter.next().ok_or_else(|| {
(
CFormatErrorType::IncompleteFormat,
iter.peek().map(|x| x.0).unwrap_or(0),
)
})?;
let format_type = match c.to_char_lossy() {
'd' => CFormatType::Number(DecimalD),
'i' => CFormatType::Number(DecimalI),
'u' => CFormatType::Number(DecimalU),
'o' => CFormatType::Number(Octal),
'x' => CFormatType::Number(HexLower),
'X' => CFormatType::Number(HexUpper),
'e' => CFormatType::Float(ExponentLower),
'E' => CFormatType::Float(ExponentUpper),
'f' => CFormatType::Float(PointDecimalLower),
'F' => CFormatType::Float(PointDecimalUpper),
'g' => CFormatType::Float(GeneralLower),
'G' => CFormatType::Float(GeneralUpper),
'c' => CFormatType::Character(CCharacterType::Character),
'r' => CFormatType::String(CFormatConversion::Repr),
's' => CFormatType::String(CFormatConversion::Str),
'b' => CFormatType::String(CFormatConversion::Bytes),
'a' => CFormatType::String(CFormatConversion::Ascii),
_ => return Err((CFormatErrorType::UnsupportedFormatChar(c.into()), index)),
};
Ok(format_type)
}
fn parse_quantity<C, I>(iter: &mut ParseIter<I>) -> Result<Option<CFormatQuantity>, ParsingError>
where
C: FormatChar,
I: Iterator<Item = C>,
{
if let Some(&(_, c)) = iter.peek() {
if c.eq_char('*') {
iter.next().unwrap();
return Ok(Some(CFormatQuantity::FromValuesTuple));
}
if let Some(i) = c.to_char_lossy().to_digit(10) {
let mut num = i as i32;
iter.next().unwrap();
while let Some(&(index, c)) = iter.peek() {
if let Some(i) = c.to_char_lossy().to_digit(10) {
num = num
.checked_mul(10)
.and_then(|num| num.checked_add(i as i32))
.ok_or((CFormatErrorType::IntTooBig, index))?;
iter.next().unwrap();
} else {
break;
}
}
return Ok(Some(CFormatQuantity::Amount(num.unsigned_abs() as usize)));
}
}
Ok(None)
}
fn parse_precision<C, I>(iter: &mut ParseIter<I>) -> Result<Option<CFormatPrecision>, ParsingError>
where
C: FormatChar,
I: Iterator<Item = C>,
{
if iter.next_if(|(_, c)| c.eq_char('.')).is_some() {
let quantity = parse_quantity(iter)?;
let precision = quantity.map_or(CFormatPrecision::Dot, CFormatPrecision::Quantity);
return Ok(Some(precision));
}
Ok(None)
}
fn parse_text_inside_parentheses<T, I>(iter: &mut ParseIter<I>) -> Option<T>
where
T: FormatBuf,
I: Iterator<Item = T::Char>,
{
let mut counter: i32 = 1;
let mut contained_text = T::default();
loop {
let (_, c) = iter.next()?;
match c.to_char_lossy() {
'(' => {
counter += 1;
}
')' => {
counter -= 1;
}
_ => (),
}
if counter > 0 {
contained_text.extend([c]);
} else {
break;
}
}
Some(contained_text)
}
#[derive(Debug, PartialEq)]
pub enum CFormatPart<T> {
Literal(T),
Spec(CFormatSpecKeyed<T>),
}
impl<T> CFormatPart<T> {
#[inline]
pub const fn is_specifier(&self) -> bool {
matches!(self, Self::Spec { .. })
}
#[inline]
pub const fn has_key(&self) -> bool {
match self {
Self::Spec(s) => s.mapping_key.is_some(),
_ => false,
}
}
}
#[derive(Debug, PartialEq)]
pub struct CFormatStrOrBytes<S> {
parts: Vec<(usize, CFormatPart<S>)>,
}
impl<S> CFormatStrOrBytes<S> {
pub fn check_specifiers(&self) -> Option<(usize, bool)> {
let mut count = 0;
let mut mapping_required = false;
for (_, part) in &self.parts {
if part.is_specifier() {
let has_key = part.has_key();
if count == 0 {
mapping_required = has_key;
} else if mapping_required != has_key {
return None;
}
count += 1;
}
}
Some((count, mapping_required))
}
#[inline]
pub fn iter(&self) -> impl Iterator<Item = &(usize, CFormatPart<S>)> {
self.parts.iter()
}
#[inline]
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut (usize, CFormatPart<S>)> {
self.parts.iter_mut()
}
pub fn parse<I>(iter: &mut ParseIter<I>) -> Result<Self, CFormatError>
where
S: FormatBuf,
I: Iterator<Item = S::Char>,
{
let mut parts = vec![];
let mut literal = S::default();
let mut part_index = 0;
while let Some((index, c)) = iter.next() {
if c.eq_char('%') {
if let Some(&(_, second)) = iter.peek() {
if second.eq_char('%') {
iter.next().unwrap();
literal.extend([second]);
continue;
} else {
if !literal.is_empty() {
parts.push((
part_index,
CFormatPart::Literal(core::mem::take(&mut literal)),
));
}
let spec = CFormatSpecKeyed::parse(iter).map_err(|err| CFormatError {
typ: err.0,
index: err.1,
})?;
parts.push((index, CFormatPart::Spec(spec)));
if let Some(&(index, _)) = iter.peek() {
part_index = index;
}
}
} else {
return Err(CFormatError {
typ: CFormatErrorType::IncompleteFormat,
index: index + 1,
});
}
} else {
literal.extend([c]);
}
}
if !literal.is_empty() {
parts.push((part_index, CFormatPart::Literal(literal)));
}
Ok(Self { parts })
}
}
impl<S> IntoIterator for CFormatStrOrBytes<S> {
type Item = (usize, CFormatPart<S>);
type IntoIter = alloc::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.parts.into_iter()
}
}
pub type CFormatBytes = CFormatStrOrBytes<Vec<u8>>;
impl CFormatBytes {
pub fn parse_from_bytes(bytes: &[u8]) -> Result<Self, CFormatError> {
let mut iter = bytes.iter().cloned().enumerate().peekable();
Self::parse(&mut iter)
}
}
pub type CFormatString = CFormatStrOrBytes<String>;
impl FromStr for CFormatString {
type Err = CFormatError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let mut iter = text.chars().enumerate().peekable();
Self::parse(&mut iter)
}
}
pub type CFormatWtf8 = CFormatStrOrBytes<Wtf8Buf>;
impl CFormatWtf8 {
pub fn parse_from_wtf8(s: &Wtf8) -> Result<Self, CFormatError> {
let mut iter = s.code_points().enumerate().peekable();
Self::parse(&mut iter)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fill_and_align() {
assert_eq!(
"%10s"
.parse::<CFormatSpec>()
.unwrap()
.format_string("test".to_owned()),
" test".to_owned()
);
assert_eq!(
"%-10s"
.parse::<CFormatSpec>()
.unwrap()
.format_string("test".to_owned()),
"test ".to_owned()
);
assert_eq!(
"%#10x"
.parse::<CFormatSpec>()
.unwrap()
.format_number(&BigInt::from(0x1337)),
" 0x1337".to_owned()
);
assert_eq!(
"%-#10x"
.parse::<CFormatSpec>()
.unwrap()
.format_number(&BigInt::from(0x1337)),
"0x1337 ".to_owned()
);
}
#[test]
fn test_parse_key() {
let expected = Ok(CFormatSpecKeyed {
mapping_key: Some("amount".to_owned()),
spec: CFormatSpec {
format_type: CFormatType::Number(CNumberType::DecimalD),
min_field_width: None,
precision: None,
flags: CConversionFlags::empty(),
},
});
assert_eq!("%(amount)d".parse::<CFormatSpecKeyed<String>>(), expected);
let expected = Ok(CFormatSpecKeyed {
mapping_key: Some("m((u(((l((((ti))))p)))l))e".to_owned()),
spec: CFormatSpec {
format_type: CFormatType::Number(CNumberType::DecimalD),
min_field_width: None,
precision: None,
flags: CConversionFlags::empty(),
},
});
assert_eq!(
"%(m((u(((l((((ti))))p)))l))e)d".parse::<CFormatSpecKeyed<String>>(),
expected
);
}
#[test]
fn test_format_parse_key_fail() {
assert_eq!(
"%(aged".parse::<CFormatString>(),
Err(CFormatError {
typ: CFormatErrorType::UnmatchedKeyParentheses,
index: 1
})
);
}
#[test]
fn test_format_parse_type_fail() {
assert_eq!(
"Hello %n".parse::<CFormatString>(),
Err(CFormatError {
typ: CFormatErrorType::UnsupportedFormatChar('n'.into()),
index: 7
})
);
}
#[test]
fn test_incomplete_format_fail() {
assert_eq!(
"Hello %".parse::<CFormatString>(),
Err(CFormatError {
typ: CFormatErrorType::IncompleteFormat,
index: 7
})
);
}
#[test]
fn test_parse_flags() {
let expected = Ok(CFormatSpec {
format_type: CFormatType::Number(CNumberType::DecimalD),
min_field_width: Some(CFormatQuantity::Amount(10)),
precision: None,
flags: CConversionFlags::all(),
});
let parsed = "% 0 -+++###10d".parse::<CFormatSpec>();
assert_eq!(parsed, expected);
assert_eq!(
parsed.unwrap().format_number(&BigInt::from(12)),
"+12 ".to_owned()
);
}
#[test]
fn test_parse_and_format_string() {
assert_eq!(
"%5.4s"
.parse::<CFormatSpec>()
.unwrap()
.format_string("Hello, World!".to_owned()),
" Hell".to_owned()
);
assert_eq!(
"%-5.4s"
.parse::<CFormatSpec>()
.unwrap()
.format_string("Hello, World!".to_owned()),
"Hell ".to_owned()
);
assert_eq!(
"%.s"
.parse::<CFormatSpec>()
.unwrap()
.format_string("Hello, World!".to_owned()),
"".to_owned()
);
assert_eq!(
"%5.s"
.parse::<CFormatSpec>()
.unwrap()
.format_string("Hello, World!".to_owned()),
" ".to_owned()
);
}
#[test]
fn test_parse_and_format_unicode_string() {
assert_eq!(
"%.2s"
.parse::<CFormatSpec>()
.unwrap()
.format_string("❤❤❤❤❤❤❤❤".to_owned()),
"❤❤".to_owned()
);
}
#[test]
fn test_parse_and_format_number() {
assert_eq!(
"%5d"
.parse::<CFormatSpec>()
.unwrap()
.format_number(&BigInt::from(27)),
" 27".to_owned()
);
assert_eq!(
"%05d"
.parse::<CFormatSpec>()
.unwrap()
.format_number(&BigInt::from(27)),
"00027".to_owned()
);
assert_eq!(
"%.5d"
.parse::<CFormatSpec>()
.unwrap()
.format_number(&BigInt::from(27)),
"00027".to_owned()
);
assert_eq!(
"%+05d"
.parse::<CFormatSpec>()
.unwrap()
.format_number(&BigInt::from(27)),
"+0027".to_owned()
);
assert_eq!(
"%-d"
.parse::<CFormatSpec>()
.unwrap()
.format_number(&BigInt::from(-27)),
"-27".to_owned()
);
assert_eq!(
"% d"
.parse::<CFormatSpec>()
.unwrap()
.format_number(&BigInt::from(27)),
" 27".to_owned()
);
assert_eq!(
"% d"
.parse::<CFormatSpec>()
.unwrap()
.format_number(&BigInt::from(-27)),
"-27".to_owned()
);
assert_eq!(
"%08x"
.parse::<CFormatSpec>()
.unwrap()
.format_number(&BigInt::from(0x1337)),
"00001337".to_owned()
);
assert_eq!(
"%#010x"
.parse::<CFormatSpec>()
.unwrap()
.format_number(&BigInt::from(0x1337)),
"0x00001337".to_owned()
);
assert_eq!(
"%-#010x"
.parse::<CFormatSpec>()
.unwrap()
.format_number(&BigInt::from(0x1337)),
"0x1337 ".to_owned()
);
}
#[test]
fn test_parse_and_format_float() {
assert_eq!(
"%f".parse::<CFormatSpec>().unwrap().format_float(1.2345),
"1.234500"
);
assert_eq!(
"%.2f".parse::<CFormatSpec>().unwrap().format_float(1.2345),
"1.23"
);
assert_eq!(
"%.f".parse::<CFormatSpec>().unwrap().format_float(1.2345),
"1"
);
assert_eq!(
"%+.f".parse::<CFormatSpec>().unwrap().format_float(1.2345),
"+1"
);
assert_eq!(
"%+f".parse::<CFormatSpec>().unwrap().format_float(1.2345),
"+1.234500"
);
assert_eq!(
"% f".parse::<CFormatSpec>().unwrap().format_float(1.2345),
" 1.234500"
);
assert_eq!(
"%f".parse::<CFormatSpec>().unwrap().format_float(-1.2345),
"-1.234500"
);
assert_eq!(
"%f".parse::<CFormatSpec>()
.unwrap()
.format_float(1.2345678901),
"1.234568"
);
}
#[test]
fn test_format_parse() {
let fmt = "Hello, my name is %s and I'm %d years old";
let expected = Ok(CFormatString {
parts: vec![
(0, CFormatPart::Literal("Hello, my name is ".to_owned())),
(
18,
CFormatPart::Spec(CFormatSpecKeyed {
mapping_key: None,
spec: CFormatSpec {
format_type: CFormatType::String(CFormatConversion::Str),
min_field_width: None,
precision: None,
flags: CConversionFlags::empty(),
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | true |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/borrow.rs | crates/common/src/borrow.rs | use crate::lock::{
MapImmutable, PyImmutableMappedMutexGuard, PyMappedMutexGuard, PyMappedRwLockReadGuard,
PyMappedRwLockWriteGuard, PyMutexGuard, PyRwLockReadGuard, PyRwLockWriteGuard,
};
use alloc::fmt;
use core::ops::{Deref, DerefMut};
macro_rules! impl_from {
($lt:lifetime, $gen:ident, $t:ty, $($var:ident($from:ty),)*) => {
$(
impl<$lt, $gen: ?Sized> From<$from> for $t {
fn from(t: $from) -> Self {
Self::$var(t)
}
}
)*
};
}
#[derive(Debug)]
pub enum BorrowedValue<'a, T: ?Sized> {
Ref(&'a T),
MuLock(PyMutexGuard<'a, T>),
MappedMuLock(PyImmutableMappedMutexGuard<'a, T>),
ReadLock(PyRwLockReadGuard<'a, T>),
MappedReadLock(PyMappedRwLockReadGuard<'a, T>),
}
impl_from!('a, T, BorrowedValue<'a, T>,
Ref(&'a T),
MuLock(PyMutexGuard<'a, T>),
MappedMuLock(PyImmutableMappedMutexGuard<'a, T>),
ReadLock(PyRwLockReadGuard<'a, T>),
MappedReadLock(PyMappedRwLockReadGuard<'a, T>),
);
impl<'a, T: ?Sized> BorrowedValue<'a, T> {
pub fn map<U: ?Sized, F>(s: Self, f: F) -> BorrowedValue<'a, U>
where
F: FnOnce(&T) -> &U,
{
match s {
Self::Ref(r) => BorrowedValue::Ref(f(r)),
Self::MuLock(m) => BorrowedValue::MappedMuLock(PyMutexGuard::map_immutable(m, f)),
Self::MappedMuLock(m) => {
BorrowedValue::MappedMuLock(PyImmutableMappedMutexGuard::map(m, f))
}
Self::ReadLock(r) => BorrowedValue::MappedReadLock(PyRwLockReadGuard::map(r, f)),
Self::MappedReadLock(m) => {
BorrowedValue::MappedReadLock(PyMappedRwLockReadGuard::map(m, f))
}
}
}
}
impl<T: ?Sized> Deref for BorrowedValue<'_, T> {
type Target = T;
fn deref(&self) -> &T {
match self {
Self::Ref(r) => r,
Self::MuLock(m) => m,
Self::MappedMuLock(m) => m,
Self::ReadLock(r) => r,
Self::MappedReadLock(m) => m,
}
}
}
impl fmt::Display for BorrowedValue<'_, str> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self.deref(), f)
}
}
#[derive(Debug)]
pub enum BorrowedValueMut<'a, T: ?Sized> {
RefMut(&'a mut T),
MuLock(PyMutexGuard<'a, T>),
MappedMuLock(PyMappedMutexGuard<'a, T>),
WriteLock(PyRwLockWriteGuard<'a, T>),
MappedWriteLock(PyMappedRwLockWriteGuard<'a, T>),
}
impl_from!('a, T, BorrowedValueMut<'a, T>,
RefMut(&'a mut T),
MuLock(PyMutexGuard<'a, T>),
MappedMuLock(PyMappedMutexGuard<'a, T>),
WriteLock(PyRwLockWriteGuard<'a, T>),
MappedWriteLock(PyMappedRwLockWriteGuard<'a, T>),
);
impl<'a, T: ?Sized> BorrowedValueMut<'a, T> {
pub fn map<U: ?Sized, F>(s: Self, f: F) -> BorrowedValueMut<'a, U>
where
F: FnOnce(&mut T) -> &mut U,
{
match s {
Self::RefMut(r) => BorrowedValueMut::RefMut(f(r)),
Self::MuLock(m) => BorrowedValueMut::MappedMuLock(PyMutexGuard::map(m, f)),
Self::MappedMuLock(m) => BorrowedValueMut::MappedMuLock(PyMappedMutexGuard::map(m, f)),
Self::WriteLock(r) => BorrowedValueMut::MappedWriteLock(PyRwLockWriteGuard::map(r, f)),
Self::MappedWriteLock(m) => {
BorrowedValueMut::MappedWriteLock(PyMappedRwLockWriteGuard::map(m, f))
}
}
}
}
impl<T: ?Sized> Deref for BorrowedValueMut<'_, T> {
type Target = T;
fn deref(&self) -> &T {
match self {
Self::RefMut(r) => r,
Self::MuLock(m) => m,
Self::MappedMuLock(m) => m,
Self::WriteLock(w) => w,
Self::MappedWriteLock(w) => w,
}
}
}
impl<T: ?Sized> DerefMut for BorrowedValueMut<'_, T> {
fn deref_mut(&mut self) -> &mut T {
match self {
Self::RefMut(r) => r,
Self::MuLock(m) => &mut *m,
Self::MappedMuLock(m) => &mut *m,
Self::WriteLock(w) => &mut *w,
Self::MappedWriteLock(w) => &mut *w,
}
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/lib.rs | crates/common/src/lib.rs | //! A crate to hold types and functions common to all rustpython components.
#![cfg_attr(all(target_os = "wasi", target_env = "p2"), feature(wasip2))]
extern crate alloc;
#[macro_use]
mod macros;
pub use macros::*;
pub mod atomic;
pub mod borrow;
pub mod boxvec;
pub mod cformat;
#[cfg(any(unix, windows, target_os = "wasi"))]
pub mod crt_fd;
pub mod encodings;
#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
pub mod fileutils;
pub mod float_ops;
pub mod format;
pub mod hash;
pub mod int;
pub mod linked_list;
pub mod lock;
pub mod os;
pub mod rand;
pub mod rc;
pub mod refcount;
pub mod static_cell;
pub mod str;
#[cfg(windows)]
pub mod windows;
pub use rustpython_wtf8 as wtf8;
pub mod vendored {
pub use ascii;
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/float_ops.rs | crates/common/src/float_ops.rs | use malachite_bigint::{BigInt, ToBigInt};
use num_traits::{Float, Signed, ToPrimitive, Zero};
use std::f64;
pub const fn decompose_float(value: f64) -> (f64, i32) {
if 0.0 == value {
(0.0, 0i32)
} else {
let bits = value.to_bits();
let exponent: i32 = ((bits >> 52) & 0x7ff) as i32 - 1022;
let mantissa_bits = bits & (0x000f_ffff_ffff_ffff) | (1022 << 52);
(f64::from_bits(mantissa_bits), exponent)
}
}
/// Equate an integer to a float.
///
/// Returns true if and only if, when converted to each others types, both are equal.
///
/// # Examples
///
/// ```
/// use malachite_bigint::BigInt;
/// use rustpython_common::float_ops::eq_int;
/// let a = 1.0f64;
/// let b = BigInt::from(1);
/// let c = 2.0f64;
/// assert!(eq_int(a, &b));
/// assert!(!eq_int(c, &b));
/// ```
///
pub fn eq_int(value: f64, other: &BigInt) -> bool {
if let (Some(self_int), Some(other_float)) = (value.to_bigint(), other.to_f64()) {
value == other_float && self_int == *other
} else {
false
}
}
pub fn lt_int(value: f64, other_int: &BigInt) -> bool {
match (value.to_bigint(), other_int.to_f64()) {
(Some(self_int), Some(other_float)) => value < other_float || self_int < *other_int,
// finite float, other_int too big for float,
// the result depends only on other_int’s sign
(Some(_), None) => other_int.is_positive(),
// infinite float must be bigger or lower than any int, depending on its sign
_ if value.is_infinite() => value.is_sign_negative(),
// NaN, always false
_ => false,
}
}
pub fn gt_int(value: f64, other_int: &BigInt) -> bool {
match (value.to_bigint(), other_int.to_f64()) {
(Some(self_int), Some(other_float)) => value > other_float || self_int > *other_int,
// finite float, other_int too big for float,
// the result depends only on other_int’s sign
(Some(_), None) => other_int.is_negative(),
// infinite float must be bigger or lower than any int, depending on its sign
_ if value.is_infinite() => value.is_sign_positive(),
// NaN, always false
_ => false,
}
}
pub const fn div(v1: f64, v2: f64) -> Option<f64> {
if v2 != 0.0 { Some(v1 / v2) } else { None }
}
pub fn mod_(v1: f64, v2: f64) -> Option<f64> {
if v2 != 0.0 {
let val = v1 % v2;
match (v1.signum() as i32, v2.signum() as i32) {
(1, 1) | (-1, -1) => Some(val),
_ if (v1 == 0.0) || (v1.abs() == v2.abs()) => Some(val.copysign(v2)),
_ => Some((val + v2).copysign(v2)),
}
} else {
None
}
}
pub fn floordiv(v1: f64, v2: f64) -> Option<f64> {
if v2 != 0.0 {
Some((v1 / v2).floor())
} else {
None
}
}
pub fn divmod(v1: f64, v2: f64) -> Option<(f64, f64)> {
if v2 != 0.0 {
let mut m = v1 % v2;
let mut d = (v1 - m) / v2;
if v2.is_sign_negative() != m.is_sign_negative() {
m += v2;
d -= 1.0;
}
Some((d, m))
} else {
None
}
}
// nextafter algorithm based off of https://gitlab.com/bronsonbdevost/next_afterf
#[allow(clippy::float_cmp)]
pub fn nextafter(x: f64, y: f64) -> f64 {
if x == y {
y
} else if x.is_nan() || y.is_nan() {
f64::NAN
} else if x >= f64::INFINITY {
f64::MAX
} else if x <= f64::NEG_INFINITY {
f64::MIN
} else if x == 0.0 {
f64::from_bits(1).copysign(y)
} else {
// next x after 0 if y is farther from 0 than x, otherwise next towards 0
// the sign is a separate bit in floats, so bits+1 moves away from 0 no matter the float
let b = x.to_bits();
let bits = if (y > x) == (x > 0.0) { b + 1 } else { b - 1 };
let ret = f64::from_bits(bits);
if ret == 0.0 { ret.copysign(x) } else { ret }
}
}
#[allow(clippy::float_cmp)]
pub fn nextafter_with_steps(x: f64, y: f64, steps: u64) -> f64 {
if x == y {
y
} else if x.is_nan() || y.is_nan() {
f64::NAN
} else if x >= f64::INFINITY {
f64::MAX
} else if x <= f64::NEG_INFINITY {
f64::MIN
} else if x == 0.0 {
f64::from_bits(1).copysign(y)
} else {
if steps == 0 {
return x;
}
if x.is_nan() {
return x;
}
if y.is_nan() {
return y;
}
let sign_bit: u64 = 1 << 63;
let mut ux = x.to_bits();
let uy = y.to_bits();
let ax = ux & !sign_bit;
let ay = uy & !sign_bit;
// If signs are different
if ((ux ^ uy) & sign_bit) != 0 {
return if ax + ay <= steps {
f64::from_bits(uy)
} else if ax < steps {
let result = (uy & sign_bit) | (steps - ax);
f64::from_bits(result)
} else {
ux -= steps;
f64::from_bits(ux)
};
}
// If signs are the same
if ax > ay {
if ax - ay >= steps {
ux -= steps;
f64::from_bits(ux)
} else {
f64::from_bits(uy)
}
} else if ay - ax >= steps {
ux += steps;
f64::from_bits(ux)
} else {
f64::from_bits(uy)
}
}
}
pub fn ulp(x: f64) -> f64 {
if x.is_nan() {
return x;
}
let x = x.abs();
let x2 = nextafter(x, f64::INFINITY);
if x2.is_infinite() {
// special case: x is the largest positive representable float
let x2 = nextafter(x, f64::NEG_INFINITY);
x - x2
} else {
x2 - x
}
}
pub fn round_float_digits(x: f64, ndigits: i32) -> Option<f64> {
let float = if ndigits.is_zero() {
let fract = x.fract();
if (fract.abs() - 0.5).abs() < f64::EPSILON {
if x.trunc() % 2.0 == 0.0 {
x - fract
} else {
x + fract
}
} else {
x.round()
}
} else {
const NDIGITS_MAX: i32 =
((f64::MANTISSA_DIGITS as i32 - f64::MIN_EXP) as f64 * f64::consts::LOG10_2) as i32;
const NDIGITS_MIN: i32 = -(((f64::MAX_EXP + 1) as f64 * f64::consts::LOG10_2) as i32);
if ndigits > NDIGITS_MAX {
x
} else if ndigits < NDIGITS_MIN {
0.0f64.copysign(x)
} else {
let (y, pow1, pow2) = if ndigits >= 0 {
// according to cpython: pow1 and pow2 are each safe from overflow, but
// pow1*pow2 ~= pow(10.0, ndigits) might overflow
let (pow1, pow2) = if ndigits > 22 {
(10.0.powf((ndigits - 22) as f64), 1e22)
} else {
(10.0.powf(ndigits as f64), 1.0)
};
let y = (x * pow1) * pow2;
if !y.is_finite() {
return Some(x);
}
(y, pow1, Some(pow2))
} else {
let pow1 = 10.0.powf((-ndigits) as f64);
(x / pow1, pow1, None)
};
let z = y.round();
#[allow(clippy::float_cmp)]
let z = if (y - z).abs() == 0.5 {
2.0 * (y / 2.0).round()
} else {
z
};
let z = if let Some(pow2) = pow2 {
// ndigits >= 0
(z / pow2) / pow1
} else {
z * pow1
};
if !z.is_finite() {
// overflow
return None;
}
z
}
};
Some(float)
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/os.rs | crates/common/src/os.rs | // spell-checker:disable
// TODO: we can move more os-specific bindings/interfaces from stdlib::{os, posix, nt} to here
use core::str::Utf8Error;
use std::{io, process::ExitCode};
/// Convert exit code to std::process::ExitCode
///
/// On Windows, this supports the full u32 range including STATUS_CONTROL_C_EXIT (0xC000013A).
/// On other platforms, only the lower 8 bits are used.
pub fn exit_code(code: u32) -> ExitCode {
#[cfg(windows)]
{
// For large exit codes like STATUS_CONTROL_C_EXIT (0xC000013A),
// we need to call std::process::exit() directly since ExitCode::from(u8)
// would truncate the value, and ExitCode::from_raw() is still unstable.
// FIXME: side effect in exit_code is not ideal.
if code > u8::MAX as u32 {
std::process::exit(code as i32)
}
}
ExitCode::from(code as u8)
}
pub trait ErrorExt {
fn posix_errno(&self) -> i32;
}
impl ErrorExt for io::Error {
#[cfg(not(windows))]
fn posix_errno(&self) -> i32 {
self.raw_os_error().unwrap_or(0)
}
#[cfg(windows)]
fn posix_errno(&self) -> i32 {
let winerror = self.raw_os_error().unwrap_or(0);
winerror_to_errno(winerror)
}
}
/// Get the last error from C runtime library functions (like _dup, _dup2, _fstat, etc.)
/// CRT functions set errno, not GetLastError(), so we need to read errno directly.
#[cfg(windows)]
pub fn errno_io_error() -> io::Error {
let errno: i32 = get_errno();
let winerror = errno_to_winerror(errno);
io::Error::from_raw_os_error(winerror)
}
#[cfg(not(windows))]
pub fn errno_io_error() -> io::Error {
std::io::Error::last_os_error()
}
#[cfg(windows)]
pub fn get_errno() -> i32 {
unsafe extern "C" {
fn _get_errno(pValue: *mut i32) -> i32;
}
let mut errno = 0;
unsafe { suppress_iph!(_get_errno(&mut errno)) };
errno
}
#[cfg(not(windows))]
pub fn get_errno() -> i32 {
std::io::Error::last_os_error().posix_errno()
}
/// Set errno to the specified value.
#[cfg(windows)]
pub fn set_errno(value: i32) {
unsafe extern "C" {
fn _set_errno(value: i32) -> i32;
}
unsafe { suppress_iph!(_set_errno(value)) };
}
#[cfg(unix)]
pub fn set_errno(value: i32) {
nix::errno::Errno::from_raw(value).set();
}
#[cfg(unix)]
pub fn bytes_as_os_str(b: &[u8]) -> Result<&std::ffi::OsStr, Utf8Error> {
use std::os::unix::ffi::OsStrExt;
Ok(std::ffi::OsStr::from_bytes(b))
}
#[cfg(not(unix))]
pub fn bytes_as_os_str(b: &[u8]) -> Result<&std::ffi::OsStr, Utf8Error> {
Ok(core::str::from_utf8(b)?.as_ref())
}
#[cfg(unix)]
pub use std::os::unix::ffi;
#[cfg(target_os = "wasi")]
pub use std::os::wasi::ffi;
#[cfg(windows)]
pub fn errno_to_winerror(errno: i32) -> i32 {
use libc::*;
use windows_sys::Win32::Foundation::*;
let winerror = match errno {
ENOENT => ERROR_FILE_NOT_FOUND,
E2BIG => ERROR_BAD_ENVIRONMENT,
ENOEXEC => ERROR_BAD_FORMAT,
EBADF => ERROR_INVALID_HANDLE,
ECHILD => ERROR_WAIT_NO_CHILDREN,
EAGAIN => ERROR_NO_PROC_SLOTS,
ENOMEM => ERROR_NOT_ENOUGH_MEMORY,
EACCES => ERROR_ACCESS_DENIED,
EEXIST => ERROR_FILE_EXISTS,
EXDEV => ERROR_NOT_SAME_DEVICE,
ENOTDIR => ERROR_DIRECTORY,
EMFILE => ERROR_TOO_MANY_OPEN_FILES,
ENOSPC => ERROR_DISK_FULL,
EPIPE => ERROR_BROKEN_PIPE,
ENOTEMPTY => ERROR_DIR_NOT_EMPTY,
EILSEQ => ERROR_NO_UNICODE_TRANSLATION,
EINVAL => ERROR_INVALID_FUNCTION,
_ => ERROR_INVALID_FUNCTION,
};
winerror as _
}
// winerror: https://learn.microsoft.com/windows/win32/debug/system-error-codes--0-499-
// errno: https://learn.microsoft.com/cpp/c-runtime-library/errno-constants?view=msvc-170
#[cfg(windows)]
pub fn winerror_to_errno(winerror: i32) -> i32 {
use libc::*;
use windows_sys::Win32::{
Foundation::*,
Networking::WinSock::{WSAEACCES, WSAEBADF, WSAEFAULT, WSAEINTR, WSAEINVAL, WSAEMFILE},
};
// Unwrap FACILITY_WIN32 HRESULT errors.
// if ((winerror & 0xFFFF0000) == 0x80070000) {
// winerror &= 0x0000FFFF;
// }
// Winsock error codes (10000-11999) are errno values.
if (10000..12000).contains(&winerror) {
match winerror {
WSAEINTR | WSAEBADF | WSAEACCES | WSAEFAULT | WSAEINVAL | WSAEMFILE => {
// Winsock definitions of errno values. See WinSock2.h
return winerror - 10000;
}
_ => return winerror as _,
}
}
#[allow(non_upper_case_globals)]
match winerror as u32 {
ERROR_FILE_NOT_FOUND
| ERROR_PATH_NOT_FOUND
| ERROR_INVALID_DRIVE
| ERROR_NO_MORE_FILES
| ERROR_BAD_NETPATH
| ERROR_BAD_NET_NAME
| ERROR_BAD_PATHNAME
| ERROR_FILENAME_EXCED_RANGE => ENOENT,
ERROR_BAD_ENVIRONMENT => E2BIG,
ERROR_BAD_FORMAT
| ERROR_INVALID_STARTING_CODESEG
| ERROR_INVALID_STACKSEG
| ERROR_INVALID_MODULETYPE
| ERROR_INVALID_EXE_SIGNATURE
| ERROR_EXE_MARKED_INVALID
| ERROR_BAD_EXE_FORMAT
| ERROR_ITERATED_DATA_EXCEEDS_64k
| ERROR_INVALID_MINALLOCSIZE
| ERROR_DYNLINK_FROM_INVALID_RING
| ERROR_IOPL_NOT_ENABLED
| ERROR_INVALID_SEGDPL
| ERROR_AUTODATASEG_EXCEEDS_64k
| ERROR_RING2SEG_MUST_BE_MOVABLE
| ERROR_RELOC_CHAIN_XEEDS_SEGLIM
| ERROR_INFLOOP_IN_RELOC_CHAIN => ENOEXEC,
ERROR_INVALID_HANDLE | ERROR_INVALID_TARGET_HANDLE | ERROR_DIRECT_ACCESS_HANDLE => EBADF,
ERROR_WAIT_NO_CHILDREN | ERROR_CHILD_NOT_COMPLETE => ECHILD,
ERROR_NO_PROC_SLOTS | ERROR_MAX_THRDS_REACHED | ERROR_NESTING_NOT_ALLOWED => EAGAIN,
ERROR_ARENA_TRASHED
| ERROR_NOT_ENOUGH_MEMORY
| ERROR_INVALID_BLOCK
| ERROR_NOT_ENOUGH_QUOTA => ENOMEM,
ERROR_ACCESS_DENIED
| ERROR_CURRENT_DIRECTORY
| ERROR_WRITE_PROTECT
| ERROR_BAD_UNIT
| ERROR_NOT_READY
| ERROR_BAD_COMMAND
| ERROR_CRC
| ERROR_BAD_LENGTH
| ERROR_SEEK
| ERROR_NOT_DOS_DISK
| ERROR_SECTOR_NOT_FOUND
| ERROR_OUT_OF_PAPER
| ERROR_WRITE_FAULT
| ERROR_READ_FAULT
| ERROR_GEN_FAILURE
| ERROR_SHARING_VIOLATION
| ERROR_LOCK_VIOLATION
| ERROR_WRONG_DISK
| ERROR_SHARING_BUFFER_EXCEEDED
| ERROR_NETWORK_ACCESS_DENIED
| ERROR_CANNOT_MAKE
| ERROR_FAIL_I24
| ERROR_DRIVE_LOCKED
| ERROR_SEEK_ON_DEVICE
| ERROR_NOT_LOCKED
| ERROR_LOCK_FAILED
| 35 => EACCES,
ERROR_FILE_EXISTS | ERROR_ALREADY_EXISTS => EEXIST,
ERROR_NOT_SAME_DEVICE => EXDEV,
ERROR_DIRECTORY => ENOTDIR,
ERROR_TOO_MANY_OPEN_FILES => EMFILE,
ERROR_DISK_FULL => ENOSPC,
ERROR_BROKEN_PIPE | ERROR_NO_DATA => EPIPE,
ERROR_DIR_NOT_EMPTY => ENOTEMPTY,
ERROR_NO_UNICODE_TRANSLATION => EILSEQ,
ERROR_INVALID_FUNCTION
| ERROR_INVALID_ACCESS
| ERROR_INVALID_DATA
| ERROR_INVALID_PARAMETER
| ERROR_NEGATIVE_SEEK => EINVAL,
_ => EINVAL,
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/lock.rs | crates/common/src/lock.rs | //! A module containing [`lock_api`]-based lock types that are or are not `Send + Sync`
//! depending on whether the `threading` feature of this module is enabled.
use lock_api::{
MappedMutexGuard, MappedRwLockReadGuard, MappedRwLockWriteGuard, Mutex, MutexGuard, RwLock,
RwLockReadGuard, RwLockUpgradableReadGuard, RwLockWriteGuard,
};
cfg_if::cfg_if! {
if #[cfg(feature = "threading")] {
pub use parking_lot::{RawMutex, RawRwLock, RawThreadId};
pub use once_cell::sync::{Lazy, OnceCell};
} else {
mod cell_lock;
pub use cell_lock::{RawCellMutex as RawMutex, RawCellRwLock as RawRwLock, SingleThreadId as RawThreadId};
pub use once_cell::unsync::{Lazy, OnceCell};
}
}
mod immutable_mutex;
pub use immutable_mutex::*;
mod thread_mutex;
pub use thread_mutex::*;
pub type PyMutex<T> = Mutex<RawMutex, T>;
pub type PyMutexGuard<'a, T> = MutexGuard<'a, RawMutex, T>;
pub type PyMappedMutexGuard<'a, T> = MappedMutexGuard<'a, RawMutex, T>;
pub type PyImmutableMappedMutexGuard<'a, T> = ImmutableMappedMutexGuard<'a, RawMutex, T>;
pub type PyThreadMutex<T> = ThreadMutex<RawMutex, RawThreadId, T>;
pub type PyThreadMutexGuard<'a, T> = ThreadMutexGuard<'a, RawMutex, RawThreadId, T>;
pub type PyMappedThreadMutexGuard<'a, T> = MappedThreadMutexGuard<'a, RawMutex, RawThreadId, T>;
pub type PyRwLock<T> = RwLock<RawRwLock, T>;
pub type PyRwLockUpgradableReadGuard<'a, T> = RwLockUpgradableReadGuard<'a, RawRwLock, T>;
pub type PyRwLockReadGuard<'a, T> = RwLockReadGuard<'a, RawRwLock, T>;
pub type PyMappedRwLockReadGuard<'a, T> = MappedRwLockReadGuard<'a, RawRwLock, T>;
pub type PyRwLockWriteGuard<'a, T> = RwLockWriteGuard<'a, RawRwLock, T>;
pub type PyMappedRwLockWriteGuard<'a, T> = MappedRwLockWriteGuard<'a, RawRwLock, T>;
// can add fn const_{mutex,rw_lock}() if necessary, but we probably won't need to
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/boxvec.rs | crates/common/src/boxvec.rs | // spell-checker:disable
//! An unresizable vector backed by a `Box<[T]>`
#![allow(clippy::needless_lifetimes)]
use alloc::{fmt, slice};
use core::{
borrow::{Borrow, BorrowMut},
cmp,
mem::{self, MaybeUninit},
ops::{Bound, Deref, DerefMut, RangeBounds},
ptr,
};
pub struct BoxVec<T> {
xs: Box<[MaybeUninit<T>]>,
len: usize,
}
impl<T> Drop for BoxVec<T> {
fn drop(&mut self) {
self.clear();
// MaybeUninit inhibits array's drop
}
}
macro_rules! panic_oob {
($method_name:expr, $index:expr, $len:expr) => {
panic!(
concat!(
"BoxVec::",
$method_name,
": index {} is out of bounds in vector of length {}"
),
$index, $len
)
};
}
impl<T> BoxVec<T> {
pub fn new(n: usize) -> Self {
Self {
xs: Box::new_uninit_slice(n),
len: 0,
}
}
#[inline]
pub const fn len(&self) -> usize {
self.len
}
#[inline]
pub const fn is_empty(&self) -> bool {
self.len() == 0
}
#[inline]
pub const fn capacity(&self) -> usize {
self.xs.len()
}
pub const fn is_full(&self) -> bool {
self.len() == self.capacity()
}
pub const fn remaining_capacity(&self) -> usize {
self.capacity() - self.len()
}
pub fn push(&mut self, element: T) {
self.try_push(element).unwrap()
}
pub fn try_push(&mut self, element: T) -> Result<(), CapacityError<T>> {
if self.len() < self.capacity() {
unsafe {
self.push_unchecked(element);
}
Ok(())
} else {
Err(CapacityError::new(element))
}
}
/// # Safety
/// Must ensure that self.len() < self.capacity()
pub unsafe fn push_unchecked(&mut self, element: T) {
let len = self.len();
debug_assert!(len < self.capacity());
// SAFETY: len < capacity
unsafe {
ptr::write(self.get_unchecked_ptr(len), element);
self.set_len(len + 1);
}
}
/// Get pointer to where element at `index` would be
unsafe fn get_unchecked_ptr(&mut self, index: usize) -> *mut T {
unsafe { self.xs.as_mut_ptr().add(index).cast() }
}
pub fn insert(&mut self, index: usize, element: T) {
self.try_insert(index, element).unwrap()
}
pub fn try_insert(&mut self, index: usize, element: T) -> Result<(), CapacityError<T>> {
if index > self.len() {
panic_oob!("try_insert", index, self.len())
}
if self.len() == self.capacity() {
return Err(CapacityError::new(element));
}
let len = self.len();
// follows is just like Vec<T>
unsafe {
// infallible
// The spot to put the new value
{
let p: *mut _ = self.get_unchecked_ptr(index);
// Shift everything over to make space. (Duplicating the
// `index`th element into two consecutive places.)
ptr::copy(p, p.offset(1), len - index);
// Write it in, overwriting the first copy of the `index`th
// element.
ptr::write(p, element);
}
self.set_len(len + 1);
}
Ok(())
}
pub fn pop(&mut self) -> Option<T> {
if self.is_empty() {
return None;
}
unsafe {
let new_len = self.len() - 1;
self.set_len(new_len);
Some(ptr::read(self.get_unchecked_ptr(new_len)))
}
}
pub fn swap_remove(&mut self, index: usize) -> T {
self.swap_pop(index)
.unwrap_or_else(|| panic_oob!("swap_remove", index, self.len()))
}
pub fn swap_pop(&mut self, index: usize) -> Option<T> {
let len = self.len();
if index >= len {
return None;
}
self.swap(index, len - 1);
self.pop()
}
pub fn remove(&mut self, index: usize) -> T {
self.pop_at(index)
.unwrap_or_else(|| panic_oob!("remove", index, self.len()))
}
pub fn pop_at(&mut self, index: usize) -> Option<T> {
if index >= self.len() {
None
} else {
self.drain(index..=index).next()
}
}
pub fn truncate(&mut self, new_len: usize) {
unsafe {
if new_len < self.len() {
let tail: *mut [_] = &mut self[new_len..];
self.len = new_len;
ptr::drop_in_place(tail);
}
}
}
/// Remove all elements in the vector.
pub fn clear(&mut self) {
self.truncate(0)
}
/// Retains only the elements specified by the predicate.
///
/// In other words, remove all elements `e` such that `f(&mut e)` returns false.
/// This method operates in place and preserves the order of the retained
/// elements.
pub fn retain<F>(&mut self, mut f: F)
where
F: FnMut(&mut T) -> bool,
{
let len = self.len();
let mut del = 0;
{
let v = &mut **self;
for i in 0..len {
if !f(&mut v[i]) {
del += 1;
} else if del > 0 {
v.swap(i - del, i);
}
}
}
if del > 0 {
self.drain(len - del..);
}
}
/// Set the vector’s length without dropping or moving out elements
///
/// This method is `unsafe` because it changes the notion of the
/// number of “valid” elements in the vector. Use with care.
///
/// This method uses *debug assertions* to check that `length` is
/// not greater than the capacity.
///
/// # Safety
/// Must ensure that length <= self.capacity()
pub unsafe fn set_len(&mut self, length: usize) {
debug_assert!(length <= self.capacity());
self.len = length;
}
/// Copy and appends all elements in a slice to the `BoxVec`.
///
/// # Errors
///
/// This method will return an error if the capacity left (see
/// [`remaining_capacity`]) is smaller then the length of the provided
/// slice.
///
/// [`remaining_capacity`]: #method.remaining_capacity
pub fn try_extend_from_slice(&mut self, other: &[T]) -> Result<(), CapacityError>
where
T: Copy,
{
if self.remaining_capacity() < other.len() {
return Err(CapacityError::new(()));
}
let self_len = self.len();
let other_len = other.len();
unsafe {
let dst = self.as_mut_ptr().add(self_len);
ptr::copy_nonoverlapping(other.as_ptr(), dst, other_len);
self.set_len(self_len + other_len);
}
Ok(())
}
/// Create a draining iterator that removes the specified range in the vector
/// and yields the removed items from start to end. The element range is
/// removed even if the iterator is not consumed until the end.
///
/// Note: It is unspecified how many elements are removed from the vector,
/// if the `Drain` value is leaked.
///
/// **Panics** if the starting point is greater than the end point or if
/// the end point is greater than the length of the vector.
pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
where
R: RangeBounds<usize>,
{
// Memory safety
//
// When the Drain is first created, it shortens the length of
// the source vector to make sure no uninitialized or moved-from elements
// are accessible at all if the Drain's destructor never gets to run.
//
// Drain will ptr::read out the values to remove.
// When finished, remaining tail of the vec is copied back to cover
// the hole, and the vector length is restored to the new length.
//
let len = self.len();
let start = match range.start_bound() {
Bound::Unbounded => 0,
Bound::Included(&i) => i,
Bound::Excluded(&i) => i.saturating_add(1),
};
let end = match range.end_bound() {
Bound::Excluded(&j) => j,
Bound::Included(&j) => j.saturating_add(1),
Bound::Unbounded => len,
};
self.drain_range(start, end)
}
fn drain_range(&mut self, start: usize, end: usize) -> Drain<'_, T> {
let len = self.len();
// bounds check happens here (before length is changed!)
let range_slice: *const _ = &self[start..end];
// Calling `set_len` creates a fresh and thus unique mutable references, making all
// older aliases we created invalid. So we cannot call that function.
self.len = start;
unsafe {
Drain {
tail_start: end,
tail_len: len - end,
iter: (*range_slice).iter(),
vec: ptr::NonNull::from(self),
}
}
}
/// Return a slice containing all elements of the vector.
pub fn as_slice(&self) -> &[T] {
self
}
/// Return a mutable slice containing all elements of the vector.
pub fn as_mut_slice(&mut self) -> &mut [T] {
self
}
/// Return a raw pointer to the vector's buffer.
#[inline]
pub fn as_ptr(&self) -> *const T {
self.xs.as_ptr().cast()
}
/// Return a raw mutable pointer to the vector's buffer.
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut T {
self.xs.as_mut_ptr().cast()
}
}
impl<T> Deref for BoxVec<T> {
type Target = [T];
#[inline]
fn deref(&self) -> &[T] {
unsafe { slice::from_raw_parts(self.as_ptr(), self.len()) }
}
}
impl<T> DerefMut for BoxVec<T> {
#[inline]
fn deref_mut(&mut self) -> &mut [T] {
let len = self.len();
unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), len) }
}
}
/// Iterate the `BoxVec` with references to each element.
impl<'a, T> IntoIterator for &'a BoxVec<T> {
type Item = &'a T;
type IntoIter = slice::Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
/// Iterate the `BoxVec` with mutable references to each element.
impl<'a, T> IntoIterator for &'a mut BoxVec<T> {
type Item = &'a mut T;
type IntoIter = slice::IterMut<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
/// Iterate the `BoxVec` with each element by value.
///
/// The vector is consumed by this operation.
impl<T> IntoIterator for BoxVec<T> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
IntoIter { index: 0, v: self }
}
}
/// By-value iterator for `BoxVec`.
pub struct IntoIter<T> {
index: usize,
v: BoxVec<T>,
}
impl<T> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
if self.index == self.v.len {
None
} else {
unsafe {
let index = self.index;
self.index += 1;
Some(ptr::read(self.v.get_unchecked_ptr(index)))
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.v.len() - self.index;
(len, Some(len))
}
}
impl<T> DoubleEndedIterator for IntoIter<T> {
fn next_back(&mut self) -> Option<T> {
if self.index == self.v.len {
None
} else {
unsafe {
let new_len = self.v.len() - 1;
self.v.set_len(new_len);
Some(ptr::read(self.v.get_unchecked_ptr(new_len)))
}
}
}
}
impl<T> ExactSizeIterator for IntoIter<T> {}
impl<T> Drop for IntoIter<T> {
fn drop(&mut self) {
// panic safety: Set length to 0 before dropping elements.
let index = self.index;
let len = self.v.len();
unsafe {
self.v.set_len(0);
let elements = slice::from_raw_parts_mut(self.v.get_unchecked_ptr(index), len - index);
ptr::drop_in_place(elements);
}
}
}
impl<T> fmt::Debug for IntoIter<T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(&self.v[self.index..]).finish()
}
}
/// A draining iterator for `BoxVec`.
pub struct Drain<'a, T> {
/// Index of tail to preserve
tail_start: usize,
/// Length of tail
tail_len: usize,
/// Current remaining range to remove
iter: slice::Iter<'a, T>,
vec: ptr::NonNull<BoxVec<T>>,
}
unsafe impl<T: Sync> Sync for Drain<'_, T> {}
unsafe impl<T: Sync> Send for Drain<'_, T> {}
impl<T> Iterator for Drain<'_, T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.iter
.next()
.map(|elt| unsafe { ptr::read(elt as *const _) })
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<T> DoubleEndedIterator for Drain<'_, T> {
fn next_back(&mut self) -> Option<Self::Item> {
self.iter
.next_back()
.map(|elt| unsafe { ptr::read(elt as *const _) })
}
}
impl<T> ExactSizeIterator for Drain<'_, T> {}
impl<'a, T> Drain<'a, T> {
pub fn as_slice(&self) -> &'a [T] {
self.iter.as_slice()
}
}
impl<T> Drop for Drain<'_, T> {
fn drop(&mut self) {
// len is currently 0 so panicking while dropping will not cause a double drop.
for _ in self.by_ref() {}
if self.tail_len > 0 {
unsafe {
let source_vec = self.vec.as_mut();
// memmove back untouched tail, update to new length
let start = source_vec.len();
let tail = self.tail_start;
let src = source_vec.as_ptr().add(tail);
let dst = source_vec.as_mut_ptr().add(start);
ptr::copy(src, dst, self.tail_len);
source_vec.set_len(start + self.tail_len);
}
}
}
}
struct ScopeExitGuard<T, Data, F>
where
F: FnMut(&Data, &mut T),
{
value: T,
data: Data,
f: F,
}
impl<T, Data, F> Drop for ScopeExitGuard<T, Data, F>
where
F: FnMut(&Data, &mut T),
{
fn drop(&mut self) {
(self.f)(&self.data, &mut self.value)
}
}
/// Extend the `BoxVec` with an iterator.
///
/// Does not extract more items than there is space for. No error
/// occurs if there are more iterator elements.
impl<T> Extend<T> for BoxVec<T> {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
let take = self.capacity() - self.len();
unsafe {
let len = self.len();
let mut ptr = raw_ptr_add(self.as_mut_ptr(), len);
let end_ptr = raw_ptr_add(ptr, take);
// Keep the length in a separate variable, write it back on scope
// exit. To help the compiler with alias analysis and stuff.
// We update the length to handle panic in the iteration of the
// user's iterator, without dropping any elements on the floor.
let mut guard = ScopeExitGuard {
value: &mut self.len,
data: len,
f: move |&len, self_len| {
**self_len = len;
},
};
let mut iter = iter.into_iter();
loop {
if core::ptr::eq(ptr, end_ptr) {
break;
}
if let Some(elt) = iter.next() {
raw_ptr_write(ptr, elt);
ptr = raw_ptr_add(ptr, 1);
guard.data += 1;
} else {
break;
}
}
}
}
}
/// Rawptr add but uses arithmetic distance for ZST
unsafe fn raw_ptr_add<T>(ptr: *mut T, offset: usize) -> *mut T {
if mem::size_of::<T>() == 0 {
// Special case for ZST
(ptr as usize).wrapping_add(offset) as _
} else {
unsafe { ptr.add(offset) }
}
}
unsafe fn raw_ptr_write<T>(ptr: *mut T, value: T) {
if mem::size_of::<T>() == 0 {
/* nothing */
} else {
unsafe { ptr::write(ptr, value) }
}
}
impl<T> Clone for BoxVec<T>
where
T: Clone,
{
fn clone(&self) -> Self {
let mut new = Self::new(self.capacity());
new.extend(self.iter().cloned());
new
}
fn clone_from(&mut self, rhs: &Self) {
// recursive case for the common prefix
let prefix = cmp::min(self.len(), rhs.len());
self[..prefix].clone_from_slice(&rhs[..prefix]);
if prefix < self.len() {
// rhs was shorter
for _ in 0..self.len() - prefix {
self.pop();
}
} else {
let rhs_elems = rhs[self.len()..].iter().cloned();
self.extend(rhs_elems);
}
}
}
impl<T> PartialEq for BoxVec<T>
where
T: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
**self == **other
}
}
impl<T> PartialEq<[T]> for BoxVec<T>
where
T: PartialEq,
{
fn eq(&self, other: &[T]) -> bool {
**self == *other
}
}
impl<T> Eq for BoxVec<T> where T: Eq {}
impl<T> Borrow<[T]> for BoxVec<T> {
fn borrow(&self) -> &[T] {
self
}
}
impl<T> BorrowMut<[T]> for BoxVec<T> {
fn borrow_mut(&mut self) -> &mut [T] {
self
}
}
impl<T> AsRef<[T]> for BoxVec<T> {
fn as_ref(&self) -> &[T] {
self
}
}
impl<T> AsMut<[T]> for BoxVec<T> {
fn as_mut(&mut self) -> &mut [T] {
self
}
}
impl<T> fmt::Debug for BoxVec<T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
(**self).fmt(f)
}
}
/// Error value indicating insufficient capacity
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
pub struct CapacityError<T = ()> {
element: T,
}
impl<T> CapacityError<T> {
/// Create a new `CapacityError` from `element`.
pub const fn new(element: T) -> Self {
Self { element }
}
/// Extract the overflowing element
pub fn element(self) -> T {
self.element
}
/// Convert into a `CapacityError` that does not carry an element.
pub fn simplify(self) -> CapacityError {
CapacityError { element: () }
}
}
const CAPERROR: &str = "insufficient capacity";
impl<T> core::error::Error for CapacityError<T> {}
impl<T> fmt::Display for CapacityError<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{CAPERROR}")
}
}
impl<T> fmt::Debug for CapacityError<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "capacity error: {CAPERROR}")
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/rand.rs | crates/common/src/rand.rs | /// Get `N` bytes of random data.
///
/// This function is mildly expensive to call, as it fetches random data
/// directly from the OS entropy source.
///
/// # Panics
///
/// Panics if the OS entropy source returns an error.
pub fn os_random<const N: usize>() -> [u8; N] {
let mut buf = [0u8; N];
getrandom::fill(&mut buf).unwrap();
buf
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/macros.rs | crates/common/src/macros.rs | /// Suppress the MSVC invalid parameter handler, which by default crashes the process. Does nothing
/// on non-MSVC targets.
#[macro_export]
macro_rules! suppress_iph {
($e:expr) => {
$crate::__suppress_iph_impl!($e)
};
}
#[macro_export]
#[doc(hidden)]
#[cfg(all(windows, target_env = "msvc"))]
macro_rules! __suppress_iph_impl {
($e:expr) => {{
let old = $crate::__macro_private::_set_thread_local_invalid_parameter_handler(
$crate::__macro_private::silent_iph_handler,
);
let ret = $e;
$crate::__macro_private::_set_thread_local_invalid_parameter_handler(old);
ret
}};
}
#[cfg(not(all(windows, target_env = "msvc")))]
#[macro_export]
#[doc(hidden)]
macro_rules! __suppress_iph_impl {
($e:expr) => {
$e
};
}
#[doc(hidden)]
pub mod __macro_private {
#[cfg(target_env = "msvc")]
type InvalidParamHandler = extern "C" fn(
*const libc::wchar_t,
*const libc::wchar_t,
*const libc::wchar_t,
libc::c_uint,
libc::uintptr_t,
);
#[cfg(target_env = "msvc")]
unsafe extern "C" {
pub fn _set_thread_local_invalid_parameter_handler(
pNew: InvalidParamHandler,
) -> InvalidParamHandler;
}
#[cfg(target_env = "msvc")]
pub extern "C" fn silent_iph_handler(
_: *const libc::wchar_t,
_: *const libc::wchar_t,
_: *const libc::wchar_t,
_: libc::c_uint,
_: libc::uintptr_t,
) {
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/windows.rs | crates/common/src/windows.rs | use rustpython_wtf8::Wtf8;
use std::{
ffi::{OsStr, OsString},
os::windows::ffi::{OsStrExt, OsStringExt},
};
/// _MAX_ENV from Windows CRT stdlib.h - maximum environment variable size
pub const _MAX_ENV: usize = 32767;
pub trait ToWideString {
fn to_wide(&self) -> Vec<u16>;
fn to_wide_with_nul(&self) -> Vec<u16>;
}
impl<T> ToWideString for T
where
T: AsRef<OsStr>,
{
fn to_wide(&self) -> Vec<u16> {
self.as_ref().encode_wide().collect()
}
fn to_wide_with_nul(&self) -> Vec<u16> {
self.as_ref().encode_wide().chain(Some(0)).collect()
}
}
impl ToWideString for OsStr {
fn to_wide(&self) -> Vec<u16> {
self.encode_wide().collect()
}
fn to_wide_with_nul(&self) -> Vec<u16> {
self.encode_wide().chain(Some(0)).collect()
}
}
impl ToWideString for Wtf8 {
fn to_wide(&self) -> Vec<u16> {
self.encode_wide().collect()
}
fn to_wide_with_nul(&self) -> Vec<u16> {
self.encode_wide().chain(Some(0)).collect()
}
}
pub trait FromWideString
where
Self: Sized,
{
fn from_wides_until_nul(wide: &[u16]) -> Self;
}
impl FromWideString for OsString {
fn from_wides_until_nul(wide: &[u16]) -> OsString {
let len = wide.iter().take_while(|&&c| c != 0).count();
OsString::from_wide(&wide[..len])
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/rc.rs | crates/common/src/rc.rs | #[cfg(not(feature = "threading"))]
use alloc::rc::Rc;
#[cfg(feature = "threading")]
use alloc::sync::Arc;
// type aliases instead of new-types because you can't do `fn method(self: PyRc<Self>)` with a
// newtype; requires the arbitrary_self_types unstable feature
#[cfg(feature = "threading")]
pub type PyRc<T> = Arc<T>;
#[cfg(not(feature = "threading"))]
pub type PyRc<T> = Rc<T>;
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/crt_fd.rs | crates/common/src/crt_fd.rs | //! A module implementing an io type backed by the C runtime's file descriptors, i.e. what's
//! returned from libc::open, even on windows.
use alloc::fmt;
use core::cmp;
use std::{ffi, io};
#[cfg(not(windows))]
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
#[cfg(windows)]
use std::os::windows::io::BorrowedHandle;
mod c {
pub(super) use libc::*;
#[cfg(windows)]
pub(super) use libc::commit as fsync;
#[cfg(windows)]
unsafe extern "C" {
#[link_name = "_chsize_s"]
pub(super) fn ftruncate(fd: i32, len: i64) -> i32;
}
}
// this is basically what CPython has for Py_off_t; windows uses long long
// for offsets, other platforms just use off_t
#[cfg(not(windows))]
pub type Offset = c::off_t;
#[cfg(windows)]
pub type Offset = c::c_longlong;
#[cfg(not(windows))]
pub type Raw = RawFd;
#[cfg(windows)]
pub type Raw = i32;
#[inline]
fn cvt<I: num_traits::PrimInt>(ret: I) -> io::Result<I> {
if ret < I::zero() {
// CRT functions set errno, not GetLastError(), so use errno_io_error
Err(crate::os::errno_io_error())
} else {
Ok(ret)
}
}
fn cvt_fd(ret: Raw) -> io::Result<Owned> {
cvt(ret).map(|fd| unsafe { Owned::from_raw(fd) })
}
const MAX_RW: usize = if cfg!(any(windows, target_vendor = "apple")) {
i32::MAX as usize
} else {
isize::MAX as usize
};
#[cfg(not(windows))]
type OwnedInner = OwnedFd;
#[cfg(not(windows))]
type BorrowedInner<'fd> = BorrowedFd<'fd>;
#[cfg(windows)]
mod win {
use super::*;
use std::marker::PhantomData;
use std::mem::ManuallyDrop;
#[repr(transparent)]
pub(super) struct OwnedInner(i32);
impl OwnedInner {
#[inline]
pub unsafe fn from_raw_fd(fd: Raw) -> Self {
Self(fd)
}
#[inline]
pub fn as_raw_fd(&self) -> Raw {
self.0
}
#[inline]
pub fn into_raw_fd(self) -> Raw {
let me = ManuallyDrop::new(self);
me.0
}
}
impl Drop for OwnedInner {
#[inline]
fn drop(&mut self) {
let _ = _close(self.0);
}
}
#[derive(Copy, Clone)]
#[repr(transparent)]
pub(super) struct BorrowedInner<'fd> {
fd: Raw,
_marker: PhantomData<&'fd Owned>,
}
impl BorrowedInner<'_> {
#[inline]
pub const unsafe fn borrow_raw(fd: Raw) -> Self {
Self {
fd,
_marker: PhantomData,
}
}
#[inline]
pub fn as_raw_fd(&self) -> Raw {
self.fd
}
}
}
#[cfg(windows)]
use self::win::{BorrowedInner, OwnedInner};
#[repr(transparent)]
pub struct Owned {
inner: OwnedInner,
}
impl fmt::Debug for Owned {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("crt_fd::Owned")
.field(&self.as_raw())
.finish()
}
}
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct Borrowed<'fd> {
inner: BorrowedInner<'fd>,
}
impl<'fd> PartialEq for Borrowed<'fd> {
fn eq(&self, other: &Self) -> bool {
self.as_raw() == other.as_raw()
}
}
impl<'fd> Eq for Borrowed<'fd> {}
impl fmt::Debug for Borrowed<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("crt_fd::Borrowed")
.field(&self.as_raw())
.finish()
}
}
impl Owned {
/// Create a `crt_fd::Owned` from a raw file descriptor.
///
/// # Safety
///
/// `fd` must be a valid file descriptor.
#[inline]
pub unsafe fn from_raw(fd: Raw) -> Self {
let inner = unsafe { OwnedInner::from_raw_fd(fd) };
Self { inner }
}
/// Create a `crt_fd::Owned` from a raw file descriptor.
///
/// Returns an error if `fd` is -1.
///
/// # Safety
///
/// `fd` must be a valid file descriptor.
#[inline]
pub unsafe fn try_from_raw(fd: Raw) -> io::Result<Self> {
if fd == -1 {
Err(ebadf())
} else {
Ok(unsafe { Self::from_raw(fd) })
}
}
#[inline]
pub fn borrow(&self) -> Borrowed<'_> {
unsafe { Borrowed::borrow_raw(self.as_raw()) }
}
#[inline]
pub fn as_raw(&self) -> Raw {
self.inner.as_raw_fd()
}
#[inline]
pub fn into_raw(self) -> Raw {
self.inner.into_raw_fd()
}
pub fn leak<'fd>(self) -> Borrowed<'fd> {
unsafe { Borrowed::borrow_raw(self.into_raw()) }
}
}
#[cfg(unix)]
impl From<Owned> for OwnedFd {
fn from(fd: Owned) -> Self {
fd.inner
}
}
#[cfg(unix)]
impl From<OwnedFd> for Owned {
fn from(fd: OwnedFd) -> Self {
Self { inner: fd }
}
}
#[cfg(unix)]
impl AsFd for Owned {
fn as_fd(&self) -> BorrowedFd<'_> {
self.inner.as_fd()
}
}
#[cfg(unix)]
impl AsRawFd for Owned {
fn as_raw_fd(&self) -> RawFd {
self.as_raw()
}
}
#[cfg(unix)]
impl FromRawFd for Owned {
unsafe fn from_raw_fd(fd: RawFd) -> Self {
unsafe { Self::from_raw(fd) }
}
}
#[cfg(unix)]
impl IntoRawFd for Owned {
fn into_raw_fd(self) -> RawFd {
self.into_raw()
}
}
impl<'fd> Borrowed<'fd> {
/// Create a `crt_fd::Borrowed` from a raw file descriptor.
///
/// # Safety
///
/// `fd` must be a valid file descriptor.
#[inline]
pub const unsafe fn borrow_raw(fd: Raw) -> Self {
let inner = unsafe { BorrowedInner::borrow_raw(fd) };
Self { inner }
}
/// Create a `crt_fd::Borrowed` from a raw file descriptor.
///
/// Returns an error if `fd` is -1.
///
/// # Safety
///
/// `fd` must be a valid file descriptor.
#[inline]
pub unsafe fn try_borrow_raw(fd: Raw) -> io::Result<Self> {
if fd == -1 {
Err(ebadf())
} else {
Ok(unsafe { Self::borrow_raw(fd) })
}
}
#[inline]
pub fn as_raw(self) -> Raw {
self.inner.as_raw_fd()
}
}
#[cfg(unix)]
impl<'fd> From<Borrowed<'fd>> for BorrowedFd<'fd> {
fn from(fd: Borrowed<'fd>) -> Self {
fd.inner
}
}
#[cfg(unix)]
impl<'fd> From<BorrowedFd<'fd>> for Borrowed<'fd> {
fn from(fd: BorrowedFd<'fd>) -> Self {
Self { inner: fd }
}
}
#[cfg(unix)]
impl AsFd for Borrowed<'_> {
fn as_fd(&self) -> BorrowedFd<'_> {
self.inner.as_fd()
}
}
#[cfg(unix)]
impl AsRawFd for Borrowed<'_> {
fn as_raw_fd(&self) -> RawFd {
self.as_raw()
}
}
#[inline]
fn ebadf() -> io::Error {
io::Error::from_raw_os_error(c::EBADF)
}
pub fn open(path: &ffi::CStr, flags: i32, mode: i32) -> io::Result<Owned> {
cvt_fd(unsafe { c::open(path.as_ptr(), flags, mode) })
}
#[cfg(windows)]
pub fn wopen(path: &widestring::WideCStr, flags: i32, mode: i32) -> io::Result<Owned> {
cvt_fd(unsafe { suppress_iph!(c::wopen(path.as_ptr(), flags, mode)) })
}
#[cfg(all(any(unix, target_os = "wasi"), not(target_os = "redox")))]
pub fn openat(dir: Borrowed<'_>, path: &ffi::CStr, flags: i32, mode: i32) -> io::Result<Owned> {
cvt_fd(unsafe { c::openat(dir.as_raw(), path.as_ptr(), flags, mode) })
}
pub fn fsync(fd: Borrowed<'_>) -> io::Result<()> {
cvt(unsafe { suppress_iph!(c::fsync(fd.as_raw())) })?;
Ok(())
}
fn _close(fd: Raw) -> io::Result<()> {
cvt(unsafe { suppress_iph!(c::close(fd)) })?;
Ok(())
}
pub fn close(fd: Owned) -> io::Result<()> {
_close(fd.into_raw())
}
pub fn ftruncate(fd: Borrowed<'_>, len: Offset) -> io::Result<()> {
let ret = unsafe { suppress_iph!(c::ftruncate(fd.as_raw(), len)) };
// On Windows, _chsize_s returns 0 on success, or a positive error code (errno value) on failure.
// On other platforms, ftruncate returns 0 on success, or -1 on failure with errno set.
#[cfg(windows)]
{
if ret != 0 {
// _chsize_s returns errno directly, convert to Windows error code
let winerror = crate::os::errno_to_winerror(ret);
return Err(io::Error::from_raw_os_error(winerror));
}
}
#[cfg(not(windows))]
{
cvt(ret)?;
}
Ok(())
}
#[cfg(windows)]
pub fn as_handle(fd: Borrowed<'_>) -> io::Result<BorrowedHandle<'_>> {
use windows_sys::Win32::Foundation::{HANDLE, INVALID_HANDLE_VALUE};
unsafe extern "C" {
fn _get_osfhandle(fd: Borrowed<'_>) -> c::intptr_t;
}
let handle = unsafe { suppress_iph!(_get_osfhandle(fd)) };
if handle as HANDLE == INVALID_HANDLE_VALUE {
// _get_osfhandle is a CRT function that sets errno, not GetLastError()
Err(crate::os::errno_io_error())
} else {
Ok(unsafe { BorrowedHandle::borrow_raw(handle as _) })
}
}
fn _write(fd: Raw, buf: &[u8]) -> io::Result<usize> {
let count = cmp::min(buf.len(), MAX_RW);
let n = cvt(unsafe { suppress_iph!(c::write(fd, buf.as_ptr() as _, count as _)) })?;
Ok(n as usize)
}
fn _read(fd: Raw, buf: &mut [u8]) -> io::Result<usize> {
let count = cmp::min(buf.len(), MAX_RW);
let n = cvt(unsafe { suppress_iph!(libc::read(fd, buf.as_mut_ptr() as _, count as _)) })?;
Ok(n as usize)
}
pub fn write(fd: Borrowed<'_>, buf: &[u8]) -> io::Result<usize> {
_write(fd.as_raw(), buf)
}
pub fn read(fd: Borrowed<'_>, buf: &mut [u8]) -> io::Result<usize> {
_read(fd.as_raw(), buf)
}
macro_rules! impl_rw {
($t:ty) => {
impl io::Write for $t {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
_write(self.as_raw(), buf)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl io::Read for $t {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
_read(self.as_raw(), buf)
}
}
};
}
impl_rw!(Owned);
impl_rw!(Borrowed<'_>);
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/format.rs | crates/common/src/format.rs | // spell-checker:ignore ddfe
use core::ops::Deref;
use core::{cmp, str::FromStr};
use itertools::{Itertools, PeekingNext};
use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_bigint::{BigInt, Sign};
use num_complex::Complex64;
use num_traits::FromPrimitive;
use num_traits::{Signed, cast::ToPrimitive};
use rustpython_literal::float;
use rustpython_literal::format::Case;
use crate::wtf8::{CodePoint, Wtf8, Wtf8Buf};
trait FormatParse {
fn parse(text: &Wtf8) -> (Option<Self>, &Wtf8)
where
Self: Sized;
}
#[derive(Debug, Copy, Clone, PartialEq)]
#[repr(u8)]
pub enum FormatConversion {
Str = b's',
Repr = b'r',
Ascii = b'b',
Bytes = b'a',
}
impl FormatParse for FormatConversion {
fn parse(text: &Wtf8) -> (Option<Self>, &Wtf8) {
let Some(conversion) = Self::from_string(text) else {
return (None, text);
};
let mut chars = text.code_points();
chars.next(); // Consume the bang
chars.next(); // Consume one r,s,a char
(Some(conversion), chars.as_wtf8())
}
}
impl FormatConversion {
pub fn from_char(c: CodePoint) -> Option<Self> {
match c.to_char_lossy() {
's' => Some(Self::Str),
'r' => Some(Self::Repr),
'a' => Some(Self::Ascii),
'b' => Some(Self::Bytes),
_ => None,
}
}
fn from_string(text: &Wtf8) -> Option<Self> {
let mut chars = text.code_points();
if chars.next()? != '!' {
return None;
}
Self::from_char(chars.next()?)
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum FormatAlign {
Left,
Right,
AfterSign,
Center,
}
impl FormatAlign {
fn from_char(c: CodePoint) -> Option<Self> {
match c.to_char_lossy() {
'<' => Some(Self::Left),
'>' => Some(Self::Right),
'=' => Some(Self::AfterSign),
'^' => Some(Self::Center),
_ => None,
}
}
}
impl FormatParse for FormatAlign {
fn parse(text: &Wtf8) -> (Option<Self>, &Wtf8) {
let mut chars = text.code_points();
if let Some(maybe_align) = chars.next().and_then(Self::from_char) {
(Some(maybe_align), chars.as_wtf8())
} else {
(None, text)
}
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum FormatSign {
Plus,
Minus,
MinusOrSpace,
}
impl FormatParse for FormatSign {
fn parse(text: &Wtf8) -> (Option<Self>, &Wtf8) {
let mut chars = text.code_points();
match chars.next().and_then(CodePoint::to_char) {
Some('-') => (Some(Self::Minus), chars.as_wtf8()),
Some('+') => (Some(Self::Plus), chars.as_wtf8()),
Some(' ') => (Some(Self::MinusOrSpace), chars.as_wtf8()),
_ => (None, text),
}
}
}
#[derive(Debug, PartialEq)]
pub enum FormatGrouping {
Comma,
Underscore,
}
impl FormatParse for FormatGrouping {
fn parse(text: &Wtf8) -> (Option<Self>, &Wtf8) {
let mut chars = text.code_points();
match chars.next().and_then(CodePoint::to_char) {
Some('_') => (Some(Self::Underscore), chars.as_wtf8()),
Some(',') => (Some(Self::Comma), chars.as_wtf8()),
_ => (None, text),
}
}
}
impl From<&FormatGrouping> for char {
fn from(fg: &FormatGrouping) -> Self {
match fg {
FormatGrouping::Comma => ',',
FormatGrouping::Underscore => '_',
}
}
}
#[derive(Debug, PartialEq)]
pub enum FormatType {
String,
Binary,
Character,
Decimal,
Octal,
Number(Case),
Hex(Case),
Exponent(Case),
GeneralFormat(Case),
FixedPoint(Case),
Percentage,
}
impl From<&FormatType> for char {
fn from(from: &FormatType) -> Self {
match from {
FormatType::String => 's',
FormatType::Binary => 'b',
FormatType::Character => 'c',
FormatType::Decimal => 'd',
FormatType::Octal => 'o',
FormatType::Number(Case::Lower) => 'n',
FormatType::Number(Case::Upper) => 'N',
FormatType::Hex(Case::Lower) => 'x',
FormatType::Hex(Case::Upper) => 'X',
FormatType::Exponent(Case::Lower) => 'e',
FormatType::Exponent(Case::Upper) => 'E',
FormatType::GeneralFormat(Case::Lower) => 'g',
FormatType::GeneralFormat(Case::Upper) => 'G',
FormatType::FixedPoint(Case::Lower) => 'f',
FormatType::FixedPoint(Case::Upper) => 'F',
FormatType::Percentage => '%',
}
}
}
impl FormatParse for FormatType {
fn parse(text: &Wtf8) -> (Option<Self>, &Wtf8) {
let mut chars = text.code_points();
match chars.next().and_then(CodePoint::to_char) {
Some('s') => (Some(Self::String), chars.as_wtf8()),
Some('b') => (Some(Self::Binary), chars.as_wtf8()),
Some('c') => (Some(Self::Character), chars.as_wtf8()),
Some('d') => (Some(Self::Decimal), chars.as_wtf8()),
Some('o') => (Some(Self::Octal), chars.as_wtf8()),
Some('n') => (Some(Self::Number(Case::Lower)), chars.as_wtf8()),
Some('N') => (Some(Self::Number(Case::Upper)), chars.as_wtf8()),
Some('x') => (Some(Self::Hex(Case::Lower)), chars.as_wtf8()),
Some('X') => (Some(Self::Hex(Case::Upper)), chars.as_wtf8()),
Some('e') => (Some(Self::Exponent(Case::Lower)), chars.as_wtf8()),
Some('E') => (Some(Self::Exponent(Case::Upper)), chars.as_wtf8()),
Some('f') => (Some(Self::FixedPoint(Case::Lower)), chars.as_wtf8()),
Some('F') => (Some(Self::FixedPoint(Case::Upper)), chars.as_wtf8()),
Some('g') => (Some(Self::GeneralFormat(Case::Lower)), chars.as_wtf8()),
Some('G') => (Some(Self::GeneralFormat(Case::Upper)), chars.as_wtf8()),
Some('%') => (Some(Self::Percentage), chars.as_wtf8()),
_ => (None, text),
}
}
}
#[derive(Debug, PartialEq)]
pub struct FormatSpec {
conversion: Option<FormatConversion>,
fill: Option<CodePoint>,
align: Option<FormatAlign>,
sign: Option<FormatSign>,
alternate_form: bool,
width: Option<usize>,
grouping_option: Option<FormatGrouping>,
precision: Option<usize>,
format_type: Option<FormatType>,
}
fn get_num_digits(text: &Wtf8) -> usize {
for (index, character) in text.code_point_indices() {
if !character.is_char_and(|c| c.is_ascii_digit()) {
return index;
}
}
text.len()
}
fn parse_fill_and_align(text: &Wtf8) -> (Option<CodePoint>, Option<FormatAlign>, &Wtf8) {
let char_indices: Vec<(usize, CodePoint)> = text.code_point_indices().take(3).collect();
if char_indices.is_empty() {
(None, None, text)
} else if char_indices.len() == 1 {
let (maybe_align, remaining) = FormatAlign::parse(text);
(None, maybe_align, remaining)
} else {
let (maybe_align, remaining) = FormatAlign::parse(&text[char_indices[1].0..]);
if maybe_align.is_some() {
(Some(char_indices[0].1), maybe_align, remaining)
} else {
let (only_align, only_align_remaining) = FormatAlign::parse(text);
(None, only_align, only_align_remaining)
}
}
}
fn parse_number(text: &Wtf8) -> Result<(Option<usize>, &Wtf8), FormatSpecError> {
let num_digits: usize = get_num_digits(text);
if num_digits == 0 {
return Ok((None, text));
}
if let Some(num) = parse_usize(&text[..num_digits]) {
Ok((Some(num), &text[num_digits..]))
} else {
// NOTE: this condition is different from CPython
Err(FormatSpecError::DecimalDigitsTooMany)
}
}
fn parse_alternate_form(text: &Wtf8) -> (bool, &Wtf8) {
let mut chars = text.code_points();
match chars.next().and_then(CodePoint::to_char) {
Some('#') => (true, chars.as_wtf8()),
_ => (false, text),
}
}
fn parse_zero(text: &Wtf8) -> (bool, &Wtf8) {
let mut chars = text.code_points();
match chars.next().and_then(CodePoint::to_char) {
Some('0') => (true, chars.as_wtf8()),
_ => (false, text),
}
}
fn parse_precision(text: &Wtf8) -> Result<(Option<usize>, &Wtf8), FormatSpecError> {
let mut chars = text.code_points();
Ok(match chars.next().and_then(CodePoint::to_char) {
Some('.') => {
let (size, remaining) = parse_number(chars.as_wtf8())?;
if let Some(size) = size {
if size > i32::MAX as usize {
return Err(FormatSpecError::PrecisionTooBig);
}
(Some(size), remaining)
} else {
(None, text)
}
}
_ => (None, text),
})
}
impl FormatSpec {
pub fn parse(text: impl AsRef<Wtf8>) -> Result<Self, FormatSpecError> {
Self::_parse(text.as_ref())
}
fn _parse(text: &Wtf8) -> Result<Self, FormatSpecError> {
// get_integer in CPython
let (conversion, text) = FormatConversion::parse(text);
let (mut fill, mut align, text) = parse_fill_and_align(text);
let (sign, text) = FormatSign::parse(text);
let (alternate_form, text) = parse_alternate_form(text);
let (zero, text) = parse_zero(text);
let (width, text) = parse_number(text)?;
let (grouping_option, text) = FormatGrouping::parse(text);
if let Some(grouping) = &grouping_option {
Self::validate_separator(grouping, text)?;
}
let (precision, text) = parse_precision(text)?;
let (format_type, text) = FormatType::parse(text);
if !text.is_empty() {
return Err(FormatSpecError::InvalidFormatSpecifier);
}
if zero && fill.is_none() {
fill.replace('0'.into());
align = align.or(Some(FormatAlign::AfterSign));
}
Ok(Self {
conversion,
fill,
align,
sign,
alternate_form,
width,
grouping_option,
precision,
format_type,
})
}
fn validate_separator(grouping: &FormatGrouping, text: &Wtf8) -> Result<(), FormatSpecError> {
let mut chars = text.code_points().peekable();
match chars.peek().and_then(|cp| CodePoint::to_char(*cp)) {
Some(c) if c == ',' || c == '_' => {
if c == char::from(grouping) {
Err(FormatSpecError::UnspecifiedFormat(c, c))
} else {
Err(FormatSpecError::ExclusiveFormat(',', '_'))
}
}
_ => Ok(()),
}
}
fn compute_fill_string(fill_char: CodePoint, fill_chars_needed: i32) -> Wtf8Buf {
(0..fill_chars_needed).map(|_| fill_char).collect()
}
fn add_magnitude_separators_for_char(
magnitude_str: String,
inter: i32,
sep: char,
disp_digit_cnt: i32,
) -> String {
// Don't add separators to the floating decimal point of numbers
let mut parts = magnitude_str.splitn(2, '.');
let magnitude_int_str = parts.next().unwrap().to_string();
let dec_digit_cnt = magnitude_str.len() as i32 - magnitude_int_str.len() as i32;
let int_digit_cnt = disp_digit_cnt - dec_digit_cnt;
let mut result = Self::separate_integer(magnitude_int_str, inter, sep, int_digit_cnt);
if let Some(part) = parts.next() {
result.push_str(&format!(".{part}"))
}
result
}
fn separate_integer(
magnitude_str: String,
inter: i32,
sep: char,
disp_digit_cnt: i32,
) -> String {
let magnitude_len = magnitude_str.len() as i32;
let offset = (disp_digit_cnt % (inter + 1) == 0) as i32;
let disp_digit_cnt = disp_digit_cnt + offset;
let pad_cnt = disp_digit_cnt - magnitude_len;
let sep_cnt = disp_digit_cnt / (inter + 1);
let diff = pad_cnt - sep_cnt;
if pad_cnt > 0 && diff > 0 {
// separate with 0 padding
let padding = "0".repeat(diff as usize);
let padded_num = format!("{padding}{magnitude_str}");
Self::insert_separator(padded_num, inter, sep, sep_cnt)
} else {
// separate without padding
let sep_cnt = (magnitude_len - 1) / inter;
Self::insert_separator(magnitude_str, inter, sep, sep_cnt)
}
}
fn insert_separator(mut magnitude_str: String, inter: i32, sep: char, sep_cnt: i32) -> String {
let magnitude_len = magnitude_str.len() as i32;
for i in 1..=sep_cnt {
magnitude_str.insert((magnitude_len - inter * i) as usize, sep);
}
magnitude_str
}
fn validate_format(&self, default_format_type: FormatType) -> Result<(), FormatSpecError> {
let format_type = self.format_type.as_ref().unwrap_or(&default_format_type);
match (&self.grouping_option, format_type) {
(
Some(FormatGrouping::Comma),
FormatType::String
| FormatType::Character
| FormatType::Binary
| FormatType::Octal
| FormatType::Hex(_)
| FormatType::Number(_),
) => {
let ch = char::from(format_type);
Err(FormatSpecError::UnspecifiedFormat(',', ch))
}
(
Some(FormatGrouping::Underscore),
FormatType::String | FormatType::Character | FormatType::Number(_),
) => {
let ch = char::from(format_type);
Err(FormatSpecError::UnspecifiedFormat('_', ch))
}
_ => Ok(()),
}
}
const fn get_separator_interval(&self) -> usize {
match self.format_type {
Some(FormatType::Binary | FormatType::Octal | FormatType::Hex(_)) => 4,
Some(
FormatType::Decimal
| FormatType::FixedPoint(_)
| FormatType::GeneralFormat(_)
| FormatType::Exponent(_)
| FormatType::Percentage,
) => 3,
None => 3,
_ => panic!("Separators only valid for numbers!"),
}
}
fn add_magnitude_separators(&self, magnitude_str: String, prefix: &str) -> String {
match &self.grouping_option {
Some(fg) => {
let sep = char::from(fg);
let inter = self.get_separator_interval().try_into().unwrap();
let magnitude_len = magnitude_str.len();
let disp_digit_cnt = if self.fill == Some('0'.into())
&& self.align == Some(FormatAlign::AfterSign)
{
let width = self.width.unwrap_or(magnitude_len) as i32 - prefix.len() as i32;
cmp::max(width, magnitude_len as i32)
} else {
magnitude_len as i32
};
Self::add_magnitude_separators_for_char(magnitude_str, inter, sep, disp_digit_cnt)
}
None => magnitude_str,
}
}
pub fn format_bool(&self, input: bool) -> Result<String, FormatSpecError> {
let x = u8::from(input);
match &self.format_type {
Some(
FormatType::Binary
| FormatType::Decimal
| FormatType::Octal
| FormatType::Number(Case::Lower)
| FormatType::Hex(_)
| FormatType::GeneralFormat(_)
| FormatType::Character,
) => self.format_int(&BigInt::from_u8(x).unwrap()),
Some(FormatType::Exponent(_) | FormatType::FixedPoint(_) | FormatType::Percentage) => {
self.format_float(x as f64)
}
None => {
let first_letter = (input.to_string().as_bytes()[0] as char).to_uppercase();
Ok(first_letter.collect::<String>() + &input.to_string()[1..])
}
_ => Err(FormatSpecError::InvalidFormatSpecifier),
}
}
pub fn format_float(&self, num: f64) -> Result<String, FormatSpecError> {
self.validate_format(FormatType::FixedPoint(Case::Lower))?;
let precision = self.precision.unwrap_or(6);
let magnitude = num.abs();
let raw_magnitude_str: Result<String, FormatSpecError> = match &self.format_type {
Some(FormatType::FixedPoint(case)) => Ok(float::format_fixed(
precision,
magnitude,
*case,
self.alternate_form,
)),
Some(FormatType::Decimal)
| Some(FormatType::Binary)
| Some(FormatType::Octal)
| Some(FormatType::Hex(_))
| Some(FormatType::String)
| Some(FormatType::Character)
| Some(FormatType::Number(Case::Upper)) => {
let ch = char::from(self.format_type.as_ref().unwrap());
Err(FormatSpecError::UnknownFormatCode(ch, "float"))
}
Some(FormatType::GeneralFormat(case)) | Some(FormatType::Number(case)) => {
let precision = if precision == 0 { 1 } else { precision };
Ok(float::format_general(
precision,
magnitude,
*case,
self.alternate_form,
false,
))
}
Some(FormatType::Exponent(case)) => Ok(float::format_exponent(
precision,
magnitude,
*case,
self.alternate_form,
)),
Some(FormatType::Percentage) => match magnitude {
magnitude if magnitude.is_nan() => Ok("nan%".to_owned()),
magnitude if magnitude.is_infinite() => Ok("inf%".to_owned()),
_ => {
let result = format!("{:.*}", precision, magnitude * 100.0);
let point = float::decimal_point_or_empty(precision, self.alternate_form);
Ok(format!("{result}{point}%"))
}
},
None => match magnitude {
magnitude if magnitude.is_nan() => Ok("nan".to_owned()),
magnitude if magnitude.is_infinite() => Ok("inf".to_owned()),
_ => match self.precision {
Some(precision) => Ok(float::format_general(
precision,
magnitude,
Case::Lower,
self.alternate_form,
true,
)),
None => Ok(float::to_string(magnitude)),
},
},
};
let format_sign = self.sign.unwrap_or(FormatSign::Minus);
let sign_str = if num.is_sign_negative() && !num.is_nan() {
"-"
} else {
match format_sign {
FormatSign::Plus => "+",
FormatSign::Minus => "",
FormatSign::MinusOrSpace => " ",
}
};
let magnitude_str = self.add_magnitude_separators(raw_magnitude_str?, sign_str);
self.format_sign_and_align(&AsciiStr::new(&magnitude_str), sign_str, FormatAlign::Right)
}
#[inline]
fn format_int_radix(&self, magnitude: BigInt, radix: u32) -> Result<String, FormatSpecError> {
match self.precision {
Some(_) => Err(FormatSpecError::PrecisionNotAllowed),
None => Ok(magnitude.to_str_radix(radix)),
}
}
pub fn format_int(&self, num: &BigInt) -> Result<String, FormatSpecError> {
self.validate_format(FormatType::Decimal)?;
let magnitude = num.abs();
let prefix = if self.alternate_form {
match self.format_type {
Some(FormatType::Binary) => "0b",
Some(FormatType::Octal) => "0o",
Some(FormatType::Hex(Case::Lower)) => "0x",
Some(FormatType::Hex(Case::Upper)) => "0X",
_ => "",
}
} else {
""
};
let raw_magnitude_str = match self.format_type {
Some(FormatType::Binary) => self.format_int_radix(magnitude, 2),
Some(FormatType::Decimal) => self.format_int_radix(magnitude, 10),
Some(FormatType::Octal) => self.format_int_radix(magnitude, 8),
Some(FormatType::Hex(Case::Lower)) => self.format_int_radix(magnitude, 16),
Some(FormatType::Hex(Case::Upper)) => match self.precision {
Some(_) => Err(FormatSpecError::PrecisionNotAllowed),
None => {
let mut result = magnitude.to_str_radix(16);
result.make_ascii_uppercase();
Ok(result)
}
},
Some(FormatType::Number(Case::Lower)) => self.format_int_radix(magnitude, 10),
Some(FormatType::Number(Case::Upper)) => {
Err(FormatSpecError::UnknownFormatCode('N', "int"))
}
Some(FormatType::String) => Err(FormatSpecError::UnknownFormatCode('s', "int")),
Some(FormatType::Character) => match (self.sign, self.alternate_form) {
(Some(_), _) => Err(FormatSpecError::NotAllowed("Sign")),
(_, true) => Err(FormatSpecError::NotAllowed("Alternate form (#)")),
(_, _) => match num.to_u32() {
Some(n) if n <= 0x10ffff => Ok(core::char::from_u32(n).unwrap().to_string()),
Some(_) | None => Err(FormatSpecError::CodeNotInRange),
},
},
Some(FormatType::GeneralFormat(_))
| Some(FormatType::FixedPoint(_))
| Some(FormatType::Exponent(_))
| Some(FormatType::Percentage) => match num.to_f64() {
Some(float) => return self.format_float(float),
_ => Err(FormatSpecError::UnableToConvert),
},
None => self.format_int_radix(magnitude, 10),
}?;
let format_sign = self.sign.unwrap_or(FormatSign::Minus);
let sign_str = match num.sign() {
Sign::Minus => "-",
_ => match format_sign {
FormatSign::Plus => "+",
FormatSign::Minus => "",
FormatSign::MinusOrSpace => " ",
},
};
let sign_prefix = format!("{sign_str}{prefix}");
let magnitude_str = self.add_magnitude_separators(raw_magnitude_str, &sign_prefix);
self.format_sign_and_align(
&AsciiStr::new(&magnitude_str),
&sign_prefix,
FormatAlign::Right,
)
}
pub fn format_string<T>(&self, s: &T) -> Result<String, FormatSpecError>
where
T: CharLen + Deref<Target = str>,
{
self.validate_format(FormatType::String)?;
match self.format_type {
Some(FormatType::String) | None => self
.format_sign_and_align(s, "", FormatAlign::Left)
.map(|mut value| {
if let Some(precision) = self.precision {
value.truncate(precision);
}
value
}),
_ => {
let ch = char::from(self.format_type.as_ref().unwrap());
Err(FormatSpecError::UnknownFormatCode(ch, "str"))
}
}
}
pub fn format_complex(&self, num: &Complex64) -> Result<String, FormatSpecError> {
let (formatted_re, formatted_im) = self.format_complex_re_im(num)?;
// Enclose in parentheses if there is no format type and formatted_re is not empty
let magnitude_str = if self.format_type.is_none() && !formatted_re.is_empty() {
format!("({formatted_re}{formatted_im})")
} else {
format!("{formatted_re}{formatted_im}")
};
if let Some(FormatAlign::AfterSign) = &self.align {
return Err(FormatSpecError::AlignmentFlag);
}
match &self.fill.unwrap_or(' '.into()).to_char() {
Some('0') => Err(FormatSpecError::ZeroPadding),
_ => self.format_sign_and_align(&AsciiStr::new(&magnitude_str), "", FormatAlign::Right),
}
}
fn format_complex_re_im(&self, num: &Complex64) -> Result<(String, String), FormatSpecError> {
// Format real part
let mut formatted_re = String::new();
if num.re != 0.0 || num.re.is_negative_zero() || self.format_type.is_some() {
let sign_re = if num.re.is_sign_negative() && !num.is_nan() {
"-"
} else {
match self.sign.unwrap_or(FormatSign::Minus) {
FormatSign::Plus => "+",
FormatSign::Minus => "",
FormatSign::MinusOrSpace => " ",
}
};
let re = self.format_complex_float(num.re)?;
formatted_re = format!("{sign_re}{re}");
}
// Format imaginary part
let sign_im = if num.im.is_sign_negative() && !num.im.is_nan() {
"-"
} else if formatted_re.is_empty() {
""
} else {
"+"
};
let im = self.format_complex_float(num.im)?;
Ok((formatted_re, format!("{sign_im}{im}j")))
}
fn format_complex_float(&self, num: f64) -> Result<String, FormatSpecError> {
self.validate_format(FormatType::FixedPoint(Case::Lower))?;
let precision = self.precision.unwrap_or(6);
let magnitude = num.abs();
let magnitude_str = match &self.format_type {
Some(FormatType::Decimal)
| Some(FormatType::Binary)
| Some(FormatType::Octal)
| Some(FormatType::Hex(_))
| Some(FormatType::String)
| Some(FormatType::Character)
| Some(FormatType::Number(Case::Upper))
| Some(FormatType::Percentage) => {
let ch = char::from(self.format_type.as_ref().unwrap());
Err(FormatSpecError::UnknownFormatCode(ch, "complex"))
}
Some(FormatType::FixedPoint(case)) => Ok(float::format_fixed(
precision,
magnitude,
*case,
self.alternate_form,
)),
Some(FormatType::GeneralFormat(case)) | Some(FormatType::Number(case)) => {
let precision = if precision == 0 { 1 } else { precision };
Ok(float::format_general(
precision,
magnitude,
*case,
self.alternate_form,
false,
))
}
Some(FormatType::Exponent(case)) => Ok(float::format_exponent(
precision,
magnitude,
*case,
self.alternate_form,
)),
None => match magnitude {
magnitude if magnitude.is_nan() => Ok("nan".to_owned()),
magnitude if magnitude.is_infinite() => Ok("inf".to_owned()),
_ => match self.precision {
Some(precision) => Ok(float::format_general(
precision,
magnitude,
Case::Lower,
self.alternate_form,
true,
)),
None => {
if magnitude.fract() == 0.0 {
Ok(magnitude.trunc().to_string())
} else {
Ok(magnitude.to_string())
}
}
},
},
}?;
match &self.grouping_option {
Some(fg) => {
let sep = char::from(fg);
let inter = self.get_separator_interval().try_into().unwrap();
let len = magnitude_str.len() as i32;
let separated_magnitude =
Self::add_magnitude_separators_for_char(magnitude_str, inter, sep, len);
Ok(separated_magnitude)
}
None => Ok(magnitude_str),
}
}
fn format_sign_and_align<T>(
&self,
magnitude_str: &T,
sign_str: &str,
default_align: FormatAlign,
) -> Result<String, FormatSpecError>
where
T: CharLen + Deref<Target = str>,
{
let align = self.align.unwrap_or(default_align);
let num_chars = magnitude_str.char_len();
let fill_char = self.fill.unwrap_or(' '.into());
let fill_chars_needed: i32 = self.width.map_or(0, |w| {
cmp::max(0, (w as i32) - (num_chars as i32) - (sign_str.len() as i32))
});
let magnitude_str = magnitude_str.deref();
Ok(match align {
FormatAlign::Left => format!(
"{}{}{}",
sign_str,
magnitude_str,
Self::compute_fill_string(fill_char, fill_chars_needed)
),
FormatAlign::Right => format!(
"{}{}{}",
Self::compute_fill_string(fill_char, fill_chars_needed),
sign_str,
magnitude_str
),
FormatAlign::AfterSign => format!(
"{}{}{}",
sign_str,
Self::compute_fill_string(fill_char, fill_chars_needed),
magnitude_str
),
FormatAlign::Center => {
let left_fill_chars_needed = fill_chars_needed / 2;
let right_fill_chars_needed = fill_chars_needed - left_fill_chars_needed;
let left_fill_string = Self::compute_fill_string(fill_char, left_fill_chars_needed);
let right_fill_string =
Self::compute_fill_string(fill_char, right_fill_chars_needed);
format!("{left_fill_string}{sign_str}{magnitude_str}{right_fill_string}")
}
})
}
}
pub trait CharLen {
/// Returns the number of characters in the text
fn char_len(&self) -> usize;
}
struct AsciiStr<'a> {
inner: &'a str,
}
impl<'a> AsciiStr<'a> {
const fn new(inner: &'a str) -> Self {
Self { inner }
}
}
impl CharLen for AsciiStr<'_> {
fn char_len(&self) -> usize {
self.inner.len()
}
}
impl Deref for AsciiStr<'_> {
type Target = str;
fn deref(&self) -> &Self::Target {
self.inner
}
}
#[derive(Debug, PartialEq)]
pub enum FormatSpecError {
DecimalDigitsTooMany,
PrecisionTooBig,
InvalidFormatSpecifier,
UnspecifiedFormat(char, char),
ExclusiveFormat(char, char),
UnknownFormatCode(char, &'static str),
PrecisionNotAllowed,
NotAllowed(&'static str),
UnableToConvert,
CodeNotInRange,
ZeroPadding,
AlignmentFlag,
NotImplemented(char, &'static str),
}
#[derive(Debug, PartialEq)]
pub enum FormatParseError {
UnmatchedBracket,
MissingStartBracket,
UnescapedStartBracketInLiteral,
InvalidFormatSpecifier,
UnknownConversion,
EmptyAttribute,
MissingRightBracket,
InvalidCharacterAfterRightBracket,
}
impl FromStr for FormatSpec {
type Err = FormatSpecError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::parse(s)
}
}
#[derive(Debug, PartialEq)]
pub enum FieldNamePart {
Attribute(Wtf8Buf),
Index(usize),
StringIndex(Wtf8Buf),
}
impl FieldNamePart {
fn parse_part(
chars: &mut impl PeekingNext<Item = CodePoint>,
) -> Result<Option<Self>, FormatParseError> {
chars
.next()
.map(|ch| match ch.to_char_lossy() {
'.' => {
let mut attribute = Wtf8Buf::new();
for ch in chars.peeking_take_while(|ch| *ch != '.' && *ch != '[') {
attribute.push(ch);
}
if attribute.is_empty() {
Err(FormatParseError::EmptyAttribute)
} else {
Ok(Self::Attribute(attribute))
}
}
'[' => {
let mut index = Wtf8Buf::new();
for ch in chars {
if ch == ']' {
return if index.is_empty() {
Err(FormatParseError::EmptyAttribute)
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | true |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/hash.rs | crates/common/src/hash.rs | use core::hash::{BuildHasher, Hash, Hasher};
use malachite_bigint::BigInt;
use num_traits::ToPrimitive;
use siphasher::sip::SipHasher24;
pub type PyHash = i64;
pub type PyUHash = u64;
/// A PyHash value used to represent a missing hash value, e.g. means "not yet computed" for
/// `str`'s hash cache
pub const SENTINEL: PyHash = -1;
/// Prime multiplier used in string and various other hashes.
pub const MULTIPLIER: PyHash = 1_000_003; // 0xf4243
/// Numeric hashes are based on reduction modulo the prime 2**_BITS - 1
pub const BITS: usize = 61;
pub const MODULUS: PyUHash = (1 << BITS) - 1;
pub const INF: PyHash = 314_159;
pub const NAN: PyHash = 0;
pub const IMAG: PyHash = MULTIPLIER;
pub const ALGO: &str = "siphash24";
pub const HASH_BITS: usize = core::mem::size_of::<PyHash>() * 8;
// SipHasher24 takes 2 u64s as a seed
pub const SEED_BITS: usize = core::mem::size_of::<u64>() * 2 * 8;
// pub const CUTOFF: usize = 7;
pub struct HashSecret {
k0: u64,
k1: u64,
}
impl BuildHasher for HashSecret {
type Hasher = SipHasher24;
fn build_hasher(&self) -> Self::Hasher {
SipHasher24::new_with_keys(self.k0, self.k1)
}
}
impl HashSecret {
pub fn new(seed: u32) -> Self {
let mut buf = [0u8; 16];
lcg_urandom(seed, &mut buf);
let (left, right) = buf.split_at(8);
let k0 = u64::from_le_bytes(left.try_into().unwrap());
let k1 = u64::from_le_bytes(right.try_into().unwrap());
Self { k0, k1 }
}
}
impl HashSecret {
pub fn hash_value<T: Hash + ?Sized>(&self, data: &T) -> PyHash {
fix_sentinel(mod_int(self.hash_one(data) as _))
}
pub fn hash_iter<'a, T: 'a, I, F, E>(&self, iter: I, hash_func: F) -> Result<PyHash, E>
where
I: IntoIterator<Item = &'a T>,
F: Fn(&'a T) -> Result<PyHash, E>,
{
let mut hasher = self.build_hasher();
for element in iter {
let item_hash = hash_func(element)?;
item_hash.hash(&mut hasher);
}
Ok(fix_sentinel(mod_int(hasher.finish() as PyHash)))
}
pub fn hash_bytes(&self, value: &[u8]) -> PyHash {
if value.is_empty() {
0
} else {
self.hash_value(value)
}
}
pub fn hash_str(&self, value: &str) -> PyHash {
self.hash_bytes(value.as_bytes())
}
}
#[inline]
pub const fn hash_pointer(value: usize) -> PyHash {
// TODO: 32bit?
let hash = (value >> 4) | value;
hash as _
}
#[inline]
pub fn hash_float(value: f64) -> Option<PyHash> {
// cpython _Py_HashDouble
if !value.is_finite() {
return if value.is_infinite() {
Some(if value > 0.0 { INF } else { -INF })
} else {
None
};
}
let frexp = super::float_ops::decompose_float(value);
// process 28 bits at a time; this should work well both for binary
// and hexadecimal floating point.
let mut m = frexp.0;
let mut e = frexp.1;
let mut x: PyUHash = 0;
while m != 0.0 {
x = ((x << 28) & MODULUS) | (x >> (BITS - 28));
m *= 268_435_456.0; // 2**28
e -= 28;
let y = m as PyUHash; // pull out integer part
m -= y as f64;
x += y;
if x >= MODULUS {
x -= MODULUS;
}
}
// adjust for the exponent; first reduce it modulo BITS
const BITS32: i32 = BITS as i32;
e = if e >= 0 {
e % BITS32
} else {
BITS32 - 1 - ((-1 - e) % BITS32)
};
x = ((x << e) & MODULUS) | (x >> (BITS32 - e));
Some(fix_sentinel(x as PyHash * value.signum() as PyHash))
}
pub fn hash_bigint(value: &BigInt) -> PyHash {
let ret = match value.to_i64() {
Some(i) => mod_int(i),
None => (value % MODULUS).to_i64().unwrap_or_else(|| unsafe {
// SAFETY: MODULUS < i64::MAX, so value % MODULUS is guaranteed to be in the range of i64
core::hint::unreachable_unchecked()
}),
};
fix_sentinel(ret)
}
#[inline]
pub const fn hash_usize(data: usize) -> PyHash {
fix_sentinel(mod_int(data as i64))
}
#[inline(always)]
pub const fn fix_sentinel(x: PyHash) -> PyHash {
if x == SENTINEL { -2 } else { x }
}
#[inline]
pub const fn mod_int(value: i64) -> PyHash {
value % MODULUS as i64
}
pub fn lcg_urandom(mut x: u32, buf: &mut [u8]) {
for b in buf {
x = x.wrapping_mul(214013);
x = x.wrapping_add(2531011);
*b = ((x >> 16) & 0xff) as u8;
}
}
#[inline]
pub const fn hash_object_id_raw(p: usize) -> PyHash {
// TODO: Use commented logic when below issue resolved.
// Ref: https://github.com/RustPython/RustPython/pull/3951#issuecomment-1193108966
/* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
excessive hash collisions for dicts and sets */
// p.rotate_right(4) as PyHash
p as PyHash
}
#[inline]
pub const fn hash_object_id(p: usize) -> PyHash {
fix_sentinel(hash_object_id_raw(p))
}
pub fn keyed_hash(key: u64, buf: &[u8]) -> u64 {
let mut hasher = SipHasher24::new_with_keys(key, 0);
buf.hash(&mut hasher);
hasher.finish()
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/linked_list.rs | crates/common/src/linked_list.rs | // spell-checker:disable
//! This module is modified from tokio::util::linked_list: <https://github.com/tokio-rs/tokio/blob/master/tokio/src/util/linked_list.rs>
//! Tokio is licensed under the MIT license:
//!
//! Copyright (c) 2021 Tokio Contributors
//!
//! Permission is hereby granted, free of charge, to any
//! person obtaining a copy of this software and associated
//! documentation files (the "Software"), to deal in the
//! Software without restriction, including without
//! limitation the rights to use, copy, modify, merge,
//! publish, distribute, sublicense, and/or sell copies of
//! the Software, and to permit persons to whom the Software
//! is furnished to do so, subject to the following
//! conditions:
//!
//! The above copyright notice and this permission notice
//! shall be included in all copies or substantial portions
//! of the Software.
//!
//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
//! ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
//! TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
//! PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
//! SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//! CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
//! OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
//! IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
//! DEALINGS IN THE SOFTWARE.
//!
//! Original header:
//!
//! An intrusive double linked list of data.
//!
//! The data structure supports tracking pinned nodes. Most of the data
//! structure's APIs are `unsafe` as they require the caller to ensure the
//! specified node is actually contained by the list.
#![allow(clippy::new_without_default, clippy::missing_safety_doc)]
use core::cell::UnsafeCell;
use core::fmt;
use core::marker::{PhantomData, PhantomPinned};
use core::mem::ManuallyDrop;
use core::ptr::{self, NonNull};
/// An intrusive linked list.
///
/// Currently, the list is not emptied on drop. It is the caller's
/// responsibility to ensure the list is empty before dropping it.
pub struct LinkedList<L, T> {
/// Linked list head
head: Option<NonNull<T>>,
// /// Linked list tail
// tail: Option<NonNull<T>>,
/// Node type marker.
_marker: PhantomData<*const L>,
}
unsafe impl<L: Link> Send for LinkedList<L, L::Target> where L::Target: Send {}
unsafe impl<L: Link> Sync for LinkedList<L, L::Target> where L::Target: Sync {}
/// Defines how a type is tracked within a linked list.
///
/// In order to support storing a single type within multiple lists, accessing
/// the list pointers is decoupled from the entry type.
///
/// # Safety
///
/// Implementations must guarantee that `Target` types are pinned in memory. In
/// other words, when a node is inserted, the value will not be moved as long as
/// it is stored in the list.
pub unsafe trait Link {
/// Handle to the list entry.
///
/// This is usually a pointer-ish type.
type Handle;
/// Node type.
type Target;
/// Convert the handle to a raw pointer without consuming the handle.
#[allow(clippy::wrong_self_convention)]
fn as_raw(handle: &Self::Handle) -> NonNull<Self::Target>;
/// Convert the raw pointer to a handle
unsafe fn from_raw(ptr: NonNull<Self::Target>) -> Self::Handle;
/// Return the pointers for a node
unsafe fn pointers(target: NonNull<Self::Target>) -> NonNull<Pointers<Self::Target>>;
}
/// Previous / next pointers.
pub struct Pointers<T> {
inner: UnsafeCell<PointersInner<T>>,
}
/// We do not want the compiler to put the `noalias` attribute on mutable
/// references to this type, so the type has been made `!Unpin` with a
/// `PhantomPinned` field.
///
/// Additionally, we never access the `prev` or `next` fields directly, as any
/// such access would implicitly involve the creation of a reference to the
/// field, which we want to avoid since the fields are not `!Unpin`, and would
/// hence be given the `noalias` attribute if we were to do such an access.
/// As an alternative to accessing the fields directly, the `Pointers` type
/// provides getters and setters for the two fields, and those are implemented
/// using raw pointer casts and offsets, which is valid since the struct is
/// #[repr(C)].
///
/// See this link for more information:
/// <https://github.com/rust-lang/rust/pull/82834>
#[repr(C)]
struct PointersInner<T> {
/// The previous node in the list. null if there is no previous node.
///
/// This field is accessed through pointer manipulation, so it is not dead code.
#[allow(dead_code)]
prev: Option<NonNull<T>>,
/// The next node in the list. null if there is no previous node.
///
/// This field is accessed through pointer manipulation, so it is not dead code.
#[allow(dead_code)]
next: Option<NonNull<T>>,
/// This type is !Unpin due to the heuristic from:
/// <https://github.com/rust-lang/rust/pull/82834>
_pin: PhantomPinned,
}
unsafe impl<T: Send> Send for PointersInner<T> {}
unsafe impl<T: Sync> Sync for PointersInner<T> {}
unsafe impl<T: Send> Send for Pointers<T> {}
unsafe impl<T: Sync> Sync for Pointers<T> {}
// ===== impl LinkedList =====
impl<L, T> LinkedList<L, T> {
/// Creates an empty linked list.
pub const fn new() -> Self {
Self {
head: None,
// tail: None,
_marker: PhantomData,
}
}
}
impl<L: Link> LinkedList<L, L::Target> {
/// Adds an element first in the list.
pub fn push_front(&mut self, val: L::Handle) {
// The value should not be dropped, it is being inserted into the list
let val = ManuallyDrop::new(val);
let ptr = L::as_raw(&val);
assert_ne!(self.head, Some(ptr));
unsafe {
L::pointers(ptr).as_mut().set_next(self.head);
L::pointers(ptr).as_mut().set_prev(None);
if let Some(head) = self.head {
L::pointers(head).as_mut().set_prev(Some(ptr));
}
self.head = Some(ptr);
// if self.tail.is_none() {
// self.tail = Some(ptr);
// }
}
}
// /// Removes the last element from a list and returns it, or None if it is
// /// empty.
// pub fn pop_back(&mut self) -> Option<L::Handle> {
// unsafe {
// let last = self.tail?;
// self.tail = L::pointers(last).as_ref().get_prev();
// if let Some(prev) = L::pointers(last).as_ref().get_prev() {
// L::pointers(prev).as_mut().set_next(None);
// } else {
// self.head = None
// }
// L::pointers(last).as_mut().set_prev(None);
// L::pointers(last).as_mut().set_next(None);
// Some(L::from_raw(last))
// }
// }
/// Returns whether the linked list does not contain any node
pub const fn is_empty(&self) -> bool {
self.head.is_none()
// if self.head.is_some() {
// return false;
// }
// assert!(self.tail.is_none());
// true
}
/// Removes the specified node from the list
///
/// # Safety
///
/// The caller **must** ensure that `node` is currently contained by
/// `self` or not contained by any other list.
pub unsafe fn remove(&mut self, node: NonNull<L::Target>) -> Option<L::Handle> {
unsafe {
if let Some(prev) = L::pointers(node).as_ref().get_prev() {
debug_assert_eq!(L::pointers(prev).as_ref().get_next(), Some(node));
L::pointers(prev)
.as_mut()
.set_next(L::pointers(node).as_ref().get_next());
} else {
if self.head != Some(node) {
return None;
}
self.head = L::pointers(node).as_ref().get_next();
}
if let Some(next) = L::pointers(node).as_ref().get_next() {
debug_assert_eq!(L::pointers(next).as_ref().get_prev(), Some(node));
L::pointers(next)
.as_mut()
.set_prev(L::pointers(node).as_ref().get_prev());
} else {
// // This might be the last item in the list
// if self.tail != Some(node) {
// return None;
// }
// self.tail = L::pointers(node).as_ref().get_prev();
}
L::pointers(node).as_mut().set_next(None);
L::pointers(node).as_mut().set_prev(None);
Some(L::from_raw(node))
}
}
// pub fn last(&self) -> Option<&L::Target> {
// let tail = self.tail.as_ref()?;
// unsafe { Some(&*tail.as_ptr()) }
// }
// === rustpython additions ===
pub fn iter(&self) -> impl Iterator<Item = &L::Target> {
core::iter::successors(self.head, |node| unsafe {
L::pointers(*node).as_ref().get_next()
})
.map(|ptr| unsafe { ptr.as_ref() })
}
}
impl<L: Link> fmt::Debug for LinkedList<L, L::Target> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LinkedList")
.field("head", &self.head)
// .field("tail", &self.tail)
.finish()
}
}
impl<L: Link> Default for LinkedList<L, L::Target> {
fn default() -> Self {
Self::new()
}
}
// ===== impl DrainFilter =====
pub struct DrainFilter<'a, T: Link, F> {
list: &'a mut LinkedList<T, T::Target>,
filter: F,
curr: Option<NonNull<T::Target>>,
}
impl<T: Link> LinkedList<T, T::Target> {
pub const fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
where
F: FnMut(&mut T::Target) -> bool,
{
let curr = self.head;
DrainFilter {
curr,
filter,
list: self,
}
}
}
impl<T, F> Iterator for DrainFilter<'_, T, F>
where
T: Link,
F: FnMut(&mut T::Target) -> bool,
{
type Item = T::Handle;
fn next(&mut self) -> Option<Self::Item> {
while let Some(curr) = self.curr {
// safety: the pointer references data contained by the list
self.curr = unsafe { T::pointers(curr).as_ref() }.get_next();
// safety: the value is still owned by the linked list.
if (self.filter)(unsafe { &mut *curr.as_ptr() }) {
return unsafe { self.list.remove(curr) };
}
}
None
}
}
// ===== impl Pointers =====
impl<T> Pointers<T> {
/// Create a new set of empty pointers
pub const fn new() -> Self {
Self {
inner: UnsafeCell::new(PointersInner {
prev: None,
next: None,
_pin: PhantomPinned,
}),
}
}
const fn get_prev(&self) -> Option<NonNull<T>> {
// SAFETY: prev is the first field in PointersInner, which is #[repr(C)].
unsafe {
let inner = self.inner.get();
let prev = inner as *const Option<NonNull<T>>;
ptr::read(prev)
}
}
const fn get_next(&self) -> Option<NonNull<T>> {
// SAFETY: next is the second field in PointersInner, which is #[repr(C)].
unsafe {
let inner = self.inner.get();
let prev = inner as *const Option<NonNull<T>>;
let next = prev.add(1);
ptr::read(next)
}
}
const fn set_prev(&mut self, value: Option<NonNull<T>>) {
// SAFETY: prev is the first field in PointersInner, which is #[repr(C)].
unsafe {
let inner = self.inner.get();
let prev = inner as *mut Option<NonNull<T>>;
ptr::write(prev, value);
}
}
const fn set_next(&mut self, value: Option<NonNull<T>>) {
// SAFETY: next is the second field in PointersInner, which is #[repr(C)].
unsafe {
let inner = self.inner.get();
let prev = inner as *mut Option<NonNull<T>>;
let next = prev.add(1);
ptr::write(next, value);
}
}
}
impl<T> fmt::Debug for Pointers<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let prev = self.get_prev();
let next = self.get_next();
f.debug_struct("Pointers")
.field("prev", &prev)
.field("next", &next)
.finish()
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/int.rs | crates/common/src/int.rs | use malachite_base::{num::conversion::traits::RoundingInto, rounding_modes::RoundingMode};
use malachite_bigint::{BigInt, BigUint, Sign};
use malachite_q::Rational;
use num_traits::{One, ToPrimitive, Zero};
pub fn true_div(numerator: &BigInt, denominator: &BigInt) -> f64 {
let rational = Rational::from_integers_ref(numerator.into(), denominator.into());
match rational.rounding_into(RoundingMode::Nearest) {
// returned value is $t::MAX but still less than the original
(val, core::cmp::Ordering::Less) if val == f64::MAX => f64::INFINITY,
// returned value is $t::MIN but still greater than the original
(val, core::cmp::Ordering::Greater) if val == f64::MIN => f64::NEG_INFINITY,
(val, _) => val,
}
}
pub fn float_to_ratio(value: f64) -> Option<(BigInt, BigInt)> {
let sign = match core::cmp::PartialOrd::partial_cmp(&value, &0.0)? {
core::cmp::Ordering::Less => Sign::Minus,
core::cmp::Ordering::Equal => return Some((BigInt::zero(), BigInt::one())),
core::cmp::Ordering::Greater => Sign::Plus,
};
Rational::try_from(value).ok().map(|x| {
let (numer, denom) = x.into_numerator_and_denominator();
(
BigInt::from_biguint(sign, numer.into()),
BigUint::from(denom).into(),
)
})
}
#[derive(Debug, Eq, PartialEq)]
pub enum BytesToIntError {
InvalidLiteral { base: u32 },
InvalidBase,
DigitLimit { got: usize, limit: usize },
}
// https://github.com/python/cpython/blob/4e665351082c50018fb31d80db25b4693057393e/Objects/longobject.c#L2977
// https://github.com/python/cpython/blob/4e665351082c50018fb31d80db25b4693057393e/Objects/longobject.c#L2884
pub fn bytes_to_int(
buf: &[u8],
mut base: u32,
digit_limit: usize,
) -> Result<BigInt, BytesToIntError> {
if base != 0 && !(2..=36).contains(&base) {
return Err(BytesToIntError::InvalidBase);
}
let mut buf = buf.trim_ascii();
// split sign
let sign = match buf.first() {
Some(b'+') => Some(Sign::Plus),
Some(b'-') => Some(Sign::Minus),
None => return Err(BytesToIntError::InvalidLiteral { base }),
_ => None,
};
if sign.is_some() {
buf = &buf[1..];
}
let mut error_if_nonzero = false;
if base == 0 {
match (buf.first(), buf.get(1)) {
(Some(v), _) if *v != b'0' => base = 10,
(_, Some(b'x' | b'X')) => base = 16,
(_, Some(b'o' | b'O')) => base = 8,
(_, Some(b'b' | b'B')) => base = 2,
(_, _) => {
// "old" (C-style) octal literal, now invalid. it might still be zero though
base = 10;
error_if_nonzero = true;
}
}
}
if error_if_nonzero {
if let [_first, others @ .., last] = buf {
let is_zero = *last == b'0' && others.iter().all(|&c| c == b'0' || c == b'_');
if !is_zero {
return Err(BytesToIntError::InvalidLiteral { base });
}
}
return Ok(BigInt::zero());
}
if buf.first().is_some_and(|&v| v == b'0')
&& buf.get(1).is_some_and(|&v| {
(base == 16 && (v == b'x' || v == b'X'))
|| (base == 8 && (v == b'o' || v == b'O'))
|| (base == 2 && (v == b'b' || v == b'B'))
})
{
buf = &buf[2..];
// One underscore allowed here
if buf.first().is_some_and(|&v| v == b'_') {
buf = &buf[1..];
}
}
// Reject empty strings
let mut prev = *buf
.first()
.ok_or(BytesToIntError::InvalidLiteral { base })?;
// Leading underscore not allowed
if prev == b'_' || !prev.is_ascii_alphanumeric() {
return Err(BytesToIntError::InvalidLiteral { base });
}
// Verify all characters are digits and underscores
let mut digits = 1;
for &cur in buf.iter().skip(1) {
if cur == b'_' {
// Double underscore not allowed
if prev == b'_' {
return Err(BytesToIntError::InvalidLiteral { base });
}
} else if cur.is_ascii_alphanumeric() {
digits += 1;
} else {
return Err(BytesToIntError::InvalidLiteral { base });
}
prev = cur;
}
// Trailing underscore not allowed
if prev == b'_' {
return Err(BytesToIntError::InvalidLiteral { base });
}
if digit_limit > 0 && !base.is_power_of_two() && digits > digit_limit {
return Err(BytesToIntError::DigitLimit {
got: digits,
limit: digit_limit,
});
}
let uint = BigUint::parse_bytes(buf, base).ok_or(BytesToIntError::InvalidLiteral { base })?;
Ok(BigInt::from_biguint(sign.unwrap_or(Sign::Plus), uint))
}
// num-bigint now returns Some(inf) for to_f64() in some cases, so just keep that the same for now
#[inline(always)]
pub fn bigint_to_finite_float(int: &BigInt) -> Option<f64> {
int.to_f64().filter(|f| f.is_finite())
}
#[cfg(test)]
mod tests {
use super::*;
const DIGIT_LIMIT: usize = 4300; // Default of Cpython
#[test]
fn bytes_to_int_valid() {
for ((buf, base), expected) in [
(("0b101", 2), BigInt::from(5)),
(("0x_10", 16), BigInt::from(16)),
(("0b", 16), BigInt::from(11)),
(("+0b101", 2), BigInt::from(5)),
(("0_0_0", 10), BigInt::from(0)),
(("000", 0), BigInt::from(0)),
(("0_100", 10), BigInt::from(100)),
] {
assert_eq!(
bytes_to_int(buf.as_bytes(), base, DIGIT_LIMIT),
Ok(expected)
);
}
}
#[test]
fn bytes_to_int_invalid_literal() {
for ((buf, base), expected) in [
(("09_99", 0), BytesToIntError::InvalidLiteral { base: 10 }),
(("0_", 0), BytesToIntError::InvalidLiteral { base: 10 }),
(("0_", 2), BytesToIntError::InvalidLiteral { base: 2 }),
] {
assert_eq!(
bytes_to_int(buf.as_bytes(), base, DIGIT_LIMIT),
Err(expected)
)
}
}
#[test]
fn bytes_to_int_invalid_base() {
for base in [1, 37] {
assert_eq!(
bytes_to_int("012345".as_bytes(), base, DIGIT_LIMIT),
Err(BytesToIntError::InvalidBase)
)
}
}
#[test]
fn bytes_to_int_digit_limit() {
assert_eq!(
bytes_to_int("012345".as_bytes(), 10, 5),
Err(BytesToIntError::DigitLimit { got: 6, limit: 5 })
);
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/atomic.rs | crates/common/src/atomic.rs | use core::ptr::{self, NonNull};
pub use core::sync::atomic::*;
pub use radium::Radium;
mod sealed {
pub trait Sealed {}
}
pub trait PyAtomicScalar: sealed::Sealed {
type Radium: Radium<Item = Self>;
}
pub type PyAtomic<T> = <T as PyAtomicScalar>::Radium;
#[cfg(feature = "threading")]
macro_rules! atomic_ty {
($i:ty, $atomic:ty) => {
$atomic
};
}
#[cfg(not(feature = "threading"))]
macro_rules! atomic_ty {
($i:ty, $atomic:ty) => {
core::cell::Cell<$i>
};
}
macro_rules! impl_atomic_scalar {
($(($i:ty, $atomic:ty),)*) => {
$(
impl sealed::Sealed for $i {}
impl PyAtomicScalar for $i {
type Radium = atomic_ty!($i, $atomic);
}
)*
};
}
impl_atomic_scalar!(
(u8, AtomicU8),
(i8, AtomicI8),
(u16, AtomicU16),
(i16, AtomicI16),
(u32, AtomicU32),
(i32, AtomicI32),
(u64, AtomicU64),
(i64, AtomicI64),
(usize, AtomicUsize),
(isize, AtomicIsize),
(bool, AtomicBool),
);
impl<T> sealed::Sealed for *mut T {}
impl<T> PyAtomicScalar for *mut T {
type Radium = atomic_ty!(*mut T, AtomicPtr<T>);
}
pub struct OncePtr<T> {
inner: PyAtomic<*mut T>,
}
impl<T> Default for OncePtr<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> OncePtr<T> {
#[inline]
pub fn new() -> Self {
Self {
inner: Radium::new(ptr::null_mut()),
}
}
pub fn get(&self) -> Option<NonNull<T>> {
NonNull::new(self.inner.load(Ordering::Acquire))
}
pub fn set(&self, value: NonNull<T>) -> Result<(), NonNull<T>> {
let exchange = self.inner.compare_exchange(
ptr::null_mut(),
value.as_ptr(),
Ordering::AcqRel,
Ordering::Acquire,
);
match exchange {
Ok(_) => Ok(()),
Err(_) => Err(value),
}
}
pub fn get_or_init<F>(&self, f: F) -> NonNull<T>
where
F: FnOnce() -> Box<T>,
{
enum Void {}
match self.get_or_try_init(|| Ok::<_, Void>(f())) {
Ok(val) => val,
Err(void) => match void {},
}
}
pub fn get_or_try_init<F, E>(&self, f: F) -> Result<NonNull<T>, E>
where
F: FnOnce() -> Result<Box<T>, E>,
{
if let Some(val) = self.get() {
return Ok(val);
}
Ok(self.initialize(f()?))
}
#[cold]
fn initialize(&self, val: Box<T>) -> NonNull<T> {
let ptr = Box::into_raw(val);
let exchange =
self.inner
.compare_exchange(ptr::null_mut(), ptr, Ordering::AcqRel, Ordering::Acquire);
let ptr = match exchange {
Ok(_) => ptr,
Err(winner) => {
drop(unsafe { Box::from_raw(ptr) });
winner
}
};
unsafe { NonNull::new_unchecked(ptr) }
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/str.rs | crates/common/src/str.rs | // spell-checker:ignore uncomputed
use crate::atomic::{PyAtomic, Radium};
use crate::format::CharLen;
use crate::wtf8::{CodePoint, Wtf8, Wtf8Buf};
use ascii::{AsciiChar, AsciiStr, AsciiString};
use core::fmt;
use core::ops::{Bound, RangeBounds};
use core::sync::atomic::Ordering::Relaxed;
#[cfg(not(target_arch = "wasm32"))]
#[allow(non_camel_case_types)]
pub type wchar_t = libc::wchar_t;
#[cfg(target_arch = "wasm32")]
#[allow(non_camel_case_types)]
pub type wchar_t = u32;
/// Utf8 + state.ascii (+ PyUnicode_Kind in future)
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum StrKind {
Ascii,
Utf8,
Wtf8,
}
impl core::ops::BitOr for StrKind {
type Output = Self;
fn bitor(self, other: Self) -> Self {
use StrKind::*;
match (self, other) {
(Wtf8, _) | (_, Wtf8) => Wtf8,
(Utf8, _) | (_, Utf8) => Utf8,
(Ascii, Ascii) => Ascii,
}
}
}
impl StrKind {
pub const fn is_ascii(&self) -> bool {
matches!(self, Self::Ascii)
}
pub const fn is_utf8(&self) -> bool {
matches!(self, Self::Ascii | Self::Utf8)
}
#[inline(always)]
pub fn can_encode(&self, code: CodePoint) -> bool {
match self {
Self::Ascii => code.is_ascii(),
Self::Utf8 => code.to_char().is_some(),
Self::Wtf8 => true,
}
}
}
pub trait DeduceStrKind {
fn str_kind(&self) -> StrKind;
}
impl DeduceStrKind for str {
fn str_kind(&self) -> StrKind {
if self.is_ascii() {
StrKind::Ascii
} else {
StrKind::Utf8
}
}
}
impl DeduceStrKind for Wtf8 {
fn str_kind(&self) -> StrKind {
if self.is_ascii() {
StrKind::Ascii
} else if self.is_utf8() {
StrKind::Utf8
} else {
StrKind::Wtf8
}
}
}
impl DeduceStrKind for String {
fn str_kind(&self) -> StrKind {
(**self).str_kind()
}
}
impl DeduceStrKind for Wtf8Buf {
fn str_kind(&self) -> StrKind {
(**self).str_kind()
}
}
impl<T: DeduceStrKind + ?Sized> DeduceStrKind for &T {
fn str_kind(&self) -> StrKind {
(**self).str_kind()
}
}
impl<T: DeduceStrKind + ?Sized> DeduceStrKind for Box<T> {
fn str_kind(&self) -> StrKind {
(**self).str_kind()
}
}
#[derive(Debug)]
pub enum PyKindStr<'a> {
Ascii(&'a AsciiStr),
Utf8(&'a str),
Wtf8(&'a Wtf8),
}
#[derive(Debug, Clone)]
pub struct StrData {
data: Box<Wtf8>,
kind: StrKind,
len: StrLen,
}
struct StrLen(PyAtomic<usize>);
impl From<usize> for StrLen {
#[inline(always)]
fn from(value: usize) -> Self {
Self(Radium::new(value))
}
}
impl fmt::Debug for StrLen {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let len = self.0.load(Relaxed);
if len == usize::MAX {
f.write_str("<uncomputed>")
} else {
len.fmt(f)
}
}
}
impl StrLen {
#[inline(always)]
fn zero() -> Self {
0usize.into()
}
#[inline(always)]
fn uncomputed() -> Self {
usize::MAX.into()
}
}
impl Clone for StrLen {
fn clone(&self) -> Self {
Self(self.0.load(Relaxed).into())
}
}
impl Default for StrData {
fn default() -> Self {
Self {
data: <Box<Wtf8>>::default(),
kind: StrKind::Ascii,
len: StrLen::zero(),
}
}
}
impl From<Box<Wtf8>> for StrData {
fn from(value: Box<Wtf8>) -> Self {
// doing the check is ~10x faster for ascii, and is actually only 2% slower worst case for
// non-ascii; see https://github.com/RustPython/RustPython/pull/2586#issuecomment-844611532
let kind = value.str_kind();
unsafe { Self::new_str_unchecked(value, kind) }
}
}
impl From<Box<str>> for StrData {
#[inline]
fn from(value: Box<str>) -> Self {
// doing the check is ~10x faster for ascii, and is actually only 2% slower worst case for
// non-ascii; see https://github.com/RustPython/RustPython/pull/2586#issuecomment-844611532
let kind = value.str_kind();
unsafe { Self::new_str_unchecked(value.into(), kind) }
}
}
impl From<Box<AsciiStr>> for StrData {
#[inline]
fn from(value: Box<AsciiStr>) -> Self {
Self {
len: value.len().into(),
data: value.into(),
kind: StrKind::Ascii,
}
}
}
impl From<AsciiChar> for StrData {
fn from(ch: AsciiChar) -> Self {
AsciiString::from(ch).into_boxed_ascii_str().into()
}
}
impl From<char> for StrData {
fn from(ch: char) -> Self {
if let Ok(ch) = ascii::AsciiChar::from_ascii(ch) {
ch.into()
} else {
Self {
data: ch.to_string().into(),
kind: StrKind::Utf8,
len: 1.into(),
}
}
}
}
impl From<CodePoint> for StrData {
fn from(ch: CodePoint) -> Self {
if let Some(ch) = ch.to_char() {
ch.into()
} else {
Self {
data: Wtf8Buf::from(ch).into(),
kind: StrKind::Wtf8,
len: 1.into(),
}
}
}
}
impl StrData {
/// # Safety
///
/// Given `bytes` must be valid data for given `kind`
pub unsafe fn new_str_unchecked(data: Box<Wtf8>, kind: StrKind) -> Self {
let len = match kind {
StrKind::Ascii => data.len().into(),
_ => StrLen::uncomputed(),
};
Self { data, kind, len }
}
/// # Safety
///
/// `char_len` must be accurate.
pub unsafe fn new_with_char_len(data: Box<Wtf8>, kind: StrKind, char_len: usize) -> Self {
Self {
data,
kind,
len: char_len.into(),
}
}
#[inline]
pub const fn as_wtf8(&self) -> &Wtf8 {
&self.data
}
#[inline]
pub fn as_str(&self) -> Option<&str> {
self.kind
.is_utf8()
.then(|| unsafe { core::str::from_utf8_unchecked(self.data.as_bytes()) })
}
pub fn as_ascii(&self) -> Option<&AsciiStr> {
self.kind
.is_ascii()
.then(|| unsafe { AsciiStr::from_ascii_unchecked(self.data.as_bytes()) })
}
pub const fn kind(&self) -> StrKind {
self.kind
}
#[inline]
pub fn as_str_kind(&self) -> PyKindStr<'_> {
match self.kind {
StrKind::Ascii => {
PyKindStr::Ascii(unsafe { AsciiStr::from_ascii_unchecked(self.data.as_bytes()) })
}
StrKind::Utf8 => {
PyKindStr::Utf8(unsafe { core::str::from_utf8_unchecked(self.data.as_bytes()) })
}
StrKind::Wtf8 => PyKindStr::Wtf8(&self.data),
}
}
#[inline]
pub fn len(&self) -> usize {
self.data.len()
}
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
#[inline]
pub fn char_len(&self) -> usize {
match self.len.0.load(Relaxed) {
usize::MAX => self._compute_char_len(),
len => len,
}
}
#[cold]
fn _compute_char_len(&self) -> usize {
let len = if let Some(s) = self.as_str() {
// utf8 chars().count() is optimized
s.chars().count()
} else {
self.data.code_points().count()
};
// len cannot be usize::MAX, since vec.capacity() < sys.maxsize
self.len.0.store(len, Relaxed);
len
}
pub fn nth_char(&self, index: usize) -> CodePoint {
match self.as_str_kind() {
PyKindStr::Ascii(s) => s[index].into(),
PyKindStr::Utf8(s) => s.chars().nth(index).unwrap().into(),
PyKindStr::Wtf8(w) => w.code_points().nth(index).unwrap(),
}
}
}
impl core::fmt::Display for StrData {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.data.fmt(f)
}
}
impl CharLen for StrData {
fn char_len(&self) -> usize {
self.char_len()
}
}
pub fn try_get_chars(s: &str, range: impl RangeBounds<usize>) -> Option<&str> {
let mut chars = s.chars();
let start = match range.start_bound() {
Bound::Included(&i) => i,
Bound::Excluded(&i) => i + 1,
Bound::Unbounded => 0,
};
for _ in 0..start {
chars.next()?;
}
let s = chars.as_str();
let range_len = match range.end_bound() {
Bound::Included(&i) => i + 1 - start,
Bound::Excluded(&i) => i - start,
Bound::Unbounded => return Some(s),
};
char_range_end(s, range_len).map(|end| &s[..end])
}
pub fn get_chars(s: &str, range: impl RangeBounds<usize>) -> &str {
try_get_chars(s, range).unwrap()
}
#[inline]
pub fn char_range_end(s: &str, n_chars: usize) -> Option<usize> {
let i = match n_chars.checked_sub(1) {
Some(last_char_index) => {
let (index, c) = s.char_indices().nth(last_char_index)?;
index + c.len_utf8()
}
None => 0,
};
Some(i)
}
pub fn try_get_codepoints(w: &Wtf8, range: impl RangeBounds<usize>) -> Option<&Wtf8> {
let mut chars = w.code_points();
let start = match range.start_bound() {
Bound::Included(&i) => i,
Bound::Excluded(&i) => i + 1,
Bound::Unbounded => 0,
};
for _ in 0..start {
chars.next()?;
}
let s = chars.as_wtf8();
let range_len = match range.end_bound() {
Bound::Included(&i) => i + 1 - start,
Bound::Excluded(&i) => i - start,
Bound::Unbounded => return Some(s),
};
codepoint_range_end(s, range_len).map(|end| &s[..end])
}
pub fn get_codepoints(w: &Wtf8, range: impl RangeBounds<usize>) -> &Wtf8 {
try_get_codepoints(w, range).unwrap()
}
#[inline]
pub fn codepoint_range_end(s: &Wtf8, n_chars: usize) -> Option<usize> {
let i = match n_chars.checked_sub(1) {
Some(last_char_index) => {
let (index, c) = s.code_point_indices().nth(last_char_index)?;
index + c.len_wtf8()
}
None => 0,
};
Some(i)
}
pub fn zfill(bytes: &[u8], width: usize) -> Vec<u8> {
if width <= bytes.len() {
bytes.to_vec()
} else {
let (sign, s) = match bytes.first() {
Some(_sign @ b'+') | Some(_sign @ b'-') => {
(unsafe { bytes.get_unchecked(..1) }, &bytes[1..])
}
_ => (&b""[..], bytes),
};
let mut filled = Vec::new();
filled.extend_from_slice(sign);
filled.extend(core::iter::repeat_n(b'0', width - bytes.len()));
filled.extend_from_slice(s);
filled
}
}
/// Convert a string to ascii compatible, escaping unicode-s into escape
/// sequences.
pub fn to_ascii(value: &str) -> AsciiString {
let mut ascii = Vec::new();
for c in value.chars() {
if c.is_ascii() {
ascii.push(c as u8);
} else {
let c = c as i64;
let hex = if c < 0x100 {
format!("\\x{c:02x}")
} else if c < 0x10000 {
format!("\\u{c:04x}")
} else {
format!("\\U{c:08x}")
};
ascii.append(&mut hex.into_bytes());
}
}
unsafe { AsciiString::from_ascii_unchecked(ascii) }
}
pub struct UnicodeEscapeCodepoint(pub CodePoint);
impl fmt::Display for UnicodeEscapeCodepoint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let c = self.0.to_u32();
if c >= 0x10000 {
write!(f, "\\U{c:08x}")
} else if c >= 0x100 {
write!(f, "\\u{c:04x}")
} else {
write!(f, "\\x{c:02x}")
}
}
}
pub mod levenshtein {
use core::cell::RefCell;
use std::thread_local;
pub const MOVE_COST: usize = 2;
const CASE_COST: usize = 1;
const MAX_STRING_SIZE: usize = 40;
const fn substitution_cost(mut a: u8, mut b: u8) -> usize {
if (a & 31) != (b & 31) {
return MOVE_COST;
}
if a == b {
return 0;
}
if a.is_ascii_uppercase() {
a += b'a' - b'A';
}
if b.is_ascii_uppercase() {
b += b'a' - b'A';
}
if a == b { CASE_COST } else { MOVE_COST }
}
pub fn levenshtein_distance(a: &[u8], b: &[u8], max_cost: usize) -> usize {
thread_local! {
#[allow(clippy::declare_interior_mutable_const)]
static BUFFER: RefCell<[usize; MAX_STRING_SIZE]> = const {
RefCell::new([0usize; MAX_STRING_SIZE])
};
}
if a == b {
return 0;
}
let (mut a_bytes, mut b_bytes) = (a, b);
let (mut a_begin, mut a_end) = (0usize, a.len());
let (mut b_begin, mut b_end) = (0usize, b.len());
while a_end > 0 && b_end > 0 && (a_bytes[a_begin] == b_bytes[b_begin]) {
a_begin += 1;
b_begin += 1;
a_end -= 1;
b_end -= 1;
}
while a_end > 0
&& b_end > 0
&& (a_bytes[a_begin + a_end - 1] == b_bytes[b_begin + b_end - 1])
{
a_end -= 1;
b_end -= 1;
}
if a_end == 0 || b_end == 0 {
return (a_end + b_end) * MOVE_COST;
}
if a_end > MAX_STRING_SIZE || b_end > MAX_STRING_SIZE {
return max_cost + 1;
}
if b_end < a_end {
core::mem::swap(&mut a_bytes, &mut b_bytes);
core::mem::swap(&mut a_begin, &mut b_begin);
core::mem::swap(&mut a_end, &mut b_end);
}
if (b_end - a_end) * MOVE_COST > max_cost {
return max_cost + 1;
}
BUFFER.with_borrow_mut(|buffer| {
for (i, x) in buffer.iter_mut().take(a_end).enumerate() {
*x = (i + 1) * MOVE_COST;
}
let mut result = 0usize;
for (b_index, b_code) in b_bytes[b_begin..(b_begin + b_end)].iter().enumerate() {
result = b_index * MOVE_COST;
let mut distance = result;
let mut minimum = usize::MAX;
for (a_index, a_code) in a_bytes[a_begin..(a_begin + a_end)].iter().enumerate() {
let substitute = distance + substitution_cost(*b_code, *a_code);
distance = buffer[a_index];
let insert_delete = usize::min(result, distance) + MOVE_COST;
result = usize::min(insert_delete, substitute);
buffer[a_index] = result;
if result < minimum {
minimum = result;
}
}
if minimum > max_cost {
return max_cost + 1;
}
}
result
})
}
}
/// Replace all tabs in a string with spaces, using the given tab size.
pub fn expandtabs(input: &str, tab_size: usize) -> String {
let tab_stop = tab_size;
let mut expanded_str = String::with_capacity(input.len());
let mut tab_size = tab_stop;
let mut col_count = 0usize;
for ch in input.chars() {
match ch {
'\t' => {
let num_spaces = tab_size - col_count;
col_count += num_spaces;
let expand = " ".repeat(num_spaces);
expanded_str.push_str(&expand);
}
'\r' | '\n' => {
expanded_str.push(ch);
col_count = 0;
tab_size = 0;
}
_ => {
expanded_str.push(ch);
col_count += 1;
}
}
if col_count >= tab_size {
tab_size += tab_stop;
}
}
expanded_str
}
/// Creates an [`AsciiStr`][ascii::AsciiStr] from a string literal, throwing a compile error if the
/// literal isn't actually ascii.
///
/// ```compile_fail
/// # use rustpython_common::str::ascii;
/// ascii!("I ❤️ Rust & Python");
/// ```
#[macro_export]
macro_rules! ascii {
($x:expr $(,)?) => {{
let s = const {
let s: &str = $x;
assert!(s.is_ascii(), "ascii!() argument is not an ascii string");
s
};
unsafe { $crate::vendored::ascii::AsciiStr::from_ascii_unchecked(s.as_bytes()) }
}};
}
pub use ascii;
// TODO: this should probably live in a crate like unic or unicode-properties
const UNICODE_DECIMAL_VALUES: &[char] = &[
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨',
'٩', '۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹', '߀', '߁', '߂', '߃', '߄', '߅', '߆', '߇',
'߈', '߉', '०', '१', '२', '३', '४', '५', '६', '७', '८', '९', '০', '১', '২', '৩', '৪', '৫', '৬',
'৭', '৮', '৯', '੦', '੧', '੨', '੩', '੪', '੫', '੬', '੭', '੮', '੯', '૦', '૧', '૨', '૩', '૪', '૫',
'૬', '૭', '૮', '૯', '୦', '୧', '୨', '୩', '୪', '୫', '୬', '୭', '୮', '୯', '௦', '௧', '௨', '௩', '௪',
'௫', '௬', '௭', '௮', '௯', '౦', '౧', '౨', '౩', '౪', '౫', '౬', '౭', '౮', '౯', '೦', '೧', '೨', '೩',
'೪', '೫', '೬', '೭', '೮', '೯', '൦', '൧', '൨', '൩', '൪', '൫', '൬', '൭', '൮', '൯', '෦', '෧', '෨',
'෩', '෪', '෫', '෬', '෭', '෮', '෯', '๐', '๑', '๒', '๓', '๔', '๕', '๖', '๗', '๘', '๙', '໐', '໑',
'໒', '໓', '໔', '໕', '໖', '໗', '໘', '໙', '༠', '༡', '༢', '༣', '༤', '༥', '༦', '༧', '༨', '༩', '၀',
'၁', '၂', '၃', '၄', '၅', '၆', '၇', '၈', '၉', '႐', '႑', '႒', '႓', '႔', '႕', '႖', '႗', '႘', '႙',
'០', '១', '២', '៣', '៤', '៥', '៦', '៧', '៨', '៩', '᠐', '᠑', '᠒', '᠓', '᠔', '᠕', '᠖', '᠗', '᠘',
'᠙', '᥆', '᥇', '᥈', '᥉', '᥊', '᥋', '᥌', '᥍', '᥎', '᥏', '᧐', '᧑', '᧒', '᧓', '᧔', '᧕', '᧖', '᧗',
'᧘', '᧙', '᪀', '᪁', '᪂', '᪃', '᪄', '᪅', '᪆', '᪇', '᪈', '᪉', '᪐', '᪑', '᪒', '᪓', '᪔', '᪕', '᪖',
'᪗', '᪘', '᪙', '᭐', '᭑', '᭒', '᭓', '᭔', '᭕', '᭖', '᭗', '᭘', '᭙', '᮰', '᮱', '᮲', '᮳', '᮴', '᮵',
'᮶', '᮷', '᮸', '᮹', '᱀', '᱁', '᱂', '᱃', '᱄', '᱅', '᱆', '᱇', '᱈', '᱉', '᱐', '᱑', '᱒', '᱓', '᱔',
'᱕', '᱖', '᱗', '᱘', '᱙', '꘠', '꘡', '꘢', '꘣', '꘤', '꘥', '꘦', '꘧', '꘨', '꘩', '꣐', '꣑', '꣒', '꣓',
'꣔', '꣕', '꣖', '꣗', '꣘', '꣙', '꤀', '꤁', '꤂', '꤃', '꤄', '꤅', '꤆', '꤇', '꤈', '꤉', '꧐', '꧑', '꧒',
'꧓', '꧔', '꧕', '꧖', '꧗', '꧘', '꧙', '꧰', '꧱', '꧲', '꧳', '꧴', '꧵', '꧶', '꧷', '꧸', '꧹', '꩐', '꩑',
'꩒', '꩓', '꩔', '꩕', '꩖', '꩗', '꩘', '꩙', '꯰', '꯱', '꯲', '꯳', '꯴', '꯵', '꯶', '꯷', '꯸', '꯹', '0',
'1', '2', '3', '4', '5', '6', '7', '8', '9', '𐒠', '𐒡', '𐒢', '𐒣', '𐒤', '𐒥', '𐒦', '𐒧',
'𐒨', '𐒩', '𑁦', '𑁧', '𑁨', '𑁩', '𑁪', '𑁫', '𑁬', '𑁭', '𑁮', '𑁯', '𑃰', '𑃱', '𑃲', '𑃳', '𑃴', '𑃵', '𑃶',
'𑃷', '𑃸', '𑃹', '𑄶', '𑄷', '𑄸', '𑄹', '𑄺', '𑄻', '𑄼', '𑄽', '𑄾', '𑄿', '𑇐', '𑇑', '𑇒', '𑇓', '𑇔', '𑇕',
'𑇖', '𑇗', '𑇘', '𑇙', '𑋰', '𑋱', '𑋲', '𑋳', '𑋴', '𑋵', '𑋶', '𑋷', '𑋸', '𑋹', '𑑐', '𑑑', '𑑒', '𑑓', '𑑔',
'𑑕', '𑑖', '𑑗', '𑑘', '𑑙', '𑓐', '𑓑', '𑓒', '𑓓', '𑓔', '𑓕', '𑓖', '𑓗', '𑓘', '𑓙', '𑙐', '𑙑', '𑙒', '𑙓',
'𑙔', '𑙕', '𑙖', '𑙗', '𑙘', '𑙙', '𑛀', '𑛁', '𑛂', '𑛃', '𑛄', '𑛅', '𑛆', '𑛇', '𑛈', '𑛉', '𑜰', '𑜱', '𑜲',
'𑜳', '𑜴', '𑜵', '𑜶', '𑜷', '𑜸', '𑜹', '𑣠', '𑣡', '𑣢', '𑣣', '𑣤', '𑣥', '𑣦', '𑣧', '𑣨', '𑣩', '𑱐', '𑱑',
'𑱒', '𑱓', '𑱔', '𑱕', '𑱖', '𑱗', '𑱘', '𑱙', '𑵐', '𑵑', '𑵒', '𑵓', '𑵔', '𑵕', '𑵖', '𑵗', '𑵘', '𑵙', '𖩠',
'𖩡', '𖩢', '𖩣', '𖩤', '𖩥', '𖩦', '𖩧', '𖩨', '𖩩', '𖭐', '𖭑', '𖭒', '𖭓', '𖭔', '𖭕', '𖭖', '𖭗', '𖭘', '𖭙',
'𝟎', '𝟏', '𝟐', '𝟑', '𝟒', '𝟓', '𝟔', '𝟕', '𝟖', '𝟗', '𝟘', '𝟙', '𝟚', '𝟛', '𝟜', '𝟝', '𝟞', '𝟟', '𝟠',
'𝟡', '𝟢', '𝟣', '𝟤', '𝟥', '𝟦', '𝟧', '𝟨', '𝟩', '𝟪', '𝟫', '𝟬', '𝟭', '𝟮', '𝟯', '𝟰', '𝟱', '𝟲', '𝟳',
'𝟴', '𝟵', '𝟶', '𝟷', '𝟸', '𝟹', '𝟺', '𝟻', '𝟼', '𝟽', '𝟾', '𝟿', '𞥐', '𞥑', '𞥒', '𞥓', '𞥔', '𞥕', '𞥖',
'𞥗', '𞥘', '𞥙',
];
pub fn char_to_decimal(ch: char) -> Option<u8> {
UNICODE_DECIMAL_VALUES
.binary_search(&ch)
.ok()
.map(|i| (i % 10) as u8)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_chars() {
let s = "0123456789";
assert_eq!(get_chars(s, 3..7), "3456");
assert_eq!(get_chars(s, 3..7), &s[3..7]);
let s = "0유니코드 문자열9";
assert_eq!(get_chars(s, 3..7), "코드 문");
let s = "0😀😃😄😁😆😅😂🤣9";
assert_eq!(get_chars(s, 3..7), "😄😁😆😅");
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/refcount.rs | crates/common/src/refcount.rs | use crate::atomic::{Ordering::*, PyAtomic, Radium};
/// from alloc::sync
/// A soft limit on the amount of references that may be made to an `Arc`.
///
/// Going above this limit will abort your program (although not
/// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references.
const MAX_REFCOUNT: usize = isize::MAX as usize;
pub struct RefCount {
strong: PyAtomic<usize>,
}
impl Default for RefCount {
fn default() -> Self {
Self::new()
}
}
impl RefCount {
const MASK: usize = MAX_REFCOUNT;
pub fn new() -> Self {
Self {
strong: Radium::new(1),
}
}
#[inline]
pub fn get(&self) -> usize {
self.strong.load(SeqCst)
}
#[inline]
pub fn inc(&self) {
let old_size = self.strong.fetch_add(1, Relaxed);
if old_size & Self::MASK == Self::MASK {
std::process::abort();
}
}
/// Returns true if successful
#[inline]
pub fn safe_inc(&self) -> bool {
self.strong
.fetch_update(AcqRel, Acquire, |prev| (prev != 0).then_some(prev + 1))
.is_ok()
}
/// Decrement the reference count. Returns true when the refcount drops to 0.
#[inline]
pub fn dec(&self) -> bool {
if self.strong.fetch_sub(1, Release) != 1 {
return false;
}
PyAtomic::<usize>::fence(Acquire);
true
}
}
impl RefCount {
// move these functions out and give separated type once type range is stabilized
pub fn leak(&self) {
debug_assert!(!self.is_leaked());
const BIT_MARKER: usize = (isize::MAX as usize) + 1;
debug_assert_eq!(BIT_MARKER.count_ones(), 1);
debug_assert_eq!(BIT_MARKER.leading_zeros(), 0);
self.strong.fetch_add(BIT_MARKER, Relaxed);
}
pub fn is_leaked(&self) -> bool {
(self.strong.load(Acquire) as isize) < 0
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/fileutils.rs | crates/common/src/fileutils.rs | // Python/fileutils.c in CPython
#![allow(non_snake_case)]
#[cfg(not(windows))]
pub use libc::stat as StatStruct;
#[cfg(windows)]
pub use windows::{StatStruct, fstat};
#[cfg(not(windows))]
pub fn fstat(fd: crate::crt_fd::Borrowed<'_>) -> std::io::Result<StatStruct> {
let mut stat = core::mem::MaybeUninit::uninit();
unsafe {
let ret = libc::fstat(fd.as_raw(), stat.as_mut_ptr());
if ret == -1 {
Err(crate::os::errno_io_error())
} else {
Ok(stat.assume_init())
}
}
}
#[cfg(windows)]
pub mod windows {
use crate::crt_fd;
use crate::windows::ToWideString;
use libc::{S_IFCHR, S_IFDIR, S_IFMT};
use std::ffi::{CString, OsStr, OsString};
use std::os::windows::io::AsRawHandle;
use std::sync::OnceLock;
use windows_sys::Win32::Foundation::{
ERROR_INVALID_HANDLE, ERROR_NOT_SUPPORTED, FILETIME, FreeLibrary, SetLastError,
};
use windows_sys::Win32::Storage::FileSystem::{
BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_READONLY,
FILE_ATTRIBUTE_REPARSE_POINT, FILE_BASIC_INFO, FILE_ID_INFO, FILE_TYPE_CHAR,
FILE_TYPE_DISK, FILE_TYPE_PIPE, FILE_TYPE_UNKNOWN, FileBasicInfo, FileIdInfo,
GetFileInformationByHandle, GetFileInformationByHandleEx, GetFileType,
};
use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW};
use windows_sys::Win32::System::SystemServices::IO_REPARSE_TAG_SYMLINK;
use windows_sys::core::PCWSTR;
pub const S_IFIFO: libc::c_int = 0o010000;
pub const S_IFLNK: libc::c_int = 0o120000;
pub const SECS_BETWEEN_EPOCHS: i64 = 11644473600; // Seconds between 1.1.1601 and 1.1.1970
#[derive(Default)]
pub struct StatStruct {
pub st_dev: libc::c_ulong,
pub st_ino: u64,
pub st_mode: libc::c_ushort,
pub st_nlink: i32,
pub st_uid: i32,
pub st_gid: i32,
pub st_rdev: libc::c_ulong,
pub st_size: u64,
pub st_atime: libc::time_t,
pub st_atime_nsec: i32,
pub st_mtime: libc::time_t,
pub st_mtime_nsec: i32,
pub st_ctime: libc::time_t,
pub st_ctime_nsec: i32,
pub st_birthtime: libc::time_t,
pub st_birthtime_nsec: i32,
pub st_file_attributes: libc::c_ulong,
pub st_reparse_tag: u32,
pub st_ino_high: u64,
}
impl StatStruct {
// update_st_mode_from_path in cpython
pub fn update_st_mode_from_path(&mut self, path: &OsStr, attr: u32) {
if attr & FILE_ATTRIBUTE_DIRECTORY == 0 {
let file_extension = path
.to_wide()
.split(|&c| c == '.' as u16)
.next_back()
.and_then(|s| String::from_utf16(s).ok());
if let Some(file_extension) = file_extension
&& (file_extension.eq_ignore_ascii_case("exe")
|| file_extension.eq_ignore_ascii_case("bat")
|| file_extension.eq_ignore_ascii_case("cmd")
|| file_extension.eq_ignore_ascii_case("com"))
{
self.st_mode |= 0o111;
}
}
}
}
// _Py_fstat_noraise in cpython
pub fn fstat(fd: crt_fd::Borrowed<'_>) -> std::io::Result<StatStruct> {
let h = crt_fd::as_handle(fd);
if h.is_err() {
unsafe { SetLastError(ERROR_INVALID_HANDLE) };
}
let h = h?;
let h = h.as_raw_handle();
// reset stat?
let file_type = unsafe { GetFileType(h as _) };
if file_type == FILE_TYPE_UNKNOWN {
return Err(std::io::Error::last_os_error());
}
if file_type != FILE_TYPE_DISK {
let st_mode = if file_type == FILE_TYPE_CHAR {
S_IFCHR
} else if file_type == FILE_TYPE_PIPE {
S_IFIFO
} else {
0
} as u16;
return Ok(StatStruct {
st_mode,
..Default::default()
});
}
let mut info = unsafe { std::mem::zeroed() };
let mut basic_info: FILE_BASIC_INFO = unsafe { std::mem::zeroed() };
let mut id_info: FILE_ID_INFO = unsafe { std::mem::zeroed() };
if unsafe { GetFileInformationByHandle(h as _, &mut info) } == 0
|| unsafe {
GetFileInformationByHandleEx(
h as _,
FileBasicInfo,
&mut basic_info as *mut _ as *mut _,
std::mem::size_of_val(&basic_info) as u32,
)
} == 0
{
return Err(std::io::Error::last_os_error());
}
let p_id_info = if unsafe {
GetFileInformationByHandleEx(
h as _,
FileIdInfo,
&mut id_info as *mut _ as *mut _,
std::mem::size_of_val(&id_info) as u32,
)
} == 0
{
None
} else {
Some(&id_info)
};
Ok(attribute_data_to_stat(
&info,
0,
Some(&basic_info),
p_id_info,
))
}
fn large_integer_to_time_t_nsec(input: i64) -> (libc::time_t, libc::c_int) {
let nsec_out = (input % 10_000_000) * 100; // FILETIME is in units of 100 nsec.
let time_out = ((input / 10_000_000) - SECS_BETWEEN_EPOCHS) as libc::time_t;
(time_out, nsec_out as _)
}
fn file_time_to_time_t_nsec(in_ptr: &FILETIME) -> (libc::time_t, libc::c_int) {
let in_val: i64 = unsafe { core::mem::transmute_copy(in_ptr) };
let nsec_out = (in_val % 10_000_000) * 100; // FILETIME is in units of 100 nsec.
let time_out = (in_val / 10_000_000) - SECS_BETWEEN_EPOCHS;
(time_out, nsec_out as _)
}
fn attribute_data_to_stat(
info: &BY_HANDLE_FILE_INFORMATION,
reparse_tag: u32,
basic_info: Option<&FILE_BASIC_INFO>,
id_info: Option<&FILE_ID_INFO>,
) -> StatStruct {
let mut st_mode = attributes_to_mode(info.dwFileAttributes);
let st_size = ((info.nFileSizeHigh as u64) << 32) + info.nFileSizeLow as u64;
let st_dev: libc::c_ulong = if let Some(id_info) = id_info {
id_info.VolumeSerialNumber as _
} else {
info.dwVolumeSerialNumber
};
let st_rdev = 0;
let (st_birthtime, st_ctime, st_mtime, st_atime) = if let Some(basic_info) = basic_info {
(
large_integer_to_time_t_nsec(basic_info.CreationTime),
large_integer_to_time_t_nsec(basic_info.ChangeTime),
large_integer_to_time_t_nsec(basic_info.LastWriteTime),
large_integer_to_time_t_nsec(basic_info.LastAccessTime),
)
} else {
(
file_time_to_time_t_nsec(&info.ftCreationTime),
(0, 0),
file_time_to_time_t_nsec(&info.ftLastWriteTime),
file_time_to_time_t_nsec(&info.ftLastAccessTime),
)
};
let st_nlink = info.nNumberOfLinks as i32;
let st_ino = if let Some(id_info) = id_info {
let file_id: [u64; 2] = unsafe { core::mem::transmute_copy(&id_info.FileId) };
file_id
} else {
let ino = ((info.nFileIndexHigh as u64) << 32) + info.nFileIndexLow as u64;
[ino, 0]
};
if info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0
&& reparse_tag == IO_REPARSE_TAG_SYMLINK
{
st_mode = (st_mode & !(S_IFMT as u16)) | (S_IFLNK as u16);
}
let st_file_attributes = info.dwFileAttributes;
StatStruct {
st_dev,
st_ino: st_ino[0],
st_mode,
st_nlink,
st_uid: 0,
st_gid: 0,
st_rdev,
st_size,
st_atime: st_atime.0,
st_atime_nsec: st_atime.1,
st_mtime: st_mtime.0,
st_mtime_nsec: st_mtime.1,
st_ctime: st_ctime.0,
st_ctime_nsec: st_ctime.1,
st_birthtime: st_birthtime.0,
st_birthtime_nsec: st_birthtime.1,
st_file_attributes,
st_reparse_tag: reparse_tag,
st_ino_high: st_ino[1],
}
}
const fn attributes_to_mode(attr: u32) -> u16 {
let mut m = 0;
if attr & FILE_ATTRIBUTE_DIRECTORY != 0 {
m |= libc::S_IFDIR | 0o111; // IFEXEC for user,group,other
} else {
m |= libc::S_IFREG;
}
if attr & FILE_ATTRIBUTE_READONLY != 0 {
m |= 0o444;
} else {
m |= 0o666;
}
m as _
}
#[repr(C)]
pub struct FILE_STAT_BASIC_INFORMATION {
pub FileId: i64,
pub CreationTime: i64,
pub LastAccessTime: i64,
pub LastWriteTime: i64,
pub ChangeTime: i64,
pub AllocationSize: i64,
pub EndOfFile: i64,
pub FileAttributes: u32,
pub ReparseTag: u32,
pub NumberOfLinks: u32,
pub DeviceType: u32,
pub DeviceCharacteristics: u32,
pub Reserved: u32,
pub VolumeSerialNumber: i64,
pub FileId128: [u64; 2],
}
#[repr(C)]
#[allow(dead_code)]
pub enum FILE_INFO_BY_NAME_CLASS {
FileStatByNameInfo,
FileStatLxByNameInfo,
FileCaseSensitiveByNameInfo,
FileStatBasicByNameInfo,
MaximumFileInfoByNameClass,
}
// _Py_GetFileInformationByName in cpython
pub fn get_file_information_by_name(
file_name: &OsStr,
file_information_class: FILE_INFO_BY_NAME_CLASS,
) -> std::io::Result<FILE_STAT_BASIC_INFORMATION> {
static GET_FILE_INFORMATION_BY_NAME: OnceLock<
Option<
unsafe extern "system" fn(
PCWSTR,
FILE_INFO_BY_NAME_CLASS,
*mut libc::c_void,
u32,
) -> i32,
>,
> = OnceLock::new();
let GetFileInformationByName = GET_FILE_INFORMATION_BY_NAME
.get_or_init(|| {
let library_name = OsString::from("api-ms-win-core-file-l2-1-4").to_wide_with_nul();
let module = unsafe { LoadLibraryW(library_name.as_ptr()) };
if module.is_null() {
return None;
}
let name = CString::new("GetFileInformationByName").unwrap();
if let Some(proc) =
unsafe { GetProcAddress(module, name.as_bytes_with_nul().as_ptr()) }
{
Some(unsafe {
core::mem::transmute::<
unsafe extern "system" fn() -> isize,
unsafe extern "system" fn(
*const u16,
FILE_INFO_BY_NAME_CLASS,
*mut libc::c_void,
u32,
) -> i32,
>(proc)
})
} else {
unsafe { FreeLibrary(module) };
None
}
})
.ok_or_else(|| std::io::Error::from_raw_os_error(ERROR_NOT_SUPPORTED as _))?;
let file_name = file_name.to_wide_with_nul();
let file_info_buffer_size = std::mem::size_of::<FILE_STAT_BASIC_INFORMATION>() as u32;
let mut file_info_buffer = std::mem::MaybeUninit::<FILE_STAT_BASIC_INFORMATION>::uninit();
unsafe {
if GetFileInformationByName(
file_name.as_ptr(),
file_information_class as _,
file_info_buffer.as_mut_ptr() as _,
file_info_buffer_size,
) == 0
{
Err(std::io::Error::last_os_error())
} else {
Ok(file_info_buffer.assume_init())
}
}
}
pub fn stat_basic_info_to_stat(info: &FILE_STAT_BASIC_INFORMATION) -> StatStruct {
use windows_sys::Win32::Storage::FileSystem;
use windows_sys::Win32::System::Ioctl;
const S_IFMT: u16 = self::S_IFMT as _;
const S_IFDIR: u16 = self::S_IFDIR as _;
const S_IFCHR: u16 = self::S_IFCHR as _;
const S_IFIFO: u16 = self::S_IFIFO as _;
const S_IFLNK: u16 = self::S_IFLNK as _;
let mut st_mode = attributes_to_mode(info.FileAttributes);
let st_size = info.EndOfFile as u64;
let st_birthtime = large_integer_to_time_t_nsec(info.CreationTime);
let st_ctime = large_integer_to_time_t_nsec(info.ChangeTime);
let st_mtime = large_integer_to_time_t_nsec(info.LastWriteTime);
let st_atime = large_integer_to_time_t_nsec(info.LastAccessTime);
let st_nlink = info.NumberOfLinks as _;
let st_dev = info.VolumeSerialNumber as u32;
// File systems with less than 128-bits zero pad into this field
let st_ino = info.FileId128;
// bpo-37834: Only actual symlinks set the S_IFLNK flag. But lstat() will
// open other name surrogate reparse points without traversing them. To
// detect/handle these, check st_file_attributes and st_reparse_tag.
let st_reparse_tag = info.ReparseTag;
if info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0
&& info.ReparseTag == IO_REPARSE_TAG_SYMLINK
{
// set the bits that make this a symlink
st_mode = (st_mode & !S_IFMT) | S_IFLNK;
}
let st_file_attributes = info.FileAttributes;
match info.DeviceType {
FileSystem::FILE_DEVICE_DISK
| Ioctl::FILE_DEVICE_VIRTUAL_DISK
| Ioctl::FILE_DEVICE_DFS
| FileSystem::FILE_DEVICE_CD_ROM
| Ioctl::FILE_DEVICE_CONTROLLER
| Ioctl::FILE_DEVICE_DATALINK => {}
Ioctl::FILE_DEVICE_DISK_FILE_SYSTEM
| Ioctl::FILE_DEVICE_CD_ROM_FILE_SYSTEM
| Ioctl::FILE_DEVICE_NETWORK_FILE_SYSTEM => {
st_mode = (st_mode & !S_IFMT) | 0x6000; // _S_IFBLK
}
Ioctl::FILE_DEVICE_CONSOLE
| Ioctl::FILE_DEVICE_NULL
| Ioctl::FILE_DEVICE_KEYBOARD
| Ioctl::FILE_DEVICE_MODEM
| Ioctl::FILE_DEVICE_MOUSE
| Ioctl::FILE_DEVICE_PARALLEL_PORT
| Ioctl::FILE_DEVICE_PRINTER
| Ioctl::FILE_DEVICE_SCREEN
| Ioctl::FILE_DEVICE_SERIAL_PORT
| Ioctl::FILE_DEVICE_SOUND => {
st_mode = (st_mode & !S_IFMT) | S_IFCHR;
}
Ioctl::FILE_DEVICE_NAMED_PIPE => {
st_mode = (st_mode & !S_IFMT) | S_IFIFO;
}
_ => {
if info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0 {
st_mode = (st_mode & !S_IFMT) | S_IFDIR;
}
}
}
StatStruct {
st_dev,
st_ino: st_ino[0],
st_mode,
st_nlink,
st_uid: 0,
st_gid: 0,
st_rdev: 0,
st_size,
st_atime: st_atime.0,
st_atime_nsec: st_atime.1,
st_mtime: st_mtime.0,
st_mtime_nsec: st_mtime.1,
st_ctime: st_ctime.0,
st_ctime_nsec: st_ctime.1,
st_birthtime: st_birthtime.0,
st_birthtime_nsec: st_birthtime.1,
st_file_attributes,
st_reparse_tag,
st_ino_high: st_ino[1],
}
}
}
// _Py_fopen_obj in cpython (Python/fileutils.c:1757-1835)
// Open a file using std::fs::File and convert to FILE*
// Automatically handles path encoding and EINTR retries
pub fn fopen(path: &std::path::Path, mode: &str) -> std::io::Result<*mut libc::FILE> {
use alloc::ffi::CString;
use std::fs::File;
// Currently only supports read mode
// Can be extended to support "wb", "w+b", etc. if needed
if mode != "rb" {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("unsupported mode: {}", mode),
));
}
// Open file using std::fs::File (handles path encoding and EINTR automatically)
let file = File::open(path)?;
#[cfg(windows)]
{
use std::os::windows::io::IntoRawHandle;
// Convert File handle to CRT file descriptor
let handle = file.into_raw_handle();
let fd = unsafe { libc::open_osfhandle(handle as isize, libc::O_RDONLY) };
if fd == -1 {
return Err(std::io::Error::last_os_error());
}
// Convert fd to FILE*
let mode_cstr = CString::new(mode).unwrap();
let fp = unsafe { libc::fdopen(fd, mode_cstr.as_ptr()) };
if fp.is_null() {
unsafe { libc::close(fd) };
return Err(std::io::Error::last_os_error());
}
// Set non-inheritable (Windows needs this explicitly)
if let Err(e) = set_inheritable(fd, false) {
unsafe { libc::fclose(fp) };
return Err(e);
}
Ok(fp)
}
#[cfg(not(windows))]
{
use std::os::fd::IntoRawFd;
// Convert File to raw fd
let fd = file.into_raw_fd();
// Convert fd to FILE*
let mode_cstr = CString::new(mode).unwrap();
let fp = unsafe { libc::fdopen(fd, mode_cstr.as_ptr()) };
if fp.is_null() {
unsafe { libc::close(fd) };
return Err(std::io::Error::last_os_error());
}
// Unix: O_CLOEXEC is already set by File::open, so non-inheritable is automatic
Ok(fp)
}
}
// set_inheritable in cpython (Python/fileutils.c:1443-1570)
// Set the inheritable flag of the specified file descriptor
// Only used on Windows; Unix automatically sets O_CLOEXEC
#[cfg(windows)]
fn set_inheritable(fd: libc::c_int, inheritable: bool) -> std::io::Result<()> {
use windows_sys::Win32::Foundation::{
HANDLE, HANDLE_FLAG_INHERIT, INVALID_HANDLE_VALUE, SetHandleInformation,
};
let handle = unsafe { libc::get_osfhandle(fd) };
if handle == INVALID_HANDLE_VALUE as isize {
return Err(std::io::Error::last_os_error());
}
let flags = if inheritable { HANDLE_FLAG_INHERIT } else { 0 };
let result = unsafe { SetHandleInformation(handle as HANDLE, HANDLE_FLAG_INHERIT, flags) };
if result == 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/encodings.rs | crates/common/src/encodings.rs | use core::ops::{self, Range};
use num_traits::ToPrimitive;
use crate::str::StrKind;
use crate::wtf8::{CodePoint, Wtf8, Wtf8Buf};
pub trait StrBuffer: AsRef<Wtf8> {
fn is_compatible_with(&self, kind: StrKind) -> bool {
let s = self.as_ref();
match kind {
StrKind::Ascii => s.is_ascii(),
StrKind::Utf8 => s.is_utf8(),
StrKind::Wtf8 => true,
}
}
}
pub trait CodecContext: Sized {
type Error;
type StrBuf: StrBuffer;
type BytesBuf: AsRef<[u8]>;
fn string(&self, s: Wtf8Buf) -> Self::StrBuf;
fn bytes(&self, b: Vec<u8>) -> Self::BytesBuf;
}
pub trait EncodeContext: CodecContext {
fn full_data(&self) -> &Wtf8;
fn data_len(&self) -> StrSize;
fn remaining_data(&self) -> &Wtf8;
fn position(&self) -> StrSize;
fn restart_from(&mut self, pos: StrSize) -> Result<(), Self::Error>;
fn error_encoding(&self, range: Range<StrSize>, reason: Option<&str>) -> Self::Error;
fn handle_error<E>(
&mut self,
errors: &E,
range: Range<StrSize>,
reason: Option<&str>,
) -> Result<EncodeReplace<Self>, Self::Error>
where
E: EncodeErrorHandler<Self>,
{
let (replace, restart) = errors.handle_encode_error(self, range, reason)?;
self.restart_from(restart)?;
Ok(replace)
}
}
pub trait DecodeContext: CodecContext {
fn full_data(&self) -> &[u8];
fn remaining_data(&self) -> &[u8];
fn position(&self) -> usize;
fn advance(&mut self, by: usize);
fn restart_from(&mut self, pos: usize) -> Result<(), Self::Error>;
fn error_decoding(&self, byte_range: Range<usize>, reason: Option<&str>) -> Self::Error;
fn handle_error<E>(
&mut self,
errors: &E,
byte_range: Range<usize>,
reason: Option<&str>,
) -> Result<Self::StrBuf, Self::Error>
where
E: DecodeErrorHandler<Self>,
{
let (replace, restart) = errors.handle_decode_error(self, byte_range, reason)?;
self.restart_from(restart)?;
Ok(replace)
}
}
pub trait EncodeErrorHandler<Ctx: EncodeContext> {
fn handle_encode_error(
&self,
ctx: &mut Ctx,
range: Range<StrSize>,
reason: Option<&str>,
) -> Result<(EncodeReplace<Ctx>, StrSize), Ctx::Error>;
}
pub trait DecodeErrorHandler<Ctx: DecodeContext> {
fn handle_decode_error(
&self,
ctx: &mut Ctx,
byte_range: Range<usize>,
reason: Option<&str>,
) -> Result<(Ctx::StrBuf, usize), Ctx::Error>;
}
pub enum EncodeReplace<Ctx: CodecContext> {
Str(Ctx::StrBuf),
Bytes(Ctx::BytesBuf),
}
#[derive(Copy, Clone, Default, Debug)]
pub struct StrSize {
pub bytes: usize,
pub chars: usize,
}
fn iter_code_points(w: &Wtf8) -> impl Iterator<Item = (StrSize, CodePoint)> {
w.code_point_indices()
.enumerate()
.map(|(chars, (bytes, c))| (StrSize { bytes, chars }, c))
}
impl ops::Add for StrSize {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self {
bytes: self.bytes + rhs.bytes,
chars: self.chars + rhs.chars,
}
}
}
impl ops::AddAssign for StrSize {
fn add_assign(&mut self, rhs: Self) {
self.bytes += rhs.bytes;
self.chars += rhs.chars;
}
}
struct DecodeError<'a> {
valid_prefix: &'a str,
rest: &'a [u8],
err_len: Option<usize>,
}
/// # Safety
/// `v[..valid_up_to]` must be valid utf8
const unsafe fn make_decode_err(
v: &[u8],
valid_up_to: usize,
err_len: Option<usize>,
) -> DecodeError<'_> {
let (valid_prefix, rest) = unsafe { v.split_at_unchecked(valid_up_to) };
let valid_prefix = unsafe { core::str::from_utf8_unchecked(valid_prefix) };
DecodeError {
valid_prefix,
rest,
err_len,
}
}
enum HandleResult<'a> {
Done,
Error {
err_len: Option<usize>,
reason: &'a str,
},
}
fn decode_utf8_compatible<Ctx, E, DecodeF, ErrF>(
mut ctx: Ctx,
errors: &E,
decode: DecodeF,
handle_error: ErrF,
) -> Result<(Wtf8Buf, usize), Ctx::Error>
where
Ctx: DecodeContext,
E: DecodeErrorHandler<Ctx>,
DecodeF: Fn(&[u8]) -> Result<&str, DecodeError<'_>>,
ErrF: Fn(&[u8], Option<usize>) -> HandleResult<'static>,
{
if ctx.remaining_data().is_empty() {
return Ok((Wtf8Buf::new(), 0));
}
let mut out = Wtf8Buf::with_capacity(ctx.remaining_data().len());
loop {
match decode(ctx.remaining_data()) {
Ok(decoded) => {
out.push_str(decoded);
ctx.advance(decoded.len());
break;
}
Err(e) => {
out.push_str(e.valid_prefix);
match handle_error(e.rest, e.err_len) {
HandleResult::Done => {
ctx.advance(e.valid_prefix.len());
break;
}
HandleResult::Error { err_len, reason } => {
let err_start = ctx.position() + e.valid_prefix.len();
let err_end = match err_len {
Some(len) => err_start + len,
None => ctx.full_data().len(),
};
let err_range = err_start..err_end;
let replace = ctx.handle_error(errors, err_range, Some(reason))?;
out.push_wtf8(replace.as_ref());
continue;
}
}
}
}
}
Ok((out, ctx.position()))
}
#[inline]
fn encode_utf8_compatible<Ctx, E>(
mut ctx: Ctx,
errors: &E,
err_reason: &str,
target_kind: StrKind,
) -> Result<Vec<u8>, Ctx::Error>
where
Ctx: EncodeContext,
E: EncodeErrorHandler<Ctx>,
{
// let mut data = s.as_ref();
// let mut char_data_index = 0;
let mut out = Vec::<u8>::with_capacity(ctx.remaining_data().len());
loop {
let data = ctx.remaining_data();
let mut iter = iter_code_points(data);
let Some((i, _)) = iter.find(|(_, c)| !target_kind.can_encode(*c)) else {
break;
};
out.extend_from_slice(&ctx.remaining_data().as_bytes()[..i.bytes]);
let err_start = ctx.position() + i;
// number of non-compatible chars between the first non-compatible char and the next compatible char
let err_end = match { iter }.find(|(_, c)| target_kind.can_encode(*c)) {
Some((i, _)) => ctx.position() + i,
None => ctx.data_len(),
};
let range = err_start..err_end;
let replace = ctx.handle_error(errors, range.clone(), Some(err_reason))?;
match replace {
EncodeReplace::Str(s) => {
if s.is_compatible_with(target_kind) {
out.extend_from_slice(s.as_ref().as_bytes());
} else {
return Err(ctx.error_encoding(range, Some(err_reason)));
}
}
EncodeReplace::Bytes(b) => {
out.extend_from_slice(b.as_ref());
}
}
}
out.extend_from_slice(ctx.remaining_data().as_bytes());
Ok(out)
}
pub mod errors {
use crate::str::UnicodeEscapeCodepoint;
use super::*;
use core::fmt::Write;
pub struct Strict;
impl<Ctx: EncodeContext> EncodeErrorHandler<Ctx> for Strict {
fn handle_encode_error(
&self,
ctx: &mut Ctx,
range: Range<StrSize>,
reason: Option<&str>,
) -> Result<(EncodeReplace<Ctx>, StrSize), Ctx::Error> {
Err(ctx.error_encoding(range, reason))
}
}
impl<Ctx: DecodeContext> DecodeErrorHandler<Ctx> for Strict {
fn handle_decode_error(
&self,
ctx: &mut Ctx,
byte_range: Range<usize>,
reason: Option<&str>,
) -> Result<(Ctx::StrBuf, usize), Ctx::Error> {
Err(ctx.error_decoding(byte_range, reason))
}
}
pub struct Ignore;
impl<Ctx: EncodeContext> EncodeErrorHandler<Ctx> for Ignore {
fn handle_encode_error(
&self,
ctx: &mut Ctx,
range: Range<StrSize>,
_reason: Option<&str>,
) -> Result<(EncodeReplace<Ctx>, StrSize), Ctx::Error> {
Ok((EncodeReplace::Bytes(ctx.bytes(b"".into())), range.end))
}
}
impl<Ctx: DecodeContext> DecodeErrorHandler<Ctx> for Ignore {
fn handle_decode_error(
&self,
ctx: &mut Ctx,
byte_range: Range<usize>,
_reason: Option<&str>,
) -> Result<(Ctx::StrBuf, usize), Ctx::Error> {
Ok((ctx.string("".into()), byte_range.end))
}
}
pub struct Replace;
impl<Ctx: EncodeContext> EncodeErrorHandler<Ctx> for Replace {
fn handle_encode_error(
&self,
ctx: &mut Ctx,
range: Range<StrSize>,
_reason: Option<&str>,
) -> Result<(EncodeReplace<Ctx>, StrSize), Ctx::Error> {
let replace = "?".repeat(range.end.chars - range.start.chars);
Ok((EncodeReplace::Str(ctx.string(replace.into())), range.end))
}
}
impl<Ctx: DecodeContext> DecodeErrorHandler<Ctx> for Replace {
fn handle_decode_error(
&self,
ctx: &mut Ctx,
byte_range: Range<usize>,
_reason: Option<&str>,
) -> Result<(Ctx::StrBuf, usize), Ctx::Error> {
Ok((
ctx.string(char::REPLACEMENT_CHARACTER.to_string().into()),
byte_range.end,
))
}
}
pub struct XmlCharRefReplace;
impl<Ctx: EncodeContext> EncodeErrorHandler<Ctx> for XmlCharRefReplace {
fn handle_encode_error(
&self,
ctx: &mut Ctx,
range: Range<StrSize>,
_reason: Option<&str>,
) -> Result<(EncodeReplace<Ctx>, StrSize), Ctx::Error> {
let err_str = &ctx.full_data()[range.start.bytes..range.end.bytes];
let num_chars = range.end.chars - range.start.chars;
// capacity rough guess; assuming that the codepoints are 3 digits in decimal + the &#;
let mut out = String::with_capacity(num_chars * 6);
for c in err_str.code_points() {
write!(out, "&#{};", c.to_u32()).unwrap()
}
Ok((EncodeReplace::Str(ctx.string(out.into())), range.end))
}
}
pub struct BackslashReplace;
impl<Ctx: EncodeContext> EncodeErrorHandler<Ctx> for BackslashReplace {
fn handle_encode_error(
&self,
ctx: &mut Ctx,
range: Range<StrSize>,
_reason: Option<&str>,
) -> Result<(EncodeReplace<Ctx>, StrSize), Ctx::Error> {
let err_str = &ctx.full_data()[range.start.bytes..range.end.bytes];
let num_chars = range.end.chars - range.start.chars;
// minimum 4 output bytes per char: \xNN
let mut out = String::with_capacity(num_chars * 4);
for c in err_str.code_points() {
write!(out, "{}", UnicodeEscapeCodepoint(c)).unwrap();
}
Ok((EncodeReplace::Str(ctx.string(out.into())), range.end))
}
}
impl<Ctx: DecodeContext> DecodeErrorHandler<Ctx> for BackslashReplace {
fn handle_decode_error(
&self,
ctx: &mut Ctx,
byte_range: Range<usize>,
_reason: Option<&str>,
) -> Result<(Ctx::StrBuf, usize), Ctx::Error> {
let err_bytes = &ctx.full_data()[byte_range.clone()];
let mut replace = String::with_capacity(4 * err_bytes.len());
for &c in err_bytes {
write!(replace, "\\x{c:02x}").unwrap();
}
Ok((ctx.string(replace.into()), byte_range.end))
}
}
pub struct NameReplace;
impl<Ctx: EncodeContext> EncodeErrorHandler<Ctx> for NameReplace {
fn handle_encode_error(
&self,
ctx: &mut Ctx,
range: Range<StrSize>,
_reason: Option<&str>,
) -> Result<(EncodeReplace<Ctx>, StrSize), Ctx::Error> {
let err_str = &ctx.full_data()[range.start.bytes..range.end.bytes];
let num_chars = range.end.chars - range.start.chars;
let mut out = String::with_capacity(num_chars * 4);
for c in err_str.code_points() {
let c_u32 = c.to_u32();
if let Some(c_name) = c.to_char().and_then(unicode_names2::name) {
write!(out, "\\N{{{c_name}}}").unwrap();
} else if c_u32 >= 0x10000 {
write!(out, "\\U{c_u32:08x}").unwrap();
} else if c_u32 >= 0x100 {
write!(out, "\\u{c_u32:04x}").unwrap();
} else {
write!(out, "\\x{c_u32:02x}").unwrap();
}
}
Ok((EncodeReplace::Str(ctx.string(out.into())), range.end))
}
}
pub struct SurrogateEscape;
impl<Ctx: EncodeContext> EncodeErrorHandler<Ctx> for SurrogateEscape {
fn handle_encode_error(
&self,
ctx: &mut Ctx,
range: Range<StrSize>,
reason: Option<&str>,
) -> Result<(EncodeReplace<Ctx>, StrSize), Ctx::Error> {
let err_str = &ctx.full_data()[range.start.bytes..range.end.bytes];
let num_chars = range.end.chars - range.start.chars;
let mut out = Vec::with_capacity(num_chars);
for ch in err_str.code_points() {
let ch = ch.to_u32();
if !(0xdc80..=0xdcff).contains(&ch) {
// Not a UTF-8b surrogate, fail with original exception
return Err(ctx.error_encoding(range, reason));
}
out.push((ch - 0xdc00) as u8);
}
Ok((EncodeReplace::Bytes(ctx.bytes(out)), range.end))
}
}
impl<Ctx: DecodeContext> DecodeErrorHandler<Ctx> for SurrogateEscape {
fn handle_decode_error(
&self,
ctx: &mut Ctx,
byte_range: Range<usize>,
reason: Option<&str>,
) -> Result<(Ctx::StrBuf, usize), Ctx::Error> {
let err_bytes = &ctx.full_data()[byte_range.clone()];
let mut consumed = 0;
let mut replace = Wtf8Buf::with_capacity(4 * byte_range.len());
while consumed < 4 && consumed < byte_range.len() {
let c = err_bytes[consumed] as u16;
// Refuse to escape ASCII bytes
if c < 128 {
break;
}
replace.push(CodePoint::from(0xdc00 + c));
consumed += 1;
}
if consumed == 0 {
return Err(ctx.error_decoding(byte_range, reason));
}
Ok((ctx.string(replace), byte_range.start + consumed))
}
}
}
pub mod utf8 {
use super::*;
pub const ENCODING_NAME: &str = "utf-8";
#[inline]
pub fn encode<Ctx, E>(ctx: Ctx, errors: &E) -> Result<Vec<u8>, Ctx::Error>
where
Ctx: EncodeContext,
E: EncodeErrorHandler<Ctx>,
{
encode_utf8_compatible(ctx, errors, "surrogates not allowed", StrKind::Utf8)
}
pub fn decode<Ctx: DecodeContext, E: DecodeErrorHandler<Ctx>>(
ctx: Ctx,
errors: &E,
final_decode: bool,
) -> Result<(Wtf8Buf, usize), Ctx::Error> {
decode_utf8_compatible(
ctx,
errors,
|v| {
core::str::from_utf8(v).map_err(|e| {
// SAFETY: as specified in valid_up_to's documentation, input[..e.valid_up_to()]
// is valid utf8
unsafe { make_decode_err(v, e.valid_up_to(), e.error_len()) }
})
},
|rest, err_len| {
let first_err = rest[0];
if matches!(first_err, 0x80..=0xc1 | 0xf5..=0xff) {
HandleResult::Error {
err_len: Some(1),
reason: "invalid start byte",
}
} else if err_len.is_none() {
// error_len() == None means unexpected eof
if final_decode {
HandleResult::Error {
err_len,
reason: "unexpected end of data",
}
} else {
HandleResult::Done
}
} else if !final_decode && matches!(rest, [0xed, 0xa0..=0xbf]) {
// truncated surrogate
HandleResult::Done
} else {
HandleResult::Error {
err_len,
reason: "invalid continuation byte",
}
}
},
)
}
}
pub mod latin_1 {
use super::*;
pub const ENCODING_NAME: &str = "latin-1";
const ERR_REASON: &str = "ordinal not in range(256)";
#[inline]
pub fn encode<Ctx, E>(mut ctx: Ctx, errors: &E) -> Result<Vec<u8>, Ctx::Error>
where
Ctx: EncodeContext,
E: EncodeErrorHandler<Ctx>,
{
let mut out = Vec::<u8>::new();
loop {
let data = ctx.remaining_data();
let mut iter = iter_code_points(ctx.remaining_data());
let Some((i, ch)) = iter.find(|(_, c)| !c.is_ascii()) else {
break;
};
out.extend_from_slice(&data.as_bytes()[..i.bytes]);
let err_start = ctx.position() + i;
if let Some(byte) = ch.to_u32().to_u8() {
drop(iter);
out.push(byte);
// if the codepoint is between 128..=255, it's utf8-length is 2
ctx.restart_from(err_start + StrSize { bytes: 2, chars: 1 })?;
} else {
// number of non-latin_1 chars between the first non-latin_1 char and the next latin_1 char
let err_end = match { iter }.find(|(_, c)| c.to_u32() <= 255) {
Some((i, _)) => ctx.position() + i,
None => ctx.data_len(),
};
let err_range = err_start..err_end;
let replace = ctx.handle_error(errors, err_range.clone(), Some(ERR_REASON))?;
match replace {
EncodeReplace::Str(s) => {
if s.as_ref().code_points().any(|c| c.to_u32() > 255) {
return Err(ctx.error_encoding(err_range, Some(ERR_REASON)));
}
out.extend(s.as_ref().code_points().map(|c| c.to_u32() as u8));
}
EncodeReplace::Bytes(b) => {
out.extend_from_slice(b.as_ref());
}
}
}
}
out.extend_from_slice(ctx.remaining_data().as_bytes());
Ok(out)
}
pub fn decode<Ctx: DecodeContext, E: DecodeErrorHandler<Ctx>>(
ctx: Ctx,
_errors: &E,
) -> Result<(Wtf8Buf, usize), Ctx::Error> {
let out: String = ctx.remaining_data().iter().map(|c| *c as char).collect();
let out_len = out.len();
Ok((out.into(), out_len))
}
}
pub mod ascii {
use super::*;
use ::ascii::AsciiStr;
pub const ENCODING_NAME: &str = "ascii";
const ERR_REASON: &str = "ordinal not in range(128)";
#[inline]
pub fn encode<Ctx, E>(ctx: Ctx, errors: &E) -> Result<Vec<u8>, Ctx::Error>
where
Ctx: EncodeContext,
E: EncodeErrorHandler<Ctx>,
{
encode_utf8_compatible(ctx, errors, ERR_REASON, StrKind::Ascii)
}
pub fn decode<Ctx: DecodeContext, E: DecodeErrorHandler<Ctx>>(
ctx: Ctx,
errors: &E,
) -> Result<(Wtf8Buf, usize), Ctx::Error> {
decode_utf8_compatible(
ctx,
errors,
|v| {
AsciiStr::from_ascii(v).map(|s| s.as_str()).map_err(|e| {
// SAFETY: as specified in valid_up_to's documentation, input[..e.valid_up_to()]
// is valid ascii & therefore valid utf8
unsafe { make_decode_err(v, e.valid_up_to(), Some(1)) }
})
},
|_rest, err_len| HandleResult::Error {
err_len,
reason: ERR_REASON,
},
)
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/lock/thread_mutex.rs | crates/common/src/lock/thread_mutex.rs | #![allow(clippy::needless_lifetimes)]
use alloc::fmt;
use core::{
cell::UnsafeCell,
marker::PhantomData,
ops::{Deref, DerefMut},
ptr::NonNull,
sync::atomic::{AtomicUsize, Ordering},
};
use lock_api::{GetThreadId, GuardNoSend, RawMutex};
// based off ReentrantMutex from lock_api
/// A mutex type that knows when it would deadlock
pub struct RawThreadMutex<R: RawMutex, G: GetThreadId> {
owner: AtomicUsize,
mutex: R,
get_thread_id: G,
}
impl<R: RawMutex, G: GetThreadId> RawThreadMutex<R, G> {
#[allow(clippy::declare_interior_mutable_const)]
pub const INIT: Self = Self {
owner: AtomicUsize::new(0),
mutex: R::INIT,
get_thread_id: G::INIT,
};
#[inline]
fn lock_internal<F: FnOnce() -> bool>(&self, try_lock: F) -> Option<bool> {
let id = self.get_thread_id.nonzero_thread_id().get();
if self.owner.load(Ordering::Relaxed) == id {
return None;
} else {
if !try_lock() {
return Some(false);
}
self.owner.store(id, Ordering::Relaxed);
}
Some(true)
}
/// Blocks for the mutex to be available, and returns true if the mutex isn't already
/// locked on the current thread.
pub fn lock(&self) -> bool {
self.lock_internal(|| {
self.mutex.lock();
true
})
.is_some()
}
/// Returns `Some(true)` if able to successfully lock without blocking, `Some(false)`
/// otherwise, and `None` when the mutex is already locked on the current thread.
pub fn try_lock(&self) -> Option<bool> {
self.lock_internal(|| self.mutex.try_lock())
}
/// Unlocks this mutex. The inner mutex may not be unlocked if
/// this mutex was acquired previously in the current thread.
///
/// # Safety
///
/// This method may only be called if the mutex is held by the current thread.
pub unsafe fn unlock(&self) {
self.owner.store(0, Ordering::Relaxed);
unsafe { self.mutex.unlock() };
}
}
unsafe impl<R: RawMutex + Send, G: GetThreadId + Send> Send for RawThreadMutex<R, G> {}
unsafe impl<R: RawMutex + Sync, G: GetThreadId + Sync> Sync for RawThreadMutex<R, G> {}
pub struct ThreadMutex<R: RawMutex, G: GetThreadId, T: ?Sized> {
raw: RawThreadMutex<R, G>,
data: UnsafeCell<T>,
}
impl<R: RawMutex, G: GetThreadId, T> ThreadMutex<R, G, T> {
pub const fn new(val: T) -> Self {
Self {
raw: RawThreadMutex::INIT,
data: UnsafeCell::new(val),
}
}
pub fn into_inner(self) -> T {
self.data.into_inner()
}
}
impl<R: RawMutex, G: GetThreadId, T: Default> Default for ThreadMutex<R, G, T> {
fn default() -> Self {
Self::new(T::default())
}
}
impl<R: RawMutex, G: GetThreadId, T> From<T> for ThreadMutex<R, G, T> {
fn from(val: T) -> Self {
Self::new(val)
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized> ThreadMutex<R, G, T> {
pub fn lock(&self) -> Option<ThreadMutexGuard<'_, R, G, T>> {
if self.raw.lock() {
Some(ThreadMutexGuard {
mu: self,
marker: PhantomData,
})
} else {
None
}
}
pub fn try_lock(&self) -> Result<ThreadMutexGuard<'_, R, G, T>, TryLockThreadError> {
match self.raw.try_lock() {
Some(true) => Ok(ThreadMutexGuard {
mu: self,
marker: PhantomData,
}),
Some(false) => Err(TryLockThreadError::Other),
None => Err(TryLockThreadError::Current),
}
}
}
// Whether ThreadMutex::try_lock failed because the mutex was already locked on another thread or
// on the current thread
pub enum TryLockThreadError {
Other,
Current,
}
struct LockedPlaceholder(&'static str);
impl fmt::Debug for LockedPlaceholder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.0)
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized + fmt::Debug> fmt::Debug for ThreadMutex<R, G, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.try_lock() {
Ok(guard) => f
.debug_struct("ThreadMutex")
.field("data", &&*guard)
.finish(),
Err(e) => {
let msg = match e {
TryLockThreadError::Other => "<locked on other thread>",
TryLockThreadError::Current => "<locked on current thread>",
};
f.debug_struct("ThreadMutex")
.field("data", &LockedPlaceholder(msg))
.finish()
}
}
}
}
unsafe impl<R: RawMutex + Send, G: GetThreadId + Send, T: ?Sized + Send> Send
for ThreadMutex<R, G, T>
{
}
unsafe impl<R: RawMutex + Sync, G: GetThreadId + Sync, T: ?Sized + Send> Sync
for ThreadMutex<R, G, T>
{
}
pub struct ThreadMutexGuard<'a, R: RawMutex, G: GetThreadId, T: ?Sized> {
mu: &'a ThreadMutex<R, G, T>,
marker: PhantomData<(&'a mut T, GuardNoSend)>,
}
impl<'a, R: RawMutex, G: GetThreadId, T: ?Sized> ThreadMutexGuard<'a, R, G, T> {
pub fn map<U, F: FnOnce(&mut T) -> &mut U>(
mut s: Self,
f: F,
) -> MappedThreadMutexGuard<'a, R, G, U> {
let data = f(&mut s).into();
let mu = &s.mu.raw;
core::mem::forget(s);
MappedThreadMutexGuard {
mu,
data,
marker: PhantomData,
}
}
pub fn try_map<U, F: FnOnce(&mut T) -> Option<&mut U>>(
mut s: Self,
f: F,
) -> Result<MappedThreadMutexGuard<'a, R, G, U>, Self> {
if let Some(data) = f(&mut s) {
let data = data.into();
let mu = &s.mu.raw;
core::mem::forget(s);
Ok(MappedThreadMutexGuard {
mu,
data,
marker: PhantomData,
})
} else {
Err(s)
}
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized> Deref for ThreadMutexGuard<'_, R, G, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.mu.data.get() }
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized> DerefMut for ThreadMutexGuard<'_, R, G, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.mu.data.get() }
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized> Drop for ThreadMutexGuard<'_, R, G, T> {
fn drop(&mut self) {
unsafe { self.mu.raw.unlock() }
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized + fmt::Display> fmt::Display
for ThreadMutexGuard<'_, R, G, T>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized + fmt::Debug> fmt::Debug
for ThreadMutexGuard<'_, R, G, T>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
pub struct MappedThreadMutexGuard<'a, R: RawMutex, G: GetThreadId, T: ?Sized> {
mu: &'a RawThreadMutex<R, G>,
data: NonNull<T>,
marker: PhantomData<(&'a mut T, GuardNoSend)>,
}
impl<'a, R: RawMutex, G: GetThreadId, T: ?Sized> MappedThreadMutexGuard<'a, R, G, T> {
pub fn map<U, F: FnOnce(&mut T) -> &mut U>(
mut s: Self,
f: F,
) -> MappedThreadMutexGuard<'a, R, G, U> {
let data = f(&mut s).into();
let mu = s.mu;
core::mem::forget(s);
MappedThreadMutexGuard {
mu,
data,
marker: PhantomData,
}
}
pub fn try_map<U, F: FnOnce(&mut T) -> Option<&mut U>>(
mut s: Self,
f: F,
) -> Result<MappedThreadMutexGuard<'a, R, G, U>, Self> {
if let Some(data) = f(&mut s) {
let data = data.into();
let mu = s.mu;
core::mem::forget(s);
Ok(MappedThreadMutexGuard {
mu,
data,
marker: PhantomData,
})
} else {
Err(s)
}
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized> Deref for MappedThreadMutexGuard<'_, R, G, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.data.as_ref() }
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized> DerefMut for MappedThreadMutexGuard<'_, R, G, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { self.data.as_mut() }
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized> Drop for MappedThreadMutexGuard<'_, R, G, T> {
fn drop(&mut self) {
unsafe { self.mu.unlock() }
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized + fmt::Display> fmt::Display
for MappedThreadMutexGuard<'_, R, G, T>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl<R: RawMutex, G: GetThreadId, T: ?Sized + fmt::Debug> fmt::Debug
for MappedThreadMutexGuard<'_, R, G, T>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/lock/immutable_mutex.rs | crates/common/src/lock/immutable_mutex.rs | #![allow(clippy::needless_lifetimes)]
use alloc::fmt;
use core::{marker::PhantomData, ops::Deref};
use lock_api::{MutexGuard, RawMutex};
/// A mutex guard that has an exclusive lock, but only an immutable reference; useful if you
/// need to map a mutex guard with a function that returns an `&T`. Construct using the
/// [`MapImmutable`] trait.
pub struct ImmutableMappedMutexGuard<'a, R: RawMutex, T: ?Sized> {
raw: &'a R,
data: *const T,
_marker: PhantomData<(&'a T, R::GuardMarker)>,
}
// main constructor for ImmutableMappedMutexGuard
// TODO: patch lock_api to have a MappedMutexGuard::raw method, and have this implementation be for
// MappedMutexGuard
impl<'a, R: RawMutex, T: ?Sized> MapImmutable<'a, R, T> for MutexGuard<'a, R, T> {
fn map_immutable<U: ?Sized, F>(s: Self, f: F) -> ImmutableMappedMutexGuard<'a, R, U>
where
F: FnOnce(&T) -> &U,
{
let raw = unsafe { MutexGuard::mutex(&s).raw() };
let data = f(&s) as *const U;
core::mem::forget(s);
ImmutableMappedMutexGuard {
raw,
data,
_marker: PhantomData,
}
}
}
impl<'a, R: RawMutex, T: ?Sized> ImmutableMappedMutexGuard<'a, R, T> {
pub fn map<U: ?Sized, F>(s: Self, f: F) -> ImmutableMappedMutexGuard<'a, R, U>
where
F: FnOnce(&T) -> &U,
{
let raw = s.raw;
let data = f(&s) as *const U;
core::mem::forget(s);
ImmutableMappedMutexGuard {
raw,
data,
_marker: PhantomData,
}
}
}
impl<R: RawMutex, T: ?Sized> Deref for ImmutableMappedMutexGuard<'_, R, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
// SAFETY: self.data is valid for the lifetime of the guard
unsafe { &*self.data }
}
}
impl<R: RawMutex, T: ?Sized> Drop for ImmutableMappedMutexGuard<'_, R, T> {
fn drop(&mut self) {
// SAFETY: An ImmutableMappedMutexGuard always holds the lock
unsafe { self.raw.unlock() }
}
}
impl<R: RawMutex, T: fmt::Debug + ?Sized> fmt::Debug for ImmutableMappedMutexGuard<'_, R, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<R: RawMutex, T: fmt::Display + ?Sized> fmt::Display for ImmutableMappedMutexGuard<'_, R, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
pub trait MapImmutable<'a, R: RawMutex, T: ?Sized> {
fn map_immutable<U: ?Sized, F>(s: Self, f: F) -> ImmutableMappedMutexGuard<'a, R, U>
where
F: FnOnce(&T) -> &U;
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/common/src/lock/cell_lock.rs | crates/common/src/lock/cell_lock.rs | // spell-checker:ignore upgradably sharedly
use core::{cell::Cell, num::NonZero};
use lock_api::{
GetThreadId, RawMutex, RawRwLock, RawRwLockDowngrade, RawRwLockRecursive, RawRwLockUpgrade,
RawRwLockUpgradeDowngrade,
};
pub struct RawCellMutex {
locked: Cell<bool>,
}
unsafe impl RawMutex for RawCellMutex {
#[allow(clippy::declare_interior_mutable_const)]
const INIT: Self = Self {
locked: Cell::new(false),
};
type GuardMarker = lock_api::GuardNoSend;
#[inline]
fn lock(&self) {
if self.is_locked() {
deadlock("", "Mutex")
}
self.locked.set(true)
}
#[inline]
fn try_lock(&self) -> bool {
if self.is_locked() {
false
} else {
self.locked.set(true);
true
}
}
unsafe fn unlock(&self) {
self.locked.set(false)
}
#[inline]
fn is_locked(&self) -> bool {
self.locked.get()
}
}
const WRITER_BIT: usize = 0b01;
const ONE_READER: usize = 0b10;
pub struct RawCellRwLock {
state: Cell<usize>,
}
impl RawCellRwLock {
#[inline]
fn is_exclusive(&self) -> bool {
self.state.get() & WRITER_BIT != 0
}
}
unsafe impl RawRwLock for RawCellRwLock {
#[allow(clippy::declare_interior_mutable_const)]
const INIT: Self = Self {
state: Cell::new(0),
};
type GuardMarker = <RawCellMutex as RawMutex>::GuardMarker;
#[inline]
fn lock_shared(&self) {
if !self.try_lock_shared() {
deadlock("sharedly ", "RwLock")
}
}
#[inline]
fn try_lock_shared(&self) -> bool {
// TODO: figure out whether this is realistic; could maybe help
// debug deadlocks from 2+ read() in the same thread?
// if self.is_locked() {
// false
// } else {
// self.state.set(ONE_READER);
// true
// }
self.try_lock_shared_recursive()
}
#[inline]
unsafe fn unlock_shared(&self) {
self.state.set(self.state.get() - ONE_READER)
}
#[inline]
fn lock_exclusive(&self) {
if !self.try_lock_exclusive() {
deadlock("exclusively ", "RwLock")
}
self.state.set(WRITER_BIT)
}
#[inline]
fn try_lock_exclusive(&self) -> bool {
if self.is_locked() {
false
} else {
self.state.set(WRITER_BIT);
true
}
}
unsafe fn unlock_exclusive(&self) {
self.state.set(0)
}
fn is_locked(&self) -> bool {
self.state.get() != 0
}
}
unsafe impl RawRwLockDowngrade for RawCellRwLock {
unsafe fn downgrade(&self) {
self.state.set(ONE_READER);
}
}
unsafe impl RawRwLockUpgrade for RawCellRwLock {
#[inline]
fn lock_upgradable(&self) {
if !self.try_lock_upgradable() {
deadlock("upgradably+sharedly ", "RwLock")
}
}
#[inline]
fn try_lock_upgradable(&self) -> bool {
// defer to normal -- we can always try to upgrade
self.try_lock_shared()
}
#[inline]
unsafe fn unlock_upgradable(&self) {
unsafe { self.unlock_shared() }
}
#[inline]
unsafe fn upgrade(&self) {
if !unsafe { self.try_upgrade() } {
deadlock("upgrade ", "RwLock")
}
}
#[inline]
unsafe fn try_upgrade(&self) -> bool {
if self.state.get() == ONE_READER {
self.state.set(WRITER_BIT);
true
} else {
false
}
}
}
unsafe impl RawRwLockUpgradeDowngrade for RawCellRwLock {
#[inline]
unsafe fn downgrade_upgradable(&self) {
// no-op -- we're always upgradable
}
#[inline]
unsafe fn downgrade_to_upgradable(&self) {
self.state.set(ONE_READER);
}
}
unsafe impl RawRwLockRecursive for RawCellRwLock {
#[inline]
fn lock_shared_recursive(&self) {
if !self.try_lock_shared_recursive() {
deadlock("recursively+sharedly ", "RwLock")
}
}
#[inline]
fn try_lock_shared_recursive(&self) -> bool {
if self.is_exclusive() {
false
} else if let Some(new) = self.state.get().checked_add(ONE_READER) {
self.state.set(new);
true
} else {
false
}
}
}
#[cold]
#[inline(never)]
fn deadlock(lock_kind: &str, ty: &str) -> ! {
panic!("deadlock: tried to {lock_kind}lock a Cell{ty} twice")
}
pub struct SingleThreadId(());
unsafe impl GetThreadId for SingleThreadId {
const INIT: Self = Self(());
fn nonzero_thread_id(&self) -> NonZero<usize> {
NonZero::new(1).unwrap()
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/derive-impl/src/pytraverse.rs | crates/derive-impl/src/pytraverse.rs | use proc_macro2::TokenStream;
use quote::quote;
use syn::{Attribute, DeriveInput, Field, Result};
struct TraverseAttr {
/// set to `true` if the attribute is `#[pytraverse(skip)]`
skip: bool,
}
const ATTR_TRAVERSE: &str = "pytraverse";
/// only accept `#[pytraverse(skip)]` for now
fn pytraverse_arg(attr: &Attribute) -> Option<Result<TraverseAttr>> {
if !attr.path().is_ident(ATTR_TRAVERSE) {
return None;
}
let ret = || {
let mut skip = false;
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("skip") {
if skip {
return Err(meta.error("already specified skip"));
}
skip = true;
} else {
return Err(meta.error("unknown attr"));
}
Ok(())
})?;
Ok(TraverseAttr { skip })
};
Some(ret())
}
fn field_to_traverse_code(field: &Field) -> Result<TokenStream> {
let pytraverse_attrs = field
.attrs
.iter()
.filter_map(pytraverse_arg)
.collect::<core::result::Result<Vec<_>, _>>()?;
let do_trace = if pytraverse_attrs.len() > 1 {
bail_span!(
field,
"found multiple #[pytraverse] attributes on the same field, expect at most one"
)
} else if pytraverse_attrs.is_empty() {
// default to always traverse every field
true
} else {
!pytraverse_attrs[0].skip
};
let name = field.ident.as_ref().ok_or_else(|| {
syn::Error::new_spanned(
field.clone(),
"Field should have a name in non-tuple struct",
)
})?;
if do_trace {
Ok(quote!(
::rustpython_vm::object::Traverse::traverse(&self.#name, tracer_fn);
))
} else {
Ok(quote!())
}
}
/// not trace corresponding field
fn gen_trace_code(item: &mut DeriveInput) -> Result<TokenStream> {
match &mut item.data {
syn::Data::Struct(s) => {
let fields = &mut s.fields;
match fields {
syn::Fields::Named(fields) => {
let res: Vec<TokenStream> = fields
.named
.iter_mut()
.map(|f| -> Result<TokenStream> { field_to_traverse_code(f) })
.collect::<Result<_>>()?;
let res = res.into_iter().collect::<TokenStream>();
Ok(res)
}
syn::Fields::Unnamed(fields) => {
let res: TokenStream = (0..fields.unnamed.len())
.map(|i| {
let i = syn::Index::from(i);
quote!(
::rustpython_vm::object::Traverse::traverse(&self.#i, tracer_fn);
)
})
.collect();
Ok(res)
}
_ => Err(syn::Error::new_spanned(
fields,
"Only named and unnamed fields are supported",
)),
}
}
_ => Err(syn::Error::new_spanned(item, "Only structs are supported")),
}
}
pub(crate) fn impl_pytraverse(mut item: DeriveInput) -> Result<TokenStream> {
let trace_code = gen_trace_code(&mut item)?;
let ty = &item.ident;
// Add Traverse bound to all type parameters
for param in &mut item.generics.params {
if let syn::GenericParam::Type(type_param) = param {
type_param
.bounds
.push(syn::parse_quote!(::rustpython_vm::object::Traverse));
}
}
let (impl_generics, ty_generics, where_clause) = item.generics.split_for_impl();
let ret = quote! {
unsafe impl #impl_generics ::rustpython_vm::object::Traverse for #ty #ty_generics #where_clause {
fn traverse(&self, tracer_fn: &mut ::rustpython_vm::object::TraverseFn) {
#trace_code
}
}
};
Ok(ret)
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/derive-impl/src/pymodule.rs | crates/derive-impl/src/pymodule.rs | use crate::error::Diagnostic;
use crate::pystructseq::PyStructSequenceMeta;
use crate::util::{
ALL_ALLOWED_NAMES, AttrItemMeta, AttributeExt, ClassItemMeta, ContentItem, ContentItemInner,
ErrorVec, ItemMeta, ItemNursery, ModuleItemMeta, SimpleItemMeta, format_doc, iter_use_idents,
pyclass_ident_and_attrs, text_signature,
};
use core::str::FromStr;
use proc_macro2::{Delimiter, Group, TokenStream, TokenTree};
use quote::{ToTokens, quote, quote_spanned};
use rustpython_doc::DB;
use std::collections::HashSet;
use syn::{Attribute, Ident, Item, Result, parse_quote, spanned::Spanned};
use syn_ext::ext::*;
use syn_ext::types::PunctuatedNestedMeta;
#[derive(Clone, Copy, Eq, PartialEq)]
enum AttrName {
Function,
Attr,
Class,
Exception,
StructSequence,
}
impl core::fmt::Display for AttrName {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let s = match self {
Self::Function => "pyfunction",
Self::Attr => "pyattr",
Self::Class => "pyclass",
Self::Exception => "pyexception",
Self::StructSequence => "pystruct_sequence",
};
s.fmt(f)
}
}
impl FromStr for AttrName {
type Err = String;
fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
Ok(match s {
"pyfunction" => Self::Function,
"pyattr" => Self::Attr,
"pyclass" => Self::Class,
"pyexception" => Self::Exception,
"pystruct_sequence" => Self::StructSequence,
s => {
return Err(s.to_owned());
}
})
}
}
#[derive(Default)]
struct ModuleContext {
name: String,
function_items: FunctionNursery,
attribute_items: ItemNursery,
has_extend_module: bool, // TODO: check if `fn extend_module` exists
errors: Vec<syn::Error>,
}
pub fn impl_pymodule(attr: PunctuatedNestedMeta, module_item: Item) -> Result<TokenStream> {
let (doc, mut module_item) = match module_item {
Item::Mod(m) => (m.attrs.doc(), m),
other => bail_span!(other, "#[pymodule] can only be on a full module"),
};
let fake_ident = Ident::new("pymodule", module_item.span());
let module_meta =
ModuleItemMeta::from_nested(module_item.ident.clone(), fake_ident, attr.into_iter())?;
// generation resources
let mut context = ModuleContext {
name: module_meta.simple_name()?,
..Default::default()
};
let items = module_item.items_mut().ok_or_else(|| {
module_meta.new_meta_error("requires actual module, not a module declaration")
})?;
// collect to context
for item in items.iter_mut() {
if matches!(item, Item::Impl(_) | Item::Trait(_)) {
// #[pyclass] implementations
continue;
}
let r = item.try_split_attr_mut(|attrs, item| {
let (py_items, cfgs) = attrs_to_module_items(attrs, module_item_new)?;
for py_item in py_items.iter().rev() {
let r = py_item.gen_module_item(ModuleItemArgs {
item,
attrs,
context: &mut context,
cfgs: cfgs.as_slice(),
});
context.errors.ok_or_push(r);
}
Ok(())
});
context.errors.ok_or_push(r);
}
// append additional items
let module_name = context.name.as_str();
let function_items = context.function_items.validate()?;
let attribute_items = context.attribute_items.validate()?;
let doc = doc.or_else(|| DB.get(module_name).copied().map(str::to_owned));
let doc = if let Some(doc) = doc {
quote!(Some(#doc))
} else {
quote!(None)
};
let is_submodule = module_meta.sub()?;
let withs = module_meta.with()?;
if !is_submodule {
items.extend([
parse_quote! {
pub(crate) const MODULE_NAME: &'static str = #module_name;
},
parse_quote! {
pub(crate) const DOC: Option<&'static str> = #doc;
},
parse_quote! {
pub(crate) fn __module_def(
ctx: &::rustpython_vm::Context,
) -> &'static ::rustpython_vm::builtins::PyModuleDef {
DEF.get_or_init(|| {
let mut def = ::rustpython_vm::builtins::PyModuleDef {
name: ctx.intern_str(MODULE_NAME),
doc: DOC.map(|doc| ctx.intern_str(doc)),
methods: METHOD_DEFS,
slots: Default::default(),
};
def.slots.exec = Some(extend_module);
def
})
}
},
parse_quote! {
#[allow(dead_code)]
pub(crate) fn make_module(
vm: &::rustpython_vm::VirtualMachine
) -> ::rustpython_vm::PyRef<::rustpython_vm::builtins::PyModule> {
use ::rustpython_vm::PyPayload;
let module = ::rustpython_vm::builtins::PyModule::from_def(__module_def(&vm.ctx)).into_ref(&vm.ctx);
__init_dict(vm, &module);
extend_module(vm, &module).unwrap();
module
}
},
]);
}
if !is_submodule && !context.has_extend_module {
items.push(parse_quote! {
pub(crate) fn extend_module(vm: &::rustpython_vm::VirtualMachine, module: &::rustpython_vm::Py<::rustpython_vm::builtins::PyModule>) -> ::rustpython_vm::PyResult<()> {
__extend_module(vm, module);
Ok(())
}
});
}
let method_defs = if withs.is_empty() {
quote!(#function_items)
} else {
quote!({
const OWN_METHODS: &'static [::rustpython_vm::function::PyMethodDef] = &#function_items;
rustpython_vm::function::PyMethodDef::__const_concat_arrays::<
{ OWN_METHODS.len() #(+ super::#withs::METHOD_DEFS.len())* },
>(&[#(super::#withs::METHOD_DEFS,)* OWN_METHODS])
})
};
items.extend([
parse_quote! {
::rustpython_vm::common::static_cell! {
pub(crate) static DEF: ::rustpython_vm::builtins::PyModuleDef;
}
},
parse_quote! {
pub(crate) const METHOD_DEFS: &'static [::rustpython_vm::function::PyMethodDef] = &#method_defs;
},
parse_quote! {
pub(crate) fn __init_attributes(
vm: &::rustpython_vm::VirtualMachine,
module: &::rustpython_vm::Py<::rustpython_vm::builtins::PyModule>,
) {
#(
super::#withs::__init_attributes(vm, module);
)*
let ctx = &vm.ctx;
#attribute_items
}
},
parse_quote! {
pub(crate) fn __extend_module(
vm: &::rustpython_vm::VirtualMachine,
module: &::rustpython_vm::Py<::rustpython_vm::builtins::PyModule>,
) {
module.__init_methods(vm).unwrap();
__init_attributes(vm, module);
}
},
parse_quote! {
pub(crate) fn __init_dict(
vm: &::rustpython_vm::VirtualMachine,
module: &::rustpython_vm::Py<::rustpython_vm::builtins::PyModule>,
) {
::rustpython_vm::builtins::PyModule::__init_dict_from_def(vm, module);
}
},
]);
Ok(if let Some(error) = context.errors.into_error() {
let error = Diagnostic::from(error);
quote! {
#module_item
#error
}
} else {
module_item.into_token_stream()
})
}
fn module_item_new(
index: usize,
attr_name: AttrName,
py_attrs: Vec<usize>,
) -> Box<dyn ModuleItem<AttrName = AttrName>> {
match attr_name {
AttrName::Function => Box::new(FunctionItem {
inner: ContentItemInner { index, attr_name },
py_attrs,
}),
AttrName::Attr => Box::new(AttributeItem {
inner: ContentItemInner { index, attr_name },
py_attrs,
}),
// pyexception is treated like pyclass - both define types
AttrName::Class | AttrName::Exception => Box::new(ClassItem {
inner: ContentItemInner { index, attr_name },
py_attrs,
}),
AttrName::StructSequence => Box::new(StructSequenceItem {
inner: ContentItemInner { index, attr_name },
py_attrs,
}),
}
}
fn attrs_to_module_items<F, R>(attrs: &[Attribute], item_new: F) -> Result<(Vec<R>, Vec<Attribute>)>
where
F: Fn(usize, AttrName, Vec<usize>) -> R,
{
let mut cfgs: Vec<Attribute> = Vec::new();
let mut result = Vec::new();
let mut iter = attrs.iter().enumerate().peekable();
while let Some((_, attr)) = iter.peek() {
// take all cfgs but no py items
let attr = *attr;
if let Some(ident) = attr.get_ident() {
let attr_name = ident.to_string();
if attr_name == "cfg" {
cfgs.push(attr.clone());
} else if ALL_ALLOWED_NAMES.contains(&attr_name.as_str()) {
break;
}
}
iter.next();
}
let mut closed = false;
let mut py_attrs = Vec::new();
for (i, attr) in iter {
// take py items but no cfgs
let attr_name = if let Some(ident) = attr.get_ident() {
ident.to_string()
} else {
continue;
};
if attr_name == "cfg" {
bail_span!(attr, "#[py*] items must be placed under `cfgs`")
}
let attr_name = match AttrName::from_str(attr_name.as_str()) {
Ok(name) => name,
Err(wrong_name) => {
if !ALL_ALLOWED_NAMES.contains(&wrong_name.as_str()) {
continue;
} else if closed {
bail_span!(attr, "Only one #[pyattr] annotated #[py*] item can exist")
} else {
bail_span!(attr, "#[pymodule] doesn't accept #[{}]", wrong_name)
}
}
};
if attr_name == AttrName::Attr {
if !result.is_empty() {
bail_span!(
attr,
"#[pyattr] must be placed on top of other #[py*] items",
)
}
py_attrs.push(i);
continue;
}
if py_attrs.is_empty() {
result.push(item_new(i, attr_name, Vec::new()));
} else {
match attr_name {
AttrName::Class
| AttrName::Function
| AttrName::Exception
| AttrName::StructSequence => {
result.push(item_new(i, attr_name, py_attrs.clone()));
}
_ => {
bail_span!(
attr,
"#[pyclass], #[pyfunction], #[pyexception], or #[pystruct_sequence] can follow #[pyattr]",
)
}
}
py_attrs.clear();
closed = true;
}
}
if let Some(last) = py_attrs.pop() {
assert!(!closed);
result.push(item_new(last, AttrName::Attr, py_attrs));
}
Ok((result, cfgs))
}
#[derive(Default)]
struct FunctionNursery {
items: Vec<FunctionNurseryItem>,
}
struct FunctionNurseryItem {
py_names: Vec<String>,
cfgs: Vec<Attribute>,
ident: Ident,
doc: String,
}
impl FunctionNursery {
fn add_item(&mut self, item: FunctionNurseryItem) {
self.items.push(item);
}
fn validate(self) -> Result<ValidatedFunctionNursery> {
let mut name_set = HashSet::new();
for item in &self.items {
for py_name in &item.py_names {
if !name_set.insert((py_name.to_owned(), &item.cfgs)) {
bail_span!(item.ident, "duplicate method name `{}`", py_name);
}
}
}
Ok(ValidatedFunctionNursery(self))
}
}
struct ValidatedFunctionNursery(FunctionNursery);
impl ToTokens for ValidatedFunctionNursery {
fn to_tokens(&self, tokens: &mut TokenStream) {
let mut inner_tokens = TokenStream::new();
let flags = quote! { rustpython_vm::function::PyMethodFlags::empty() };
for item in &self.0.items {
let ident = &item.ident;
let cfgs = &item.cfgs;
let cfgs = quote!(#(#cfgs)*);
let py_names = &item.py_names;
let doc = &item.doc;
let doc = quote!(Some(#doc));
inner_tokens.extend(quote![
#(
#cfgs
rustpython_vm::function::PyMethodDef::new_const(
#py_names,
#ident,
#flags,
#doc,
),
)*
]);
}
let array: TokenTree = Group::new(Delimiter::Bracket, inner_tokens).into();
tokens.extend([array]);
}
}
/// #[pyfunction]
struct FunctionItem {
inner: ContentItemInner<AttrName>,
py_attrs: Vec<usize>,
}
/// #[pyclass]
struct ClassItem {
inner: ContentItemInner<AttrName>,
py_attrs: Vec<usize>,
}
/// #[pyattr]
struct AttributeItem {
inner: ContentItemInner<AttrName>,
py_attrs: Vec<usize>,
}
/// #[pystruct_sequence]
struct StructSequenceItem {
inner: ContentItemInner<AttrName>,
py_attrs: Vec<usize>,
}
impl ContentItem for FunctionItem {
type AttrName = AttrName;
fn inner(&self) -> &ContentItemInner<AttrName> {
&self.inner
}
}
impl ContentItem for ClassItem {
type AttrName = AttrName;
fn inner(&self) -> &ContentItemInner<AttrName> {
&self.inner
}
}
impl ContentItem for AttributeItem {
type AttrName = AttrName;
fn inner(&self) -> &ContentItemInner<AttrName> {
&self.inner
}
}
impl ContentItem for StructSequenceItem {
type AttrName = AttrName;
fn inner(&self) -> &ContentItemInner<AttrName> {
&self.inner
}
}
struct ModuleItemArgs<'a> {
item: &'a mut Item,
attrs: &'a mut Vec<Attribute>,
context: &'a mut ModuleContext,
cfgs: &'a [Attribute],
}
impl<'a> ModuleItemArgs<'a> {
fn module_name(&'a self) -> &'a str {
self.context.name.as_str()
}
}
trait ModuleItem: ContentItem {
fn gen_module_item(&self, args: ModuleItemArgs<'_>) -> Result<()>;
}
impl ModuleItem for FunctionItem {
fn gen_module_item(&self, args: ModuleItemArgs<'_>) -> Result<()> {
let func = args
.item
.function_or_method()
.map_err(|_| self.new_syn_error(args.item.span(), "can only be on a function"))?;
let ident = &func.sig().ident;
let item_attr = args.attrs.remove(self.index());
let item_meta = SimpleItemMeta::from_attr(ident.clone(), &item_attr)?;
let py_name = item_meta.simple_name()?;
let sig_doc = text_signature(func.sig(), &py_name);
let module = args.module_name();
// TODO: doc must exist at least one of code or CPython
let doc = args.attrs.doc().or_else(|| {
DB.get(&format!("{module}.{py_name}"))
.copied()
.map(str::to_owned)
});
let doc = if let Some(doc) = doc {
format_doc(&sig_doc, &doc)
} else {
sig_doc
};
let py_names = {
if self.py_attrs.is_empty() {
vec![py_name]
} else {
let mut py_names = HashSet::new();
py_names.insert(py_name);
for attr_index in self.py_attrs.iter().rev() {
let mut loop_unit = || {
let attr_attr = args.attrs.remove(*attr_index);
let item_meta = SimpleItemMeta::from_attr(ident.clone(), &attr_attr)?;
let py_name = item_meta.simple_name()?;
let inserted = py_names.insert(py_name.clone());
if !inserted {
return Err(self.new_syn_error(
ident.span(),
&format!(
"`{py_name}` is duplicated name for multiple py* attribute"
),
));
}
Ok(())
};
let r = loop_unit();
args.context.errors.ok_or_push(r);
}
let py_names: Vec<_> = py_names.into_iter().collect();
py_names
}
};
args.context.function_items.add_item(FunctionNurseryItem {
ident: ident.to_owned(),
py_names,
cfgs: args.cfgs.to_vec(),
doc,
});
Ok(())
}
}
impl ModuleItem for ClassItem {
fn gen_module_item(&self, args: ModuleItemArgs<'_>) -> Result<()> {
let (ident, _) = pyclass_ident_and_attrs(args.item)?;
let (class_name, class_new) = {
let class_attr = &mut args.attrs[self.inner.index];
let no_attr = class_attr.try_remove_name("no_attr")?;
if self.py_attrs.is_empty() {
// check no_attr before ClassItemMeta::from_attr
if no_attr.is_none() {
bail_span!(
ident,
"#[{name}] requires #[pyattr] to be a module attribute. \
To keep it free type, try #[{name}(no_attr)]",
name = self.attr_name()
)
}
}
let no_attr = no_attr.is_some();
let is_use = matches!(&args.item, syn::Item::Use(_));
let class_meta = ClassItemMeta::from_attr(ident.clone(), class_attr)?;
let module_name = args.context.name.clone();
let module_name = if let Some(class_module_name) = class_meta.module().ok().flatten() {
class_module_name
} else {
class_attr.fill_nested_meta("module", || {
parse_quote! {module = #module_name}
})?;
module_name
};
let class_name = if no_attr && is_use {
"<NO ATTR>".to_owned()
} else {
class_meta.class_name()?
};
let class_new = quote_spanned!(ident.span() =>
let new_class = <#ident as ::rustpython_vm::class::PyClassImpl>::make_class(ctx);
new_class.set_attr(rustpython_vm::identifier!(ctx, __module__), vm.new_pyobj(#module_name));
);
(class_name, class_new)
};
let mut py_names = Vec::new();
for attr_index in self.py_attrs.iter().rev() {
let mut loop_unit = || {
let attr_attr = args.attrs.remove(*attr_index);
let item_meta = SimpleItemMeta::from_attr(ident.clone(), &attr_attr)?;
let py_name = item_meta
.optional_name()
.unwrap_or_else(|| class_name.clone());
py_names.push(py_name);
Ok(())
};
let r = loop_unit();
args.context.errors.ok_or_push(r);
}
let set_attr = match py_names.len() {
0 => quote! {
let _ = new_class; // suppress warning
let _ = vm.ctx.intern_str(#class_name);
},
1 => {
let py_name = &py_names[0];
quote! {
vm.__module_set_attr(&module, vm.ctx.intern_str(#py_name), new_class).unwrap();
}
}
_ => quote! {
for name in [#(#py_names,)*] {
vm.__module_set_attr(&module, vm.ctx.intern_str(name), new_class.clone()).unwrap();
}
},
};
args.context.attribute_items.add_item(
ident.clone(),
py_names,
args.cfgs.to_vec(),
quote_spanned! { ident.span() =>
#class_new
#set_attr
},
0,
)?;
Ok(())
}
}
impl ModuleItem for StructSequenceItem {
fn gen_module_item(&self, args: ModuleItemArgs<'_>) -> Result<()> {
// Get the struct identifier (this IS the Python type, e.g., PyStructTime)
let pytype_ident = match args.item {
Item::Struct(s) => s.ident.clone(),
other => bail_span!(other, "#[pystruct_sequence] can only be on a struct"),
};
// Parse the #[pystruct_sequence(name = "...", module = "...", no_attr)] attribute
let structseq_attr = &args.attrs[self.inner.index];
let meta = PyStructSequenceMeta::from_attr(pytype_ident.clone(), structseq_attr)?;
let class_name = meta.class_name()?.ok_or_else(|| {
syn::Error::new_spanned(
structseq_attr,
"#[pystruct_sequence] requires name parameter",
)
})?;
let module_name = meta.module()?.unwrap_or_else(|| args.context.name.clone());
let no_attr = meta.no_attr()?;
// Generate the class creation code
let class_new = quote_spanned!(pytype_ident.span() =>
let new_class = <#pytype_ident as ::rustpython_vm::class::PyClassImpl>::make_class(ctx);
new_class.set_attr(rustpython_vm::identifier!(ctx, __module__), vm.new_pyobj(#module_name));
);
// Handle py_attrs for custom names, or use class_name as default
let mut py_names = Vec::new();
for attr_index in self.py_attrs.iter().rev() {
let attr_attr = args.attrs.remove(*attr_index);
let item_meta = SimpleItemMeta::from_attr(pytype_ident.clone(), &attr_attr)?;
let py_name = item_meta
.optional_name()
.unwrap_or_else(|| class_name.clone());
py_names.push(py_name);
}
// Require explicit #[pyattr] or no_attr, like #[pyclass]
if self.py_attrs.is_empty() && !no_attr {
bail_span!(
pytype_ident,
"#[pystruct_sequence] requires #[pyattr] to be a module attribute. \
To keep it free type, try #[pystruct_sequence(..., no_attr)]"
)
}
let set_attr = match py_names.len() {
0 => quote! {
let _ = new_class; // suppress warning
},
1 => {
let py_name = &py_names[0];
quote! {
vm.__module_set_attr(&module, vm.ctx.intern_str(#py_name), new_class).unwrap();
}
}
_ => quote! {
for name in [#(#py_names,)*] {
vm.__module_set_attr(&module, vm.ctx.intern_str(name), new_class.clone()).unwrap();
}
},
};
args.context.attribute_items.add_item(
pytype_ident.clone(),
py_names,
args.cfgs.to_vec(),
quote_spanned! { pytype_ident.span() =>
#class_new
#set_attr
},
0,
)?;
Ok(())
}
}
impl ModuleItem for AttributeItem {
fn gen_module_item(&self, args: ModuleItemArgs<'_>) -> Result<()> {
let cfgs = args.cfgs.to_vec();
let attr = args.attrs.remove(self.index());
let (ident, py_name, let_obj) = match args.item {
Item::Fn(syn::ItemFn { sig, block, .. }) => {
let ident = &sig.ident;
// If `once` keyword is in #[pyattr],
// wrapping it with static_cell for preventing it from using it as function
let attr_meta = AttrItemMeta::from_attr(ident.clone(), &attr)?;
if attr_meta.inner()._bool("once")? {
let stmts = &block.stmts;
let return_type = match &sig.output {
syn::ReturnType::Default => {
unreachable!("#[pyattr] attached function must have return type.")
}
syn::ReturnType::Type(_, ty) => ty,
};
let stmt: syn::Stmt = parse_quote! {
{
rustpython_common::static_cell! {
static ERROR: #return_type;
}
ERROR
.get_or_init(|| {
#(#stmts)*
})
.clone()
}
};
block.stmts = vec![stmt];
}
let py_name = attr_meta.simple_name()?;
(
ident.clone(),
py_name,
quote_spanned! { ident.span() =>
let obj = vm.new_pyobj(#ident(vm));
},
)
}
Item::Const(syn::ItemConst { ident, .. }) => {
let item_meta = SimpleItemMeta::from_attr(ident.clone(), &attr)?;
let py_name = item_meta.simple_name()?;
(
ident.clone(),
py_name,
quote_spanned! { ident.span() =>
let obj = vm.new_pyobj(#ident);
},
)
}
Item::Use(item) => {
if !self.py_attrs.is_empty() {
return Err(self
.new_syn_error(item.span(), "Only single #[pyattr] is allowed for `use`"));
}
let _ = iter_use_idents(item, |ident, is_unique| {
let item_meta = SimpleItemMeta::from_attr(ident.clone(), &attr)?;
let py_name = if is_unique {
item_meta.simple_name()?
} else if item_meta.optional_name().is_some() {
// this check actually doesn't need to be placed in loop
return Err(self.new_syn_error(
ident.span(),
"`name` attribute is not allowed for multiple use items",
));
} else {
ident.to_string()
};
let tokens = quote_spanned! { ident.span() =>
vm.__module_set_attr(module, vm.ctx.intern_str(#py_name), vm.new_pyobj(#ident)).unwrap();
};
args.context.attribute_items.add_item(
ident.clone(),
vec![py_name],
cfgs.clone(),
tokens,
1,
)?;
Ok(())
})?;
return Ok(());
}
other => {
return Err(
self.new_syn_error(other.span(), "can only be on a function, const and use")
);
}
};
let (tokens, py_names) = if self.py_attrs.is_empty() {
(
quote_spanned! { ident.span() => {
#let_obj
vm.__module_set_attr(module, vm.ctx.intern_str(#py_name), obj).unwrap();
}},
vec![py_name],
)
} else {
let mut names = vec![py_name];
for attr_index in self.py_attrs.iter().rev() {
let mut loop_unit = || {
let attr_attr = args.attrs.remove(*attr_index);
let item_meta = AttrItemMeta::from_attr(ident.clone(), &attr_attr)?;
if item_meta.inner()._bool("once")? {
return Err(self.new_syn_error(
ident.span(),
"#[pyattr(once)] is only allowed for the bottom-most item",
));
}
let py_name = item_meta.optional_name().ok_or_else(|| {
self.new_syn_error(
ident.span(),
"#[pyattr(name = ...)] is mandatory except for the bottom-most item",
)
})?;
names.push(py_name);
Ok(())
};
let r = loop_unit();
args.context.errors.ok_or_push(r);
}
(
quote_spanned! { ident.span() => {
#let_obj
for name in [#(#names),*] {
vm.__module_set_attr(module, vm.ctx.intern_str(name), obj.clone()).unwrap();
}
}},
names,
)
};
args.context
.attribute_items
.add_item(ident, py_names, cfgs, tokens, 1)?;
Ok(())
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/derive-impl/src/lib.rs | crates/derive-impl/src/lib.rs | #![recursion_limit = "128"]
#![doc(html_logo_url = "https://raw.githubusercontent.com/RustPython/RustPython/main/logo.png")]
#![doc(html_root_url = "https://docs.rs/rustpython-derive/")]
extern crate proc_macro;
#[macro_use]
extern crate maplit;
#[macro_use]
mod error;
#[macro_use]
mod util;
mod compile_bytecode;
mod from_args;
mod pyclass;
mod pymodule;
mod pypayload;
mod pystructseq;
mod pytraverse;
use error::Diagnostic;
use proc_macro2::TokenStream;
use quote::ToTokens;
use syn::{DeriveInput, Item};
use syn_ext::types::PunctuatedNestedMeta;
pub use compile_bytecode::Compiler;
fn result_to_tokens(result: Result<TokenStream, impl Into<Diagnostic>>) -> TokenStream {
result
.map_err(|e| e.into())
.unwrap_or_else(ToTokens::into_token_stream)
}
pub fn derive_from_args(input: DeriveInput) -> TokenStream {
result_to_tokens(from_args::impl_from_args(input))
}
pub fn pyclass(attr: PunctuatedNestedMeta, item: Item) -> TokenStream {
if matches!(item, syn::Item::Impl(_) | syn::Item::Trait(_)) {
result_to_tokens(pyclass::impl_pyclass_impl(attr, item))
} else {
result_to_tokens(pyclass::impl_pyclass(attr, item))
}
}
pub fn pyexception(attr: PunctuatedNestedMeta, item: Item) -> TokenStream {
if matches!(item, syn::Item::Impl(_)) {
result_to_tokens(pyclass::impl_pyexception_impl(attr, item))
} else {
result_to_tokens(pyclass::impl_pyexception(attr, item))
}
}
pub fn pymodule(attr: PunctuatedNestedMeta, item: Item) -> TokenStream {
result_to_tokens(pymodule::impl_pymodule(attr, item))
}
pub fn pystruct_sequence(attr: PunctuatedNestedMeta, item: Item) -> TokenStream {
result_to_tokens(pystructseq::impl_pystruct_sequence(attr, item))
}
pub fn pystruct_sequence_data(attr: PunctuatedNestedMeta, item: Item) -> TokenStream {
result_to_tokens(pystructseq::impl_pystruct_sequence_data(attr, item))
}
pub fn py_compile(input: TokenStream, compiler: &dyn Compiler) -> TokenStream {
result_to_tokens(compile_bytecode::impl_py_compile(input, compiler))
}
pub fn py_freeze(input: TokenStream, compiler: &dyn Compiler) -> TokenStream {
result_to_tokens(compile_bytecode::impl_py_freeze(input, compiler))
}
pub fn pypayload(input: DeriveInput) -> TokenStream {
result_to_tokens(pypayload::impl_pypayload(input))
}
pub fn pytraverse(item: DeriveInput) -> TokenStream {
result_to_tokens(pytraverse::impl_pytraverse(item))
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/derive-impl/src/compile_bytecode.rs | crates/derive-impl/src/compile_bytecode.rs | //! Parsing and processing for this form:
//! ```ignore
//! py_compile!(
//! // either:
//! source = "python_source_code",
//! // or
//! file = "file/path/relative/to/$CARGO_MANIFEST_DIR",
//!
//! // the mode to compile the code in
//! mode = "exec", // or "eval" or "single"
//! // the path put into the CodeObject, defaults to "frozen"
//! module_name = "frozen",
//! )
//! ```
use crate::Diagnostic;
use proc_macro2::{Span, TokenStream};
use quote::quote;
use rustpython_compiler_core::{Mode, bytecode::CodeObject, frozen};
use std::sync::LazyLock;
use std::{
collections::HashMap,
env, fs,
path::{Path, PathBuf},
};
use syn::{
self, LitByteStr, LitStr, Macro,
parse::{ParseStream, Parser, Result as ParseResult},
spanned::Spanned,
};
static CARGO_MANIFEST_DIR: LazyLock<PathBuf> = LazyLock::new(|| {
PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is not present"))
});
enum CompilationSourceKind {
/// Source is a File (Path)
File(PathBuf),
/// Direct Raw source code
SourceCode(String),
/// Source is a directory
Dir(PathBuf),
}
struct CompiledModule {
code: CodeObject,
package: bool,
}
struct CompilationSource {
kind: CompilationSourceKind,
span: (Span, Span),
}
pub trait Compiler {
fn compile(
&self,
source: &str,
mode: Mode,
module_name: String,
) -> Result<CodeObject, Box<dyn core::error::Error>>;
}
impl CompilationSource {
fn compile_string<D: core::fmt::Display, F: FnOnce() -> D>(
&self,
source: &str,
mode: Mode,
module_name: String,
compiler: &dyn Compiler,
origin: F,
) -> Result<CodeObject, Diagnostic> {
compiler.compile(source, mode, module_name).map_err(|err| {
Diagnostic::spans_error(
self.span,
format!("Python compile error from {}: {}", origin(), err),
)
})
}
fn compile(
&self,
mode: Mode,
module_name: String,
compiler: &dyn Compiler,
) -> Result<HashMap<String, CompiledModule>, Diagnostic> {
match &self.kind {
CompilationSourceKind::Dir(rel_path) => self.compile_dir(
&CARGO_MANIFEST_DIR.join(rel_path),
String::new(),
mode,
compiler,
),
_ => Ok(hashmap! {
module_name.clone() => CompiledModule {
code: self.compile_single(mode, module_name, compiler)?,
package: false,
},
}),
}
}
fn compile_single(
&self,
mode: Mode,
module_name: String,
compiler: &dyn Compiler,
) -> Result<CodeObject, Diagnostic> {
match &self.kind {
CompilationSourceKind::File(rel_path) => {
let path = CARGO_MANIFEST_DIR.join(rel_path);
let source = fs::read_to_string(&path).map_err(|err| {
Diagnostic::spans_error(
self.span,
format!("Error reading file {path:?}: {err}"),
)
})?;
self.compile_string(&source, mode, module_name, compiler, || rel_path.display())
}
CompilationSourceKind::SourceCode(code) => self.compile_string(
&textwrap::dedent(code),
mode,
module_name,
compiler,
|| "string literal",
),
CompilationSourceKind::Dir(_) => {
unreachable!("Can't use compile_single with directory source")
}
}
}
fn compile_dir(
&self,
path: &Path,
parent: String,
mode: Mode,
compiler: &dyn Compiler,
) -> Result<HashMap<String, CompiledModule>, Diagnostic> {
let mut code_map = HashMap::new();
let paths = fs::read_dir(path)
.or_else(|e| {
if cfg!(windows)
&& let Ok(real_path) = fs::read_to_string(path.canonicalize().unwrap())
{
return fs::read_dir(real_path.trim());
}
Err(e)
})
.map_err(|err| {
Diagnostic::spans_error(self.span, format!("Error listing dir {path:?}: {err}"))
})?;
for path in paths {
let path = path.map_err(|err| {
Diagnostic::spans_error(self.span, format!("Failed to list file: {err}"))
})?;
let path = path.path();
let file_name = path.file_name().unwrap().to_str().ok_or_else(|| {
Diagnostic::spans_error(self.span, format!("Invalid UTF-8 in file name {path:?}"))
})?;
if path.is_dir() {
code_map.extend(self.compile_dir(
&path,
if parent.is_empty() {
file_name.to_string()
} else {
format!("{parent}.{file_name}")
},
mode,
compiler,
)?);
} else if file_name.ends_with(".py") {
let stem = path.file_stem().unwrap().to_str().unwrap();
let is_init = stem == "__init__";
let module_name = if is_init {
parent.clone()
} else if parent.is_empty() {
stem.to_owned()
} else {
format!("{parent}.{stem}")
};
let compile_path = |src_path: &Path| {
let source = fs::read_to_string(src_path).map_err(|err| {
Diagnostic::spans_error(
self.span,
format!("Error reading file {path:?}: {err}"),
)
})?;
self.compile_string(&source, mode, module_name.clone(), compiler, || {
path.strip_prefix(&*CARGO_MANIFEST_DIR)
.ok()
.unwrap_or(&path)
.display()
})
};
let code = compile_path(&path).or_else(|e| {
if cfg!(windows)
&& let Ok(real_path) = fs::read_to_string(path.canonicalize().unwrap())
{
let joined = path.parent().unwrap().join(real_path.trim());
if joined.exists() {
return compile_path(&joined);
} else {
return Err(e);
}
}
Err(e)
});
let code = match code {
Ok(code) => code,
Err(_)
if stem.starts_with("badsyntax_")
| parent.ends_with(".encoded_modules") =>
{
// TODO: handle with macro arg rather than hard-coded path
continue;
}
Err(e) => return Err(e),
};
code_map.insert(
module_name,
CompiledModule {
code,
package: is_init,
},
);
}
}
Ok(code_map)
}
}
impl PyCompileArgs {
fn parse(input: TokenStream, allow_dir: bool) -> Result<Self, Diagnostic> {
let mut module_name = None;
let mut mode = None;
let mut source: Option<CompilationSource> = None;
let mut crate_name = None;
fn assert_source_empty(source: &Option<CompilationSource>) -> Result<(), syn::Error> {
if let Some(source) = source {
Err(syn::Error::new(
source.span.0,
"Cannot have more than one source",
))
} else {
Ok(())
}
}
syn::meta::parser(|meta| {
let ident = meta
.path
.get_ident()
.ok_or_else(|| meta.error("unknown arg"))?;
let check_str = || meta.value()?.call(parse_str);
if ident == "mode" {
let s = check_str()?;
match s.value().parse() {
Ok(mode_val) => mode = Some(mode_val),
Err(e) => bail_span!(s, "{}", e),
}
} else if ident == "module_name" {
module_name = Some(check_str()?.value())
} else if ident == "source" {
assert_source_empty(&source)?;
let code = check_str()?.value();
source = Some(CompilationSource {
kind: CompilationSourceKind::SourceCode(code),
span: (ident.span(), meta.input.cursor().span()),
});
} else if ident == "file" {
assert_source_empty(&source)?;
let path = check_str()?.value().into();
source = Some(CompilationSource {
kind: CompilationSourceKind::File(path),
span: (ident.span(), meta.input.cursor().span()),
});
} else if ident == "dir" {
if !allow_dir {
bail_span!(ident, "py_compile doesn't accept dir")
}
assert_source_empty(&source)?;
let path = check_str()?.value().into();
source = Some(CompilationSource {
kind: CompilationSourceKind::Dir(path),
span: (ident.span(), meta.input.cursor().span()),
});
} else if ident == "crate_name" {
let name = check_str()?.parse()?;
crate_name = Some(name);
} else {
return Err(meta.error("unknown attr"));
}
Ok(())
})
.parse2(input)?;
let source = source.ok_or_else(|| {
syn::Error::new(
Span::call_site(),
"Must have either file or source in py_compile!()/py_freeze!()",
)
})?;
Ok(Self {
source,
mode: mode.unwrap_or(Mode::Exec),
module_name: module_name.unwrap_or_else(|| "frozen".to_owned()),
crate_name: crate_name.unwrap_or_else(|| syn::parse_quote!(::rustpython_vm)),
})
}
}
fn parse_str(input: ParseStream<'_>) -> ParseResult<LitStr> {
let span = input.span();
if input.peek(LitStr) {
input.parse()
} else if let Ok(mac) = input.parse::<Macro>() {
Ok(LitStr::new(&mac.tokens.to_string(), mac.span()))
} else {
Err(syn::Error::new(span, "Expected string or stringify macro"))
}
}
struct PyCompileArgs {
source: CompilationSource,
mode: Mode,
module_name: String,
crate_name: syn::Path,
}
pub fn impl_py_compile(
input: TokenStream,
compiler: &dyn Compiler,
) -> Result<TokenStream, Diagnostic> {
let args = PyCompileArgs::parse(input, false)?;
let crate_name = args.crate_name;
let code = args
.source
.compile_single(args.mode, args.module_name, compiler)?;
let frozen = frozen::FrozenCodeObject::encode(&code);
let bytes = LitByteStr::new(&frozen.bytes, Span::call_site());
let output = quote! {
#crate_name::frozen::FrozenCodeObject { bytes: &#bytes[..] }
};
Ok(output)
}
pub fn impl_py_freeze(
input: TokenStream,
compiler: &dyn Compiler,
) -> Result<TokenStream, Diagnostic> {
let args = PyCompileArgs::parse(input, true)?;
let crate_name = args.crate_name;
let code_map = args.source.compile(args.mode, args.module_name, compiler)?;
let data = frozen::FrozenLib::encode(code_map.iter().map(|(k, v)| {
let v = frozen::FrozenModule {
code: frozen::FrozenCodeObject::encode(&v.code),
package: v.package,
};
(&**k, v)
}));
let bytes = LitByteStr::new(&data.bytes, Span::call_site());
let output = quote! {
#crate_name::frozen::FrozenLib::from_ref(#bytes)
};
Ok(output)
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/derive-impl/src/pystructseq.rs | crates/derive-impl/src/pystructseq.rs | use crate::util::{ItemMeta, ItemMetaInner};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{DeriveInput, Ident, Item, Result};
use syn_ext::ext::{AttributeExt, GetIdent};
use syn_ext::types::{Meta, PunctuatedNestedMeta};
// #[pystruct_sequence_data] - For Data structs
/// Field kind for struct sequence
#[derive(Clone, Copy, PartialEq, Eq)]
enum FieldKind {
/// Named visible field (has getter, shown in repr)
Named,
/// Unnamed visible field (index-only, no getter)
Unnamed,
/// Hidden/skipped field (stored in tuple, but hidden from repr/len/index)
Skipped,
}
/// Parsed field with its kind
struct ParsedField {
ident: Ident,
kind: FieldKind,
/// Optional cfg attributes for conditional compilation
cfg_attrs: Vec<syn::Attribute>,
}
/// Parsed field info from struct
struct FieldInfo {
/// All fields in order with their kinds
fields: Vec<ParsedField>,
}
impl FieldInfo {
fn named_fields(&self) -> Vec<&ParsedField> {
self.fields
.iter()
.filter(|f| f.kind == FieldKind::Named)
.collect()
}
fn visible_fields(&self) -> Vec<&ParsedField> {
self.fields
.iter()
.filter(|f| f.kind != FieldKind::Skipped)
.collect()
}
fn skipped_fields(&self) -> Vec<&ParsedField> {
self.fields
.iter()
.filter(|f| f.kind == FieldKind::Skipped)
.collect()
}
fn n_unnamed_fields(&self) -> usize {
self.fields
.iter()
.filter(|f| f.kind == FieldKind::Unnamed)
.count()
}
}
/// Parse field info from struct
fn parse_fields(input: &mut DeriveInput) -> Result<FieldInfo> {
let syn::Data::Struct(struc) = &mut input.data else {
bail_span!(input, "#[pystruct_sequence_data] can only be on a struct")
};
let syn::Fields::Named(fields) = &mut struc.fields else {
bail_span!(
input,
"#[pystruct_sequence_data] can only be on a struct with named fields"
);
};
let mut parsed_fields = Vec::with_capacity(fields.named.len());
for field in &mut fields.named {
let mut skip = false;
let mut unnamed = false;
let mut attrs_to_remove = Vec::new();
let mut cfg_attrs = Vec::new();
for (i, attr) in field.attrs.iter().enumerate() {
// Collect cfg attributes for conditional compilation
if attr.path().is_ident("cfg") {
cfg_attrs.push(attr.clone());
continue;
}
if !attr.path().is_ident("pystruct_sequence") {
continue;
}
let Ok(meta) = attr.parse_meta() else {
continue;
};
let Meta::List(l) = meta else {
bail_span!(input, "Only #[pystruct_sequence(...)] form is allowed");
};
let idents: Vec<_> = l
.nested
.iter()
.filter_map(|n| n.get_ident())
.cloned()
.collect();
for ident in idents {
match ident.to_string().as_str() {
"skip" => {
skip = true;
}
"unnamed" => {
unnamed = true;
}
_ => {
bail_span!(ident, "Unknown item for #[pystruct_sequence(...)]")
}
}
}
attrs_to_remove.push(i);
}
// Remove attributes in reverse order
attrs_to_remove.sort_unstable_by(|a, b| b.cmp(a));
for index in attrs_to_remove {
field.attrs.remove(index);
}
let ident = field.ident.clone().unwrap();
let kind = if skip {
FieldKind::Skipped
} else if unnamed {
FieldKind::Unnamed
} else {
FieldKind::Named
};
parsed_fields.push(ParsedField {
ident,
kind,
cfg_attrs,
});
}
Ok(FieldInfo {
fields: parsed_fields,
})
}
/// Check if `try_from_object` is present in attribute arguments
fn has_try_from_object(attr: &PunctuatedNestedMeta) -> bool {
attr.iter().any(|nested| {
nested
.get_ident()
.is_some_and(|ident| ident == "try_from_object")
})
}
/// Attribute macro for Data structs: #[pystruct_sequence_data(...)]
///
/// Generates:
/// - `REQUIRED_FIELD_NAMES` constant (named visible fields)
/// - `OPTIONAL_FIELD_NAMES` constant (hidden/skipped fields)
/// - `UNNAMED_FIELDS_LEN` constant
/// - `into_tuple()` method
/// - Field index constants (e.g., `TM_YEAR_INDEX`)
///
/// Options:
/// - `try_from_object`: Generate `try_from_elements()` method and `TryFromObject` impl
pub(crate) fn impl_pystruct_sequence_data(
attr: PunctuatedNestedMeta,
item: Item,
) -> Result<TokenStream> {
let Item::Struct(item_struct) = item else {
bail_span!(
item,
"#[pystruct_sequence_data] can only be applied to structs"
);
};
let try_from_object = has_try_from_object(&attr);
let mut input: DeriveInput = DeriveInput {
attrs: item_struct.attrs.clone(),
vis: item_struct.vis.clone(),
ident: item_struct.ident.clone(),
generics: item_struct.generics.clone(),
data: syn::Data::Struct(syn::DataStruct {
struct_token: item_struct.struct_token,
fields: item_struct.fields.clone(),
semi_token: item_struct.semi_token,
}),
};
let field_info = parse_fields(&mut input)?;
let data_ident = &input.ident;
let named_fields = field_info.named_fields();
let visible_fields = field_info.visible_fields();
let skipped_fields = field_info.skipped_fields();
let n_unnamed_fields = field_info.n_unnamed_fields();
// Generate field index constants for visible fields (with cfg guards)
let field_indices: Vec<_> = visible_fields
.iter()
.enumerate()
.map(|(i, field)| {
let const_name = format_ident!("{}_INDEX", field.ident.to_string().to_uppercase());
let cfg_attrs = &field.cfg_attrs;
quote! {
#(#cfg_attrs)*
pub const #const_name: usize = #i;
}
})
.collect();
// Generate field name entries with cfg guards for named fields
let named_field_names: Vec<_> = named_fields
.iter()
.map(|f| {
let ident = &f.ident;
let cfg_attrs = &f.cfg_attrs;
if cfg_attrs.is_empty() {
quote! { stringify!(#ident), }
} else {
quote! {
#(#cfg_attrs)*
{ stringify!(#ident) },
}
}
})
.collect();
// Generate field name entries with cfg guards for skipped fields
let skipped_field_names: Vec<_> = skipped_fields
.iter()
.map(|f| {
let ident = &f.ident;
let cfg_attrs = &f.cfg_attrs;
if cfg_attrs.is_empty() {
quote! { stringify!(#ident), }
} else {
quote! {
#(#cfg_attrs)*
{ stringify!(#ident) },
}
}
})
.collect();
// Generate into_tuple items with cfg guards
let visible_tuple_items: Vec<_> = visible_fields
.iter()
.map(|f| {
let ident = &f.ident;
let cfg_attrs = &f.cfg_attrs;
if cfg_attrs.is_empty() {
quote! {
::rustpython_vm::convert::ToPyObject::to_pyobject(self.#ident, vm),
}
} else {
quote! {
#(#cfg_attrs)*
{ ::rustpython_vm::convert::ToPyObject::to_pyobject(self.#ident, vm) },
}
}
})
.collect();
let skipped_tuple_items: Vec<_> = skipped_fields
.iter()
.map(|f| {
let ident = &f.ident;
let cfg_attrs = &f.cfg_attrs;
if cfg_attrs.is_empty() {
quote! {
::rustpython_vm::convert::ToPyObject::to_pyobject(self.#ident, vm),
}
} else {
quote! {
#(#cfg_attrs)*
{ ::rustpython_vm::convert::ToPyObject::to_pyobject(self.#ident, vm) },
}
}
})
.collect();
// Generate TryFromObject impl only when try_from_object=true
let try_from_object_impl = if try_from_object {
let n_required = visible_fields.len();
quote! {
impl ::rustpython_vm::TryFromObject for #data_ident {
fn try_from_object(
vm: &::rustpython_vm::VirtualMachine,
obj: ::rustpython_vm::PyObjectRef,
) -> ::rustpython_vm::PyResult<Self> {
let seq: Vec<::rustpython_vm::PyObjectRef> = obj.try_into_value(vm)?;
if seq.len() < #n_required {
return Err(vm.new_type_error(format!(
"{} requires at least {} elements",
stringify!(#data_ident),
#n_required
)));
}
<Self as ::rustpython_vm::types::PyStructSequenceData>::try_from_elements(seq, vm)
}
}
}
} else {
quote! {}
};
// Generate try_from_elements trait override only when try_from_object=true
let try_from_elements_trait_override = if try_from_object {
let visible_field_inits: Vec<_> = visible_fields
.iter()
.map(|f| {
let ident = &f.ident;
let cfg_attrs = &f.cfg_attrs;
if cfg_attrs.is_empty() {
quote! { #ident: iter.next().unwrap().clone().try_into_value(vm)?, }
} else {
quote! {
#(#cfg_attrs)*
#ident: iter.next().unwrap().clone().try_into_value(vm)?,
}
}
})
.collect();
let skipped_field_inits: Vec<_> = skipped_fields
.iter()
.map(|f| {
let ident = &f.ident;
let cfg_attrs = &f.cfg_attrs;
if cfg_attrs.is_empty() {
quote! {
#ident: match iter.next() {
Some(v) => v.clone().try_into_value(vm)?,
None => vm.ctx.none(),
},
}
} else {
quote! {
#(#cfg_attrs)*
#ident: match iter.next() {
Some(v) => v.clone().try_into_value(vm)?,
None => vm.ctx.none(),
},
}
}
})
.collect();
quote! {
fn try_from_elements(
elements: Vec<::rustpython_vm::PyObjectRef>,
vm: &::rustpython_vm::VirtualMachine,
) -> ::rustpython_vm::PyResult<Self> {
let mut iter = elements.into_iter();
Ok(Self {
#(#visible_field_inits)*
#(#skipped_field_inits)*
})
}
}
} else {
quote! {}
};
let output = quote! {
impl #data_ident {
#(#field_indices)*
}
// PyStructSequenceData trait impl
impl ::rustpython_vm::types::PyStructSequenceData for #data_ident {
const REQUIRED_FIELD_NAMES: &'static [&'static str] = &[#(#named_field_names)*];
const OPTIONAL_FIELD_NAMES: &'static [&'static str] = &[#(#skipped_field_names)*];
const UNNAMED_FIELDS_LEN: usize = #n_unnamed_fields;
fn into_tuple(self, vm: &::rustpython_vm::VirtualMachine) -> ::rustpython_vm::builtins::PyTuple {
let items = vec![
#(#visible_tuple_items)*
#(#skipped_tuple_items)*
];
::rustpython_vm::builtins::PyTuple::new_unchecked(items.into_boxed_slice())
}
#try_from_elements_trait_override
}
#try_from_object_impl
};
// For attribute macro, we need to output the original struct as well
// But first, strip #[pystruct_sequence] attributes from fields
let mut clean_struct = item_struct.clone();
if let syn::Fields::Named(ref mut fields) = clean_struct.fields {
for field in &mut fields.named {
field
.attrs
.retain(|attr| !attr.path().is_ident("pystruct_sequence"));
}
}
Ok(quote! {
#clean_struct
#output
})
}
// #[pystruct_sequence(...)] - For Python type structs
/// Meta parser for #[pystruct_sequence(...)]
pub(crate) struct PyStructSequenceMeta {
inner: ItemMetaInner,
}
impl ItemMeta for PyStructSequenceMeta {
const ALLOWED_NAMES: &'static [&'static str] = &["name", "module", "data", "no_attr"];
fn from_inner(inner: ItemMetaInner) -> Self {
Self { inner }
}
fn inner(&self) -> &ItemMetaInner {
&self.inner
}
}
impl PyStructSequenceMeta {
pub fn class_name(&self) -> Result<Option<String>> {
const KEY: &str = "name";
let inner = self.inner();
if let Some((_, meta)) = inner.meta_map.get(KEY) {
if let Meta::NameValue(syn::MetaNameValue {
value:
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(lit),
..
}),
..
}) = meta
{
return Ok(Some(lit.value()));
}
bail_span!(
inner.meta_ident,
"#[pystruct_sequence({KEY}=value)] expects a string value"
)
} else {
Ok(None)
}
}
pub fn module(&self) -> Result<Option<String>> {
const KEY: &str = "module";
let inner = self.inner();
if let Some((_, meta)) = inner.meta_map.get(KEY) {
if let Meta::NameValue(syn::MetaNameValue {
value:
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(lit),
..
}),
..
}) = meta
{
return Ok(Some(lit.value()));
}
bail_span!(
inner.meta_ident,
"#[pystruct_sequence({KEY}=value)] expects a string value"
)
} else {
Ok(None)
}
}
fn data_type(&self) -> Result<Ident> {
const KEY: &str = "data";
let inner = self.inner();
if let Some((_, meta)) = inner.meta_map.get(KEY) {
if let Meta::NameValue(syn::MetaNameValue {
value:
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(lit),
..
}),
..
}) = meta
{
return Ok(format_ident!("{}", lit.value()));
}
bail_span!(
inner.meta_ident,
"#[pystruct_sequence({KEY}=value)] expects a string value"
)
} else {
bail_span!(
inner.meta_ident,
"#[pystruct_sequence] requires data parameter (e.g., data = \"DataStructName\")"
)
}
}
pub fn no_attr(&self) -> Result<bool> {
self.inner()._bool("no_attr")
}
}
/// Attribute macro for struct sequences.
///
/// Usage:
/// ```ignore
/// #[pystruct_sequence_data]
/// struct StructTimeData { ... }
///
/// #[pystruct_sequence(name = "struct_time", module = "time", data = "StructTimeData")]
/// struct PyStructTime;
/// ```
pub(crate) fn impl_pystruct_sequence(
attr: PunctuatedNestedMeta,
item: Item,
) -> Result<TokenStream> {
let Item::Struct(struct_item) = item else {
bail_span!(item, "#[pystruct_sequence] can only be applied to a struct");
};
let ident = struct_item.ident.clone();
let fake_ident = Ident::new("pystruct_sequence", ident.span());
let meta = PyStructSequenceMeta::from_nested(ident, fake_ident, attr.into_iter())?;
let pytype_ident = struct_item.ident.clone();
let pytype_vis = struct_item.vis.clone();
let data_ident = meta.data_type()?;
let class_name = meta.class_name()?.ok_or_else(|| {
syn::Error::new_spanned(
&struct_item.ident,
"#[pystruct_sequence] requires name parameter",
)
})?;
let module_name = meta.module()?;
// Module name handling
let module_name_tokens = match &module_name {
Some(m) => quote!(Some(#m)),
None => quote!(None),
};
let module_class_name = if let Some(ref m) = module_name {
format!("{}.{}", m, class_name)
} else {
class_name.clone()
};
let output = quote! {
// The Python type struct - newtype wrapping PyTuple
#[derive(Debug)]
#[repr(transparent)]
#pytype_vis struct #pytype_ident(pub ::rustpython_vm::builtins::PyTuple);
// PyClassDef for Python type
impl ::rustpython_vm::class::PyClassDef for #pytype_ident {
const NAME: &'static str = #class_name;
const MODULE_NAME: Option<&'static str> = #module_name_tokens;
const TP_NAME: &'static str = #module_class_name;
const DOC: Option<&'static str> = None;
const BASICSIZE: usize = 0;
const UNHASHABLE: bool = false;
type Base = ::rustpython_vm::builtins::PyTuple;
}
// StaticType for Python type
impl ::rustpython_vm::class::StaticType for #pytype_ident {
fn static_cell() -> &'static ::rustpython_vm::common::static_cell::StaticCell<::rustpython_vm::builtins::PyTypeRef> {
::rustpython_vm::common::static_cell! {
static CELL: ::rustpython_vm::builtins::PyTypeRef;
}
&CELL
}
fn static_baseclass() -> &'static ::rustpython_vm::Py<::rustpython_vm::builtins::PyType> {
use ::rustpython_vm::class::StaticType;
::rustpython_vm::builtins::PyTuple::static_type()
}
}
// Subtype uses base type's payload_type_id
impl ::rustpython_vm::PyPayload for #pytype_ident {
#[inline]
fn payload_type_id() -> ::std::any::TypeId {
<::rustpython_vm::builtins::PyTuple as ::rustpython_vm::PyPayload>::payload_type_id()
}
#[inline]
fn validate_downcastable_from(obj: &::rustpython_vm::PyObject) -> bool {
obj.class().fast_issubclass(<Self as ::rustpython_vm::class::StaticType>::static_type())
}
fn class(_ctx: &::rustpython_vm::vm::Context) -> &'static ::rustpython_vm::Py<::rustpython_vm::builtins::PyType> {
<Self as ::rustpython_vm::class::StaticType>::static_type()
}
}
// MaybeTraverse - delegate to inner PyTuple
impl ::rustpython_vm::object::MaybeTraverse for #pytype_ident {
fn try_traverse(&self, traverse_fn: &mut ::rustpython_vm::object::TraverseFn<'_>) {
self.0.try_traverse(traverse_fn)
}
}
// PySubclass for proper inheritance
impl ::rustpython_vm::class::PySubclass for #pytype_ident {
type Base = ::rustpython_vm::builtins::PyTuple;
#[inline]
fn as_base(&self) -> &Self::Base {
&self.0
}
}
// PyStructSequence trait for Python type
impl ::rustpython_vm::types::PyStructSequence for #pytype_ident {
type Data = #data_ident;
}
// ToPyObject for Data struct - uses PyStructSequence::from_data
impl ::rustpython_vm::convert::ToPyObject for #data_ident {
fn to_pyobject(self, vm: &::rustpython_vm::VirtualMachine) -> ::rustpython_vm::PyObjectRef {
<#pytype_ident as ::rustpython_vm::types::PyStructSequence>::from_data(self, vm).into()
}
}
};
Ok(output)
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/derive-impl/src/from_args.rs | crates/derive-impl/src/from_args.rs | use proc_macro2::TokenStream;
use quote::{ToTokens, quote};
use syn::ext::IdentExt;
use syn::meta::ParseNestedMeta;
use syn::{Attribute, Data, DeriveInput, Expr, Field, Ident, Result, Token, parse_quote};
/// The kind of the python parameter, this corresponds to the value of Parameter.kind
/// (https://docs.python.org/3/library/inspect.html#inspect.Parameter.kind)
#[derive(Default)]
enum ParameterKind {
PositionalOnly,
#[default]
PositionalOrKeyword,
KeywordOnly,
Flatten,
}
impl TryFrom<&Ident> for ParameterKind {
type Error = ();
fn try_from(ident: &Ident) -> core::result::Result<Self, Self::Error> {
Ok(match ident.to_string().as_str() {
"positional" => Self::PositionalOnly,
"any" => Self::PositionalOrKeyword,
"named" => Self::KeywordOnly,
"flatten" => Self::Flatten,
_ => return Err(()),
})
}
}
// None == quote!(Default::default())
type DefaultValue = Option<Expr>;
#[derive(Default)]
struct ArgAttribute {
name: Option<String>,
kind: ParameterKind,
default: Option<DefaultValue>,
}
impl ArgAttribute {
fn from_attribute(attr: &Attribute) -> Option<Result<Self>> {
if !attr.path().is_ident("pyarg") {
return None;
}
let inner = move || {
let mut arg_attr = None;
attr.parse_nested_meta(|meta| {
let Some(arg_attr) = &mut arg_attr else {
let kind = meta
.path
.get_ident()
.and_then(|ident| ParameterKind::try_from(ident).ok())
.ok_or_else(|| {
meta.error(
"The first argument to #[pyarg()] must be the parameter type, \
either 'positional', 'any', 'named', or 'flatten'.",
)
})?;
arg_attr = Some(Self {
name: None,
kind,
default: None,
});
return Ok(());
};
arg_attr.parse_argument(meta)
})?;
arg_attr
.ok_or_else(|| err_span!(attr, "There must be at least one argument to #[pyarg()]"))
};
Some(inner())
}
fn parse_argument(&mut self, meta: ParseNestedMeta<'_>) -> Result<()> {
if let ParameterKind::Flatten = self.kind {
return Err(meta.error("can't put additional arguments on a flatten arg"));
}
if meta.path.is_ident("default") && meta.input.peek(Token![=]) {
if matches!(self.default, Some(Some(_))) {
return Err(meta.error("Default already set"));
}
let val = meta.value()?;
self.default = Some(Some(val.parse()?))
} else if meta.path.is_ident("default") || meta.path.is_ident("optional") {
if self.default.is_none() {
self.default = Some(None);
}
} else if meta.path.is_ident("name") {
if self.name.is_some() {
return Err(meta.error("already have a name"));
}
let val = meta.value()?.parse::<syn::LitStr>()?;
self.name = Some(val.value())
} else {
return Err(meta.error("Unrecognized pyarg attribute"));
}
Ok(())
}
}
impl TryFrom<&Field> for ArgAttribute {
type Error = syn::Error;
fn try_from(field: &Field) -> core::result::Result<Self, Self::Error> {
let mut pyarg_attrs = field
.attrs
.iter()
.filter_map(Self::from_attribute)
.collect::<core::result::Result<Vec<_>, _>>()?;
if pyarg_attrs.len() >= 2 {
bail_span!(field, "Multiple pyarg attributes on field")
};
Ok(pyarg_attrs.pop().unwrap_or_default())
}
}
fn generate_field((i, field): (usize, &Field)) -> Result<TokenStream> {
let attr = ArgAttribute::try_from(field)?;
let name = field.ident.as_ref();
let name_string = name.map(|ident| ident.unraw().to_string());
if matches!(&name_string, Some(s) if s.starts_with("_phantom")) {
return Ok(quote! {
#name: ::std::marker::PhantomData,
});
}
let field_name = match name {
Some(id) => id.to_token_stream(),
None => syn::Index::from(i).into_token_stream(),
};
if let ParameterKind::Flatten = attr.kind {
return Ok(quote! {
#field_name: ::rustpython_vm::function::FromArgs::from_args(vm, args)?,
});
}
let pyname = attr
.name
.or(name_string)
.ok_or_else(|| err_span!(field, "field in tuple struct must have name attribute"))?;
let middle = quote! {
.map(|x| ::rustpython_vm::convert::TryFromObject::try_from_object(vm, x)).transpose()?
};
let ending = if let Some(default) = attr.default {
let ty = &field.ty;
let default = default.unwrap_or_else(|| parse_quote!(::std::default::Default::default()));
quote! {
.map(<#ty as ::rustpython_vm::function::FromArgOptional>::from_inner)
.unwrap_or_else(|| #default)
}
} else {
let err = match attr.kind {
ParameterKind::PositionalOnly | ParameterKind::PositionalOrKeyword => quote! {
::rustpython_vm::function::ArgumentError::TooFewArgs
},
ParameterKind::KeywordOnly => quote! {
::rustpython_vm::function::ArgumentError::RequiredKeywordArgument(#pyname.to_owned())
},
ParameterKind::Flatten => unreachable!(),
};
quote! {
.ok_or_else(|| #err)?
}
};
let file_output = match attr.kind {
ParameterKind::PositionalOnly => quote! {
#field_name: args.take_positional()#middle #ending,
},
ParameterKind::PositionalOrKeyword => quote! {
#field_name: args.take_positional_keyword(#pyname)#middle #ending,
},
ParameterKind::KeywordOnly => quote! {
#field_name: args.take_keyword(#pyname)#middle #ending,
},
ParameterKind::Flatten => unreachable!(),
};
Ok(file_output)
}
fn compute_arity_bounds(field_attrs: &[ArgAttribute]) -> (usize, usize) {
let positional_fields = field_attrs.iter().filter(|attr| {
matches!(
attr.kind,
ParameterKind::PositionalOnly | ParameterKind::PositionalOrKeyword
)
});
let min_arity = positional_fields
.clone()
.filter(|attr| attr.default.is_none())
.count();
let max_arity = positional_fields.count();
(min_arity, max_arity)
}
pub fn impl_from_args(input: DeriveInput) -> Result<TokenStream> {
let (fields, field_attrs) = match input.data {
Data::Struct(syn::DataStruct { fields, .. }) => (
fields
.iter()
.enumerate()
.map(generate_field)
.collect::<Result<TokenStream>>()?,
fields
.iter()
.filter_map(|field| field.try_into().ok())
.collect::<Vec<ArgAttribute>>(),
),
_ => bail_span!(input, "FromArgs input must be a struct"),
};
let (min_arity, max_arity) = compute_arity_bounds(&field_attrs);
let name = input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let output = quote! {
impl #impl_generics ::rustpython_vm::function::FromArgs for #name #ty_generics #where_clause {
fn arity() -> ::std::ops::RangeInclusive<usize> {
#min_arity..=#max_arity
}
fn from_args(
vm: &::rustpython_vm::VirtualMachine,
args: &mut ::rustpython_vm::function::FuncArgs
) -> ::core::result::Result<Self, ::rustpython_vm::function::ArgumentError> {
Ok(Self { #fields })
}
}
};
Ok(output)
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/derive-impl/src/error.rs | crates/derive-impl/src/error.rs | // Taken from https://github.com/rustwasm/wasm-bindgen/blob/master/crates/backend/src/error.rs
//
// Copyright (c) 2014 Alex Crichton
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#![allow(dead_code)]
use proc_macro2::*;
use quote::{ToTokens, TokenStreamExt};
use syn::parse::Error;
macro_rules! err_span {
($span:expr, $($msg:tt)*) => (
syn::Error::new_spanned(&$span, format_args!($($msg)*))
)
}
macro_rules! bail_span {
($($t:tt)*) => (
return Err(err_span!($($t)*).into())
)
}
// macro_rules! push_err_span {
// ($diagnostics:expr, $($t:tt)*) => {
// $diagnostics.push(err_span!($($t)*))
// };
// }
// macro_rules! push_diag_result {
// ($diags:expr, $x:expr $(,)?) => {
// if let Err(e) = $x {
// $diags.push(e);
// }
// };
// }
#[derive(Debug)]
pub struct Diagnostic {
inner: Repr,
}
#[derive(Debug)]
enum Repr {
Single {
text: String,
span: Option<(Span, Span)>,
},
SynError(Error),
Multi {
diagnostics: Vec<Diagnostic>,
},
}
impl Diagnostic {
pub fn error<T: Into<String>>(text: T) -> Self {
Self {
inner: Repr::Single {
text: text.into(),
span: None,
},
}
}
pub(crate) fn spans_error<T: Into<String>>(spans: (Span, Span), text: T) -> Self {
Self {
inner: Repr::Single {
text: text.into(),
span: Some(spans),
},
}
}
pub fn from_vec(diagnostics: Vec<Self>) -> Result<(), Self> {
if diagnostics.is_empty() {
Ok(())
} else {
Err(Self {
inner: Repr::Multi { diagnostics },
})
}
}
pub fn panic(&self) -> ! {
match &self.inner {
Repr::Single { text, .. } => panic!("{}", text),
Repr::SynError(error) => panic!("{}", error),
Repr::Multi { diagnostics } => diagnostics[0].panic(),
}
}
}
impl From<Error> for Diagnostic {
fn from(err: Error) -> Self {
Self {
inner: Repr::SynError(err),
}
}
}
pub fn extract_spans(node: &dyn ToTokens) -> Option<(Span, Span)> {
let mut t = TokenStream::new();
node.to_tokens(&mut t);
let mut tokens = t.into_iter();
let start = tokens.next().map(|t| t.span());
let end = tokens.last().map(|t| t.span());
start.map(|start| (start, end.unwrap_or(start)))
}
impl ToTokens for Diagnostic {
fn to_tokens(&self, dst: &mut TokenStream) {
match &self.inner {
Repr::Single { text, span } => {
let cs2 = (Span::call_site(), Span::call_site());
let (start, end) = span.unwrap_or(cs2);
dst.append(Ident::new("compile_error", start));
dst.append(Punct::new('!', Spacing::Alone));
let mut message = TokenStream::new();
message.append(Literal::string(text));
let mut group = Group::new(Delimiter::Brace, message);
group.set_span(end);
dst.append(group);
}
Repr::Multi { diagnostics } => {
for diagnostic in diagnostics {
diagnostic.to_tokens(dst);
}
}
Repr::SynError(err) => {
err.to_compile_error().to_tokens(dst);
}
}
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/derive-impl/src/util.rs | crates/derive-impl/src/util.rs | use itertools::Itertools;
use proc_macro2::{Span, TokenStream};
use quote::{ToTokens, quote};
use std::collections::{HashMap, HashSet};
use syn::{Attribute, Ident, Result, Signature, UseTree, spanned::Spanned};
use syn_ext::{
ext::{AttributeExt as SynAttributeExt, *},
types::*,
};
pub(crate) const ALL_ALLOWED_NAMES: &[&str] = &[
"pymethod",
"pyclassmethod",
"pystaticmethod",
"pygetset",
"pyfunction",
"pyclass",
"pyexception",
"pystruct_sequence",
"pyattr",
"pyslot",
"extend_class",
"pymember",
];
#[derive(Clone)]
struct NurseryItem {
attr_name: Ident,
py_names: Vec<String>,
cfgs: Vec<Attribute>,
tokens: TokenStream,
sort_order: usize,
}
#[derive(Default)]
pub(crate) struct ItemNursery(Vec<NurseryItem>);
pub(crate) struct ValidatedItemNursery(ItemNursery);
impl ItemNursery {
pub fn add_item(
&mut self,
attr_name: Ident,
py_names: Vec<String>,
cfgs: Vec<Attribute>,
tokens: TokenStream,
sort_order: usize,
) -> Result<()> {
self.0.push(NurseryItem {
attr_name,
py_names,
cfgs,
tokens,
sort_order,
});
Ok(())
}
pub fn validate(self) -> Result<ValidatedItemNursery> {
let mut by_name: HashSet<(String, Vec<Attribute>)> = HashSet::new();
for item in &self.0 {
for py_name in &item.py_names {
let inserted = by_name.insert((py_name.clone(), item.cfgs.clone()));
if !inserted {
return Err(syn::Error::new(
item.attr_name.span(),
format!("Duplicated #[py*] attribute found for {:?}", &item.py_names),
));
}
}
}
Ok(ValidatedItemNursery(self))
}
}
impl ToTokens for ValidatedItemNursery {
fn to_tokens(&self, tokens: &mut TokenStream) {
let mut sorted = self.0.0.clone();
sorted.sort_by(|a, b| a.sort_order.cmp(&b.sort_order));
tokens.extend(sorted.iter().map(|item| {
let cfgs = &item.cfgs;
let tokens = &item.tokens;
quote! {
#( #cfgs )*
{
#tokens
}
}
}))
}
}
#[derive(Clone)]
pub(crate) struct ContentItemInner<T> {
pub index: usize,
pub attr_name: T,
}
pub(crate) trait ContentItem {
type AttrName: core::str::FromStr + core::fmt::Display;
fn inner(&self) -> &ContentItemInner<Self::AttrName>;
fn index(&self) -> usize {
self.inner().index
}
fn attr_name(&self) -> &Self::AttrName {
&self.inner().attr_name
}
fn new_syn_error(&self, span: Span, message: &str) -> syn::Error {
syn::Error::new(span, format!("#[{}] {}", self.attr_name(), message))
}
}
pub(crate) struct ItemMetaInner {
pub item_ident: Ident,
pub meta_ident: Ident,
pub meta_map: HashMap<String, (usize, Meta)>,
}
impl ItemMetaInner {
pub fn from_nested<I>(
item_ident: Ident,
meta_ident: Ident,
nested: I,
allowed_names: &[&'static str],
) -> Result<Self>
where
I: core::iter::Iterator<Item = NestedMeta>,
{
let (meta_map, lits) = nested.into_unique_map_and_lits(|path| {
if let Some(ident) = path.get_ident() {
let name = ident.to_string();
if allowed_names.contains(&name.as_str()) {
Ok(Some(name))
} else {
Err(err_span!(
ident,
"#[{meta_ident}({name})] is not one of allowed attributes [{}]",
allowed_names.iter().format(", ")
))
}
} else {
Ok(None)
}
})?;
if !lits.is_empty() {
bail_span!(meta_ident, "#[{meta_ident}(..)] cannot contain literal")
}
Ok(Self {
item_ident,
meta_ident,
meta_map,
})
}
pub fn item_name(&self) -> String {
self.item_ident.to_string()
}
pub fn meta_name(&self) -> String {
self.meta_ident.to_string()
}
pub fn _optional_str(&self, key: &str) -> Result<Option<String>> {
let value = if let Some((_, meta)) = self.meta_map.get(key) {
let Meta::NameValue(syn::MetaNameValue {
value:
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(lit),
..
}),
..
}) = meta
else {
bail_span!(
meta,
"#[{}({} = ...)] must exist as a string",
self.meta_name(),
key
)
};
Some(lit.value())
} else {
None
};
Ok(value)
}
pub fn _optional_path(&self, key: &str) -> Result<Option<syn::Path>> {
let value = if let Some((_, meta)) = self.meta_map.get(key) {
let Meta::NameValue(syn::MetaNameValue { value, .. }) = meta else {
bail_span!(
meta,
"#[{}({} = ...)] must be a name-value pair",
self.meta_name(),
key
)
};
// Try to parse as a Path (identifier or path like Foo or foo::Bar)
match syn::parse2::<syn::Path>(value.to_token_stream()) {
Ok(path) => Some(path),
Err(_) => {
bail_span!(
value,
"#[{}({} = ...)] must be a valid type path (e.g., PyBaseException)",
self.meta_name(),
key
)
}
}
} else {
None
};
Ok(value)
}
pub fn _has_key(&self, key: &str) -> Result<bool> {
Ok(matches!(self.meta_map.get(key), Some((_, _))))
}
pub fn _bool(&self, key: &str) -> Result<bool> {
let value = if let Some((_, meta)) = self.meta_map.get(key) {
match meta {
Meta::NameValue(syn::MetaNameValue {
value:
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Bool(lit),
..
}),
..
}) => lit.value,
Meta::Path(_) => true,
_ => bail_span!(meta, "#[{}({})] is expected", self.meta_name(), key),
}
} else {
false
};
Ok(value)
}
pub fn _optional_list(
&self,
key: &str,
) -> Result<Option<impl core::iter::Iterator<Item = &'_ NestedMeta>>> {
let value = if let Some((_, meta)) = self.meta_map.get(key) {
let Meta::List(MetaList {
path: _, nested, ..
}) = meta
else {
bail_span!(meta, "#[{}({}(...))] must be a list", self.meta_name(), key)
};
Some(nested.into_iter())
} else {
None
};
Ok(value)
}
}
pub(crate) trait ItemMeta: Sized {
const ALLOWED_NAMES: &'static [&'static str];
fn from_attr(item_ident: Ident, attr: &Attribute) -> Result<Self> {
let (meta_ident, nested) = attr.ident_and_promoted_nested()?;
Self::from_nested(item_ident, meta_ident.clone(), nested.into_iter())
}
fn from_nested<I>(item_ident: Ident, meta_ident: Ident, nested: I) -> Result<Self>
where
I: core::iter::Iterator<Item = NestedMeta>,
{
Ok(Self::from_inner(ItemMetaInner::from_nested(
item_ident,
meta_ident,
nested,
Self::ALLOWED_NAMES,
)?))
}
fn from_inner(inner: ItemMetaInner) -> Self;
fn inner(&self) -> &ItemMetaInner;
fn simple_name(&self) -> Result<String> {
let inner = self.inner();
Ok(inner
._optional_str("name")?
.unwrap_or_else(|| inner.item_name()))
}
fn optional_name(&self) -> Option<String> {
self.inner()._optional_str("name").ok().flatten()
}
fn new_meta_error(&self, msg: &str) -> syn::Error {
let inner = self.inner();
err_span!(inner.meta_ident, "#[{}] {}", inner.meta_name(), msg)
}
}
pub(crate) struct SimpleItemMeta(pub ItemMetaInner);
impl ItemMeta for SimpleItemMeta {
const ALLOWED_NAMES: &'static [&'static str] = &["name"];
fn from_inner(inner: ItemMetaInner) -> Self {
Self(inner)
}
fn inner(&self) -> &ItemMetaInner {
&self.0
}
}
pub(crate) struct ModuleItemMeta(pub ItemMetaInner);
impl ItemMeta for ModuleItemMeta {
const ALLOWED_NAMES: &'static [&'static str] = &["name", "with", "sub"];
fn from_inner(inner: ItemMetaInner) -> Self {
Self(inner)
}
fn inner(&self) -> &ItemMetaInner {
&self.0
}
}
impl ModuleItemMeta {
pub fn sub(&self) -> Result<bool> {
self.inner()._bool("sub")
}
pub fn with(&self) -> Result<Vec<&syn::Path>> {
let mut withs = Vec::new();
let Some(nested) = self.inner()._optional_list("with")? else {
return Ok(withs);
};
for meta in nested {
let NestedMeta::Meta(Meta::Path(path)) = meta else {
bail_span!(meta, "#[pymodule(with(...))] arguments should be paths")
};
withs.push(path);
}
Ok(withs)
}
}
pub(crate) struct AttrItemMeta(pub ItemMetaInner);
impl ItemMeta for AttrItemMeta {
const ALLOWED_NAMES: &'static [&'static str] = &["name", "once"];
fn from_inner(inner: ItemMetaInner) -> Self {
Self(inner)
}
fn inner(&self) -> &ItemMetaInner {
&self.0
}
}
pub(crate) struct ClassItemMeta(ItemMetaInner);
impl ItemMeta for ClassItemMeta {
const ALLOWED_NAMES: &'static [&'static str] = &[
"module",
"name",
"base",
"metaclass",
"unhashable",
"ctx",
"impl",
"traverse",
];
fn from_inner(inner: ItemMetaInner) -> Self {
Self(inner)
}
fn inner(&self) -> &ItemMetaInner {
&self.0
}
}
impl ClassItemMeta {
pub fn class_name(&self) -> Result<String> {
const KEY: &str = "name";
let inner = self.inner();
if let Some((_, meta)) = inner.meta_map.get(KEY) {
match meta {
Meta::NameValue(syn::MetaNameValue {
value:
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(lit),
..
}),
..
}) => return Ok(lit.value()),
Meta::Path(_) => return Ok(inner.item_name()),
_ => {}
}
}
bail_span!(
inner.meta_ident,
"#[{attr_name}(name = ...)] must exist as a string. Try \
#[{attr_name}(name)] to use rust type name.",
attr_name = inner.meta_name()
)
}
pub fn ctx_name(&self) -> Result<Option<String>> {
self.inner()._optional_str("ctx")
}
pub fn base(&self) -> Result<Option<syn::Path>> {
self.inner()._optional_path("base")
}
pub fn unhashable(&self) -> Result<bool> {
self.inner()._bool("unhashable")
}
pub fn metaclass(&self) -> Result<Option<String>> {
self.inner()._optional_str("metaclass")
}
pub fn module(&self) -> Result<Option<String>> {
const KEY: &str = "module";
let inner = self.inner();
let value = if let Some((_, meta)) = inner.meta_map.get(KEY) {
match meta {
Meta::NameValue(syn::MetaNameValue {
value: syn::Expr::Lit(syn::ExprLit{lit:syn::Lit::Str(lit),..}),
..
}) => Ok(Some(lit.value())),
Meta::NameValue(syn::MetaNameValue {
value: syn::Expr::Lit(syn::ExprLit{lit:syn::Lit::Bool(lit),..}),
..
}) => if lit.value {
Err(lit.span())
} else {
Ok(None)
}
other => Err(other.span()),
}
} else {
Err(inner.item_ident.span())
}.map_err(|span| syn::Error::new(
span,
format!(
"#[{attr_name}(module = ...)] must exist as a string or false. Try #[{attr_name}(module = false)] for built-in types.",
attr_name=inner.meta_name()
),
))?;
Ok(value)
}
pub fn impl_attrs(&self) -> Result<Option<String>> {
self.inner()._optional_str("impl")
}
// pub fn mandatory_module(&self) -> Result<String> {
// let inner = self.inner();
// let value = self.module().ok().flatten().
// ok_or_else(|| err_span!(
// inner.meta_ident,
// "#[{attr_name}(module = ...)] must exist as a string. Built-in module is not allowed here.",
// attr_name = inner.meta_name()
// ))?;
// Ok(value)
// }
}
pub(crate) struct ExceptionItemMeta(ClassItemMeta);
impl ItemMeta for ExceptionItemMeta {
const ALLOWED_NAMES: &'static [&'static str] =
&["module", "name", "base", "unhashable", "ctx", "impl"];
fn from_inner(inner: ItemMetaInner) -> Self {
Self(ClassItemMeta(inner))
}
fn inner(&self) -> &ItemMetaInner {
&self.0.0
}
}
impl ExceptionItemMeta {
pub fn class_name(&self) -> Result<String> {
const KEY: &str = "name";
let inner = self.inner();
if let Some((_, meta)) = inner.meta_map.get(KEY) {
match meta {
Meta::NameValue(syn::MetaNameValue {
value:
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(lit),
..
}),
..
}) => return Ok(lit.value()),
Meta::Path(_) => {
return Ok({
let type_name = inner.item_name();
let Some(py_name) = type_name.as_str().strip_prefix("Py") else {
bail_span!(
inner.item_ident,
"#[pyexception] expects its underlying type to be named `Py` prefixed"
)
};
py_name.to_string()
});
}
_ => {}
}
}
bail_span!(
inner.meta_ident,
"#[{attr_name}(name = ...)] must exist as a string. Try \
#[{attr_name}(name)] to use rust type name.",
attr_name = inner.meta_name()
)
}
pub fn has_impl(&self) -> Result<bool> {
self.inner()._bool("impl")
}
}
impl core::ops::Deref for ExceptionItemMeta {
type Target = ClassItemMeta;
fn deref(&self) -> &Self::Target {
&self.0
}
}
pub(crate) trait AttributeExt: SynAttributeExt {
fn promoted_nested(&self) -> Result<PunctuatedNestedMeta>;
fn ident_and_promoted_nested(&self) -> Result<(&Ident, PunctuatedNestedMeta)>;
fn try_remove_name(&mut self, name: &str) -> Result<Option<NestedMeta>>;
fn fill_nested_meta<F>(&mut self, name: &str, new_item: F) -> Result<()>
where
F: Fn() -> NestedMeta;
}
impl AttributeExt for Attribute {
fn promoted_nested(&self) -> Result<PunctuatedNestedMeta> {
let list = self.promoted_list().map_err(|mut e| {
let name = self.get_ident().unwrap().to_string();
e.combine(err_span!(
self,
r##"#[{name} = "..."] cannot be a name/value, you probably meant \
#[{name}(name = "...")]"##,
));
e
})?;
Ok(list.nested)
}
fn ident_and_promoted_nested(&self) -> Result<(&Ident, PunctuatedNestedMeta)> {
Ok((self.get_ident().unwrap(), self.promoted_nested()?))
}
fn try_remove_name(&mut self, item_name: &str) -> Result<Option<NestedMeta>> {
self.try_meta_mut(|meta| {
let nested = match meta {
Meta::List(MetaList { nested, .. }) => Ok(nested),
other => Err(syn::Error::new(
other.span(),
format!(
"#[{name}(...)] doesn't contain '{item}' to remove",
name = other.get_ident().unwrap(),
item = item_name
),
)),
}?;
let mut found = None;
for (i, item) in nested.iter().enumerate() {
let ident = if let Some(ident) = item.get_ident() {
ident
} else {
continue;
};
if *ident != item_name {
continue;
}
if found.is_some() {
return Err(syn::Error::new(
item.span(),
format!("#[py..({item_name}...)] must be unique but found multiple times"),
));
}
found = Some(i);
}
Ok(found.map(|idx| nested.remove(idx).into_value()))
})
}
fn fill_nested_meta<F>(&mut self, name: &str, new_item: F) -> Result<()>
where
F: Fn() -> NestedMeta,
{
self.try_meta_mut(|meta| {
let list = meta.promote_to_list(Default::default())?;
let has_name = list
.nested
.iter()
.any(|nested_meta| nested_meta.get_path().is_some_and(|p| p.is_ident(name)));
if !has_name {
list.nested.push(new_item())
}
Ok(())
})
}
}
pub(crate) fn pyclass_ident_and_attrs(item: &syn::Item) -> Result<(&Ident, &[Attribute])> {
use syn::Item::*;
Ok(match item {
Struct(syn::ItemStruct { ident, attrs, .. }) => (ident, attrs),
Enum(syn::ItemEnum { ident, attrs, .. }) => (ident, attrs),
Use(item_use) => (
iter_use_idents(item_use, |ident, _is_unique| Ok(ident))?
.into_iter()
.exactly_one()
.map_err(|_| {
err_span!(
item_use,
"#[pyclass] can only be on single name use statement",
)
})?,
&item_use.attrs,
),
other => {
bail_span!(
other,
"#[pyclass] can only be on a struct, enum or use declaration",
)
}
})
}
pub(crate) fn pyexception_ident_and_attrs(item: &syn::Item) -> Result<(&Ident, &[Attribute])> {
use syn::Item::*;
Ok(match item {
Struct(syn::ItemStruct { ident, attrs, .. }) => (ident, attrs),
Enum(syn::ItemEnum { ident, attrs, .. }) => (ident, attrs),
other => {
bail_span!(other, "#[pyexception] can only be on a struct or enum",)
}
})
}
pub(crate) trait ErrorVec: Sized {
fn into_error(self) -> Option<syn::Error>;
fn into_result(self) -> Result<()> {
if let Some(error) = self.into_error() {
Err(error)
} else {
Ok(())
}
}
fn ok_or_push<T>(&mut self, r: Result<T>) -> Option<T>;
}
impl ErrorVec for Vec<syn::Error> {
fn into_error(self) -> Option<syn::Error> {
let mut iter = self.into_iter();
if let Some(mut first) = iter.next() {
for err in iter {
first.combine(err);
}
Some(first)
} else {
None
}
}
fn ok_or_push<T>(&mut self, r: Result<T>) -> Option<T> {
match r {
Ok(v) => Some(v),
Err(e) => {
self.push(e);
None
}
}
}
}
pub(crate) fn iter_use_idents<'a, F, R: 'a>(item_use: &'a syn::ItemUse, mut f: F) -> Result<Vec<R>>
where
F: FnMut(&'a syn::Ident, bool) -> Result<R>,
{
let mut result = Vec::new();
match &item_use.tree {
UseTree::Name(name) => result.push(f(&name.ident, true)?),
UseTree::Rename(rename) => result.push(f(&rename.rename, true)?),
UseTree::Path(path) => match &*path.tree {
UseTree::Name(name) => result.push(f(&name.ident, true)?),
UseTree::Rename(rename) => result.push(f(&rename.rename, true)?),
other => iter_use_tree_idents(other, &mut result, &mut f)?,
},
other => iter_use_tree_idents(other, &mut result, &mut f)?,
}
Ok(result)
}
fn iter_use_tree_idents<'a, F, R: 'a>(
tree: &'a syn::UseTree,
result: &mut Vec<R>,
f: &mut F,
) -> Result<()>
where
F: FnMut(&'a syn::Ident, bool) -> Result<R>,
{
match tree {
UseTree::Name(name) => result.push(f(&name.ident, false)?),
UseTree::Rename(rename) => result.push(f(&rename.rename, false)?),
UseTree::Path(path) => iter_use_tree_idents(&path.tree, result, f)?,
UseTree::Group(syn::UseGroup { items, .. }) => {
for subtree in items {
iter_use_tree_idents(subtree, result, f)?;
}
}
UseTree::Glob(glob) => {
bail_span!(glob, "#[py*] doesn't allow '*'")
}
}
Ok(())
}
// Best effort attempt to generate a template from which a
// __text_signature__ can be created.
pub(crate) fn text_signature(sig: &Signature, name: &str) -> String {
let signature = func_sig(sig);
if signature.starts_with("$self") {
format!("{name}({signature})")
} else {
format!("{}({}, {})", name, "$module", signature)
}
}
fn func_sig(sig: &Signature) -> String {
sig.inputs
.iter()
.filter_map(|arg| {
use syn::FnArg::*;
let arg = match arg {
Typed(typed) => typed,
Receiver(_) => return Some("$self".to_owned()),
};
let ty = arg.ty.as_ref();
let ty = quote!(#ty).to_string();
if ty == "FuncArgs" {
return Some("*args, **kwargs".to_owned());
}
if ty.starts_with('&') && ty.ends_with("VirtualMachine") {
return None;
}
let ident = match arg.pat.as_ref() {
syn::Pat::Ident(p) => p.ident.to_string(),
// FIXME: other => unreachable!("function arg pattern must be ident but found `{}`", quote!(fn #ident(.. #other ..))),
other => quote!(#other).to_string(),
};
if ident == "zelf" {
return Some("$self".to_owned());
}
if ident == "vm" {
unreachable!("type &VirtualMachine(`{ty}`) must be filtered already");
}
Some(ident)
})
.collect::<Vec<_>>()
.join(", ")
}
pub(crate) fn format_doc(sig: &str, doc: &str) -> String {
format!("{sig}\n--\n\n{doc}")
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/derive-impl/src/pyclass.rs | crates/derive-impl/src/pyclass.rs | use super::Diagnostic;
use crate::util::{
ALL_ALLOWED_NAMES, ClassItemMeta, ContentItem, ContentItemInner, ErrorVec, ExceptionItemMeta,
ItemMeta, ItemMetaInner, ItemNursery, SimpleItemMeta, format_doc, pyclass_ident_and_attrs,
pyexception_ident_and_attrs, text_signature,
};
use core::str::FromStr;
use proc_macro2::{Delimiter, Group, Span, TokenStream, TokenTree};
use quote::{ToTokens, quote, quote_spanned};
use rustpython_doc::DB;
use std::collections::{HashMap, HashSet};
use syn::{Attribute, Ident, Item, Result, parse_quote, spanned::Spanned};
use syn_ext::ext::*;
use syn_ext::types::*;
#[derive(Copy, Clone, Debug)]
enum AttrName {
Method,
ClassMethod,
StaticMethod,
GetSet,
Slot,
Attr,
ExtendClass,
Member,
}
impl core::fmt::Display for AttrName {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let s = match self {
Self::Method => "pymethod",
Self::ClassMethod => "pyclassmethod",
Self::StaticMethod => "pystaticmethod",
Self::GetSet => "pygetset",
Self::Slot => "pyslot",
Self::Attr => "pyattr",
Self::ExtendClass => "extend_class",
Self::Member => "pymember",
};
s.fmt(f)
}
}
impl FromStr for AttrName {
type Err = String;
fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
Ok(match s {
"pymethod" => Self::Method,
"pyclassmethod" => Self::ClassMethod,
"pystaticmethod" => Self::StaticMethod,
"pygetset" => Self::GetSet,
"pyslot" => Self::Slot,
"pyattr" => Self::Attr,
"extend_class" => Self::ExtendClass,
"pymember" => Self::Member,
s => {
return Err(s.to_owned());
}
})
}
}
#[derive(Default)]
struct ImplContext {
is_trait: bool,
attribute_items: ItemNursery,
method_items: MethodNursery,
getset_items: GetSetNursery,
member_items: MemberNursery,
extend_slots_items: ItemNursery,
class_extensions: Vec<TokenStream>,
errors: Vec<syn::Error>,
}
fn extract_items_into_context<'a, Item>(
context: &mut ImplContext,
items: impl Iterator<Item = &'a mut Item>,
) where
Item: ItemLike + ToTokens + GetIdent + syn_ext::ext::ItemAttrExt + 'a,
{
for item in items {
let r = item.try_split_attr_mut(|attrs, item| {
let (py_items, cfgs) = attrs_to_content_items(attrs, impl_item_new::<Item>)?;
for py_item in py_items.iter().rev() {
let r = py_item.gen_impl_item(ImplItemArgs::<Item> {
item,
attrs,
context,
cfgs: cfgs.as_slice(),
});
context.errors.ok_or_push(r);
}
Ok(())
});
context.errors.ok_or_push(r);
}
context.errors.ok_or_push(context.method_items.validate());
context.errors.ok_or_push(context.getset_items.validate());
context.errors.ok_or_push(context.member_items.validate());
}
pub(crate) fn impl_pyclass_impl(attr: PunctuatedNestedMeta, item: Item) -> Result<TokenStream> {
let mut context = ImplContext::default();
let mut tokens = match item {
Item::Impl(mut imp) => {
extract_items_into_context(&mut context, imp.items.iter_mut());
let (impl_ty, payload_guess) = match imp.self_ty.as_ref() {
syn::Type::Path(syn::TypePath {
path: syn::Path { segments, .. },
..
}) if segments.len() == 1 => {
let segment = &segments[0];
let payload_ty = if segment.ident == "Py" || segment.ident == "PyRef" {
match &segment.arguments {
syn::PathArguments::AngleBracketed(
syn::AngleBracketedGenericArguments { args, .. },
) if args.len() == 1 => {
let arg = &args[0];
match arg {
syn::GenericArgument::Type(syn::Type::Path(
syn::TypePath {
path: syn::Path { segments, .. },
..
},
)) if segments.len() == 1 => segments[0].ident.clone(),
_ => {
return Err(syn::Error::new_spanned(
segment,
"Py{Ref}<T> is expected but Py{Ref}<?> is found",
));
}
}
}
_ => {
return Err(syn::Error::new_spanned(
segment,
"Py{Ref}<T> is expected but Py{Ref}? is found",
));
}
}
} else {
if !matches!(segment.arguments, syn::PathArguments::None) {
return Err(syn::Error::new_spanned(
segment,
"PyImpl can only be implemented for Py{Ref}<T> or T",
));
}
segment.ident.clone()
};
(segment.ident.clone(), payload_ty)
}
_ => {
return Err(syn::Error::new_spanned(
imp.self_ty,
"PyImpl can only be implemented for Py{Ref}<T> or T",
));
}
};
let ExtractedImplAttrs {
payload: attr_payload,
flags,
with_impl,
with_method_defs,
with_slots,
itemsize,
} = extract_impl_attrs(attr, &impl_ty)?;
let payload_ty = attr_payload.unwrap_or(payload_guess);
let method_def = &context.method_items;
let getset_impl = &context.getset_items;
let member_impl = &context.member_items;
let extend_impl = context.attribute_items.validate()?;
let slots_impl = context.extend_slots_items.validate()?;
let class_extensions = &context.class_extensions;
let extra_methods = [
parse_quote! {
const __OWN_METHOD_DEFS: &'static [::rustpython_vm::function::PyMethodDef] = &#method_def;
},
parse_quote! {
fn __extend_py_class(
ctx: &::rustpython_vm::Context,
class: &'static ::rustpython_vm::Py<::rustpython_vm::builtins::PyType>,
) {
#getset_impl
#member_impl
#extend_impl
#(#class_extensions)*
}
},
{
let itemsize_impl = itemsize.as_ref().map(|size| {
quote! {
slots.itemsize = #size;
}
});
parse_quote! {
fn __extend_slots(slots: &mut ::rustpython_vm::types::PyTypeSlots) {
#itemsize_impl
#slots_impl
}
}
},
];
imp.items.extend(extra_methods);
let is_main_impl = impl_ty == payload_ty;
if is_main_impl {
let method_defs = if with_method_defs.is_empty() {
quote!(#impl_ty::__OWN_METHOD_DEFS)
} else {
quote!(
rustpython_vm::function::PyMethodDef::__const_concat_arrays::<
{ #impl_ty::__OWN_METHOD_DEFS.len() #(+ #with_method_defs.len())* },
>(&[#impl_ty::__OWN_METHOD_DEFS, #(#with_method_defs,)*])
)
};
quote! {
#imp
impl ::rustpython_vm::class::PyClassImpl for #payload_ty {
const TP_FLAGS: ::rustpython_vm::types::PyTypeFlags = #flags;
fn impl_extend_class(
ctx: &::rustpython_vm::Context,
class: &'static ::rustpython_vm::Py<::rustpython_vm::builtins::PyType>,
) {
#impl_ty::__extend_py_class(ctx, class);
#with_impl
}
const METHOD_DEFS: &'static [::rustpython_vm::function::PyMethodDef] = &#method_defs;
fn extend_slots(slots: &mut ::rustpython_vm::types::PyTypeSlots) {
#with_slots
#impl_ty::__extend_slots(slots);
}
}
}
} else {
imp.into_token_stream()
}
}
Item::Trait(mut trai) => {
let mut context = ImplContext {
is_trait: true,
..Default::default()
};
let mut has_extend_slots = false;
for item in &trai.items {
let has = match item {
syn::TraitItem::Fn(item) => item.sig.ident == "extend_slots",
_ => false,
};
if has {
has_extend_slots = has;
break;
}
}
extract_items_into_context(&mut context, trai.items.iter_mut());
let ExtractedImplAttrs {
with_impl,
with_slots,
..
} = extract_impl_attrs(attr, &trai.ident)?;
let method_def = &context.method_items;
let getset_impl = &context.getset_items;
let member_impl = &context.member_items;
let extend_impl = &context.attribute_items.validate()?;
let slots_impl = &context.extend_slots_items.validate()?;
let class_extensions = &context.class_extensions;
let call_extend_slots = if has_extend_slots {
quote! {
Self::extend_slots(slots);
}
} else {
quote! {}
};
let extra_methods = [
parse_quote! {
const __OWN_METHOD_DEFS: &'static [::rustpython_vm::function::PyMethodDef] = &#method_def;
},
parse_quote! {
fn __extend_py_class(
ctx: &::rustpython_vm::Context,
class: &'static ::rustpython_vm::Py<::rustpython_vm::builtins::PyType>,
) {
#getset_impl
#member_impl
#extend_impl
#with_impl
#(#class_extensions)*
}
},
parse_quote! {
fn __extend_slots(slots: &mut ::rustpython_vm::types::PyTypeSlots) {
#with_slots
#slots_impl
#call_extend_slots
}
},
];
trai.items.extend(extra_methods);
trai.into_token_stream()
}
item => item.into_token_stream(),
};
if let Some(error) = context.errors.into_error() {
let error = Diagnostic::from(error);
tokens = quote! {
#tokens
#error
}
}
Ok(tokens)
}
/// Validates that when a base class is specified, the struct has the base type as its first field.
/// This ensures proper memory layout for subclassing (required for #[repr(transparent)] to work correctly).
fn validate_base_field(item: &Item, base_path: &syn::Path) -> Result<()> {
let Item::Struct(item_struct) = item else {
// Only validate structs - enums with base are already an error elsewhere
return Ok(());
};
// Get the base type name for error messages
let base_name = base_path
.segments
.last()
.map(|s| s.ident.to_string())
.unwrap_or_else(|| quote!(#base_path).to_string());
match &item_struct.fields {
syn::Fields::Named(fields) => {
let Some(first_field) = fields.named.first() else {
bail_span!(
item_struct,
"#[pyclass] with base = {base_name} requires the first field to be of type {base_name}, but the struct has no fields"
);
};
if !type_matches_path(&first_field.ty, base_path) {
bail_span!(
first_field,
"#[pyclass] with base = {base_name} requires the first field to be of type {base_name}"
);
}
}
syn::Fields::Unnamed(fields) => {
let Some(first_field) = fields.unnamed.first() else {
bail_span!(
item_struct,
"#[pyclass] with base = {base_name} requires the first field to be of type {base_name}, but the struct has no fields"
);
};
if !type_matches_path(&first_field.ty, base_path) {
bail_span!(
first_field,
"#[pyclass] with base = {base_name} requires the first field to be of type {base_name}"
);
}
}
syn::Fields::Unit => {
bail_span!(
item_struct,
"#[pyclass] with base = {base_name} requires the first field to be of type {base_name}, but the struct is a unit struct"
);
}
}
Ok(())
}
/// Check if a type matches a given path (handles simple cases like `Foo` or `path::to::Foo`)
fn type_matches_path(ty: &syn::Type, path: &syn::Path) -> bool {
// Compare by converting both to string representation for macro hygiene
let ty_str = quote!(#ty).to_string().replace(' ', "");
let path_str = quote!(#path).to_string().replace(' ', "");
// Check if both are the same or if the type ends with the path's last segment
if ty_str == path_str {
return true;
}
// Also match if just the last segment matches (e.g., foo::Bar matches Bar)
let syn::Type::Path(type_path) = ty else {
return false;
};
let Some(type_last) = type_path.path.segments.last() else {
return false;
};
let Some(path_last) = path.segments.last() else {
return false;
};
type_last.ident == path_last.ident
}
fn generate_class_def(
ident: &Ident,
name: &str,
module_name: Option<&str>,
base: Option<syn::Path>,
metaclass: Option<String>,
unhashable: bool,
attrs: &[Attribute],
) -> Result<TokenStream> {
let doc = attrs.doc().or_else(|| {
let module_name = module_name.unwrap_or("builtins");
DB.get(&format!("{module_name}.{name}"))
.copied()
.map(str::to_owned)
});
let doc = if let Some(doc) = doc {
quote!(Some(#doc))
} else {
quote!(None)
};
let module_class_name = if let Some(module_name) = module_name {
format!("{module_name}.{name}")
} else {
name.to_owned()
};
let module_name = match module_name {
Some(v) => quote!(Some(#v) ),
None => quote!(None),
};
let unhashable = if unhashable {
quote!(true)
} else {
quote!(false)
};
let is_pystruct = attrs.iter().any(|attr| {
attr.path().is_ident("derive")
&& if let Ok(Meta::List(l)) = attr.parse_meta() {
l.nested
.into_iter()
.any(|n| n.get_ident().is_some_and(|p| p == "PyStructSequence"))
} else {
false
}
});
// Check if the type has #[repr(transparent)] - only then we can safely
// generate PySubclass impl (requires same memory layout as base type)
let is_repr_transparent = attrs.iter().any(|attr| {
attr.path().is_ident("repr")
&& if let Ok(Meta::List(l)) = attr.parse_meta() {
l.nested
.into_iter()
.any(|n| n.get_ident().is_some_and(|p| p == "transparent"))
} else {
false
}
});
// If repr(transparent) with a base, the type has the same memory layout as base,
// so basicsize should be 0 (no additional space beyond the base type)
// Otherwise, basicsize = sizeof(payload). The header size is added in __basicsize__ getter.
let basicsize = if is_repr_transparent && base.is_some() {
quote!(0)
} else {
quote!(std::mem::size_of::<#ident>())
};
if base.is_some() && is_pystruct {
bail_span!(ident, "PyStructSequence cannot have `base` class attr",);
}
let base_class = if is_pystruct {
Some(quote! { rustpython_vm::builtins::PyTuple })
} else {
base.as_ref().map(|typ| {
quote_spanned! { ident.span() => #typ }
})
}
.map(|typ| {
quote! {
fn static_baseclass() -> &'static ::rustpython_vm::Py<::rustpython_vm::builtins::PyType> {
use rustpython_vm::class::StaticType;
#typ::static_type()
}
}
});
let meta_class = metaclass.map(|typ| {
let typ = Ident::new(&typ, ident.span());
quote! {
fn static_metaclass() -> &'static ::rustpython_vm::Py<::rustpython_vm::builtins::PyType> {
use rustpython_vm::class::StaticType;
#typ::static_type()
}
}
});
let base_or_object = if let Some(ref base) = base {
quote! { #base }
} else {
quote! { ::rustpython_vm::builtins::PyBaseObject }
};
// Generate PySubclass impl for #[repr(transparent)] types with base class
// (tuple struct assumed, so &self.0 works)
let subclass_impl = if !is_pystruct && is_repr_transparent {
base.as_ref().map(|typ| {
quote! {
impl ::rustpython_vm::class::PySubclass for #ident {
type Base = #typ;
#[inline]
fn as_base(&self) -> &Self::Base {
&self.0
}
}
}
})
} else {
None
};
let tokens = quote! {
impl ::rustpython_vm::class::PyClassDef for #ident {
const NAME: &'static str = #name;
const MODULE_NAME: Option<&'static str> = #module_name;
const TP_NAME: &'static str = #module_class_name;
const DOC: Option<&'static str> = #doc;
const BASICSIZE: usize = #basicsize;
const UNHASHABLE: bool = #unhashable;
type Base = #base_or_object;
}
impl ::rustpython_vm::class::StaticType for #ident {
fn static_cell() -> &'static ::rustpython_vm::common::static_cell::StaticCell<::rustpython_vm::builtins::PyTypeRef> {
::rustpython_vm::common::static_cell! {
static CELL: ::rustpython_vm::builtins::PyTypeRef;
}
&CELL
}
#meta_class
#base_class
}
#subclass_impl
};
Ok(tokens)
}
pub(crate) fn impl_pyclass(attr: PunctuatedNestedMeta, item: Item) -> Result<TokenStream> {
if matches!(item, syn::Item::Use(_)) {
return Ok(quote!(#item));
}
let (ident, attrs) = pyclass_ident_and_attrs(&item)?;
let fake_ident = Ident::new("pyclass", item.span());
let class_meta = ClassItemMeta::from_nested(ident.clone(), fake_ident, attr.into_iter())?;
let class_name = class_meta.class_name()?;
let module_name = class_meta.module()?;
let base = class_meta.base()?;
let metaclass = class_meta.metaclass()?;
let unhashable = class_meta.unhashable()?;
// Validate that if base is specified, the first field must be of the base type
if let Some(ref base_path) = base {
validate_base_field(&item, base_path)?;
}
let class_def = generate_class_def(
ident,
&class_name,
module_name.as_deref(),
base.clone(),
metaclass,
unhashable,
attrs,
)?;
const ALLOWED_TRAVERSE_OPTS: &[&str] = &["manual"];
// try to know if it have a `#[pyclass(trace)]` exist on this struct
// TODO(discord9): rethink on auto detect `#[Derive(PyTrace)]`
// 1. no `traverse` at all: generate a dummy try_traverse
// 2. `traverse = "manual"`: generate a try_traverse, but not #[derive(Traverse)]
// 3. `traverse`: generate a try_traverse, and #[derive(Traverse)]
let (maybe_trace_code, derive_trace) = {
if class_meta.inner()._has_key("traverse")? {
let maybe_trace_code = quote! {
impl ::rustpython_vm::object::MaybeTraverse for #ident {
const IS_TRACE: bool = true;
fn try_traverse(&self, tracer_fn: &mut ::rustpython_vm::object::TraverseFn) {
::rustpython_vm::object::Traverse::traverse(self, tracer_fn);
}
}
};
// if the key `traverse` exist but not as key-value, _optional_str return Err(...)
// so we need to check if it is Ok(Some(...))
let value = class_meta.inner()._optional_str("traverse");
let derive_trace = if let Ok(Some(s)) = value {
if !ALLOWED_TRAVERSE_OPTS.contains(&s.as_str()) {
bail_span!(
item,
"traverse attribute only accept {ALLOWED_TRAVERSE_OPTS:?} as value or no value at all",
);
}
assert_eq!(s, "manual");
quote! {}
} else {
quote! {#[derive(Traverse)]}
};
(maybe_trace_code, derive_trace)
} else {
(
// a dummy impl, which do nothing
// #attrs
quote! {
impl ::rustpython_vm::object::MaybeTraverse for #ident {
fn try_traverse(&self, tracer_fn: &mut ::rustpython_vm::object::TraverseFn) {
// do nothing
}
}
},
quote! {},
)
}
};
// Generate PyPayload impl based on whether base exists
#[allow(clippy::collapsible_else_if)]
let impl_payload = if let Some(base_type) = &base {
let class_fn = if let Some(ctx_type_name) = class_meta.ctx_name()? {
let ctx_type_ident = Ident::new(&ctx_type_name, ident.span());
quote! { ctx.types.#ctx_type_ident }
} else {
quote! { <Self as ::rustpython_vm::class::StaticType>::static_type() }
};
quote! {
// static_assertions::const_assert!(std::mem::size_of::<#base_type>() <= std::mem::size_of::<#ident>());
impl ::rustpython_vm::PyPayload for #ident {
#[inline]
fn payload_type_id() -> ::std::any::TypeId {
<#base_type as ::rustpython_vm::PyPayload>::payload_type_id()
}
#[inline]
fn validate_downcastable_from(obj: &::rustpython_vm::PyObject) -> bool {
<Self as ::rustpython_vm::class::PyClassDef>::BASICSIZE <= obj.class().slots.basicsize && obj.class().fast_issubclass(<Self as ::rustpython_vm::class::StaticType>::static_type())
}
fn class(ctx: &::rustpython_vm::vm::Context) -> &'static ::rustpython_vm::Py<::rustpython_vm::builtins::PyType> {
#class_fn
}
}
}
} else {
if let Some(ctx_type_name) = class_meta.ctx_name()? {
let ctx_type_ident = Ident::new(&ctx_type_name, ident.span());
quote! {
impl ::rustpython_vm::PyPayload for #ident {
fn class(ctx: &::rustpython_vm::vm::Context) -> &'static ::rustpython_vm::Py<::rustpython_vm::builtins::PyType> {
ctx.types.#ctx_type_ident
}
}
}
} else {
quote! {}
}
};
let empty_impl = if let Some(attrs) = class_meta.impl_attrs()? {
let attrs: Meta = parse_quote! (#attrs);
quote! {
#[pyclass(#attrs)]
impl #ident {}
}
} else {
quote! {}
};
let ret = quote! {
#derive_trace
#item
#maybe_trace_code
#class_def
#impl_payload
#empty_impl
};
Ok(ret)
}
/// Special macro to create exception types.
///
/// Why do we need it and why can't we just use `pyclass` macro instead?
/// We generate exception types with a `macro_rules`,
/// similar to how CPython does it.
/// But, inside `macro_rules` we don't have an opportunity
/// to add non-literal attributes to `pyclass`.
/// That's why we have to use this proxy.
pub(crate) fn impl_pyexception(attr: PunctuatedNestedMeta, item: Item) -> Result<TokenStream> {
let (ident, _attrs) = pyexception_ident_and_attrs(&item)?;
let fake_ident = Ident::new("pyclass", item.span());
let class_meta = ExceptionItemMeta::from_nested(ident.clone(), fake_ident, attr.into_iter())?;
let class_name = class_meta.class_name()?;
let base_class_name = class_meta.base()?;
let impl_pyclass = if class_meta.has_impl()? {
quote! {
#[pyexception]
impl #ident {}
}
} else {
quote! {}
};
let ret = quote! {
#[pyclass(module = false, name = #class_name, base = #base_class_name)]
#item
#impl_pyclass
};
Ok(ret)
}
pub(crate) fn impl_pyexception_impl(attr: PunctuatedNestedMeta, item: Item) -> Result<TokenStream> {
let Item::Impl(imp) = item else {
return Ok(item.into_token_stream());
};
// Check if with(Constructor) is specified. If Constructor trait is used, don't generate slot_new
let mut extra_attrs = Vec::new();
let mut with_items = vec![];
for nested in &attr {
if let NestedMeta::Meta(Meta::List(MetaList { path, nested, .. })) = nested {
// If we already found the constructor trait, no need to keep looking for it
if path.is_ident("with") {
for meta in nested {
with_items.push(meta.get_ident().expect("with() has non-ident item").clone());
}
continue;
}
extra_attrs.push(NestedMeta::Meta(Meta::List(MetaList {
path: path.clone(),
paren_token: Default::default(),
nested: nested.clone(),
})));
}
}
let with_contains = |with_items: &[Ident], s: &str| {
// Check if Constructor is in the list
with_items.iter().any(|ident| ident == s)
};
let syn::ItemImpl {
generics,
self_ty,
items,
..
} = &imp;
let slot_new = if with_contains(&with_items, "Constructor") {
quote!()
} else {
with_items.push(Ident::new("Constructor", Span::call_site()));
quote! {
impl ::rustpython_vm::types::Constructor for #self_ty {
type Args = ::rustpython_vm::function::FuncArgs;
fn slot_new(
cls: ::rustpython_vm::builtins::PyTypeRef,
args: ::rustpython_vm::function::FuncArgs,
vm: &::rustpython_vm::VirtualMachine,
) -> ::rustpython_vm::PyResult {
<Self as ::rustpython_vm::class::PyClassDef>::Base::slot_new(cls, args, vm)
}
fn py_new(
_cls: &::rustpython_vm::Py<::rustpython_vm::builtins::PyType>,
_args: Self::Args,
_vm: &::rustpython_vm::VirtualMachine
) -> ::rustpython_vm::PyResult<Self> {
unreachable!("slot_new is defined")
}
}
}
};
// We need this method, because of how `CPython` copies `__init__`
// from `BaseException` in `SimpleExtendsException` macro.
// See: `(initproc)BaseException_init`
// spell-checker:ignore initproc
let slot_init = if with_contains(&with_items, "Initializer") {
quote!()
} else {
with_items.push(Ident::new("Initializer", Span::call_site()));
quote! {
impl ::rustpython_vm::types::Initializer for #self_ty {
type Args = ::rustpython_vm::function::FuncArgs;
fn slot_init(
zelf: ::rustpython_vm::PyObjectRef,
args: ::rustpython_vm::function::FuncArgs,
vm: &::rustpython_vm::VirtualMachine,
) -> ::rustpython_vm::PyResult<()> {
<Self as ::rustpython_vm::class::PyClassDef>::Base::slot_init(zelf, args, vm)
}
fn init(
_zelf: ::rustpython_vm::PyRef<Self>,
_args: Self::Args,
_vm: &::rustpython_vm::VirtualMachine
) -> ::rustpython_vm::PyResult<()> {
unreachable!("slot_init is defined")
}
}
}
};
let extra_attrs_tokens = if extra_attrs.is_empty() {
quote!()
} else {
quote!(, #(#extra_attrs),*)
};
Ok(quote! {
#[pyclass(flags(BASETYPE, HAS_DICT), with(#(#with_items),*) #extra_attrs_tokens)]
impl #generics #self_ty {
#(#items)*
}
#slot_new
#slot_init
})
}
macro_rules! define_content_item {
(
$(#[$meta:meta])*
$vis:vis struct $name:ident
) => {
$(#[$meta])*
$vis struct $name {
inner: ContentItemInner<AttrName>,
}
impl ContentItem for $name {
type AttrName = AttrName;
fn inner(&self) -> &ContentItemInner<AttrName> {
&self.inner
}
}
};
}
define_content_item!(
/// #[pymethod] and #[pyclassmethod]
struct MethodItem
);
define_content_item!(
/// #[pygetset]
struct GetSetItem
);
define_content_item!(
/// #[pyslot]
struct SlotItem
);
define_content_item!(
/// #[pyattr]
struct AttributeItem
);
define_content_item!(
/// #[extend_class]
struct ExtendClassItem
);
define_content_item!(
/// #[pymember]
struct MemberItem
);
struct ImplItemArgs<'a, Item: ItemLike> {
item: &'a Item,
attrs: &'a mut Vec<Attribute>,
context: &'a mut ImplContext,
cfgs: &'a [Attribute],
}
trait ImplItem<Item>: ContentItem
where
Item: ItemLike + ToTokens + GetIdent,
{
fn gen_impl_item(&self, args: ImplItemArgs<'_, Item>) -> Result<()>;
}
impl<Item> ImplItem<Item> for MethodItem
where
Item: ItemLike + ToTokens + GetIdent,
{
fn gen_impl_item(&self, args: ImplItemArgs<'_, Item>) -> Result<()> {
let func = args
.item
.function_or_method()
.map_err(|_| self.new_syn_error(args.item.span(), "can only be on a method"))?;
let ident = &func.sig().ident;
let item_attr = args.attrs.remove(self.index());
let item_meta = MethodItemMeta::from_attr(ident.clone(), &item_attr)?;
let py_name = item_meta.method_name()?;
// Disallow slot methods - they should be defined via trait implementations
// These are exposed as wrapper_descriptor via add_operators from SLOT_DEFS
if !args.context.is_trait {
const FORBIDDEN_SLOT_METHODS: &[(&str, &str)] = &[
// Constructor/Initializer traits
("__new__", "Constructor"),
("__init__", "Initializer"),
// Representable trait
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | true |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/derive-impl/src/pypayload.rs | crates/derive-impl/src/pypayload.rs | use proc_macro2::TokenStream;
use quote::quote;
use syn::{DeriveInput, Result};
pub(crate) fn impl_pypayload(input: DeriveInput) -> Result<TokenStream> {
let ty = &input.ident;
let ret = quote! {
impl ::rustpython_vm::PyPayload for #ty {
#[inline]
fn class(_ctx: &::rustpython_vm::vm::Context) -> &'static rustpython_vm::Py<::rustpython_vm::builtins::PyType> {
<Self as ::rustpython_vm::class::StaticType>::static_type()
}
}
};
Ok(ret)
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/compiler-source/src/lib.rs | crates/compiler-source/src/lib.rs | pub use ruff_source_file::{LineIndex, OneIndexed as LineNumber, PositionEncoding, SourceLocation};
use ruff_text_size::TextRange;
pub use ruff_text_size::TextSize;
#[derive(Clone)]
pub struct SourceCode<'src> {
pub path: &'src str,
pub text: &'src str,
pub index: LineIndex,
}
impl<'src> SourceCode<'src> {
pub fn new(path: &'src str, text: &'src str) -> Self {
let index = LineIndex::from_source_text(text);
Self { path, text, index }
}
pub fn line_index(&self, offset: TextSize) -> LineNumber {
self.index.line_index(offset)
}
pub fn source_location(&self, offset: TextSize) -> SourceLocation {
self.index
.source_location(offset, self.text, PositionEncoding::Utf8)
}
pub fn get_range(&'src self, range: TextRange) -> &'src str {
&self.text[range.start().to_usize()..range.end().to_usize()]
}
}
pub struct SourceCodeOwned {
pub path: String,
pub text: String,
pub index: LineIndex,
}
impl SourceCodeOwned {
pub fn new(path: String, text: String) -> Self {
let index = LineIndex::from_source_text(&text);
Self { path, text, index }
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/compiler-core/src/frozen.rs | crates/compiler-core/src/frozen.rs | use crate::bytecode::*;
use crate::marshal::{self, Read, ReadBorrowed, Write};
/// A frozen module. Holds a frozen code object and whether it is part of a package
#[derive(Copy, Clone)]
pub struct FrozenModule<B = &'static [u8]> {
pub code: FrozenCodeObject<B>,
pub package: bool,
}
#[derive(Copy, Clone)]
pub struct FrozenCodeObject<B> {
pub bytes: B,
}
impl<B: AsRef<[u8]>> FrozenCodeObject<B> {
/// Decode a frozen code object
#[inline]
pub fn decode<Bag: AsBag>(&self, bag: Bag) -> CodeObject<<Bag::Bag as ConstantBag>::Constant> {
Self::_decode(self.bytes.as_ref(), bag.as_bag())
}
fn _decode<Bag: ConstantBag>(data: &[u8], bag: Bag) -> CodeObject<Bag::Constant> {
let decompressed = lz4_flex::decompress_size_prepended(data)
.expect("deserialize frozen CodeObject failed");
marshal::deserialize_code(&mut &decompressed[..], bag)
.expect("deserializing frozen CodeObject failed")
}
}
impl FrozenCodeObject<Vec<u8>> {
pub fn encode<C: Constant>(code: &CodeObject<C>) -> Self {
let mut data = Vec::new();
marshal::serialize_code(&mut data, code);
let bytes = lz4_flex::compress_prepend_size(&data);
Self { bytes }
}
}
#[repr(transparent)]
pub struct FrozenLib<B: ?Sized = [u8]> {
pub bytes: B,
}
impl<B: AsRef<[u8]> + ?Sized> FrozenLib<B> {
pub const fn from_ref(b: &B) -> &Self {
unsafe { &*(b as *const B as *const Self) }
}
/// Decode a library to a iterable of frozen modules
pub fn decode(&self) -> FrozenModulesIter<'_> {
let mut data = self.bytes.as_ref();
let remaining = data.read_u32().unwrap();
FrozenModulesIter { remaining, data }
}
}
impl<'a, B: AsRef<[u8]> + ?Sized> IntoIterator for &'a FrozenLib<B> {
type Item = (&'a str, FrozenModule<&'a [u8]>);
type IntoIter = FrozenModulesIter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.decode()
}
}
pub struct FrozenModulesIter<'a> {
remaining: u32,
data: &'a [u8],
}
impl<'a> Iterator for FrozenModulesIter<'a> {
type Item = (&'a str, FrozenModule<&'a [u8]>);
fn next(&mut self) -> Option<Self::Item> {
if self.remaining > 0 {
let entry = read_entry(&mut self.data).unwrap();
self.remaining -= 1;
Some(entry)
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.remaining as usize, Some(self.remaining as usize))
}
}
impl ExactSizeIterator for FrozenModulesIter<'_> {}
fn read_entry<'a>(
rdr: &mut &'a [u8],
) -> Result<(&'a str, FrozenModule<&'a [u8]>), marshal::MarshalError> {
let len = rdr.read_u32()?;
let name = rdr.read_str_borrow(len)?;
let len = rdr.read_u32()?;
let code_slice = rdr.read_slice_borrow(len)?;
let code = FrozenCodeObject { bytes: code_slice };
let package = rdr.read_u8()? != 0;
Ok((name, FrozenModule { code, package }))
}
impl FrozenLib<Vec<u8>> {
/// Encode the given iterator of frozen modules into a compressed vector of bytes
pub fn encode<'a, I, B: AsRef<[u8]>>(lib: I) -> Self
where
I: IntoIterator<Item = (&'a str, FrozenModule<B>), IntoIter: ExactSizeIterator + Clone>,
{
let iter = lib.into_iter();
let mut bytes = Vec::new();
write_lib(&mut bytes, iter);
Self { bytes }
}
}
fn write_lib<'a, B: AsRef<[u8]>>(
buf: &mut Vec<u8>,
lib: impl ExactSizeIterator<Item = (&'a str, FrozenModule<B>)>,
) {
marshal::write_len(buf, lib.len());
for (name, module) in lib {
write_entry(buf, name, module);
}
}
fn write_entry(buf: &mut Vec<u8>, name: &str, module: FrozenModule<impl AsRef<[u8]>>) {
marshal::write_vec(buf, name.as_bytes());
marshal::write_vec(buf, module.code.bytes.as_ref());
buf.write_u8(module.package as u8);
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/compiler-core/src/lib.rs | crates/compiler-core/src/lib.rs | #![doc(html_logo_url = "https://raw.githubusercontent.com/RustPython/RustPython/main/logo.png")]
#![doc(html_root_url = "https://docs.rs/rustpython-compiler-core/")]
extern crate alloc;
pub mod bytecode;
pub mod frozen;
pub mod marshal;
mod mode;
pub mod varint;
pub use mode::Mode;
pub use ruff_source_file::{
LineIndex, OneIndexed, PositionEncoding, SourceFile, SourceFileBuilder, SourceLocation,
};
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/compiler-core/src/marshal.rs | crates/compiler-core/src/marshal.rs | use crate::{OneIndexed, SourceLocation, bytecode::*};
use core::convert::Infallible;
use malachite_bigint::{BigInt, Sign};
use num_complex::Complex64;
use rustpython_wtf8::Wtf8;
pub const FORMAT_VERSION: u32 = 4;
#[derive(Debug)]
pub enum MarshalError {
/// Unexpected End Of File
Eof,
/// Invalid Bytecode
InvalidBytecode,
/// Invalid utf8 in string
InvalidUtf8,
/// Invalid source location
InvalidLocation,
/// Bad type marker
BadType,
}
impl core::fmt::Display for MarshalError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Eof => f.write_str("unexpected end of data"),
Self::InvalidBytecode => f.write_str("invalid bytecode"),
Self::InvalidUtf8 => f.write_str("invalid utf8"),
Self::InvalidLocation => f.write_str("invalid source location"),
Self::BadType => f.write_str("bad type marker"),
}
}
}
impl From<core::str::Utf8Error> for MarshalError {
fn from(_: core::str::Utf8Error) -> Self {
Self::InvalidUtf8
}
}
impl core::error::Error for MarshalError {}
type Result<T, E = MarshalError> = core::result::Result<T, E>;
#[repr(u8)]
enum Type {
// Null = b'0',
None = b'N',
False = b'F',
True = b'T',
StopIter = b'S',
Ellipsis = b'.',
Int = b'i',
Float = b'g',
Complex = b'y',
// Long = b'l', // i32
Bytes = b's', // = TYPE_STRING
// Interned = b't',
// Ref = b'r',
Tuple = b'(',
List = b'[',
Dict = b'{',
Code = b'c',
Unicode = b'u',
// Unknown = b'?',
Set = b'<',
FrozenSet = b'>',
Ascii = b'a',
// AsciiInterned = b'A',
// SmallTuple = b')',
// ShortAscii = b'z',
// ShortAsciiInterned = b'Z',
}
// const FLAG_REF: u8 = b'\x80';
impl TryFrom<u8> for Type {
type Error = MarshalError;
fn try_from(value: u8) -> Result<Self> {
use Type::*;
Ok(match value {
// b'0' => Null,
b'N' => None,
b'F' => False,
b'T' => True,
b'S' => StopIter,
b'.' => Ellipsis,
b'i' => Int,
b'g' => Float,
b'y' => Complex,
// b'l' => Long,
b's' => Bytes,
// b't' => Interned,
// b'r' => Ref,
b'(' => Tuple,
b'[' => List,
b'{' => Dict,
b'c' => Code,
b'u' => Unicode,
// b'?' => Unknown,
b'<' => Set,
b'>' => FrozenSet,
b'a' => Ascii,
// b'A' => AsciiInterned,
// b')' => SmallTuple,
// b'z' => ShortAscii,
// b'Z' => ShortAsciiInterned,
_ => return Err(MarshalError::BadType),
})
}
}
pub trait Read {
fn read_slice(&mut self, n: u32) -> Result<&[u8]>;
fn read_array<const N: usize>(&mut self) -> Result<&[u8; N]> {
self.read_slice(N as u32).map(|s| s.try_into().unwrap())
}
fn read_str(&mut self, len: u32) -> Result<&str> {
Ok(core::str::from_utf8(self.read_slice(len)?)?)
}
fn read_wtf8(&mut self, len: u32) -> Result<&Wtf8> {
Wtf8::from_bytes(self.read_slice(len)?).ok_or(MarshalError::InvalidUtf8)
}
fn read_u8(&mut self) -> Result<u8> {
Ok(u8::from_le_bytes(*self.read_array()?))
}
fn read_u16(&mut self) -> Result<u16> {
Ok(u16::from_le_bytes(*self.read_array()?))
}
fn read_u32(&mut self) -> Result<u32> {
Ok(u32::from_le_bytes(*self.read_array()?))
}
fn read_u64(&mut self) -> Result<u64> {
Ok(u64::from_le_bytes(*self.read_array()?))
}
}
pub(crate) trait ReadBorrowed<'a>: Read {
fn read_slice_borrow(&mut self, n: u32) -> Result<&'a [u8]>;
fn read_str_borrow(&mut self, len: u32) -> Result<&'a str> {
Ok(core::str::from_utf8(self.read_slice_borrow(len)?)?)
}
}
impl Read for &[u8] {
fn read_slice(&mut self, n: u32) -> Result<&[u8]> {
self.read_slice_borrow(n)
}
}
impl<'a> ReadBorrowed<'a> for &'a [u8] {
fn read_slice_borrow(&mut self, n: u32) -> Result<&'a [u8]> {
let data = self.get(..n as usize).ok_or(MarshalError::Eof)?;
*self = &self[n as usize..];
Ok(data)
}
}
pub struct Cursor<B> {
pub data: B,
pub position: usize,
}
impl<B: AsRef<[u8]>> Read for Cursor<B> {
fn read_slice(&mut self, n: u32) -> Result<&[u8]> {
let data = &self.data.as_ref()[self.position..];
let slice = data.get(..n as usize).ok_or(MarshalError::Eof)?;
self.position += n as usize;
Ok(slice)
}
}
pub fn deserialize_code<R: Read, Bag: ConstantBag>(
rdr: &mut R,
bag: Bag,
) -> Result<CodeObject<Bag::Constant>> {
let len = rdr.read_u32()?;
let raw_instructions = rdr.read_slice(len * 2)?;
let instructions = CodeUnits::try_from(raw_instructions)?;
let len = rdr.read_u32()?;
let locations = (0..len)
.map(|_| {
let start = SourceLocation {
line: OneIndexed::new(rdr.read_u32()? as _).ok_or(MarshalError::InvalidLocation)?,
character_offset: OneIndexed::from_zero_indexed(rdr.read_u32()? as _),
};
let end = SourceLocation {
line: OneIndexed::new(rdr.read_u32()? as _).ok_or(MarshalError::InvalidLocation)?,
character_offset: OneIndexed::from_zero_indexed(rdr.read_u32()? as _),
};
Ok((start, end))
})
.collect::<Result<Box<[(SourceLocation, SourceLocation)]>>>()?;
let flags = CodeFlags::from_bits_truncate(rdr.read_u16()?);
let posonlyarg_count = rdr.read_u32()?;
let arg_count = rdr.read_u32()?;
let kwonlyarg_count = rdr.read_u32()?;
let len = rdr.read_u32()?;
let source_path = bag.make_name(rdr.read_str(len)?);
let first_line_number = OneIndexed::new(rdr.read_u32()? as _);
let max_stackdepth = rdr.read_u32()?;
let len = rdr.read_u32()?;
let obj_name = bag.make_name(rdr.read_str(len)?);
let len = rdr.read_u32()?;
let qualname = bag.make_name(rdr.read_str(len)?);
let len = rdr.read_u32()?;
let cell2arg = (len != 0)
.then(|| {
(0..len)
.map(|_| Ok(rdr.read_u32()? as i32))
.collect::<Result<Box<[i32]>>>()
})
.transpose()?;
let len = rdr.read_u32()?;
let constants = (0..len)
.map(|_| deserialize_value(rdr, bag))
.collect::<Result<Box<[_]>>>()?;
let mut read_names = || {
let len = rdr.read_u32()?;
(0..len)
.map(|_| {
let len = rdr.read_u32()?;
Ok(bag.make_name(rdr.read_str(len)?))
})
.collect::<Result<Box<[_]>>>()
};
let names = read_names()?;
let varnames = read_names()?;
let cellvars = read_names()?;
let freevars = read_names()?;
// Read linetable and exceptiontable
let linetable_len = rdr.read_u32()?;
let linetable = rdr.read_slice(linetable_len)?.to_vec().into_boxed_slice();
let exceptiontable_len = rdr.read_u32()?;
let exceptiontable = rdr
.read_slice(exceptiontable_len)?
.to_vec()
.into_boxed_slice();
Ok(CodeObject {
instructions,
locations,
flags,
posonlyarg_count,
arg_count,
kwonlyarg_count,
source_path,
first_line_number,
max_stackdepth,
obj_name,
qualname,
cell2arg,
constants,
names,
varnames,
cellvars,
freevars,
linetable,
exceptiontable,
})
}
pub trait MarshalBag: Copy {
type Value;
type ConstantBag: ConstantBag;
fn make_bool(&self, value: bool) -> Self::Value;
fn make_none(&self) -> Self::Value;
fn make_ellipsis(&self) -> Self::Value;
fn make_float(&self, value: f64) -> Self::Value;
fn make_complex(&self, value: Complex64) -> Self::Value;
fn make_str(&self, value: &Wtf8) -> Self::Value;
fn make_bytes(&self, value: &[u8]) -> Self::Value;
fn make_int(&self, value: BigInt) -> Self::Value;
fn make_tuple(&self, elements: impl Iterator<Item = Self::Value>) -> Self::Value;
fn make_code(
&self,
code: CodeObject<<Self::ConstantBag as ConstantBag>::Constant>,
) -> Self::Value;
fn make_stop_iter(&self) -> Result<Self::Value>;
fn make_list(&self, it: impl Iterator<Item = Self::Value>) -> Result<Self::Value>;
fn make_set(&self, it: impl Iterator<Item = Self::Value>) -> Result<Self::Value>;
fn make_frozenset(&self, it: impl Iterator<Item = Self::Value>) -> Result<Self::Value>;
fn make_dict(
&self,
it: impl Iterator<Item = (Self::Value, Self::Value)>,
) -> Result<Self::Value>;
fn constant_bag(self) -> Self::ConstantBag;
}
impl<Bag: ConstantBag> MarshalBag for Bag {
type Value = Bag::Constant;
type ConstantBag = Self;
fn make_bool(&self, value: bool) -> Self::Value {
self.make_constant::<Bag::Constant>(BorrowedConstant::Boolean { value })
}
fn make_none(&self) -> Self::Value {
self.make_constant::<Bag::Constant>(BorrowedConstant::None)
}
fn make_ellipsis(&self) -> Self::Value {
self.make_constant::<Bag::Constant>(BorrowedConstant::Ellipsis)
}
fn make_float(&self, value: f64) -> Self::Value {
self.make_constant::<Bag::Constant>(BorrowedConstant::Float { value })
}
fn make_complex(&self, value: Complex64) -> Self::Value {
self.make_constant::<Bag::Constant>(BorrowedConstant::Complex { value })
}
fn make_str(&self, value: &Wtf8) -> Self::Value {
self.make_constant::<Bag::Constant>(BorrowedConstant::Str { value })
}
fn make_bytes(&self, value: &[u8]) -> Self::Value {
self.make_constant::<Bag::Constant>(BorrowedConstant::Bytes { value })
}
fn make_int(&self, value: BigInt) -> Self::Value {
self.make_int(value)
}
fn make_tuple(&self, elements: impl Iterator<Item = Self::Value>) -> Self::Value {
self.make_tuple(elements)
}
fn make_code(
&self,
code: CodeObject<<Self::ConstantBag as ConstantBag>::Constant>,
) -> Self::Value {
self.make_code(code)
}
fn make_stop_iter(&self) -> Result<Self::Value> {
Err(MarshalError::BadType)
}
fn make_list(&self, _: impl Iterator<Item = Self::Value>) -> Result<Self::Value> {
Err(MarshalError::BadType)
}
fn make_set(&self, _: impl Iterator<Item = Self::Value>) -> Result<Self::Value> {
Err(MarshalError::BadType)
}
fn make_frozenset(&self, _: impl Iterator<Item = Self::Value>) -> Result<Self::Value> {
Err(MarshalError::BadType)
}
fn make_dict(
&self,
_: impl Iterator<Item = (Self::Value, Self::Value)>,
) -> Result<Self::Value> {
Err(MarshalError::BadType)
}
fn constant_bag(self) -> Self::ConstantBag {
self
}
}
pub fn deserialize_value<R: Read, Bag: MarshalBag>(rdr: &mut R, bag: Bag) -> Result<Bag::Value> {
let typ = Type::try_from(rdr.read_u8()?)?;
let value = match typ {
Type::True => bag.make_bool(true),
Type::False => bag.make_bool(false),
Type::None => bag.make_none(),
Type::StopIter => bag.make_stop_iter()?,
Type::Ellipsis => bag.make_ellipsis(),
Type::Int => {
let len = rdr.read_u32()? as i32;
let sign = if len < 0 { Sign::Minus } else { Sign::Plus };
let bytes = rdr.read_slice(len.unsigned_abs())?;
let int = BigInt::from_bytes_le(sign, bytes);
bag.make_int(int)
}
Type::Float => {
let value = f64::from_bits(rdr.read_u64()?);
bag.make_float(value)
}
Type::Complex => {
let re = f64::from_bits(rdr.read_u64()?);
let im = f64::from_bits(rdr.read_u64()?);
let value = Complex64 { re, im };
bag.make_complex(value)
}
Type::Ascii | Type::Unicode => {
let len = rdr.read_u32()?;
let value = rdr.read_wtf8(len)?;
bag.make_str(value)
}
Type::Tuple => {
let len = rdr.read_u32()?;
let it = (0..len).map(|_| deserialize_value(rdr, bag));
itertools::process_results(it, |it| bag.make_tuple(it))?
}
Type::List => {
let len = rdr.read_u32()?;
let it = (0..len).map(|_| deserialize_value(rdr, bag));
itertools::process_results(it, |it| bag.make_list(it))??
}
Type::Set => {
let len = rdr.read_u32()?;
let it = (0..len).map(|_| deserialize_value(rdr, bag));
itertools::process_results(it, |it| bag.make_set(it))??
}
Type::FrozenSet => {
let len = rdr.read_u32()?;
let it = (0..len).map(|_| deserialize_value(rdr, bag));
itertools::process_results(it, |it| bag.make_frozenset(it))??
}
Type::Dict => {
let len = rdr.read_u32()?;
let it = (0..len).map(|_| {
let k = deserialize_value(rdr, bag)?;
let v = deserialize_value(rdr, bag)?;
Ok::<_, MarshalError>((k, v))
});
itertools::process_results(it, |it| bag.make_dict(it))??
}
Type::Bytes => {
// Following CPython, after marshaling, byte arrays are converted into bytes.
let len = rdr.read_u32()?;
let value = rdr.read_slice(len)?;
bag.make_bytes(value)
}
Type::Code => bag.make_code(deserialize_code(rdr, bag.constant_bag())?),
};
Ok(value)
}
pub trait Dumpable: Sized {
type Error;
type Constant: Constant;
fn with_dump<R>(&self, f: impl FnOnce(DumpableValue<'_, Self>) -> R) -> Result<R, Self::Error>;
}
pub enum DumpableValue<'a, D: Dumpable> {
Integer(&'a BigInt),
Float(f64),
Complex(Complex64),
Boolean(bool),
Str(&'a Wtf8),
Bytes(&'a [u8]),
Code(&'a CodeObject<D::Constant>),
Tuple(&'a [D]),
None,
Ellipsis,
StopIter,
List(&'a [D]),
Set(&'a [D]),
Frozenset(&'a [D]),
Dict(&'a [(D, D)]),
}
impl<'a, C: Constant> From<BorrowedConstant<'a, C>> for DumpableValue<'a, C> {
fn from(c: BorrowedConstant<'a, C>) -> Self {
match c {
BorrowedConstant::Integer { value } => Self::Integer(value),
BorrowedConstant::Float { value } => Self::Float(value),
BorrowedConstant::Complex { value } => Self::Complex(value),
BorrowedConstant::Boolean { value } => Self::Boolean(value),
BorrowedConstant::Str { value } => Self::Str(value),
BorrowedConstant::Bytes { value } => Self::Bytes(value),
BorrowedConstant::Code { code } => Self::Code(code),
BorrowedConstant::Tuple { elements } => Self::Tuple(elements),
BorrowedConstant::None => Self::None,
BorrowedConstant::Ellipsis => Self::Ellipsis,
}
}
}
impl<C: Constant> Dumpable for C {
type Error = Infallible;
type Constant = Self;
#[inline(always)]
fn with_dump<R>(&self, f: impl FnOnce(DumpableValue<'_, Self>) -> R) -> Result<R, Self::Error> {
Ok(f(self.borrow_constant().into()))
}
}
pub trait Write {
fn write_slice(&mut self, slice: &[u8]);
fn write_u8(&mut self, v: u8) {
self.write_slice(&v.to_le_bytes())
}
fn write_u16(&mut self, v: u16) {
self.write_slice(&v.to_le_bytes())
}
fn write_u32(&mut self, v: u32) {
self.write_slice(&v.to_le_bytes())
}
fn write_u64(&mut self, v: u64) {
self.write_slice(&v.to_le_bytes())
}
}
impl Write for Vec<u8> {
fn write_slice(&mut self, slice: &[u8]) {
self.extend_from_slice(slice)
}
}
pub(crate) fn write_len<W: Write>(buf: &mut W, len: usize) {
let Ok(len) = len.try_into() else {
panic!("too long to serialize")
};
buf.write_u32(len);
}
pub(crate) fn write_vec<W: Write>(buf: &mut W, slice: &[u8]) {
write_len(buf, slice.len());
buf.write_slice(slice);
}
pub fn serialize_value<W: Write, D: Dumpable>(
buf: &mut W,
constant: DumpableValue<'_, D>,
) -> Result<(), D::Error> {
match constant {
DumpableValue::Integer(int) => {
buf.write_u8(Type::Int as u8);
let (sign, bytes) = int.to_bytes_le();
let len: i32 = bytes.len().try_into().expect("too long to serialize");
let len = if sign == Sign::Minus { -len } else { len };
buf.write_u32(len as u32);
buf.write_slice(&bytes);
}
DumpableValue::Float(f) => {
buf.write_u8(Type::Float as u8);
buf.write_u64(f.to_bits());
}
DumpableValue::Complex(c) => {
buf.write_u8(Type::Complex as u8);
buf.write_u64(c.re.to_bits());
buf.write_u64(c.im.to_bits());
}
DumpableValue::Boolean(b) => {
buf.write_u8(if b { Type::True } else { Type::False } as u8);
}
DumpableValue::Str(s) => {
buf.write_u8(Type::Unicode as u8);
write_vec(buf, s.as_bytes());
}
DumpableValue::Bytes(b) => {
buf.write_u8(Type::Bytes as u8);
write_vec(buf, b);
}
DumpableValue::Code(c) => {
buf.write_u8(Type::Code as u8);
serialize_code(buf, c);
}
DumpableValue::Tuple(tup) => {
buf.write_u8(Type::Tuple as u8);
write_len(buf, tup.len());
for val in tup {
val.with_dump(|val| serialize_value(buf, val))??
}
}
DumpableValue::None => {
buf.write_u8(Type::None as u8);
}
DumpableValue::Ellipsis => {
buf.write_u8(Type::Ellipsis as u8);
}
DumpableValue::StopIter => {
buf.write_u8(Type::StopIter as u8);
}
DumpableValue::List(l) => {
buf.write_u8(Type::List as u8);
write_len(buf, l.len());
for val in l {
val.with_dump(|val| serialize_value(buf, val))??
}
}
DumpableValue::Set(set) => {
buf.write_u8(Type::Set as u8);
write_len(buf, set.len());
for val in set {
val.with_dump(|val| serialize_value(buf, val))??
}
}
DumpableValue::Frozenset(set) => {
buf.write_u8(Type::FrozenSet as u8);
write_len(buf, set.len());
for val in set {
val.with_dump(|val| serialize_value(buf, val))??
}
}
DumpableValue::Dict(d) => {
buf.write_u8(Type::Dict as u8);
write_len(buf, d.len());
for (k, v) in d {
k.with_dump(|val| serialize_value(buf, val))??;
v.with_dump(|val| serialize_value(buf, val))??;
}
}
}
Ok(())
}
pub fn serialize_code<W: Write, C: Constant>(buf: &mut W, code: &CodeObject<C>) {
write_len(buf, code.instructions.len());
// SAFETY: it's ok to transmute CodeUnit to [u8; 2]
let (_, instructions_bytes, _) = unsafe { code.instructions.align_to() };
buf.write_slice(instructions_bytes);
write_len(buf, code.locations.len());
for (start, end) in &*code.locations {
buf.write_u32(start.line.get() as _);
buf.write_u32(start.character_offset.to_zero_indexed() as _);
buf.write_u32(end.line.get() as _);
buf.write_u32(end.character_offset.to_zero_indexed() as _);
}
buf.write_u16(code.flags.bits());
buf.write_u32(code.posonlyarg_count);
buf.write_u32(code.arg_count);
buf.write_u32(code.kwonlyarg_count);
write_vec(buf, code.source_path.as_ref().as_bytes());
buf.write_u32(code.first_line_number.map_or(0, |x| x.get() as _));
buf.write_u32(code.max_stackdepth);
write_vec(buf, code.obj_name.as_ref().as_bytes());
write_vec(buf, code.qualname.as_ref().as_bytes());
let cell2arg = code.cell2arg.as_deref().unwrap_or(&[]);
write_len(buf, cell2arg.len());
for &i in cell2arg {
buf.write_u32(i as u32)
}
write_len(buf, code.constants.len());
for constant in &*code.constants {
serialize_value(buf, constant.borrow_constant().into()).unwrap_or_else(|x| match x {})
}
let mut write_names = |names: &[C::Name]| {
write_len(buf, names.len());
for name in names {
write_vec(buf, name.as_ref().as_bytes());
}
};
write_names(&code.names);
write_names(&code.varnames);
write_names(&code.cellvars);
write_names(&code.freevars);
// Serialize linetable and exceptiontable
write_vec(buf, &code.linetable);
write_vec(buf, &code.exceptiontable);
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/compiler-core/src/bytecode.rs | crates/compiler-core/src/bytecode.rs | //! Implement python as a virtual machine with bytecode. This module
//! implements bytecode structure.
use crate::{
marshal::MarshalError,
varint::{read_varint, read_varint_with_start, write_varint, write_varint_with_start},
{OneIndexed, SourceLocation},
};
use alloc::{collections::BTreeSet, fmt, vec::Vec};
use bitflags::bitflags;
use core::{hash, marker::PhantomData, mem, num::NonZeroU8, ops::Deref};
use itertools::Itertools;
use malachite_bigint::BigInt;
use num_complex::Complex64;
use rustpython_wtf8::{Wtf8, Wtf8Buf};
/// Exception table entry for zero-cost exception handling
/// Format: (start, size, target, depth<<1|lasti)
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExceptionTableEntry {
/// Start instruction offset (inclusive)
pub start: u32,
/// End instruction offset (exclusive)
pub end: u32,
/// Handler target offset
pub target: u32,
/// Stack depth at handler entry
pub depth: u16,
/// Whether to push lasti before exception
pub push_lasti: bool,
}
impl ExceptionTableEntry {
pub fn new(start: u32, end: u32, target: u32, depth: u16, push_lasti: bool) -> Self {
Self {
start,
end,
target,
depth,
push_lasti,
}
}
}
/// Encode exception table entries.
/// Uses 6-bit varint encoding with start marker (MSB) and continuation bit.
pub fn encode_exception_table(entries: &[ExceptionTableEntry]) -> alloc::boxed::Box<[u8]> {
let mut data = Vec::new();
for entry in entries {
let size = entry.end.saturating_sub(entry.start);
let depth_lasti = ((entry.depth as u32) << 1) | (entry.push_lasti as u32);
write_varint_with_start(&mut data, entry.start);
write_varint(&mut data, size);
write_varint(&mut data, entry.target);
write_varint(&mut data, depth_lasti);
}
data.into_boxed_slice()
}
/// Find exception handler for given instruction offset.
pub fn find_exception_handler(table: &[u8], offset: u32) -> Option<ExceptionTableEntry> {
let mut pos = 0;
while pos < table.len() {
let start = read_varint_with_start(table, &mut pos)?;
let size = read_varint(table, &mut pos)?;
let target = read_varint(table, &mut pos)?;
let depth_lasti = read_varint(table, &mut pos)?;
let end = start + size;
let depth = (depth_lasti >> 1) as u16;
let push_lasti = (depth_lasti & 1) != 0;
if offset >= start && offset < end {
return Some(ExceptionTableEntry {
start,
end,
target,
depth,
push_lasti,
});
}
}
None
}
/// Oparg values for [`Instruction::ConvertValue`].
///
/// ## See also
///
/// - [CPython FVC_* flags](https://github.com/python/cpython/blob/8183fa5e3f78ca6ab862de7fb8b14f3d929421e0/Include/ceval.h#L129-L132)
#[repr(u8)]
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum ConvertValueOparg {
/// No conversion.
///
/// ```python
/// f"{x}"
/// f"{x:4}"
/// ```
None = 0,
/// Converts by calling `str(<value>)`.
///
/// ```python
/// f"{x!s}"
/// f"{x!s:2}"
/// ```
Str = 1,
/// Converts by calling `repr(<value>)`.
///
/// ```python
/// f"{x!r}"
/// f"{x!r:2}"
/// ```
Repr = 2,
/// Converts by calling `ascii(<value>)`.
///
/// ```python
/// f"{x!a}"
/// f"{x!a:2}"
/// ```
Ascii = 3,
}
impl fmt::Display for ConvertValueOparg {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let out = match self {
Self::Str => "1 (str)",
Self::Repr => "2 (repr)",
Self::Ascii => "3 (ascii)",
// We should never reach this. `FVC_NONE` are being handled by `Instruction::FormatSimple`
Self::None => "",
};
write!(f, "{out}")
}
}
impl OpArgType for ConvertValueOparg {
#[inline]
fn from_op_arg(x: u32) -> Option<Self> {
Some(match x {
// Ruff `ConversionFlag::None` is `-1i8`,
// when its converted to `u8` its value is `u8::MAX`
0 | 255 => Self::None,
1 => Self::Str,
2 => Self::Repr,
3 => Self::Ascii,
_ => return None,
})
}
#[inline]
fn to_op_arg(self) -> u32 {
self as u32
}
}
/// Resume type for the RESUME instruction
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
#[repr(u32)]
pub enum ResumeType {
AtFuncStart = 0,
AfterYield = 1,
AfterYieldFrom = 2,
AfterAwait = 3,
}
/// CPython 3.11+ linetable location info codes
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum PyCodeLocationInfoKind {
// Short forms are 0 to 9
Short0 = 0,
Short1 = 1,
Short2 = 2,
Short3 = 3,
Short4 = 4,
Short5 = 5,
Short6 = 6,
Short7 = 7,
Short8 = 8,
Short9 = 9,
// One line forms are 10 to 12
OneLine0 = 10,
OneLine1 = 11,
OneLine2 = 12,
NoColumns = 13,
Long = 14,
None = 15,
}
impl PyCodeLocationInfoKind {
pub fn from_code(code: u8) -> Option<Self> {
match code {
0 => Some(Self::Short0),
1 => Some(Self::Short1),
2 => Some(Self::Short2),
3 => Some(Self::Short3),
4 => Some(Self::Short4),
5 => Some(Self::Short5),
6 => Some(Self::Short6),
7 => Some(Self::Short7),
8 => Some(Self::Short8),
9 => Some(Self::Short9),
10 => Some(Self::OneLine0),
11 => Some(Self::OneLine1),
12 => Some(Self::OneLine2),
13 => Some(Self::NoColumns),
14 => Some(Self::Long),
15 => Some(Self::None),
_ => Option::None,
}
}
pub fn is_short(&self) -> bool {
(*self as u8) <= 9
}
pub fn short_column_group(&self) -> Option<u8> {
if self.is_short() {
Some(*self as u8)
} else {
Option::None
}
}
pub fn one_line_delta(&self) -> Option<i32> {
match self {
Self::OneLine0 => Some(0),
Self::OneLine1 => Some(1),
Self::OneLine2 => Some(2),
_ => Option::None,
}
}
}
pub trait Constant: Sized {
type Name: AsRef<str>;
/// Transforms the given Constant to a BorrowedConstant
fn borrow_constant(&self) -> BorrowedConstant<'_, Self>;
}
impl Constant for ConstantData {
type Name = String;
fn borrow_constant(&self) -> BorrowedConstant<'_, Self> {
use BorrowedConstant::*;
match self {
Self::Integer { value } => Integer { value },
Self::Float { value } => Float { value: *value },
Self::Complex { value } => Complex { value: *value },
Self::Boolean { value } => Boolean { value: *value },
Self::Str { value } => Str { value },
Self::Bytes { value } => Bytes { value },
Self::Code { code } => Code { code },
Self::Tuple { elements } => Tuple { elements },
Self::None => None,
Self::Ellipsis => Ellipsis,
}
}
}
/// A Constant Bag
pub trait ConstantBag: Sized + Copy {
type Constant: Constant;
fn make_constant<C: Constant>(&self, constant: BorrowedConstant<'_, C>) -> Self::Constant;
fn make_int(&self, value: BigInt) -> Self::Constant;
fn make_tuple(&self, elements: impl Iterator<Item = Self::Constant>) -> Self::Constant;
fn make_code(&self, code: CodeObject<Self::Constant>) -> Self::Constant;
fn make_name(&self, name: &str) -> <Self::Constant as Constant>::Name;
}
pub trait AsBag {
type Bag: ConstantBag;
#[allow(clippy::wrong_self_convention)]
fn as_bag(self) -> Self::Bag;
}
impl<Bag: ConstantBag> AsBag for Bag {
type Bag = Self;
fn as_bag(self) -> Self {
self
}
}
#[derive(Clone, Copy)]
pub struct BasicBag;
impl ConstantBag for BasicBag {
type Constant = ConstantData;
fn make_constant<C: Constant>(&self, constant: BorrowedConstant<'_, C>) -> Self::Constant {
constant.to_owned()
}
fn make_int(&self, value: BigInt) -> Self::Constant {
ConstantData::Integer { value }
}
fn make_tuple(&self, elements: impl Iterator<Item = Self::Constant>) -> Self::Constant {
ConstantData::Tuple {
elements: elements.collect(),
}
}
fn make_code(&self, code: CodeObject<Self::Constant>) -> Self::Constant {
ConstantData::Code {
code: Box::new(code),
}
}
fn make_name(&self, name: &str) -> <Self::Constant as Constant>::Name {
name.to_owned()
}
}
/// Primary container of a single code object. Each python function has
/// a code object. Also a module has a code object.
#[derive(Clone)]
pub struct CodeObject<C: Constant = ConstantData> {
pub instructions: CodeUnits,
pub locations: Box<[(SourceLocation, SourceLocation)]>,
pub flags: CodeFlags,
/// Number of positional-only arguments
pub posonlyarg_count: u32,
pub arg_count: u32,
pub kwonlyarg_count: u32,
pub source_path: C::Name,
pub first_line_number: Option<OneIndexed>,
pub max_stackdepth: u32,
/// Name of the object that created this code object
pub obj_name: C::Name,
/// Qualified name of the object (like CPython's co_qualname)
pub qualname: C::Name,
pub cell2arg: Option<Box<[i32]>>,
pub constants: Box<[C]>,
pub names: Box<[C::Name]>,
pub varnames: Box<[C::Name]>,
pub cellvars: Box<[C::Name]>,
pub freevars: Box<[C::Name]>,
/// Line number table (CPython 3.11+ format)
pub linetable: Box<[u8]>,
/// Exception handling table
pub exceptiontable: Box<[u8]>,
}
bitflags! {
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct CodeFlags: u16 {
const NEW_LOCALS = 0x01;
const IS_GENERATOR = 0x02;
const IS_COROUTINE = 0x04;
const HAS_VARARGS = 0x08;
const HAS_VARKEYWORDS = 0x10;
const IS_OPTIMIZED = 0x20;
}
}
impl CodeFlags {
pub const NAME_MAPPING: &'static [(&'static str, Self)] = &[
("GENERATOR", Self::IS_GENERATOR),
("COROUTINE", Self::IS_COROUTINE),
(
"ASYNC_GENERATOR",
Self::from_bits_truncate(Self::IS_GENERATOR.bits() | Self::IS_COROUTINE.bits()),
),
("VARARGS", Self::HAS_VARARGS),
("VARKEYWORDS", Self::HAS_VARKEYWORDS),
];
}
/// an opcode argument that may be extended by a prior ExtendedArg
#[derive(Copy, Clone, PartialEq, Eq)]
#[repr(transparent)]
pub struct OpArgByte(pub u8);
impl OpArgByte {
pub const fn null() -> Self {
Self(0)
}
}
impl From<u8> for OpArgByte {
fn from(raw: u8) -> Self {
Self(raw)
}
}
impl fmt::Debug for OpArgByte {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
/// a full 32-bit op_arg, including any possible ExtendedArg extension
#[derive(Copy, Clone, Debug)]
#[repr(transparent)]
pub struct OpArg(pub u32);
impl OpArg {
pub const fn null() -> Self {
Self(0)
}
/// Returns how many CodeUnits a instruction with this op_arg will be encoded as
#[inline]
pub const fn instr_size(self) -> usize {
(self.0 > 0xff) as usize + (self.0 > 0xff_ff) as usize + (self.0 > 0xff_ff_ff) as usize + 1
}
/// returns the arg split into any necessary ExtendedArg components (in big-endian order) and
/// the arg for the real opcode itself
#[inline(always)]
pub fn split(self) -> (impl ExactSizeIterator<Item = OpArgByte>, OpArgByte) {
let mut it = self
.0
.to_le_bytes()
.map(OpArgByte)
.into_iter()
.take(self.instr_size());
let lo = it.next().unwrap();
(it.rev(), lo)
}
}
impl From<u32> for OpArg {
fn from(raw: u32) -> Self {
Self(raw)
}
}
#[derive(Default, Copy, Clone)]
#[repr(transparent)]
pub struct OpArgState {
state: u32,
}
impl OpArgState {
#[inline(always)]
pub fn get(&mut self, ins: CodeUnit) -> (Instruction, OpArg) {
let arg = self.extend(ins.arg);
if ins.op != Instruction::ExtendedArg {
self.reset();
}
(ins.op, arg)
}
#[inline(always)]
pub fn extend(&mut self, arg: OpArgByte) -> OpArg {
self.state = (self.state << 8) | u32::from(arg.0);
OpArg(self.state)
}
#[inline(always)]
pub const fn reset(&mut self) {
self.state = 0
}
}
pub trait OpArgType: Copy {
fn from_op_arg(x: u32) -> Option<Self>;
fn to_op_arg(self) -> u32;
}
impl OpArgType for u32 {
#[inline(always)]
fn from_op_arg(x: u32) -> Option<Self> {
Some(x)
}
#[inline(always)]
fn to_op_arg(self) -> u32 {
self
}
}
impl OpArgType for bool {
#[inline(always)]
fn from_op_arg(x: u32) -> Option<Self> {
Some(x != 0)
}
#[inline(always)]
fn to_op_arg(self) -> u32 {
self as u32
}
}
macro_rules! op_arg_enum_impl {
(enum $name:ident { $($(#[$var_attr:meta])* $var:ident = $value:literal,)* }) => {
impl OpArgType for $name {
fn to_op_arg(self) -> u32 {
self as u32
}
fn from_op_arg(x: u32) -> Option<Self> {
Some(match u8::try_from(x).ok()? {
$($value => Self::$var,)*
_ => return None,
})
}
}
};
}
macro_rules! op_arg_enum {
($(#[$attr:meta])* $vis:vis enum $name:ident { $($(#[$var_attr:meta])* $var:ident = $value:literal,)* }) => {
$(#[$attr])*
$vis enum $name {
$($(#[$var_attr])* $var = $value,)*
}
op_arg_enum_impl!(enum $name {
$($(#[$var_attr])* $var = $value,)*
});
};
}
#[derive(Copy, Clone)]
pub struct Arg<T: OpArgType>(PhantomData<T>);
impl<T: OpArgType> Arg<T> {
#[inline]
pub const fn marker() -> Self {
Self(PhantomData)
}
#[inline]
pub fn new(arg: T) -> (Self, OpArg) {
(Self(PhantomData), OpArg(arg.to_op_arg()))
}
#[inline]
pub fn new_single(arg: T) -> (Self, OpArgByte)
where
T: Into<u8>,
{
(Self(PhantomData), OpArgByte(arg.into()))
}
#[inline(always)]
pub fn get(self, arg: OpArg) -> T {
self.try_get(arg).unwrap()
}
#[inline(always)]
pub fn try_get(self, arg: OpArg) -> Option<T> {
T::from_op_arg(arg.0)
}
/// # Safety
/// T::from_op_arg(self) must succeed
#[inline(always)]
pub unsafe fn get_unchecked(self, arg: OpArg) -> T {
// SAFETY: requirements forwarded from caller
unsafe { T::from_op_arg(arg.0).unwrap_unchecked() }
}
}
impl<T: OpArgType> PartialEq for Arg<T> {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl<T: OpArgType> Eq for Arg<T> {}
impl<T: OpArgType> fmt::Debug for Arg<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Arg<{}>", core::any::type_name::<T>())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
#[repr(transparent)]
// XXX: if you add a new instruction that stores a Label, make sure to add it in
// Instruction::label_arg
pub struct Label(pub u32);
impl OpArgType for Label {
#[inline(always)]
fn from_op_arg(x: u32) -> Option<Self> {
Some(Self(x))
}
#[inline(always)]
fn to_op_arg(self) -> u32 {
self.0
}
}
impl fmt::Display for Label {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
op_arg_enum!(
/// The kind of Raise that occurred.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum RaiseKind {
/// Bare `raise` statement with no arguments.
/// Gets the current exception from VM state (topmost_exception).
/// Maps to RAISE_VARARGS with oparg=0.
BareRaise = 0,
/// `raise exc` - exception is on the stack.
/// Maps to RAISE_VARARGS with oparg=1.
Raise = 1,
/// `raise exc from cause` - exception and cause are on the stack.
/// Maps to RAISE_VARARGS with oparg=2.
RaiseCause = 2,
/// Reraise exception from the stack top.
/// Used in exception handler cleanup blocks (finally, except).
/// Gets exception from stack, not from VM state.
/// Maps to the RERAISE opcode.
ReraiseFromStack = 3,
}
);
op_arg_enum!(
/// Intrinsic function for CALL_INTRINSIC_1
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum IntrinsicFunction1 {
// Invalid = 0,
Print = 1,
/// Import * operation
ImportStar = 2,
// StopIterationError = 3,
// AsyncGenWrap = 4,
// UnaryPositive = 5,
/// Convert list to tuple
ListToTuple = 6,
/// Type parameter related
TypeVar = 7,
ParamSpec = 8,
TypeVarTuple = 9,
/// Generic subscript for PEP 695
SubscriptGeneric = 10,
TypeAlias = 11,
}
);
op_arg_enum!(
/// Intrinsic function for CALL_INTRINSIC_2
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum IntrinsicFunction2 {
PrepReraiseStar = 1,
TypeVarWithBound = 2,
TypeVarWithConstraint = 3,
SetFunctionTypeParams = 4,
/// Set default value for type parameter (PEP 695)
SetTypeparamDefault = 5,
}
);
pub type NameIdx = u32;
/// A Single bytecode instruction.
/// Instructions are ordered to match CPython 3.13 opcode numbers exactly.
/// HAVE_ARGUMENT = 44: opcodes 0-43 have no argument, 44+ have arguments.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(u8)]
pub enum Instruction {
// ==================== No-argument instructions (opcode < 44) ====================
// 0: CACHE - placeholder for inline cache (not executed)
Cache,
// 1: BEFORE_ASYNC_WITH
BeforeAsyncWith,
// 2: BEFORE_WITH
BeforeWith,
// 3: Reserved (BINARY_OP_INPLACE_ADD_UNICODE in CPython)
Reserved3,
// 4: BINARY_SLICE - not implemented, placeholder
BinarySlice,
// 5: BINARY_SUBSCR
BinarySubscript,
// 6: CHECK_EG_MATCH
CheckEgMatch,
// 7: CHECK_EXC_MATCH
CheckExcMatch,
// 8: CLEANUP_THROW
CleanupThrow,
// 9: DELETE_SUBSCR
DeleteSubscript,
// 10: END_ASYNC_FOR
EndAsyncFor,
// 11: END_FOR - not implemented, placeholder
EndFor,
// 12: END_SEND
EndSend,
// 13: EXIT_INIT_CHECK - not implemented, placeholder
ExitInitCheck,
// 14: FORMAT_SIMPLE
FormatSimple,
// 15: FORMAT_WITH_SPEC
FormatWithSpec,
// 16: GET_AITER
GetAIter,
// 17: RESERVED
Reserved17,
// 18: GET_ANEXT
GetANext,
// 19: GET_ITER
GetIter,
// 20: GET_LEN
GetLen,
// 21: GET_YIELD_FROM_ITER - not implemented, placeholder
GetYieldFromIter,
// 22: INTERPRETER_EXIT - not implemented, placeholder
InterpreterExit,
// 23: LOAD_ASSERTION_ERROR - not implemented, placeholder
LoadAssertionError,
// 24: LOAD_BUILD_CLASS
LoadBuildClass,
// 25: LOAD_LOCALS - not implemented, placeholder
LoadLocals,
// 26: MAKE_FUNCTION
MakeFunction,
// 27: MATCH_KEYS
MatchKeys,
// 28: MATCH_MAPPING
MatchMapping,
// 29: MATCH_SEQUENCE
MatchSequence,
// 30: NOP
Nop,
// 31: POP_EXCEPT
PopException,
// 32: POP_TOP
PopTop,
// 33: PUSH_EXC_INFO
PushExcInfo,
// 34: PUSH_NULL - not implemented, placeholder
PushNull,
// 35: RETURN_GENERATOR - not implemented, placeholder
ReturnGenerator,
// 36: RETURN_VALUE
ReturnValue,
// 37: SETUP_ANNOTATIONS
SetupAnnotation,
// 38: STORE_SLICE - not implemented, placeholder
StoreSlice,
// 39: STORE_SUBSCR
StoreSubscript,
// 40: TO_BOOL
ToBool,
// 41: UNARY_INVERT - placeholder (RustPython uses UnaryOperation)
UnaryInvert,
// 42: UNARY_NEGATIVE - placeholder
UnaryNegative,
// 43: UNARY_NOT - placeholder
UnaryNot,
// ==================== With-argument instructions (opcode >= 44) ====================
// 44: WITH_EXCEPT_START
WithExceptStart,
// 45: BINARY_OP
BinaryOp {
op: Arg<BinaryOperator>,
},
// 46: BUILD_CONST_KEY_MAP - not implemented, placeholder
BuildConstKeyMap {
size: Arg<u32>,
},
// 47: BUILD_LIST
BuildList {
size: Arg<u32>,
},
// 48: BUILD_MAP
BuildMap {
size: Arg<u32>,
},
// 49: BUILD_SET
BuildSet {
size: Arg<u32>,
},
// 50: BUILD_SLICE
BuildSlice {
argc: Arg<BuildSliceArgCount>,
},
// 51: BUILD_STRING
BuildString {
size: Arg<u32>,
},
// 52: BUILD_TUPLE
BuildTuple {
size: Arg<u32>,
},
// 53: CALL
CallFunctionPositional {
nargs: Arg<u32>,
},
// 54: CALL_FUNCTION_EX
CallFunctionEx {
has_kwargs: Arg<bool>,
},
// 55: CALL_INTRINSIC_1
CallIntrinsic1 {
func: Arg<IntrinsicFunction1>,
},
// 56: CALL_INTRINSIC_2
CallIntrinsic2 {
func: Arg<IntrinsicFunction2>,
},
// 57: CALL_KW
CallFunctionKeyword {
nargs: Arg<u32>,
},
// 58: COMPARE_OP
CompareOperation {
op: Arg<ComparisonOperator>,
},
// 59: CONTAINS_OP
ContainsOp(Arg<Invert>),
// 60: CONVERT_VALUE
ConvertValue {
oparg: Arg<ConvertValueOparg>,
},
// 61: COPY
CopyItem {
index: Arg<u32>,
},
// 62: COPY_FREE_VARS - not implemented, placeholder
CopyFreeVars {
count: Arg<u32>,
},
// 63: DELETE_ATTR
DeleteAttr {
idx: Arg<NameIdx>,
},
// 64: DELETE_DEREF
DeleteDeref(Arg<NameIdx>),
// 65: DELETE_FAST
DeleteFast(Arg<NameIdx>),
// 66: DELETE_GLOBAL
DeleteGlobal(Arg<NameIdx>),
// 67: DELETE_NAME
DeleteLocal(Arg<NameIdx>),
// 68: DICT_MERGE - not implemented, placeholder
DictMerge {
index: Arg<u32>,
},
// 69: DICT_UPDATE
DictUpdate {
index: Arg<u32>,
},
// 70: ENTER_EXECUTOR - not implemented, placeholder
EnterExecutor {
index: Arg<u32>,
},
// 71: EXTENDED_ARG
ExtendedArg,
// 72: FOR_ITER
ForIter {
target: Arg<Label>,
},
// 73: GET_AWAITABLE
GetAwaitable,
// 74: IMPORT_FROM
ImportFrom {
idx: Arg<NameIdx>,
},
// 75: IMPORT_NAME
ImportName {
idx: Arg<NameIdx>,
},
// 76: IS_OP
IsOp(Arg<Invert>),
// 77: JUMP_BACKWARD - not implemented, placeholder
JumpBackward {
target: Arg<Label>,
},
// 78: JUMP_BACKWARD_NO_INTERRUPT - not implemented, placeholder
JumpBackwardNoInterrupt {
target: Arg<Label>,
},
// 79: JUMP_FORWARD - not implemented, placeholder
JumpForward {
target: Arg<Label>,
},
// 80: LIST_APPEND
ListAppend {
i: Arg<u32>,
},
// 81: LIST_EXTEND - not implemented, placeholder
ListExtend {
i: Arg<u32>,
},
// 82: LOAD_ATTR
LoadAttr {
idx: Arg<NameIdx>,
},
// 83: LOAD_CONST
LoadConst {
idx: Arg<u32>,
},
// 84: LOAD_DEREF
LoadDeref(Arg<NameIdx>),
// 85: LOAD_FAST
LoadFast(Arg<NameIdx>),
// 86: LOAD_FAST_AND_CLEAR
LoadFastAndClear(Arg<NameIdx>),
// 87: LOAD_FAST_CHECK - not implemented, placeholder
LoadFastCheck(Arg<NameIdx>),
// 88: LOAD_FAST_LOAD_FAST - not implemented, placeholder
LoadFastLoadFast {
arg: Arg<u32>,
},
// 89: LOAD_FROM_DICT_OR_DEREF - not implemented, placeholder
LoadFromDictOrDeref(Arg<NameIdx>),
// 90: LOAD_FROM_DICT_OR_GLOBALS - not implemented, placeholder
LoadFromDictOrGlobals(Arg<NameIdx>),
// 91: LOAD_GLOBAL
LoadGlobal(Arg<NameIdx>),
// 92: LOAD_NAME
LoadNameAny(Arg<NameIdx>),
// 93: LOAD_SUPER_ATTR - not implemented, placeholder
LoadSuperAttr {
arg: Arg<u32>,
},
// 94: MAKE_CELL - not implemented, placeholder
MakeCell(Arg<NameIdx>),
// 95: MAP_ADD
MapAdd {
i: Arg<u32>,
},
// 96: MATCH_CLASS
MatchClass(Arg<u32>),
// 97: POP_JUMP_IF_FALSE
PopJumpIfFalse {
target: Arg<Label>,
},
// 98: POP_JUMP_IF_NONE - not implemented, placeholder
PopJumpIfNone {
target: Arg<Label>,
},
// 99: POP_JUMP_IF_NOT_NONE - not implemented, placeholder
PopJumpIfNotNone {
target: Arg<Label>,
},
// 100: POP_JUMP_IF_TRUE
PopJumpIfTrue {
target: Arg<Label>,
},
// 101: RAISE_VARARGS
Raise {
kind: Arg<RaiseKind>,
},
// 102: RERAISE
Reraise {
depth: Arg<u32>,
},
// 103: RETURN_CONST
ReturnConst {
idx: Arg<u32>,
},
// 104: SEND
Send {
target: Arg<Label>,
},
// 105: SET_ADD
SetAdd {
i: Arg<u32>,
},
// 106: SET_FUNCTION_ATTRIBUTE
SetFunctionAttribute {
attr: Arg<MakeFunctionFlags>,
},
// 107: SET_UPDATE - not implemented, placeholder
SetUpdate {
i: Arg<u32>,
},
// 108: STORE_ATTR
StoreAttr {
idx: Arg<NameIdx>,
},
// 109: STORE_DEREF
StoreDeref(Arg<NameIdx>),
// 110: STORE_FAST
StoreFast(Arg<NameIdx>),
// 111: STORE_FAST_LOAD_FAST
StoreFastLoadFast {
store_idx: Arg<NameIdx>,
load_idx: Arg<NameIdx>,
},
// 112: STORE_FAST_STORE_FAST - not implemented, placeholder
StoreFastStoreFast {
arg: Arg<u32>,
},
// 113: STORE_GLOBAL
StoreGlobal(Arg<NameIdx>),
// 114: STORE_NAME
StoreLocal(Arg<NameIdx>),
// 115: SWAP
Swap {
index: Arg<u32>,
},
// 116: UNPACK_EX
UnpackEx {
args: Arg<UnpackExArgs>,
},
// 117: UNPACK_SEQUENCE
UnpackSequence {
size: Arg<u32>,
},
// 118: YIELD_VALUE
YieldValue {
arg: Arg<u32>,
},
// ==================== RustPython-only instructions (119+) ====================
// 119: BREAK
Break {
target: Arg<Label>,
},
// 120: BUILD_LIST_FROM_TUPLES
BuildListFromTuples {
size: Arg<u32>,
},
// 121: BUILD_MAP_FOR_CALL
BuildMapForCall {
size: Arg<u32>,
},
// 122: BUILD_SET_FROM_TUPLES
BuildSetFromTuples {
size: Arg<u32>,
},
// 123: BUILD_TUPLE_FROM_ITER
BuildTupleFromIter,
// 124: BUILD_TUPLE_FROM_TUPLES
BuildTupleFromTuples {
size: Arg<u32>,
},
// 125: CALL_METHOD
CallMethodPositional {
nargs: Arg<u32>,
},
// 126: CALL_METHOD_KW
CallMethodKeyword {
nargs: Arg<u32>,
},
// 127: CALL_METHOD_EX
CallMethodEx {
has_kwargs: Arg<bool>,
},
// 128: CONTINUE
Continue {
target: Arg<Label>,
},
// 129: JUMP (CPython uses pseudo-op 256)
Jump {
target: Arg<Label>,
},
// 130: JUMP_IF_FALSE_OR_POP
JumpIfFalseOrPop {
target: Arg<Label>,
},
// 131: JUMP_IF_TRUE_OR_POP
JumpIfTrueOrPop {
target: Arg<Label>,
},
// 132: JUMP_IF_NOT_EXC_MATCH
JumpIfNotExcMatch(Arg<Label>),
// 133: LOAD_CLASSDEREF
LoadClassDeref(Arg<NameIdx>),
// 134: LOAD_CLOSURE (CPython uses pseudo-op 258)
LoadClosure(Arg<NameIdx>),
// 135: LOAD_METHOD (CPython uses pseudo-op 259)
LoadMethod {
idx: Arg<NameIdx>,
},
// 136: POP_BLOCK (CPython uses pseudo-op 263)
PopBlock,
// 137: REVERSE
Reverse {
amount: Arg<u32>,
},
// 138: SET_EXC_INFO
SetExcInfo,
// 139: SUBSCRIPT
Subscript,
// 140: UNARY_OP (combines UNARY_*)
UnaryOperation {
op: Arg<UnaryOperator>,
},
// 141-148: Reserved (padding to keep RESUME at 149)
Reserved141,
Reserved142,
Reserved143,
Reserved144,
Reserved145,
Reserved146,
Reserved147,
Reserved148,
// 149: RESUME
Resume {
arg: Arg<u32>,
},
// If you add a new instruction here, be sure to keep LAST_INSTRUCTION updated
}
// This must be kept up to date to avoid marshaling errors
const LAST_INSTRUCTION: Instruction = Instruction::Resume { arg: Arg::marker() };
const _: () = assert!(mem::size_of::<Instruction>() == 1);
impl From<Instruction> for u8 {
#[inline]
fn from(ins: Instruction) -> Self {
// SAFETY: there's no padding bits
unsafe { core::mem::transmute::<Instruction, Self>(ins) }
}
}
impl TryFrom<u8> for Instruction {
type Error = MarshalError;
#[inline]
fn try_from(value: u8) -> Result<Self, MarshalError> {
if value <= u8::from(LAST_INSTRUCTION) {
Ok(unsafe { core::mem::transmute::<u8, Self>(value) })
} else {
Err(MarshalError::InvalidBytecode)
}
}
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct CodeUnit {
pub op: Instruction,
pub arg: OpArgByte,
}
const _: () = assert!(mem::size_of::<CodeUnit>() == 2);
impl CodeUnit {
pub const fn new(op: Instruction, arg: OpArgByte) -> Self {
Self { op, arg }
}
}
impl TryFrom<&[u8]> for CodeUnit {
type Error = MarshalError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
match value.len() {
2 => Ok(Self::new(value[0].try_into()?, value[1].into())),
_ => Err(Self::Error::InvalidBytecode),
}
}
}
#[derive(Clone)]
pub struct CodeUnits(Box<[CodeUnit]>);
impl TryFrom<&[u8]> for CodeUnits {
type Error = MarshalError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
if !value.len().is_multiple_of(2) {
return Err(Self::Error::InvalidBytecode);
}
value.chunks_exact(2).map(CodeUnit::try_from).collect()
}
}
impl<const N: usize> From<[CodeUnit; N]> for CodeUnits {
fn from(value: [CodeUnit; N]) -> Self {
Self(Box::from(value))
}
}
impl From<Vec<CodeUnit>> for CodeUnits {
fn from(value: Vec<CodeUnit>) -> Self {
Self(value.into_boxed_slice())
}
}
impl FromIterator<CodeUnit> for CodeUnits {
fn from_iter<T: IntoIterator<Item = CodeUnit>>(iter: T) -> Self {
Self(iter.into_iter().collect())
}
}
impl Deref for CodeUnits {
type Target = [CodeUnit];
fn deref(&self) -> &Self::Target {
&self.0
}
}
use self::Instruction::*;
bitflags! {
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct MakeFunctionFlags: u8 {
const CLOSURE = 0x01;
const ANNOTATIONS = 0x02;
const KW_ONLY_DEFAULTS = 0x04;
const DEFAULTS = 0x08;
const TYPE_PARAMS = 0x10;
}
}
impl OpArgType for MakeFunctionFlags {
#[inline(always)]
fn from_op_arg(x: u32) -> Option<Self> {
Self::from_bits(x as u8)
}
#[inline(always)]
fn to_op_arg(self) -> u32 {
self.bits().into()
}
}
/// A Constant (which usually encapsulates data within it)
///
/// # Examples
/// ```
/// use rustpython_compiler_core::bytecode::ConstantData;
/// let a = ConstantData::Float {value: 120f64};
/// let b = ConstantData::Boolean {value: false};
/// assert_ne!(a, b);
/// ```
#[derive(Debug, Clone)]
pub enum ConstantData {
Tuple { elements: Vec<ConstantData> },
Integer { value: BigInt },
Float { value: f64 },
Complex { value: Complex64 },
Boolean { value: bool },
Str { value: Wtf8Buf },
Bytes { value: Vec<u8> },
Code { code: Box<CodeObject> },
None,
Ellipsis,
}
impl PartialEq for ConstantData {
fn eq(&self, other: &Self) -> bool {
use ConstantData::*;
match (self, other) {
(Integer { value: a }, Integer { value: b }) => a == b,
// we want to compare floats *by actual value* - if we have the *exact same* float
// already in a constant cache, we want to use that
(Float { value: a }, Float { value: b }) => a.to_bits() == b.to_bits(),
(Complex { value: a }, Complex { value: b }) => {
a.re.to_bits() == b.re.to_bits() && a.im.to_bits() == b.im.to_bits()
}
(Boolean { value: a }, Boolean { value: b }) => a == b,
(Str { value: a }, Str { value: b }) => a == b,
(Bytes { value: a }, Bytes { value: b }) => a == b,
(Code { code: a }, Code { code: b }) => core::ptr::eq(a.as_ref(), b.as_ref()),
(Tuple { elements: a }, Tuple { elements: b }) => a == b,
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | true |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/compiler-core/src/mode.rs | crates/compiler-core/src/mode.rs | #[derive(Clone, Copy)]
pub enum Mode {
Exec,
Eval,
Single,
/// Returns the value of the last statement in the statement list.
BlockExpr,
}
impl core::str::FromStr for Mode {
type Err = ModeParseError;
// To support `builtins.compile()` `mode` argument
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"exec" => Ok(Self::Exec),
"eval" => Ok(Self::Eval),
"single" => Ok(Self::Single),
_ => Err(ModeParseError),
}
}
}
/// Returned when a given mode is not valid.
#[derive(Debug)]
pub struct ModeParseError;
impl core::fmt::Display for ModeParseError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, r#"mode must be "exec", "eval", or "single""#)
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/compiler-core/src/varint.rs | crates/compiler-core/src/varint.rs | //! Variable-length integer encoding utilities.
//!
//! Uses 6-bit chunks with a continuation bit (0x40) to encode integers.
//! Used for exception tables and line number tables.
/// Write a variable-length unsigned integer using 6-bit chunks.
/// Returns the number of bytes written.
#[inline]
pub fn write_varint(buf: &mut Vec<u8>, mut val: u32) -> usize {
let start_len = buf.len();
while val >= 64 {
buf.push(0x40 | (val & 0x3f) as u8);
val >>= 6;
}
buf.push(val as u8);
buf.len() - start_len
}
/// Write a variable-length signed integer.
/// Returns the number of bytes written.
#[inline]
pub fn write_signed_varint(buf: &mut Vec<u8>, val: i32) -> usize {
let uval = if val < 0 {
// (0 - val as u32) handles INT_MIN correctly
((0u32.wrapping_sub(val as u32)) << 1) | 1
} else {
(val as u32) << 1
};
write_varint(buf, uval)
}
/// Write a variable-length unsigned integer with a start marker (0x80 bit).
/// Used for exception table entries where each entry starts with the marker.
pub fn write_varint_with_start(data: &mut Vec<u8>, val: u32) {
let start_pos = data.len();
write_varint(data, val);
// Set start bit on first byte
if let Some(first) = data.get_mut(start_pos) {
*first |= 0x80;
}
}
/// Read a variable-length unsigned integer that starts with a start marker (0x80 bit).
/// Returns None if not at a valid start byte or end of data.
pub fn read_varint_with_start(data: &[u8], pos: &mut usize) -> Option<u32> {
if *pos >= data.len() {
return None;
}
let first = data[*pos];
if first & 0x80 == 0 {
return None; // Not a start byte
}
*pos += 1;
let mut val = (first & 0x3f) as u32;
let mut shift = 6;
let mut has_continuation = first & 0x40 != 0;
while has_continuation && *pos < data.len() {
let byte = data[*pos];
if byte & 0x80 != 0 {
break; // Next entry start
}
*pos += 1;
val |= ((byte & 0x3f) as u32) << shift;
shift += 6;
has_continuation = byte & 0x40 != 0;
}
Some(val)
}
/// Read a variable-length unsigned integer.
/// Returns None if end of data or malformed.
pub fn read_varint(data: &[u8], pos: &mut usize) -> Option<u32> {
if *pos >= data.len() {
return None;
}
let mut val = 0u32;
let mut shift = 0;
loop {
if *pos >= data.len() {
return None;
}
let byte = data[*pos];
if byte & 0x80 != 0 && shift > 0 {
break; // Next entry start
}
*pos += 1;
val |= ((byte & 0x3f) as u32) << shift;
shift += 6;
if byte & 0x40 == 0 {
break;
}
}
Some(val)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_write_read_varint() {
let mut buf = Vec::new();
write_varint(&mut buf, 0);
write_varint(&mut buf, 63);
write_varint(&mut buf, 64);
write_varint(&mut buf, 4095);
// Values: 0, 63, 64, 4095
assert_eq!(buf.len(), 1 + 1 + 2 + 2);
}
#[test]
fn test_write_read_signed_varint() {
let mut buf = Vec::new();
write_signed_varint(&mut buf, 0);
write_signed_varint(&mut buf, 1);
write_signed_varint(&mut buf, -1);
write_signed_varint(&mut buf, i32::MIN);
assert!(!buf.is_empty());
}
#[test]
fn test_varint_with_start() {
let mut buf = Vec::new();
write_varint_with_start(&mut buf, 42);
write_varint_with_start(&mut buf, 100);
let mut pos = 0;
assert_eq!(read_varint_with_start(&buf, &mut pos), Some(42));
assert_eq!(read_varint_with_start(&buf, &mut pos), Some(100));
assert_eq!(read_varint_with_start(&buf, &mut pos), None);
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/build.rs | crates/vm/build.rs | use itertools::Itertools;
use std::{env, io::prelude::*, path::PathBuf, process::Command};
fn main() {
let frozen_libs = if cfg!(feature = "freeze-stdlib") {
"Lib/*/*.py"
} else {
"Lib/python_builtins/*.py"
};
for entry in glob::glob(frozen_libs).expect("Lib/ exists?").flatten() {
let display = entry.display();
println!("cargo:rerun-if-changed={display}");
}
println!("cargo:rerun-if-changed=../../Lib/importlib/_bootstrap.py");
println!("cargo:rustc-env=RUSTPYTHON_GIT_HASH={}", git_hash());
println!(
"cargo:rustc-env=RUSTPYTHON_GIT_TIMESTAMP={}",
git_timestamp()
);
println!("cargo:rustc-env=RUSTPYTHON_GIT_TAG={}", git_tag());
println!("cargo:rustc-env=RUSTPYTHON_GIT_BRANCH={}", git_branch());
println!("cargo:rustc-env=RUSTC_VERSION={}", rustc_version());
println!(
"cargo:rustc-env=RUSTPYTHON_TARGET_TRIPLE={}",
env::var("TARGET").unwrap()
);
let mut env_path = PathBuf::from(env::var_os("OUT_DIR").unwrap());
env_path.push("env_vars.rs");
let mut f = std::fs::File::create(env_path).unwrap();
write!(
f,
"sysvars! {{ {} }}",
std::env::vars_os().format_with(", ", |(k, v), f| f(&format_args!("{k:?} => {v:?}")))
)
.unwrap();
}
fn git_hash() -> String {
git(&["rev-parse", "--short", "HEAD"])
}
fn git_timestamp() -> String {
git(&["log", "-1", "--format=%ct"])
}
fn git_tag() -> String {
git(&["describe", "--all", "--always", "--dirty"])
}
fn git_branch() -> String {
git(&["name-rev", "--name-only", "HEAD"])
}
fn git(args: &[&str]) -> String {
command("git", args)
}
fn rustc_version() -> String {
let rustc = env::var_os("RUSTC").unwrap_or_else(|| "rustc".into());
command(rustc, &["-V"])
}
fn command(cmd: impl AsRef<std::ffi::OsStr>, args: &[&str]) -> String {
match Command::new(cmd).args(args).output() {
Ok(output) => match String::from_utf8(output.stdout) {
Ok(s) => s,
Err(err) => format!("(output error: {err})"),
},
Err(err) => format!("(command error: {err})"),
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/coroutine.rs | crates/vm/src/coroutine.rs | use crate::{
AsObject, Py, PyObject, PyObjectRef, PyResult, VirtualMachine,
builtins::{PyBaseExceptionRef, PyStrRef},
common::lock::PyMutex,
exceptions::types::PyBaseException,
frame::{ExecutionResult, FrameRef},
function::OptionalArg,
protocol::PyIterReturn,
};
use crossbeam_utils::atomic::AtomicCell;
impl ExecutionResult {
/// Turn an ExecutionResult into a PyResult that would be returned from a generator or coroutine
fn into_iter_return(self, vm: &VirtualMachine) -> PyIterReturn {
match self {
Self::Yield(value) => PyIterReturn::Return(value),
Self::Return(value) => {
let arg = if vm.is_none(&value) {
None
} else {
Some(value)
};
PyIterReturn::StopIteration(arg)
}
}
}
}
#[derive(Debug)]
pub struct Coro {
frame: FrameRef,
pub closed: AtomicCell<bool>, // TODO: https://github.com/RustPython/RustPython/pull/3183#discussion_r720560652
running: AtomicCell<bool>,
// code
// _weakreflist
name: PyMutex<PyStrRef>,
qualname: PyMutex<PyStrRef>,
exception: PyMutex<Option<PyBaseExceptionRef>>, // exc_state
}
fn gen_name(jen: &PyObject, vm: &VirtualMachine) -> &'static str {
let typ = jen.class();
if typ.is(vm.ctx.types.coroutine_type) {
"coroutine"
} else if typ.is(vm.ctx.types.async_generator) {
"async generator"
} else {
"generator"
}
}
impl Coro {
pub fn new(frame: FrameRef, name: PyStrRef, qualname: PyStrRef) -> Self {
Self {
frame,
closed: AtomicCell::new(false),
running: AtomicCell::new(false),
exception: PyMutex::default(),
name: PyMutex::new(name),
qualname: PyMutex::new(qualname),
}
}
fn maybe_close(&self, res: &PyResult<ExecutionResult>) {
match res {
Ok(ExecutionResult::Return(_)) | Err(_) => self.closed.store(true),
Ok(ExecutionResult::Yield(_)) => {}
}
}
fn run_with_context<F>(
&self,
jen: &PyObject,
vm: &VirtualMachine,
func: F,
) -> PyResult<ExecutionResult>
where
F: FnOnce(FrameRef) -> PyResult<ExecutionResult>,
{
if self.running.compare_exchange(false, true).is_err() {
return Err(vm.new_value_error(format!("{} already executing", gen_name(jen, vm))));
}
// swap exception state
// Get generator's saved exception state from last yield
let gen_exc = self.exception.lock().take();
// Use a slot to capture generator's exception state before with_frame pops
let exception_slot = &self.exception;
// Run the generator frame
// with_frame does push_exception(None) which creates a new exception context
// The caller's exception remains in the chain via prev, so topmost_exception()
// will find it if generator's exception is None
let result = vm.with_frame(self.frame.clone(), |f| {
// with_frame pushed None, creating: { exc: None, prev: caller's exc_info }
// Pop None and push generator's exception instead
// This maintains the chain: { exc: gen_exc, prev: caller's exc_info }
vm.pop_exception();
vm.push_exception(gen_exc);
let result = func(f);
// Save generator's exception state BEFORE with_frame pops
// This is the generator's current exception context
*exception_slot.lock() = vm.current_exception();
result
});
self.running.store(false);
result
}
pub fn send(
&self,
jen: &PyObject,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyIterReturn> {
if self.closed.load() {
return Ok(PyIterReturn::StopIteration(None));
}
let value = if self.frame.lasti() > 0 {
Some(value)
} else if !vm.is_none(&value) {
return Err(vm.new_type_error(format!(
"can't send non-None value to a just-started {}",
gen_name(jen, vm),
)));
} else {
None
};
let result = self.run_with_context(jen, vm, |f| f.resume(value, vm));
self.maybe_close(&result);
match result {
Ok(exec_res) => Ok(exec_res.into_iter_return(vm)),
Err(e) => {
if e.fast_isinstance(vm.ctx.exceptions.stop_iteration) {
let err =
vm.new_runtime_error(format!("{} raised StopIteration", gen_name(jen, vm)));
err.set___cause__(Some(e));
Err(err)
} else if jen.class().is(vm.ctx.types.async_generator)
&& e.fast_isinstance(vm.ctx.exceptions.stop_async_iteration)
{
let err = vm.new_runtime_error("async generator raised StopAsyncIteration");
err.set___cause__(Some(e));
Err(err)
} else {
Err(e)
}
}
}
}
pub fn throw(
&self,
jen: &PyObject,
exc_type: PyObjectRef,
exc_val: PyObjectRef,
exc_tb: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyIterReturn> {
if self.closed.load() {
return Err(vm.normalize_exception(exc_type, exc_val, exc_tb)?);
}
let result = self.run_with_context(jen, vm, |f| f.gen_throw(vm, exc_type, exc_val, exc_tb));
self.maybe_close(&result);
Ok(result?.into_iter_return(vm))
}
pub fn close(&self, jen: &PyObject, vm: &VirtualMachine) -> PyResult<()> {
if self.closed.load() {
return Ok(());
}
// If generator hasn't started (FRAME_CREATED), just mark as closed
if self.frame.lasti() == 0 {
self.closed.store(true);
return Ok(());
}
let result = self.run_with_context(jen, vm, |f| {
f.gen_throw(
vm,
vm.ctx.exceptions.generator_exit.to_owned().into(),
vm.ctx.none(),
vm.ctx.none(),
)
});
self.closed.store(true);
match result {
Ok(ExecutionResult::Yield(_)) => {
Err(vm.new_runtime_error(format!("{} ignored GeneratorExit", gen_name(jen, vm))))
}
Err(e) if !is_gen_exit(&e, vm) => Err(e),
_ => Ok(()),
}
}
pub fn running(&self) -> bool {
self.running.load()
}
pub fn closed(&self) -> bool {
self.closed.load()
}
pub fn frame(&self) -> FrameRef {
self.frame.clone()
}
pub fn name(&self) -> PyStrRef {
self.name.lock().clone()
}
pub fn set_name(&self, name: PyStrRef) {
*self.name.lock() = name;
}
pub fn qualname(&self) -> PyStrRef {
self.qualname.lock().clone()
}
pub fn set_qualname(&self, qualname: PyStrRef) {
*self.qualname.lock() = qualname;
}
pub fn repr(&self, jen: &PyObject, id: usize, vm: &VirtualMachine) -> String {
format!(
"<{} object {} at {:#x}>",
gen_name(jen, vm),
self.name.lock(),
id
)
}
}
pub fn is_gen_exit(exc: &Py<PyBaseException>, vm: &VirtualMachine) -> bool {
exc.fast_isinstance(vm.ctx.exceptions.generator_exit)
}
/// Emit DeprecationWarning for the deprecated 3-argument throw() signature.
pub fn warn_deprecated_throw_signature(
exc_val: &OptionalArg,
exc_tb: &OptionalArg,
vm: &VirtualMachine,
) -> PyResult<()> {
if exc_val.is_present() || exc_tb.is_present() {
crate::warn::warn(
vm.ctx.new_str(
"the (type, val, tb) signature of throw() is deprecated, \
use throw(val) instead",
),
Some(vm.ctx.exceptions.deprecation_warning.to_owned()),
1,
None,
vm,
)?;
}
Ok(())
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/cformat.rs | crates/vm/src/cformat.rs | //cspell:ignore bytesobject
//! Implementation of Printf-Style string formatting
//! as per the [Python Docs](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting).
use crate::common::cformat::*;
use crate::common::wtf8::{CodePoint, Wtf8, Wtf8Buf};
use crate::{
AsObject, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, TryFromObject,
VirtualMachine,
builtins::{
PyBaseExceptionRef, PyByteArray, PyBytes, PyFloat, PyInt, PyStr, try_f64_to_bigint, tuple,
},
function::ArgIntoFloat,
protocol::PyBuffer,
stdlib::builtins,
};
use itertools::Itertools;
use num_traits::cast::ToPrimitive;
fn spec_format_bytes(
vm: &VirtualMachine,
spec: &CFormatSpec,
obj: PyObjectRef,
) -> PyResult<Vec<u8>> {
match &spec.format_type {
CFormatType::String(conversion) => match conversion {
// Unlike strings, %r and %a are identical for bytes: the behaviour corresponds to
// %a for strings (not %r)
CFormatConversion::Repr | CFormatConversion::Ascii => {
let b = builtins::ascii(obj, vm)?.into();
Ok(b)
}
CFormatConversion::Str | CFormatConversion::Bytes => {
if let Ok(buffer) = PyBuffer::try_from_borrowed_object(vm, &obj) {
Ok(buffer.contiguous_or_collect(|bytes| spec.format_bytes(bytes)))
} else {
let bytes = vm
.get_special_method(&obj, identifier!(vm, __bytes__))?
.ok_or_else(|| {
vm.new_type_error(format!(
"%b requires a bytes-like object, or an object that \
implements __bytes__, not '{}'",
obj.class().name()
))
})?
.invoke((), vm)?;
let bytes = PyBytes::try_from_borrowed_object(vm, &bytes)?;
Ok(spec.format_bytes(bytes.as_bytes()))
}
}
},
CFormatType::Number(number_type) => match number_type {
CNumberType::DecimalD | CNumberType::DecimalI | CNumberType::DecimalU => {
match_class!(match &obj {
ref i @ PyInt => {
Ok(spec.format_number(i.as_bigint()).into_bytes())
}
ref f @ PyFloat => {
Ok(spec
.format_number(&try_f64_to_bigint(f.to_f64(), vm)?)
.into_bytes())
}
obj => {
if let Some(method) = vm.get_method(obj.clone(), identifier!(vm, __int__)) {
let result = method?.call((), vm)?;
if let Some(i) = result.downcast_ref::<PyInt>() {
return Ok(spec.format_number(i.as_bigint()).into_bytes());
}
}
Err(vm.new_type_error(format!(
"%{} format: a number is required, not {}",
spec.format_type.to_char(),
obj.class().name()
)))
}
})
}
_ => {
if let Some(i) = obj.downcast_ref::<PyInt>() {
Ok(spec.format_number(i.as_bigint()).into_bytes())
} else {
Err(vm.new_type_error(format!(
"%{} format: an integer is required, not {}",
spec.format_type.to_char(),
obj.class().name()
)))
}
}
},
CFormatType::Float(_) => {
let class = obj.class().to_owned();
let value = ArgIntoFloat::try_from_object(vm, obj).map_err(|e| {
if e.fast_isinstance(vm.ctx.exceptions.type_error) {
// formatfloat in bytesobject.c generates its own specific exception
// text in this case, mirror it here.
vm.new_type_error(format!("float argument required, not {}", class.name()))
} else {
e
}
})?;
Ok(spec.format_float(value.into()).into_bytes())
}
CFormatType::Character(CCharacterType::Character) => {
if let Some(i) = obj.downcast_ref::<PyInt>() {
let ch = i
.try_to_primitive::<u8>(vm)
.map_err(|_| vm.new_overflow_error("%c arg not in range(256)"))?;
return Ok(spec.format_char(ch));
}
if let Some(b) = obj.downcast_ref::<PyBytes>() {
if b.len() == 1 {
return Ok(spec.format_char(b.as_bytes()[0]));
}
} else if let Some(ba) = obj.downcast_ref::<PyByteArray>() {
let buf = ba.borrow_buf();
if buf.len() == 1 {
return Ok(spec.format_char(buf[0]));
}
}
Err(vm.new_type_error("%c requires an integer in range(256) or a single byte"))
}
}
}
fn spec_format_string(
vm: &VirtualMachine,
spec: &CFormatSpec,
obj: PyObjectRef,
idx: usize,
) -> PyResult<Wtf8Buf> {
match &spec.format_type {
CFormatType::String(conversion) => {
let result = match conversion {
CFormatConversion::Ascii => builtins::ascii(obj, vm)?.into(),
CFormatConversion::Str => obj.str(vm)?.as_wtf8().to_owned(),
CFormatConversion::Repr => obj.repr(vm)?.as_wtf8().to_owned(),
CFormatConversion::Bytes => {
// idx is the position of the %, we want the position of the b
return Err(vm.new_value_error(format!(
"unsupported format character 'b' (0x62) at index {}",
idx + 1
)));
}
};
Ok(spec.format_string(result))
}
CFormatType::Number(number_type) => match number_type {
CNumberType::DecimalD | CNumberType::DecimalI | CNumberType::DecimalU => {
match_class!(match &obj {
ref i @ PyInt => {
Ok(spec.format_number(i.as_bigint()).into())
}
ref f @ PyFloat => {
Ok(spec
.format_number(&try_f64_to_bigint(f.to_f64(), vm)?)
.into())
}
obj => {
if let Some(method) = vm.get_method(obj.clone(), identifier!(vm, __int__)) {
let result = method?.call((), vm)?;
if let Some(i) = result.downcast_ref::<PyInt>() {
return Ok(spec.format_number(i.as_bigint()).into());
}
}
Err(vm.new_type_error(format!(
"%{} format: a number is required, not {}",
spec.format_type.to_char(),
obj.class().name()
)))
}
})
}
_ => {
if let Some(i) = obj.downcast_ref::<PyInt>() {
Ok(spec.format_number(i.as_bigint()).into())
} else {
Err(vm.new_type_error(format!(
"%{} format: an integer is required, not {}",
spec.format_type.to_char(),
obj.class().name()
)))
}
}
},
CFormatType::Float(_) => {
let value = ArgIntoFloat::try_from_object(vm, obj)?;
Ok(spec.format_float(value.into()).into())
}
CFormatType::Character(CCharacterType::Character) => {
if let Some(i) = obj.downcast_ref::<PyInt>() {
let ch = i
.as_bigint()
.to_u32()
.and_then(CodePoint::from_u32)
.ok_or_else(|| vm.new_overflow_error("%c arg not in range(0x110000)"))?;
return Ok(spec.format_char(ch));
}
if let Some(s) = obj.downcast_ref::<PyStr>()
&& let Ok(ch) = s.as_wtf8().code_points().exactly_one()
{
return Ok(spec.format_char(ch));
}
Err(vm.new_type_error("%c requires int or char"))
}
}
}
fn try_update_quantity_from_element(
vm: &VirtualMachine,
element: Option<&PyObject>,
) -> PyResult<CFormatQuantity> {
match element {
Some(width_obj) => {
if let Some(i) = width_obj.downcast_ref::<PyInt>() {
let i = i.try_to_primitive::<i32>(vm)?.unsigned_abs();
Ok(CFormatQuantity::Amount(i as usize))
} else {
Err(vm.new_type_error("* wants int"))
}
}
None => Err(vm.new_type_error("not enough arguments for format string")),
}
}
fn try_conversion_flag_from_tuple(
vm: &VirtualMachine,
element: Option<&PyObject>,
) -> PyResult<CConversionFlags> {
match element {
Some(width_obj) => {
if let Some(i) = width_obj.downcast_ref::<PyInt>() {
let i = i.try_to_primitive::<i32>(vm)?;
let flags = if i < 0 {
CConversionFlags::LEFT_ADJUST
} else {
CConversionFlags::from_bits(0).unwrap()
};
Ok(flags)
} else {
Err(vm.new_type_error("* wants int"))
}
}
None => Err(vm.new_type_error("not enough arguments for format string")),
}
}
fn try_update_quantity_from_tuple<'a, I: Iterator<Item = &'a PyObjectRef>>(
vm: &VirtualMachine,
elements: &mut I,
q: &mut Option<CFormatQuantity>,
f: &mut CConversionFlags,
) -> PyResult<()> {
let Some(CFormatQuantity::FromValuesTuple) = q else {
return Ok(());
};
let element = elements.next();
f.insert(try_conversion_flag_from_tuple(
vm,
element.map(|v| v.as_ref()),
)?);
let quantity = try_update_quantity_from_element(vm, element.map(|v| v.as_ref()))?;
*q = Some(quantity);
Ok(())
}
fn try_update_precision_from_tuple<'a, I: Iterator<Item = &'a PyObjectRef>>(
vm: &VirtualMachine,
elements: &mut I,
p: &mut Option<CFormatPrecision>,
) -> PyResult<()> {
let Some(CFormatPrecision::Quantity(CFormatQuantity::FromValuesTuple)) = p else {
return Ok(());
};
let quantity = try_update_quantity_from_element(vm, elements.next().map(|v| v.as_ref()))?;
*p = Some(CFormatPrecision::Quantity(quantity));
Ok(())
}
fn specifier_error(vm: &VirtualMachine) -> PyBaseExceptionRef {
vm.new_type_error("format requires a mapping")
}
pub(crate) fn cformat_bytes(
vm: &VirtualMachine,
format_string: &[u8],
values_obj: PyObjectRef,
) -> PyResult<Vec<u8>> {
let mut format = CFormatBytes::parse_from_bytes(format_string)
.map_err(|err| vm.new_value_error(err.to_string()))?;
let (num_specifiers, mapping_required) = format
.check_specifiers()
.ok_or_else(|| specifier_error(vm))?;
let mut result = vec![];
let is_mapping = values_obj.class().has_attr(identifier!(vm, __getitem__))
&& !values_obj.fast_isinstance(vm.ctx.types.tuple_type)
&& !values_obj.fast_isinstance(vm.ctx.types.bytes_type)
&& !values_obj.fast_isinstance(vm.ctx.types.bytearray_type);
if num_specifiers == 0 {
// literal only
return if is_mapping
|| values_obj
.downcast_ref::<tuple::PyTuple>()
.is_some_and(|e| e.is_empty())
{
for (_, part) in format.iter_mut() {
match part {
CFormatPart::Literal(literal) => result.append(literal),
CFormatPart::Spec(_) => unreachable!(),
}
}
Ok(result)
} else {
Err(vm.new_type_error("not all arguments converted during bytes formatting"))
};
}
if mapping_required {
// dict
return if is_mapping {
for (_, part) in format {
match part {
CFormatPart::Literal(literal) => result.extend(literal),
CFormatPart::Spec(CFormatSpecKeyed { mapping_key, spec }) => {
let key = mapping_key.unwrap();
let value = values_obj.get_item(&key, vm)?;
let part_result = spec_format_bytes(vm, &spec, value)?;
result.extend(part_result);
}
}
}
Ok(result)
} else {
Err(vm.new_type_error("format requires a mapping"))
};
}
// tuple
let values = if let Some(tup) = values_obj.downcast_ref::<tuple::PyTuple>() {
tup.as_slice()
} else {
core::slice::from_ref(&values_obj)
};
let mut value_iter = values.iter();
for (_, part) in format {
match part {
CFormatPart::Literal(literal) => result.extend(literal),
CFormatPart::Spec(CFormatSpecKeyed { mut spec, .. }) => {
try_update_quantity_from_tuple(
vm,
&mut value_iter,
&mut spec.min_field_width,
&mut spec.flags,
)?;
try_update_precision_from_tuple(vm, &mut value_iter, &mut spec.precision)?;
let value = match value_iter.next() {
Some(obj) => Ok(obj.clone()),
None => Err(vm.new_type_error("not enough arguments for format string")),
}?;
let part_result = spec_format_bytes(vm, &spec, value)?;
result.extend(part_result);
}
}
}
// check that all arguments were converted
if value_iter.next().is_some() && !is_mapping {
Err(vm.new_type_error("not all arguments converted during bytes formatting"))
} else {
Ok(result)
}
}
pub(crate) fn cformat_string(
vm: &VirtualMachine,
format_string: &Wtf8,
values_obj: PyObjectRef,
) -> PyResult<Wtf8Buf> {
let format = CFormatWtf8::parse_from_wtf8(format_string)
.map_err(|err| vm.new_value_error(err.to_string()))?;
let (num_specifiers, mapping_required) = format
.check_specifiers()
.ok_or_else(|| specifier_error(vm))?;
let mut result = Wtf8Buf::new();
let is_mapping = values_obj.class().has_attr(identifier!(vm, __getitem__))
&& !values_obj.fast_isinstance(vm.ctx.types.tuple_type)
&& !values_obj.fast_isinstance(vm.ctx.types.str_type);
if num_specifiers == 0 {
// literal only
return if is_mapping
|| values_obj
.downcast_ref::<tuple::PyTuple>()
.is_some_and(|e| e.is_empty())
{
for (_, part) in format.iter() {
match part {
CFormatPart::Literal(literal) => result.push_wtf8(literal),
CFormatPart::Spec(_) => unreachable!(),
}
}
Ok(result)
} else {
Err(vm.new_type_error("not all arguments converted during string formatting"))
};
}
if mapping_required {
// dict
return if is_mapping {
for (idx, part) in format {
match part {
CFormatPart::Literal(literal) => result.push_wtf8(&literal),
CFormatPart::Spec(CFormatSpecKeyed { mapping_key, spec }) => {
let value = values_obj.get_item(&mapping_key.unwrap(), vm)?;
let part_result = spec_format_string(vm, &spec, value, idx)?;
result.push_wtf8(&part_result);
}
}
}
Ok(result)
} else {
Err(vm.new_type_error("format requires a mapping"))
};
}
// tuple
let values = if let Some(tup) = values_obj.downcast_ref::<tuple::PyTuple>() {
tup.as_slice()
} else {
core::slice::from_ref(&values_obj)
};
let mut value_iter = values.iter();
for (idx, part) in format {
match part {
CFormatPart::Literal(literal) => result.push_wtf8(&literal),
CFormatPart::Spec(CFormatSpecKeyed { mut spec, .. }) => {
try_update_quantity_from_tuple(
vm,
&mut value_iter,
&mut spec.min_field_width,
&mut spec.flags,
)?;
try_update_precision_from_tuple(vm, &mut value_iter, &mut spec.precision)?;
let value = match value_iter.next() {
Some(obj) => Ok(obj.clone()),
None => Err(vm.new_type_error("not enough arguments for format string")),
}?;
let part_result = spec_format_string(vm, &spec, value, idx)?;
result.push_wtf8(&part_result);
}
}
}
// check that all arguments were converted
if value_iter.next().is_some() && !is_mapping {
Err(vm.new_type_error("not all arguments converted during string formatting"))
} else {
Ok(result)
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/anystr.rs | crates/vm/src/anystr.rs | use crate::{
Py, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine,
builtins::{PyIntRef, PyTuple},
convert::TryFromBorrowedObject,
function::OptionalOption,
};
use num_traits::{cast::ToPrimitive, sign::Signed};
use core::ops::Range;
#[derive(FromArgs)]
pub struct SplitArgs<T: TryFromObject> {
#[pyarg(any, default)]
sep: Option<T>,
#[pyarg(any, default = -1)]
maxsplit: isize,
}
#[derive(FromArgs)]
pub struct SplitLinesArgs {
#[pyarg(any, default = false)]
pub keepends: bool,
}
#[derive(FromArgs)]
pub struct ExpandTabsArgs {
#[pyarg(any, default = 8)]
tabsize: isize,
}
impl ExpandTabsArgs {
pub fn tabsize(&self) -> usize {
self.tabsize.to_usize().unwrap_or(0)
}
}
#[derive(FromArgs)]
pub struct StartsEndsWithArgs {
#[pyarg(positional)]
affix: PyObjectRef,
#[pyarg(positional, default)]
start: Option<PyIntRef>,
#[pyarg(positional, default)]
end: Option<PyIntRef>,
}
impl StartsEndsWithArgs {
pub fn get_value(self, len: usize) -> (PyObjectRef, Option<Range<usize>>) {
let range = if self.start.is_some() || self.end.is_some() {
Some(adjust_indices(self.start, self.end, len))
} else {
None
};
(self.affix, range)
}
#[inline]
pub fn prepare<S, F>(self, s: &S, len: usize, substr: F) -> Option<(PyObjectRef, &S)>
where
S: ?Sized + AnyStr,
F: Fn(&S, Range<usize>) -> &S,
{
let (affix, range) = self.get_value(len);
let substr = if let Some(range) = range {
if !range.is_normal() {
return None;
}
substr(s, range)
} else {
s
};
Some((affix, substr))
}
}
fn saturate_to_isize(py_int: PyIntRef) -> isize {
let big = py_int.as_bigint();
big.to_isize().unwrap_or_else(|| {
if big.is_negative() {
isize::MIN
} else {
isize::MAX
}
})
}
// help get optional string indices
pub fn adjust_indices(start: Option<PyIntRef>, end: Option<PyIntRef>, len: usize) -> Range<usize> {
let mut start = start.map_or(0, saturate_to_isize);
let mut end = end.map_or(len as isize, saturate_to_isize);
if end > len as isize {
end = len as isize;
} else if end < 0 {
end += len as isize;
if end < 0 {
end = 0;
}
}
if start < 0 {
start += len as isize;
if start < 0 {
start = 0;
}
}
start as usize..end as usize
}
pub trait StringRange {
fn is_normal(&self) -> bool;
}
impl StringRange for Range<usize> {
fn is_normal(&self) -> bool {
self.start <= self.end
}
}
pub trait AnyStrWrapper<S: AnyStr + ?Sized> {
fn as_ref(&self) -> Option<&S>;
fn is_empty(&self) -> bool;
}
pub trait AnyStrContainer<S>
where
S: ?Sized,
{
fn new() -> Self;
fn with_capacity(capacity: usize) -> Self;
fn push_str(&mut self, s: &S);
}
pub trait AnyChar: Copy {
fn is_lowercase(self) -> bool;
fn is_uppercase(self) -> bool;
fn bytes_len(self) -> usize;
}
pub trait AnyStr {
type Char: AnyChar;
type Container: AnyStrContainer<Self> + Extend<Self::Char>;
fn to_container(&self) -> Self::Container;
fn as_bytes(&self) -> &[u8];
fn elements(&self) -> impl Iterator<Item = Self::Char>;
fn get_bytes(&self, range: Range<usize>) -> &Self;
// FIXME: get_chars is expensive for str
fn get_chars(&self, range: Range<usize>) -> &Self;
fn bytes_len(&self) -> usize;
// NOTE: str::chars().count() consumes the O(n) time. But pystr::char_len does cache.
// So using chars_len directly is too expensive and the below method shouldn't be implemented.
// fn chars_len(&self) -> usize;
fn is_empty(&self) -> bool;
fn py_add(&self, other: &Self) -> Self::Container {
let mut new = Self::Container::with_capacity(self.bytes_len() + other.bytes_len());
new.push_str(self);
new.push_str(other);
new
}
fn py_split<T, SP, SN, SW>(
&self,
args: SplitArgs<T>,
vm: &VirtualMachine,
full_obj: impl FnOnce() -> PyObjectRef,
split: SP,
splitn: SN,
split_whitespace: SW,
) -> PyResult<Vec<PyObjectRef>>
where
T: TryFromObject + AnyStrWrapper<Self>,
SP: Fn(&Self, &Self, &VirtualMachine) -> Vec<PyObjectRef>,
SN: Fn(&Self, &Self, usize, &VirtualMachine) -> Vec<PyObjectRef>,
SW: Fn(&Self, isize, &VirtualMachine) -> Vec<PyObjectRef>,
{
if args.sep.as_ref().is_some_and(|sep| sep.is_empty()) {
return Err(vm.new_value_error("empty separator"));
}
let splits = if let Some(pattern) = args.sep {
let Some(pattern) = pattern.as_ref() else {
return Ok(vec![full_obj()]);
};
if args.maxsplit < 0 {
split(self, pattern, vm)
} else {
splitn(self, pattern, (args.maxsplit + 1) as usize, vm)
}
} else {
split_whitespace(self, args.maxsplit, vm)
};
Ok(splits)
}
fn py_split_whitespace<F>(&self, maxsplit: isize, convert: F) -> Vec<PyObjectRef>
where
F: Fn(&Self) -> PyObjectRef;
fn py_rsplit_whitespace<F>(&self, maxsplit: isize, convert: F) -> Vec<PyObjectRef>
where
F: Fn(&Self) -> PyObjectRef;
#[inline]
fn py_starts_ends_with<'a, T, F>(
&self,
affix: &'a PyObject,
func_name: &str,
py_type_name: &str,
func: F,
vm: &VirtualMachine,
) -> PyResult<bool>
where
T: TryFromBorrowedObject<'a>,
F: Fn(&Self, T) -> bool,
{
single_or_tuple_any(
affix,
&|s: T| Ok(func(self, s)),
&|o| {
format!(
"{} first arg must be {} or a tuple of {}, not {}",
func_name,
py_type_name,
py_type_name,
o.class(),
)
},
vm,
)
}
#[inline]
fn py_strip<'a, S, FC, FD>(
&'a self,
chars: OptionalOption<S>,
func_chars: FC,
func_default: FD,
) -> &'a Self
where
S: AnyStrWrapper<Self>,
FC: Fn(&'a Self, &Self) -> &'a Self,
FD: Fn(&'a Self) -> &'a Self,
{
let chars = chars.flatten();
match chars {
Some(chars) => {
if let Some(chars) = chars.as_ref() {
func_chars(self, chars)
} else {
self
}
}
None => func_default(self),
}
}
#[inline]
fn py_find<F>(&self, needle: &Self, range: Range<usize>, find: F) -> Option<usize>
where
F: Fn(&Self, &Self) -> Option<usize>,
{
if range.is_normal() {
let start = range.start;
let index = find(self.get_chars(range), needle)?;
Some(start + index)
} else {
None
}
}
#[inline]
fn py_count<F>(&self, needle: &Self, range: Range<usize>, count: F) -> usize
where
F: Fn(&Self, &Self) -> usize,
{
if range.is_normal() {
count(self.get_chars(range), needle)
} else {
0
}
}
fn py_pad(&self, left: usize, right: usize, fillchar: Self::Char) -> Self::Container {
let mut u = Self::Container::with_capacity(
(left + right) * fillchar.bytes_len() + self.bytes_len(),
);
u.extend(core::iter::repeat_n(fillchar, left));
u.push_str(self);
u.extend(core::iter::repeat_n(fillchar, right));
u
}
fn py_center(&self, width: usize, fillchar: Self::Char, len: usize) -> Self::Container {
let marg = width - len;
let left = marg / 2 + (marg & width & 1);
self.py_pad(left, marg - left, fillchar)
}
fn py_ljust(&self, width: usize, fillchar: Self::Char, len: usize) -> Self::Container {
self.py_pad(0, width - len, fillchar)
}
fn py_rjust(&self, width: usize, fillchar: Self::Char, len: usize) -> Self::Container {
self.py_pad(width - len, 0, fillchar)
}
fn py_join(
&self,
mut iter: impl core::iter::Iterator<Item = PyResult<impl AnyStrWrapper<Self> + TryFromObject>>,
) -> PyResult<Self::Container> {
let mut joined = if let Some(elem) = iter.next() {
elem?.as_ref().unwrap().to_container()
} else {
return Ok(Self::Container::new());
};
for elem in iter {
let elem = elem?;
joined.push_str(self);
joined.push_str(elem.as_ref().unwrap());
}
Ok(joined)
}
fn py_partition<'a, F, S>(
&'a self,
sub: &Self,
split: F,
vm: &VirtualMachine,
) -> PyResult<(Self::Container, bool, Self::Container)>
where
F: Fn() -> S,
S: core::iter::Iterator<Item = &'a Self>,
{
if sub.is_empty() {
return Err(vm.new_value_error("empty separator"));
}
let mut sp = split();
let front = sp.next().unwrap().to_container();
let (has_mid, back) = if let Some(back) = sp.next() {
(true, back.to_container())
} else {
(false, Self::Container::new())
};
Ok((front, has_mid, back))
}
fn py_removeprefix<FC>(&self, prefix: &Self, prefix_len: usize, is_prefix: FC) -> &Self
where
FC: Fn(&Self, &Self) -> bool,
{
//if self.py_starts_with(prefix) {
if is_prefix(self, prefix) {
self.get_bytes(prefix_len..self.bytes_len())
} else {
self
}
}
fn py_removesuffix<FC>(&self, suffix: &Self, suffix_len: usize, is_suffix: FC) -> &Self
where
FC: Fn(&Self, &Self) -> bool,
{
if is_suffix(self, suffix) {
self.get_bytes(0..self.bytes_len() - suffix_len)
} else {
self
}
}
// TODO: remove this function from anystr.
// See https://github.com/RustPython/RustPython/pull/4709/files#r1141013993
fn py_bytes_splitlines<FW, W>(&self, options: SplitLinesArgs, into_wrapper: FW) -> Vec<W>
where
FW: Fn(&Self) -> W,
{
let keep = options.keepends as usize;
let mut elements = Vec::new();
let mut last_i = 0;
let mut enumerated = self.as_bytes().iter().enumerate().peekable();
while let Some((i, ch)) = enumerated.next() {
let (end_len, i_diff) = match *ch {
b'\n' => (keep, 1),
b'\r' => {
let is_rn = enumerated.next_if(|(_, ch)| **ch == b'\n').is_some();
if is_rn { (keep + keep, 2) } else { (keep, 1) }
}
_ => continue,
};
let range = last_i..i + end_len;
last_i = i + i_diff;
elements.push(into_wrapper(self.get_bytes(range)));
}
if last_i != self.bytes_len() {
elements.push(into_wrapper(self.get_bytes(last_i..self.bytes_len())));
}
elements
}
fn py_zfill(&self, width: isize) -> Vec<u8> {
let width = width.to_usize().unwrap_or(0);
rustpython_common::str::zfill(self.as_bytes(), width)
}
// Unified form of CPython functions:
// _Py_bytes_islower
// unicode_islower_impl
fn py_islower(&self) -> bool {
let mut lower = false;
for c in self.elements() {
if c.is_uppercase() {
return false;
} else if !lower && c.is_lowercase() {
lower = true
}
}
lower
}
// Unified form of CPython functions:
// Py_bytes_isupper
// unicode_isupper_impl
fn py_isupper(&self) -> bool {
let mut upper = false;
for c in self.elements() {
if c.is_lowercase() {
return false;
} else if !upper && c.is_uppercase() {
upper = true
}
}
upper
}
}
/// Tests that the predicate is True on a single value, or if the value is a tuple a tuple, then
/// test that any of the values contained within the tuples satisfies the predicate. Type parameter
/// T specifies the type that is expected, if the input value is not of that type or a tuple of
/// values of that type, then a TypeError is raised.
pub fn single_or_tuple_any<'a, T, F, M>(
obj: &'a PyObject,
predicate: &F,
message: &M,
vm: &VirtualMachine,
) -> PyResult<bool>
where
T: TryFromBorrowedObject<'a>,
F: Fn(T) -> PyResult<bool>,
M: Fn(&PyObject) -> String,
{
match obj.try_to_value::<T>(vm) {
Ok(single) => (predicate)(single),
Err(_) => {
let tuple: &Py<PyTuple> = obj
.try_to_value(vm)
.map_err(|_| vm.new_type_error((message)(obj)))?;
for obj in tuple {
if single_or_tuple_any(obj, predicate, message, vm)? {
return Ok(true);
}
}
Ok(false)
}
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/sequence.rs | crates/vm/src/sequence.rs | use crate::{
AsObject, PyObject, PyObjectRef, PyResult,
builtins::PyIntRef,
function::OptionalArg,
sliceable::SequenceIndexOp,
types::PyComparisonOp,
vm::{MAX_MEMORY_SIZE, VirtualMachine},
};
use core::ops::{Deref, Range};
use optional::Optioned;
pub trait MutObjectSequenceOp {
type Inner: ?Sized;
fn do_get(index: usize, inner: &Self::Inner) -> Option<&PyObject>;
fn do_lock(&self) -> impl Deref<Target = Self::Inner>;
fn mut_count(&self, vm: &VirtualMachine, needle: &PyObject) -> PyResult<usize> {
let mut count = 0;
self._mut_iter_equal_skeleton::<_, false>(vm, needle, 0..isize::MAX as usize, || {
count += 1
})?;
Ok(count)
}
fn mut_index_range(
&self,
vm: &VirtualMachine,
needle: &PyObject,
range: Range<usize>,
) -> PyResult<Optioned<usize>> {
self._mut_iter_equal_skeleton::<_, true>(vm, needle, range, || {})
}
fn mut_index(&self, vm: &VirtualMachine, needle: &PyObject) -> PyResult<Optioned<usize>> {
self.mut_index_range(vm, needle, 0..isize::MAX as usize)
}
fn mut_contains(&self, vm: &VirtualMachine, needle: &PyObject) -> PyResult<bool> {
self.mut_index(vm, needle).map(|x| x.is_some())
}
fn _mut_iter_equal_skeleton<F, const SHORT: bool>(
&self,
vm: &VirtualMachine,
needle: &PyObject,
range: Range<usize>,
mut f: F,
) -> PyResult<Optioned<usize>>
where
F: FnMut(),
{
let mut borrower = None;
let mut i = range.start;
let index = loop {
if i >= range.end {
break Optioned::<usize>::none();
}
let guard = if let Some(x) = borrower.take() {
x
} else {
self.do_lock()
};
let elem = if let Some(x) = Self::do_get(i, &guard) {
x
} else {
break Optioned::<usize>::none();
};
if elem.is(needle) {
f();
if SHORT {
break Optioned::<usize>::some(i);
}
borrower = Some(guard);
} else {
let elem = elem.to_owned();
drop(guard);
if elem.rich_compare_bool(needle, PyComparisonOp::Eq, vm)? {
f();
if SHORT {
break Optioned::<usize>::some(i);
}
}
}
i += 1;
};
Ok(index)
}
}
pub trait SequenceExt<T: Clone>
where
Self: AsRef<[T]>,
{
fn mul(&self, vm: &VirtualMachine, n: isize) -> PyResult<Vec<T>> {
let n = vm.check_repeat_or_overflow_error(self.as_ref().len(), n)?;
if n > 1 && core::mem::size_of_val(self.as_ref()) >= MAX_MEMORY_SIZE / n {
return Err(vm.new_memory_error(""));
}
let mut v = Vec::with_capacity(n * self.as_ref().len());
for _ in 0..n {
v.extend_from_slice(self.as_ref());
}
Ok(v)
}
}
impl<T: Clone> SequenceExt<T> for [T] {}
pub trait SequenceMutExt<T: Clone>
where
Self: AsRef<[T]>,
{
fn as_vec_mut(&mut self) -> &mut Vec<T>;
fn imul(&mut self, vm: &VirtualMachine, n: isize) -> PyResult<()> {
let n = vm.check_repeat_or_overflow_error(self.as_ref().len(), n)?;
if n == 0 {
self.as_vec_mut().clear();
} else if n != 1 {
let mut sample = self.as_vec_mut().clone();
if n != 2 {
self.as_vec_mut().reserve(sample.len() * (n - 1));
for _ in 0..n - 2 {
self.as_vec_mut().extend_from_slice(&sample);
}
}
self.as_vec_mut().append(&mut sample);
}
Ok(())
}
}
impl<T: Clone> SequenceMutExt<T> for Vec<T> {
fn as_vec_mut(&mut self) -> &mut Self {
self
}
}
#[derive(FromArgs)]
pub struct OptionalRangeArgs {
#[pyarg(positional, optional)]
start: OptionalArg<PyObjectRef>,
#[pyarg(positional, optional)]
stop: OptionalArg<PyObjectRef>,
}
impl OptionalRangeArgs {
pub fn saturate(self, len: usize, vm: &VirtualMachine) -> PyResult<(usize, usize)> {
let saturate = |obj: PyObjectRef| -> PyResult<_> {
obj.try_into_value(vm)
.map(|int: PyIntRef| int.as_bigint().saturated_at(len))
};
let start = self.start.map_or(Ok(0), saturate)?;
let stop = self.stop.map_or(Ok(len), saturate)?;
Ok((start, stop))
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/prelude.rs | crates/vm/src/prelude.rs | //! The prelude imports the various objects and traits.
//!
//! The intention is that one can include `use rustpython_vm::prelude::*`.
pub use crate::{
object::{
AsObject, Py, PyExact, PyObject, PyObjectRef, PyPayload, PyRef, PyRefExact, PyResult,
PyWeakRef,
},
vm::{Context, Interpreter, Settings, VirtualMachine},
};
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/warn.rs | crates/vm/src/warn.rs | use crate::{
AsObject, Context, Py, PyObject, PyObjectRef, PyResult, VirtualMachine,
builtins::{
PyDictRef, PyListRef, PyStr, PyStrInterned, PyStrRef, PyTuple, PyTupleRef, PyTypeRef,
},
convert::{IntoObject, TryFromObject},
types::PyComparisonOp,
};
pub struct WarningsState {
filters: PyListRef,
_once_registry: PyDictRef,
default_action: PyStrRef,
filters_version: usize,
}
impl WarningsState {
fn create_filter(ctx: &Context) -> PyListRef {
ctx.new_list(vec![
ctx.new_tuple(vec![
ctx.new_str("__main__").into(),
ctx.types.none_type.as_object().to_owned(),
ctx.exceptions.warning.as_object().to_owned(),
ctx.new_str("ACTION").into(),
ctx.new_int(0).into(),
])
.into(),
])
}
pub fn init_state(ctx: &Context) -> Self {
Self {
filters: Self::create_filter(ctx),
_once_registry: ctx.new_dict(),
default_action: ctx.new_str("default"),
filters_version: 0,
}
}
}
fn check_matched(obj: &PyObject, arg: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
if obj.class().is(vm.ctx.types.none_type) {
return Ok(true);
}
if obj.rich_compare_bool(arg, PyComparisonOp::Eq, vm)? {
return Ok(false);
}
let result = obj.call((arg.to_owned(),), vm);
Ok(result.is_ok())
}
fn get_warnings_attr(
vm: &VirtualMachine,
attr_name: &'static PyStrInterned,
try_import: bool,
) -> PyResult<Option<PyObjectRef>> {
let module = if try_import
&& !vm
.state
.finalizing
.load(core::sync::atomic::Ordering::SeqCst)
{
match vm.import("warnings", 0) {
Ok(module) => module,
Err(_) => return Ok(None),
}
} else {
// Check sys.modules for already-imported warnings module
// This is what CPython does with PyImport_GetModule
match vm.sys_module.get_attr(identifier!(vm, modules), vm) {
Ok(modules) => match modules.get_item(vm.ctx.intern_str("warnings"), vm) {
Ok(module) => module,
Err(_) => return Ok(None),
},
Err(_) => return Ok(None),
}
};
Ok(Some(module.get_attr(attr_name, vm)?))
}
pub fn warn(
message: PyStrRef,
category: Option<PyTypeRef>,
stack_level: isize,
source: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
let (filename, lineno, module, registry) = setup_context(stack_level, vm)?;
warn_explicit(
category, message, filename, lineno, module, registry, None, source, vm,
)
}
fn get_default_action(vm: &VirtualMachine) -> PyResult<PyObjectRef> {
Ok(vm.state.warnings.default_action.clone().into())
// .map_err(|_| {
// vm.new_value_error(format!(
// "_warnings.defaultaction must be a string, not '{}'",
// vm.state.warnings.default_action
// ))
// })
}
fn get_filter(
category: PyObjectRef,
text: PyObjectRef,
lineno: usize,
module: PyObjectRef,
mut _item: PyTupleRef,
vm: &VirtualMachine,
) -> PyResult {
let filters = vm.state.warnings.filters.as_object().to_owned();
let filters: PyListRef = filters
.try_into_value(vm)
.map_err(|_| vm.new_value_error("_warnings.filters must be a list"))?;
/* WarningsState.filters could change while we are iterating over it. */
for i in 0..filters.borrow_vec().len() {
let tmp_item = if let Some(tmp_item) = filters.borrow_vec().get(i).cloned() {
let tmp_item = PyTupleRef::try_from_object(vm, tmp_item)?;
(tmp_item.len() == 5).then_some(tmp_item)
} else {
None
}
.ok_or_else(|| vm.new_value_error(format!("_warnings.filters item {i} isn't a 5-tuple")))?;
/* Python code: action, msg, cat, mod, ln = item */
let action = if let Some(action) = tmp_item.first() {
action.str_utf8(vm).map(|action| action.into_object())
} else {
Err(vm.new_type_error("action must be a string"))
};
let good_msg = if let Some(msg) = tmp_item.get(1) {
check_matched(msg, &text, vm)?
} else {
false
};
let is_subclass = if let Some(cat) = tmp_item.get(2) {
category.fast_isinstance(cat.class())
} else {
false
};
let good_mod = if let Some(item_mod) = tmp_item.get(3) {
check_matched(item_mod, &module, vm)?
} else {
false
};
let ln = tmp_item.get(4).map_or(0, |ln_obj| {
ln_obj.try_int(vm).map_or(0, |ln| ln.as_u32_mask() as _)
});
if good_msg && good_mod && is_subclass && (ln == 0 || lineno == ln) {
_item = tmp_item;
return action;
}
}
get_default_action(vm)
}
fn already_warned(
registry: PyObjectRef,
key: PyObjectRef,
should_set: bool,
vm: &VirtualMachine,
) -> PyResult<bool> {
let version_obj = registry.get_item(identifier!(&vm.ctx, version), vm).ok();
let filters_version = vm.ctx.new_int(vm.state.warnings.filters_version).into();
match version_obj {
Some(version_obj)
if version_obj.try_int(vm).is_ok() || version_obj.is(&filters_version) =>
{
let already_warned = registry.get_item(key.as_ref(), vm)?;
if already_warned.is_true(vm)? {
return Ok(true);
}
}
_ => {
let registry = registry.dict();
if let Some(registry) = registry.as_ref() {
registry.clear();
let r = registry.set_item("version", filters_version, vm);
if r.is_err() {
return Ok(false);
}
}
}
}
/* This warning wasn't found in the registry, set it. */
if !should_set {
return Ok(false);
}
let item = vm.ctx.true_value.clone().into();
let _ = registry.set_item(key.as_ref(), item, vm); // ignore set error
Ok(true)
}
fn normalize_module(filename: &Py<PyStr>, vm: &VirtualMachine) -> Option<PyObjectRef> {
let obj = match filename.char_len() {
0 => vm.new_pyobj("<unknown>"),
len if len >= 3 && filename.as_bytes().ends_with(b".py") => {
vm.new_pyobj(&filename.as_wtf8()[..len - 3])
}
_ => filename.as_object().to_owned(),
};
Some(obj)
}
#[allow(clippy::too_many_arguments)]
fn warn_explicit(
category: Option<PyTypeRef>,
message: PyStrRef,
filename: PyStrRef,
lineno: usize,
module: Option<PyObjectRef>,
registry: PyObjectRef,
source_line: Option<PyObjectRef>,
source: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
let registry: PyObjectRef = registry
.try_into_value(vm)
.map_err(|_| vm.new_type_error("'registry' must be a dict or None"))?;
// Normalize module.
let module = match module.or_else(|| normalize_module(&filename, vm)) {
Some(module) => module,
None => return Ok(()),
};
// Normalize message.
let text = message.as_wtf8();
let category = if let Some(category) = category {
if !category.fast_issubclass(vm.ctx.exceptions.warning) {
return Err(vm.new_type_error(format!(
"category must be a Warning subclass, not '{}'",
category.class().name()
)));
}
category
} else {
vm.ctx.exceptions.user_warning.to_owned()
};
let category = if message.fast_isinstance(vm.ctx.exceptions.warning) {
message.class().to_owned()
} else {
category
};
// Create key.
let key = PyTuple::new_ref(
vec![
vm.ctx.new_int(3).into(),
vm.ctx.new_str(text).into(),
category.as_object().to_owned(),
vm.ctx.new_int(lineno).into(),
],
&vm.ctx,
);
if !vm.is_none(registry.as_object()) && already_warned(registry, key.into_object(), false, vm)?
{
return Ok(());
}
let item = vm.ctx.new_tuple(vec![]);
let action = get_filter(
category.as_object().to_owned(),
vm.ctx.new_str(text).into(),
lineno,
module,
item,
vm,
)?;
if action.str_utf8(vm)?.as_str().eq("error") {
return Err(vm.new_type_error(message.to_string()));
}
if action.str_utf8(vm)?.as_str().eq("ignore") {
return Ok(());
}
call_show_warning(
// t_state,
category,
message,
filename,
lineno, // lineno_obj,
source_line,
source,
vm,
)
}
fn call_show_warning(
category: PyTypeRef,
message: PyStrRef,
filename: PyStrRef,
lineno: usize,
source_line: Option<PyObjectRef>,
source: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
let Some(show_fn) =
get_warnings_attr(vm, identifier!(&vm.ctx, _showwarnmsg), source.is_some())?
else {
return show_warning(filename, lineno, message, category, source_line, vm);
};
if !show_fn.is_callable() {
return Err(vm.new_type_error("warnings._showwarnmsg() must be set to a callable"));
}
let Some(warnmsg_cls) = get_warnings_attr(vm, identifier!(&vm.ctx, WarningMessage), false)?
else {
return Err(vm.new_type_error("unable to get warnings.WarningMessage"));
};
// Create a Warning instance by calling category(message)
// This is what warnings module does
let warning_instance = category.as_object().call((message,), vm)?;
let msg = warnmsg_cls.call(
vec![
warning_instance,
category.into(),
filename.into(),
vm.new_pyobj(lineno),
vm.ctx.none(),
vm.ctx.none(),
vm.unwrap_or_none(source),
],
vm,
)?;
show_fn.call((msg,), vm)?;
Ok(())
}
fn show_warning(
_filename: PyStrRef,
_lineno: usize,
text: PyStrRef,
category: PyTypeRef,
_source_line: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
let stderr = crate::stdlib::sys::PyStderr(vm);
writeln!(stderr, "{}: {}", category.name(), text);
Ok(())
}
/// filename, module, and registry are new refs, globals is borrowed
/// Returns `Ok` on success, or `Err` on error (no new refs)
fn setup_context(
mut stack_level: isize,
vm: &VirtualMachine,
) -> PyResult<
// filename, lineno, module, registry
(PyStrRef, usize, Option<PyObjectRef>, PyObjectRef),
> {
let __warningregistry__ = "__warningregistry__";
let __name__ = "__name__";
let mut f = vm.current_frame().as_deref().cloned();
// Stack level comparisons to Python code is off by one as there is no
// warnings-related stack level to avoid.
if stack_level <= 0 || f.as_ref().is_some_and(|frame| frame.is_internal_frame()) {
loop {
stack_level -= 1;
if stack_level <= 0 {
break;
}
if let Some(tmp) = f {
f = tmp.f_back(vm);
} else {
break;
}
}
} else {
loop {
stack_level -= 1;
if stack_level <= 0 {
break;
}
if let Some(tmp) = f {
f = tmp.next_external_frame(vm);
} else {
break;
}
}
}
let (globals, filename, lineno) = if let Some(f) = f {
(f.globals.clone(), f.code.source_path, f.f_lineno())
} else if let Some(frame) = vm.current_frame() {
// We have a frame but it wasn't found during stack walking
(frame.globals.clone(), vm.ctx.intern_str("<sys>"), 1)
} else {
// No frames on the stack - use sys.__dict__ (interp->sysdict)
let globals = vm
.sys_module
.as_object()
.get_attr(identifier!(vm, __dict__), vm)
.and_then(|d| {
d.downcast::<crate::builtins::PyDict>()
.map_err(|_| vm.new_type_error("sys.__dict__ is not a dictionary"))
})?;
(globals, vm.ctx.intern_str("<sys>"), 0)
};
let registry = if let Ok(registry) = globals.get_item(__warningregistry__, vm) {
registry
} else {
let registry = vm.ctx.new_dict();
globals.set_item(__warningregistry__, registry.clone().into(), vm)?;
registry.into()
};
// Setup module.
let module = globals
.get_item(__name__, vm)
.unwrap_or_else(|_| vm.new_pyobj("<string>"));
Ok((filename.to_owned(), lineno, Some(module), registry))
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/lib.rs | crates/vm/src/lib.rs | //! This crate contains most of the python logic.
//!
//! - Interpreter
//! - Import mechanics
//! - Base objects
//!
//! Some stdlib modules are implemented here, but most of them are in the `rustpython-stdlib` module. The
// to allow `mod foo {}` in foo.rs; clippy thinks this is a mistake/misunderstanding of
// how `mod` works, but we want this sometimes for pymodule declarations
#![allow(clippy::module_inception)]
// we want to mirror python naming conventions when defining python structs, so that does mean
// uppercase acronyms, e.g. TextIOWrapper instead of TextIoWrapper
#![allow(clippy::upper_case_acronyms)]
#![doc(html_logo_url = "https://raw.githubusercontent.com/RustPython/RustPython/main/logo.png")]
#![doc(html_root_url = "https://docs.rs/rustpython-vm/")]
#[cfg(feature = "flame-it")]
#[macro_use]
extern crate flamer;
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate log;
// extern crate env_logger;
extern crate alloc;
#[macro_use]
extern crate rustpython_derive;
extern crate self as rustpython_vm;
pub use rustpython_derive::*;
//extern crate eval; use eval::eval::*;
// use py_code_object::{Function, NativeType, PyCodeObject};
// This is above everything else so that the defined macros are available everywhere
#[macro_use]
pub(crate) mod macros;
mod anystr;
pub mod buffer;
pub mod builtins;
pub mod byte;
mod bytes_inner;
pub mod cformat;
pub mod class;
mod codecs;
pub mod compiler;
pub mod convert;
mod coroutine;
mod dict_inner;
#[cfg(feature = "rustpython-compiler")]
pub mod eval;
mod exception_group;
pub mod exceptions;
pub mod format;
pub mod frame;
pub mod function;
pub mod getpath;
pub mod import;
mod intern;
pub mod iter;
pub mod object;
#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
pub mod ospath;
pub mod prelude;
pub mod protocol;
pub mod py_io;
#[cfg(feature = "serde")]
pub mod py_serde;
pub mod readline;
pub mod recursion;
pub mod scope;
pub mod sequence;
pub mod signal;
pub mod sliceable;
pub mod stdlib;
pub mod suggestion;
pub mod types;
pub mod utils;
pub mod version;
pub mod vm;
pub mod warn;
#[cfg(windows)]
pub mod windows;
pub use self::convert::{TryFromBorrowedObject, TryFromObject};
pub use self::object::{
AsObject, Py, PyAtomicRef, PyExact, PyObject, PyObjectRef, PyPayload, PyRef, PyRefExact,
PyResult, PyWeakRef,
};
pub use self::vm::{Context, Interpreter, Settings, VirtualMachine};
pub use rustpython_common as common;
pub use rustpython_compiler_core::{bytecode, frozen};
pub use rustpython_literal as literal;
#[doc(hidden)]
pub mod __exports {
pub use paste;
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/version.rs | crates/vm/src/version.rs | //! Several function to retrieve version information.
use chrono::{Local, prelude::DateTime};
use core::time::Duration;
use std::time::UNIX_EPOCH;
// = 3.13.0alpha
pub const MAJOR: usize = 3;
pub const MINOR: usize = 13;
pub const MICRO: usize = 0;
pub const RELEASELEVEL: &str = "alpha";
pub const RELEASELEVEL_N: usize = 0xA;
pub const SERIAL: usize = 0;
pub const VERSION_HEX: usize =
(MAJOR << 24) | (MINOR << 16) | (MICRO << 8) | (RELEASELEVEL_N << 4) | SERIAL;
pub fn get_version() -> String {
// Windows: include MSC v. for compatibility with ctypes.util.find_library
// MSC v.1929 = VS 2019, version 14+ makes find_msvcrt() return None
#[cfg(windows)]
let msc_info = {
let arch = if cfg!(target_pointer_width = "64") {
"64 bit (AMD64)"
} else {
"32 bit (Intel)"
};
// Include both RustPython identifier and MSC v. for compatibility
format!(" MSC v.1929 {arch}",)
};
#[cfg(not(windows))]
let msc_info = String::new();
format!(
"{:.80} ({:.80}) \n[RustPython {} with {:.80}{}]", // \n is PyPy convention
get_version_number(),
get_build_info(),
env!("CARGO_PKG_VERSION"),
COMPILER,
msc_info,
)
}
pub fn get_version_number() -> String {
format!("{MAJOR}.{MINOR}.{MICRO}{RELEASELEVEL}")
}
pub fn get_winver_number() -> String {
format!("{MAJOR}.{MINOR}")
}
const COMPILER: &str = env!("RUSTC_VERSION");
pub fn get_build_info() -> String {
// See: https://reproducible-builds.org/docs/timestamps/
let git_revision = get_git_revision();
let separator = if git_revision.is_empty() { "" } else { ":" };
let git_identifier = get_git_identifier();
format!(
"{id}{sep}{revision}, {date:.20}, {time:.9}",
id = if git_identifier.is_empty() {
"default".to_owned()
} else {
git_identifier
},
sep = separator,
revision = git_revision,
date = get_git_date(),
time = get_git_time(),
)
}
pub fn get_git_revision() -> String {
option_env!("RUSTPYTHON_GIT_HASH").unwrap_or("").to_owned()
}
pub fn get_git_tag() -> String {
option_env!("RUSTPYTHON_GIT_TAG").unwrap_or("").to_owned()
}
pub fn get_git_branch() -> String {
option_env!("RUSTPYTHON_GIT_BRANCH")
.unwrap_or("")
.to_owned()
}
pub fn get_git_identifier() -> String {
let git_tag = get_git_tag();
let git_branch = get_git_branch();
if git_tag.is_empty() || git_tag == "undefined" {
git_branch
} else {
git_tag
}
}
fn get_git_timestamp_datetime() -> DateTime<Local> {
let timestamp = option_env!("RUSTPYTHON_GIT_TIMESTAMP")
.unwrap_or("")
.to_owned();
let timestamp = timestamp.parse::<u64>().unwrap_or(0);
let datetime = UNIX_EPOCH + Duration::from_secs(timestamp);
datetime.into()
}
pub fn get_git_date() -> String {
let datetime = get_git_timestamp_datetime();
datetime.format("%b %e %Y").to_string()
}
pub fn get_git_time() -> String {
let datetime = get_git_timestamp_datetime();
datetime.format("%H:%M:%S").to_string()
}
pub fn get_git_datetime() -> String {
let date = get_git_date();
let time = get_git_time();
format!("{date} {time}")
}
// Must be aligned to Lib/importlib/_bootstrap_external.py
pub const PYC_MAGIC_NUMBER: u16 = 2997;
// CPython format: magic_number | ('\r' << 16) | ('\n' << 24)
// This protects against text-mode file reads
pub const PYC_MAGIC_NUMBER_TOKEN: u32 =
(PYC_MAGIC_NUMBER as u32) | ((b'\r' as u32) << 16) | ((b'\n' as u32) << 24);
/// Magic number as little-endian bytes for .pyc files
pub const PYC_MAGIC_NUMBER_BYTES: [u8; 4] = PYC_MAGIC_NUMBER_TOKEN.to_le_bytes();
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/byte.rs | crates/vm/src/byte.rs | //! byte operation APIs
use crate::object::AsObject;
use crate::{PyObject, PyResult, VirtualMachine};
use num_traits::ToPrimitive;
pub fn bytes_from_object(vm: &VirtualMachine, obj: &PyObject) -> PyResult<Vec<u8>> {
if let Ok(elements) = obj.try_bytes_like(vm, |bytes| bytes.to_vec()) {
return Ok(elements);
}
if !obj.fast_isinstance(vm.ctx.types.str_type)
&& let Ok(elements) = vm.map_iterable_object(obj, |x| value_from_object(vm, &x))
{
return elements;
}
Err(vm.new_type_error("can assign only bytes, buffers, or iterables of ints in range(0, 256)"))
}
pub fn value_from_object(vm: &VirtualMachine, obj: &PyObject) -> PyResult<u8> {
obj.try_index(vm)?
.as_bigint()
.to_u8()
.ok_or_else(|| vm.new_value_error("byte must be in range(0, 256)"))
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/py_io.rs | crates/vm/src/py_io.rs | use crate::{
PyObject, PyObjectRef, PyResult, VirtualMachine,
builtins::{PyBaseExceptionRef, PyBytes, PyStr},
common::ascii,
};
use alloc::fmt;
use core::ops;
use std::io;
pub trait Write {
type Error;
fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<(), Self::Error>;
}
#[repr(transparent)]
pub struct IoWriter<T>(pub T);
impl<T> IoWriter<T> {
pub fn from_ref(x: &mut T) -> &mut Self {
// SAFETY: IoWriter is repr(transparent) over T
unsafe { &mut *(x as *mut T as *mut Self) }
}
}
impl<T> ops::Deref for IoWriter<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> ops::DerefMut for IoWriter<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
impl<W> Write for IoWriter<W>
where
W: io::Write,
{
type Error = io::Error;
fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
<W as io::Write>::write_fmt(&mut self.0, args)
}
}
impl Write for String {
type Error = fmt::Error;
fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
<Self as fmt::Write>::write_fmt(self, args)
}
}
pub struct PyWriter<'vm>(pub PyObjectRef, pub &'vm VirtualMachine);
impl Write for PyWriter<'_> {
type Error = PyBaseExceptionRef;
fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<(), Self::Error> {
let PyWriter(obj, vm) = self;
vm.call_method(obj, "write", (args.to_string(),)).map(drop)
}
}
pub fn file_readline(obj: &PyObject, size: Option<usize>, vm: &VirtualMachine) -> PyResult {
let args = size.map_or_else(Vec::new, |size| vec![vm.ctx.new_int(size).into()]);
let ret = vm.call_method(obj, "readline", args)?;
let eof_err = || {
vm.new_exception(
vm.ctx.exceptions.eof_error.to_owned(),
vec![vm.ctx.new_str(ascii!("EOF when reading a line")).into()],
)
};
let ret = match_class!(match ret {
s @ PyStr => {
// Use as_wtf8() to handle strings with surrogates (e.g., surrogateescape)
let s_wtf8 = s.as_wtf8();
if s_wtf8.is_empty() {
return Err(eof_err());
}
// '\n' is ASCII, so we can check bytes directly
if s_wtf8.as_bytes().last() == Some(&b'\n') {
let no_nl = &s_wtf8[..s_wtf8.len() - 1];
vm.ctx.new_str(no_nl).into()
} else {
s.into()
}
}
b @ PyBytes => {
let buf = b.as_bytes();
if buf.is_empty() {
return Err(eof_err());
}
if buf.last() == Some(&b'\n') {
vm.ctx.new_bytes(buf[..buf.len() - 1].to_owned()).into()
} else {
b.into()
}
}
_ => return Err(vm.new_type_error("object.readline() returned non-string".to_owned())),
});
Ok(ret)
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/signal.rs | crates/vm/src/signal.rs | #![cfg_attr(target_os = "wasi", allow(dead_code))]
use crate::{PyResult, VirtualMachine};
use alloc::fmt;
use core::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
pub(crate) const NSIG: usize = 64;
static ANY_TRIGGERED: AtomicBool = AtomicBool::new(false);
// hack to get around const array repeat expressions, rust issue #79270
#[allow(clippy::declare_interior_mutable_const)]
const ATOMIC_FALSE: AtomicBool = AtomicBool::new(false);
pub(crate) static TRIGGERS: [AtomicBool; NSIG] = [ATOMIC_FALSE; NSIG];
#[cfg_attr(feature = "flame-it", flame)]
#[inline(always)]
pub fn check_signals(vm: &VirtualMachine) -> PyResult<()> {
if vm.signal_handlers.is_none() {
return Ok(());
}
if !ANY_TRIGGERED.swap(false, Ordering::Acquire) {
return Ok(());
}
trigger_signals(vm)
}
#[inline(never)]
#[cold]
fn trigger_signals(vm: &VirtualMachine) -> PyResult<()> {
// unwrap should never fail since we check above
let signal_handlers = vm.signal_handlers.as_ref().unwrap().borrow();
for (signum, trigger) in TRIGGERS.iter().enumerate().skip(1) {
let triggered = trigger.swap(false, Ordering::Relaxed);
if triggered
&& let Some(handler) = &signal_handlers[signum]
&& let Some(callable) = handler.to_callable()
{
callable.invoke((signum, vm.ctx.none()), vm)?;
}
}
if let Some(signal_rx) = &vm.signal_rx {
for f in signal_rx.rx.try_iter() {
f(vm)?;
}
}
Ok(())
}
pub(crate) fn set_triggered() {
ANY_TRIGGERED.store(true, Ordering::Release);
}
pub fn assert_in_range(signum: i32, vm: &VirtualMachine) -> PyResult<()> {
if (1..NSIG as i32).contains(&signum) {
Ok(())
} else {
Err(vm.new_value_error("signal number out of range"))
}
}
/// Similar to `PyErr_SetInterruptEx` in CPython
///
/// Missing signal handler for the given signal number is silently ignored.
#[allow(dead_code)]
#[cfg(not(target_arch = "wasm32"))]
pub fn set_interrupt_ex(signum: i32, vm: &VirtualMachine) -> PyResult<()> {
use crate::stdlib::signal::_signal::{SIG_DFL, SIG_IGN, run_signal};
assert_in_range(signum, vm)?;
match signum as usize {
SIG_DFL | SIG_IGN => Ok(()),
_ => {
// interrupt the main thread with given signal number
run_signal(signum);
Ok(())
}
}
}
pub type UserSignal = Box<dyn FnOnce(&VirtualMachine) -> PyResult<()> + Send>;
#[derive(Clone, Debug)]
pub struct UserSignalSender {
tx: mpsc::Sender<UserSignal>,
}
#[derive(Debug)]
pub struct UserSignalReceiver {
rx: mpsc::Receiver<UserSignal>,
}
impl UserSignalSender {
pub fn send(&self, sig: UserSignal) -> Result<(), UserSignalSendError> {
self.tx
.send(sig)
.map_err(|mpsc::SendError(sig)| UserSignalSendError(sig))?;
set_triggered();
Ok(())
}
}
pub struct UserSignalSendError(pub UserSignal);
impl fmt::Debug for UserSignalSendError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UserSignalSendError")
.finish_non_exhaustive()
}
}
impl fmt::Display for UserSignalSendError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("sending a signal to a exited vm")
}
}
pub fn user_signal_channel() -> (UserSignalSender, UserSignalReceiver) {
let (tx, rx) = mpsc::channel();
(UserSignalSender { tx }, UserSignalReceiver { rx })
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/class.rs | crates/vm/src/class.rs | //! Utilities to define a new Python class
use crate::{
PyPayload,
builtins::{PyBaseObject, PyType, PyTypeRef, descriptor::PyWrapper},
function::PyMethodDef,
object::Py,
types::{PyTypeFlags, PyTypeSlots, SLOT_DEFS, hash_not_implemented},
vm::Context,
};
use rustpython_common::static_cell;
/// Add slot wrapper descriptors to a type's dict
///
/// Iterates SLOT_DEFS and creates a PyWrapper for each slot that:
/// 1. Has a function set in the type's slots
/// 2. Doesn't already have an attribute in the type's dict
pub fn add_operators(class: &'static Py<PyType>, ctx: &Context) {
for def in SLOT_DEFS.iter() {
// Skip __new__ - it has special handling
if def.name == "__new__" {
continue;
}
// Special handling for __hash__ = None
if def.name == "__hash__"
&& class
.slots
.hash
.load()
.is_some_and(|h| h as usize == hash_not_implemented as usize)
{
class.set_attr(ctx.names.__hash__, ctx.none.clone().into());
continue;
}
// __getattr__ should only have a wrapper if the type explicitly defines it.
// Unlike __getattribute__, __getattr__ is not present on object by default.
// Both map to TpGetattro, but only __getattribute__ gets a wrapper from the slot.
if def.name == "__getattr__" {
continue;
}
// Get the slot function wrapped in SlotFunc
let Some(slot_func) = def.accessor.get_slot_func_with_op(&class.slots, def.op) else {
continue;
};
// Check if attribute already exists in dict
let attr_name = ctx.intern_str(def.name);
if class.attributes.read().contains_key(attr_name) {
continue;
}
// Create and add the wrapper
let wrapper = PyWrapper {
typ: class,
name: attr_name,
wrapped: slot_func,
doc: Some(def.doc),
};
class.set_attr(attr_name, wrapper.into_ref(ctx).into());
}
}
pub trait StaticType {
// Ideally, saving PyType is better than PyTypeRef
fn static_cell() -> &'static static_cell::StaticCell<PyTypeRef>;
#[inline]
fn static_metaclass() -> &'static Py<PyType> {
PyType::static_type()
}
#[inline]
fn static_baseclass() -> &'static Py<PyType> {
PyBaseObject::static_type()
}
#[inline]
fn static_type() -> &'static Py<PyType> {
#[cold]
fn fail() -> ! {
panic!(
"static type has not been initialized. e.g. the native types defined in different module may be used before importing library."
);
}
Self::static_cell().get().unwrap_or_else(|| fail())
}
fn init_manually(typ: PyTypeRef) -> &'static Py<PyType> {
let cell = Self::static_cell();
cell.set(typ)
.unwrap_or_else(|_| panic!("double initialization from init_manually"));
cell.get().unwrap()
}
fn init_builtin_type() -> &'static Py<PyType>
where
Self: PyClassImpl,
{
let typ = Self::create_static_type();
let cell = Self::static_cell();
cell.set(typ)
.unwrap_or_else(|_| panic!("double initialization of {}", Self::NAME));
cell.get().unwrap()
}
fn create_static_type() -> PyTypeRef
where
Self: PyClassImpl,
{
PyType::new_static(
Self::static_baseclass().to_owned(),
Default::default(),
Self::make_slots(),
Self::static_metaclass().to_owned(),
)
.unwrap()
}
}
pub trait PyClassDef {
const NAME: &'static str;
const MODULE_NAME: Option<&'static str>;
const TP_NAME: &'static str;
const DOC: Option<&'static str> = None;
const BASICSIZE: usize;
const ITEMSIZE: usize = 0;
const UNHASHABLE: bool = false;
// due to restriction of rust trait system, object.__base__ is None
// but PyBaseObject::Base will be PyBaseObject.
type Base: PyClassDef;
}
pub trait PyClassImpl: PyClassDef {
const TP_FLAGS: PyTypeFlags = PyTypeFlags::DEFAULT;
fn extend_class(ctx: &Context, class: &'static Py<PyType>)
where
Self: Sized,
{
#[cfg(debug_assertions)]
{
assert!(class.slots.flags.is_created_with_flags());
}
let _ = ctx.intern_str(Self::NAME); // intern type name
if Self::TP_FLAGS.has_feature(PyTypeFlags::HAS_DICT) {
let __dict__ = identifier!(ctx, __dict__);
class.set_attr(
__dict__,
ctx.new_static_getset(
"__dict__",
class,
crate::builtins::object::object_get_dict,
crate::builtins::object::object_set_dict,
)
.into(),
);
}
Self::impl_extend_class(ctx, class);
if let Some(doc) = Self::DOC {
// Only set __doc__ if it doesn't already exist (e.g., as a member descriptor)
// This matches CPython's behavior in type_dict_set_doc
let doc_attr_name = identifier!(ctx, __doc__);
if class.attributes.read().get(doc_attr_name).is_none() {
class.set_attr(doc_attr_name, ctx.new_str(doc).into());
}
}
if let Some(module_name) = Self::MODULE_NAME {
class.set_attr(
identifier!(ctx, __module__),
ctx.new_str(module_name).into(),
);
}
// Don't add __new__ attribute if slot_new is inherited from object
// (Python doesn't add __new__ to __dict__ for inherited slots)
// Exception: object itself should have __new__ in its dict
if let Some(slot_new) = class.slots.new.load() {
let object_new = ctx.types.object_type.slots.new.load();
let is_object_itself = core::ptr::eq(class, ctx.types.object_type);
let is_inherited_from_object = !is_object_itself
&& object_new.is_some_and(|obj_new| slot_new as usize == obj_new as usize);
if !is_inherited_from_object {
let bound_new = Context::genesis().slot_new_wrapper.build_bound_method(
ctx,
class.to_owned().into(),
class,
);
class.set_attr(identifier!(ctx, __new__), bound_new.into());
}
}
// Add slot wrappers using SLOT_DEFS array
add_operators(class, ctx);
// Inherit slots from base types after slots are fully initialized
for base in class.bases.read().iter() {
class.inherit_slots(base);
}
class.extend_methods(class.slots.methods, ctx);
}
fn make_class(ctx: &Context) -> PyTypeRef
where
Self: StaticType + Sized,
{
(*Self::static_cell().get_or_init(|| {
let typ = Self::create_static_type();
Self::extend_class(ctx, unsafe {
// typ will be saved in static_cell
let r: &Py<PyType> = &typ;
let r: &'static Py<PyType> = core::mem::transmute(r);
r
});
typ
}))
.to_owned()
}
fn impl_extend_class(ctx: &Context, class: &'static Py<PyType>);
const METHOD_DEFS: &'static [PyMethodDef];
fn extend_slots(slots: &mut PyTypeSlots);
fn make_slots() -> PyTypeSlots {
let mut slots = PyTypeSlots {
flags: Self::TP_FLAGS,
name: Self::TP_NAME,
basicsize: Self::BASICSIZE,
itemsize: Self::ITEMSIZE,
doc: Self::DOC,
methods: Self::METHOD_DEFS,
..Default::default()
};
if Self::UNHASHABLE {
slots.hash.store(Some(hash_not_implemented));
}
Self::extend_slots(&mut slots);
slots
}
}
/// Trait for Python subclasses that can provide a reference to their base type.
///
/// This trait is automatically implemented by the `#[pyclass]` macro when
/// `base = SomeType` is specified. It provides safe reference access to the
/// base type's payload.
///
/// For subclasses with `#[repr(transparent)]`
/// which enables ownership transfer via `into_base()`.
pub trait PySubclass: crate::PyPayload {
type Base: crate::PyPayload;
/// Returns a reference to the base type's payload.
fn as_base(&self) -> &Self::Base;
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
RustPython/RustPython | https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/recursion.rs | crates/vm/src/recursion.rs | use crate::{AsObject, PyObject, VirtualMachine};
pub struct ReprGuard<'vm> {
vm: &'vm VirtualMachine,
id: usize,
}
/// A guard to protect repr methods from recursion into itself,
impl<'vm> ReprGuard<'vm> {
/// Returns None if the guard against 'obj' is still held otherwise returns the guard. The guard
/// which is released if dropped.
pub fn enter(vm: &'vm VirtualMachine, obj: &PyObject) -> Option<Self> {
let mut guards = vm.repr_guards.borrow_mut();
// Should this be a flag on the obj itself? putting it in a global variable for now until it
// decided the form of PyObject. https://github.com/RustPython/RustPython/issues/371
let id = obj.get_id();
if guards.contains(&id) {
return None;
}
guards.insert(id);
Some(ReprGuard { vm, id })
}
}
impl Drop for ReprGuard<'_> {
fn drop(&mut self) {
self.vm.repr_guards.borrow_mut().remove(&self.id);
}
}
| rust | MIT | e1b22f19e62d47485bdb55c9f3a4698221374f5b | 2026-01-04T15:39:39.834879Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.