pub use depyler_hir::trace_decision;
pub use depyler_hir::emit_decision;
pub use depyler_hir::transpile_error;
pub use depyler_hir::transpile_bail;
pub use depyler_hir::decision_trace;
pub use depyler_hir::error;
pub use depyler_hir::hir;
pub use depyler_hir::simplified_hir;
pub use depyler_lambda::lambda_codegen;
pub use depyler_lambda::lambda_errors;
pub use depyler_lambda::lambda_inference;
pub use depyler_lambda::lambda_optimizer;
pub use depyler_lambda::lambda_testing;
pub use depyler_lambda::lambda_types;
pub use depyler_analysis::annotation_aware_type_mapper;
pub use depyler_analysis::borrowing;
pub use depyler_analysis::borrowing_context;
pub use depyler_analysis::container_element_inference;
pub use depyler_analysis::borrowing_shim;
pub use depyler_analysis::const_generic_inference;
pub use depyler_analysis::depylint;
pub use depyler_analysis::error_reporting;
pub use depyler_analysis::escape_analysis;
pub use depyler_analysis::generator_state;
pub use depyler_analysis::generator_yield_analysis;
pub use depyler_analysis::generic_inference;
pub use depyler_analysis::inlining;
pub use depyler_analysis::lifetime_analysis;
pub use depyler_analysis::migration_suggestions;
pub use depyler_analysis::optimization;
pub use depyler_analysis::optimizer;
pub use depyler_analysis::param_type_inference;
pub use depyler_analysis::performance_warnings;
pub use depyler_analysis::profiling;
pub use depyler_analysis::scoring;
pub use depyler_analysis::string_optimization;
pub use depyler_analysis::type_hints;
pub use depyler_analysis::type_inference_telemetry;
pub use depyler_analysis::type_mapper;
pub use depyler_analysis::type_propagation;
pub use depyler_analysis::type_system;
pub use depyler_tooling::chaos;
pub use depyler_tooling::codegen_shim;
pub use depyler_tooling::debug;
pub use depyler_tooling::doctest_extractor;
pub use depyler_tooling::documentation;
pub use depyler_tooling::generative_repair;
pub use depyler_tooling::hunt_mode;
pub use depyler_tooling::ide;
pub use depyler_tooling::infrastructure;
pub use depyler_tooling::library_mapping;
pub use depyler_tooling::module_mapper;
pub use depyler_tooling::module_mapper_phf;
pub use depyler_tooling::pytest_extractor;
pub use depyler_tooling::stdlib_mappings;
pub use depyler_tooling::test_generation;
pub use depyler_tooling::typeshed_ingest;
pub mod ast_bridge;
pub mod diagnostic;
pub mod backend;
pub mod cargo_first;
pub mod cargo_toml_gen;
pub mod codegen;
pub mod direct_rules;
mod direct_rules_convert; pub mod lsp;
pub mod rust_gen;
pub mod union_enum_gen;
use anyhow::Result;
use serde::{Deserialize, Serialize};
pub use backend::{TranspilationBackend, TranspilationTarget, ValidationError};
pub use error::TranspileError;
pub use simplified_hir::{
Hir, HirBinaryOp, HirExpr, HirLiteral, HirParam, HirStatement, HirType, HirUnaryOp,
};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DepylerPipeline {
analyzer: CoreAnalyzer,
transpiler: DirectTranspiler,
#[serde(skip_serializing_if = "Option::is_none")]
verifier: Option<PropertyVerifier>,
#[serde(skip)]
#[allow(dead_code)]
mcp_client: LazyMcpClient,
#[serde(skip_serializing_if = "Option::is_none")]
debug_config: Option<debug::DebugConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoreAnalyzer {
pub metrics_enabled: bool,
pub type_inference_enabled: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DirectTranspiler {
pub type_mapper: type_mapper::TypeMapper,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PropertyVerifier {
pub enable_quickcheck: bool,
pub enable_contracts: bool,
}
#[derive(Debug, Clone, Default)]
pub struct LazyMcpClient {
#[allow(dead_code)]
endpoint: Option<String>,
}
pub trait AnalyzableStage {
type Input;
type Output;
type Metrics;
fn execute(&self, input: Self::Input) -> Result<(Self::Output, Self::Metrics)>;
fn validate(&self, output: &Self::Output) -> ValidationResult;
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationResult {
pub is_valid: bool,
pub errors: Vec<String>,
pub warnings: Vec<String>,
}
impl Default for DepylerPipeline {
fn default() -> Self {
Self::new()
}
}
impl DepylerPipeline {
pub fn new() -> Self {
Self {
analyzer: CoreAnalyzer {
metrics_enabled: true,
type_inference_enabled: true,
},
transpiler: DirectTranspiler {
type_mapper: type_mapper::TypeMapper::default(),
},
verifier: None,
mcp_client: LazyMcpClient::default(),
debug_config: None,
}
}
pub fn with_verification(mut self) -> Self {
self.verifier = Some(PropertyVerifier {
enable_quickcheck: true,
enable_contracts: true,
});
self
}
pub fn with_debug(mut self, debug_config: debug::DebugConfig) -> Self {
self.debug_config = Some(debug_config);
self
}
pub fn with_nasa_mode(mut self, enabled: bool) -> Self {
self.transpiler.type_mapper.nasa_mode = enabled;
self
}
pub fn transpile_with_dependencies(
&self,
python_source: &str,
) -> Result<(String, Vec<cargo_toml_gen::Dependency>)> {
let ast = self.parse_python(python_source)?;
let (mut hir, _type_env) = ast_bridge::AstBridge::new()
.with_source(python_source.to_string())
.python_to_hir(ast)?;
let mut const_inferencer = const_generic_inference::ConstGenericInferencer::new();
const_inferencer.analyze_module(&mut hir)?;
if self.analyzer.type_inference_enabled {
let mut type_hint_provider = type_hints::TypeHintProvider::new();
let mut function_hints = Vec::new();
for (idx, func) in hir.functions.iter().enumerate() {
if let Ok(hints) = type_hint_provider.analyze_function(func) {
if !hints.is_empty() {
eprintln!("Type inference hints:");
eprintln!("{}", type_hint_provider.format_hints(&hints));
function_hints.push((idx, hints));
}
}
}
for (func_idx, hints) in function_hints {
let func = &mut hir.functions[func_idx];
for param in &mut func.params {
if matches!(param.ty, hir::Type::Unknown) {
for hint in &hints {
if let type_hints::HintTarget::Parameter(hint_param) = &hint.target {
if hint_param == ¶m.name
&& matches!(
hint.confidence,
type_hints::Confidence::High
| type_hints::Confidence::Certain
)
{
param.ty = hint.suggested_type.clone();
eprintln!(
"Applied type hint: {} -> {:?}",
param.name, param.ty
);
break;
}
}
}
}
}
if matches!(func.ret_type, hir::Type::Unknown) {
for hint in &hints {
if matches!(hint.target, type_hints::HintTarget::Return)
&& matches!(
hint.confidence,
type_hints::Confidence::Medium
| type_hints::Confidence::High
| type_hints::Confidence::Certain
)
{
func.ret_type = hint.suggested_type.clone();
eprintln!("Applied return type hint: {:?}", func.ret_type);
break;
}
}
}
}
}
type_propagation::propagate_call_site_types(&mut hir);
{
use type_system::{ConstraintCollector, TypeConstraintSolver};
let mut collector = ConstraintCollector::new();
collector.collect_module(&hir);
let constraints = collector.constraints();
if !constraints.is_empty() {
let mut solver = TypeConstraintSolver::new();
for constraint in constraints {
solver.add_constraint(constraint.clone());
}
if let Ok(solution) = solver.solve() {
let applied = collector.apply_substitutions(&mut hir, &solution);
if applied > 0 {
eprintln!("HM inference: applied {} type substitutions", applied);
}
}
}
}
if let Err(e) = type_system::unify_module_types(&mut hir) {
eprintln!("Type unification warning: {:?}", e);
}
optimization::optimize_module(&mut hir);
let hir_program = hir::HirProgram {
functions: hir.functions,
classes: hir.classes,
imports: hir.imports,
};
let mut optimizer = optimizer::Optimizer::new(optimizer::OptimizerConfig::default());
let optimized_program = optimizer.optimize_program(hir_program.clone());
if self.analyzer.metrics_enabled {
let mut migration_analyzer = migration_suggestions::MigrationAnalyzer::new(
migration_suggestions::MigrationConfig::default(),
);
let suggestions = migration_analyzer.analyze_program(&hir_program);
if !suggestions.is_empty() {
eprintln!("{}", migration_analyzer.format_suggestions(&suggestions));
}
}
if self.analyzer.metrics_enabled {
let mut perf_analyzer = performance_warnings::PerformanceAnalyzer::new(
performance_warnings::PerformanceConfig::default(),
);
let warnings = perf_analyzer.analyze_program(&hir_program);
if !warnings.is_empty() {
eprintln!("{}", perf_analyzer.format_warnings(&warnings));
}
}
if self.analyzer.metrics_enabled {
let mut profiler = profiling::Profiler::new(profiling::ProfileConfig::default());
let profile_report = profiler.analyze_program(&hir_program);
if !profile_report.metrics.is_empty() {
eprintln!("{}", profile_report.format_report());
}
}
let optimized_hir = hir::HirModule {
functions: optimized_program.functions,
imports: optimized_program.imports,
type_aliases: hir.type_aliases,
protocols: hir.protocols,
classes: optimized_program.classes,
constants: hir.constants,
top_level_stmts: hir.top_level_stmts, };
rust_gen::generate_rust_file(&optimized_hir, &self.transpiler.type_mapper)
}
pub fn transpile(&self, python_source: &str) -> Result<String> {
let ast = self.parse_python(python_source)?;
let (mut hir, _type_env) = ast_bridge::AstBridge::new()
.with_source(python_source.to_string())
.python_to_hir(ast)?;
let mut const_inferencer = const_generic_inference::ConstGenericInferencer::new();
const_inferencer.analyze_module(&mut hir)?;
if self.analyzer.type_inference_enabled {
let mut type_hint_provider = type_hints::TypeHintProvider::new();
let mut function_hints = Vec::new();
for (idx, func) in hir.functions.iter().enumerate() {
if let Ok(hints) = type_hint_provider.analyze_function(func) {
if !hints.is_empty() {
eprintln!("Type inference hints:");
eprintln!("{}", type_hint_provider.format_hints(&hints));
function_hints.push((idx, hints));
}
}
}
for (func_idx, hints) in function_hints {
let func = &mut hir.functions[func_idx];
for param in &mut func.params {
if matches!(param.ty, hir::Type::Unknown) {
for hint in &hints {
if let type_hints::HintTarget::Parameter(hint_param) = &hint.target {
if hint_param == ¶m.name
&& matches!(
hint.confidence,
type_hints::Confidence::High
| type_hints::Confidence::Certain
)
{
param.ty = hint.suggested_type.clone();
eprintln!(
"Applied type hint: {} -> {:?}",
param.name, param.ty
);
break;
}
}
}
}
}
if matches!(func.ret_type, hir::Type::Unknown) {
for hint in &hints {
if matches!(hint.target, type_hints::HintTarget::Return)
&& matches!(
hint.confidence,
type_hints::Confidence::Medium
| type_hints::Confidence::High
| type_hints::Confidence::Certain
)
{
func.ret_type = hint.suggested_type.clone();
eprintln!("Applied return type hint: {:?}", func.ret_type);
break;
}
}
}
}
}
type_propagation::propagate_call_site_types(&mut hir);
{
use type_system::{ConstraintCollector, TypeConstraintSolver};
let mut collector = ConstraintCollector::new();
collector.collect_module(&hir);
let constraints = collector.constraints();
if !constraints.is_empty() {
let mut solver = TypeConstraintSolver::new();
for constraint in constraints {
solver.add_constraint(constraint.clone());
}
if let Ok(solution) = solver.solve() {
let applied = collector.apply_substitutions(&mut hir, &solution);
if applied > 0 {
eprintln!("HM inference: applied {} type substitutions", applied);
}
}
}
}
if let Err(e) = type_system::unify_module_types(&mut hir) {
eprintln!("Type unification warning: {:?}", e);
}
optimization::optimize_module(&mut hir);
let hir_program = hir::HirProgram {
functions: hir.functions,
classes: hir.classes,
imports: hir.imports,
};
let mut optimizer = optimizer::Optimizer::new(optimizer::OptimizerConfig::default());
let optimized_program = optimizer.optimize_program(hir_program.clone());
if self.analyzer.metrics_enabled {
let mut migration_analyzer = migration_suggestions::MigrationAnalyzer::new(
migration_suggestions::MigrationConfig::default(),
);
let suggestions = migration_analyzer.analyze_program(&hir_program);
if !suggestions.is_empty() {
eprintln!("{}", migration_analyzer.format_suggestions(&suggestions));
}
}
if self.analyzer.metrics_enabled {
let mut perf_analyzer = performance_warnings::PerformanceAnalyzer::new(
performance_warnings::PerformanceConfig::default(),
);
let warnings = perf_analyzer.analyze_program(&hir_program);
if !warnings.is_empty() {
eprintln!("{}", perf_analyzer.format_warnings(&warnings));
}
}
if self.analyzer.metrics_enabled {
let mut profiler = profiling::Profiler::new(profiling::ProfileConfig::default());
let profile_report = profiler.analyze_program(&hir_program);
if !profile_report.metrics.is_empty() {
eprintln!("{}", profile_report.format_report());
}
}
let optimized_hir = hir::HirModule {
functions: optimized_program.functions,
imports: optimized_program.imports,
type_aliases: hir.type_aliases,
protocols: hir.protocols,
classes: optimized_program.classes,
constants: hir.constants,
top_level_stmts: hir.top_level_stmts, };
let (rust_code, _dependencies) =
rust_gen::generate_rust_file(&optimized_hir, &self.transpiler.type_mapper)?;
Ok(rust_code)
}
pub fn transpile_with_constraints_and_dependencies(
&self,
python_source: &str,
type_constraints: &std::collections::HashMap<String, String>,
) -> Result<(String, Vec<cargo_toml_gen::Dependency>)> {
let type_overrides: std::collections::HashMap<String, hir::Type> = type_constraints
.iter()
.map(|(var, ty_str)| (var.clone(), rust_gen::rust_type_string_to_hir(ty_str)))
.collect();
let ast = self.parse_python(python_source)?;
let (mut hir, _type_env) = ast_bridge::AstBridge::new()
.with_source(python_source.to_string())
.python_to_hir(ast)?;
for func in &mut hir.functions {
if let Some(override_type) = type_overrides.get(&func.name) {
if !matches!(override_type, hir::Type::Unknown) {
eprintln!(
"DEPYLER-1101: Overriding return type of {} to {:?}",
func.name, override_type
);
func.ret_type = override_type.clone();
}
}
for param in func.params.iter_mut() {
if let Some(override_type) = type_overrides.get(¶m.name) {
if !matches!(override_type, hir::Type::Unknown) {
eprintln!(
"DEPYLER-1101: Overriding param {} type to {:?}",
param.name, override_type
);
param.ty = override_type.clone();
}
}
}
}
let mut const_inferencer = const_generic_inference::ConstGenericInferencer::new();
const_inferencer.analyze_module(&mut hir)?;
if self.analyzer.type_inference_enabled {
let mut type_hint_provider = type_hints::TypeHintProvider::new();
let mut function_hints: Vec<(usize, Vec<type_hints::TypeHint>)> = Vec::new();
for (idx, func) in hir.functions.iter().enumerate() {
if let Ok(hints) = type_hint_provider.analyze_function(func) {
if !hints.is_empty() {
function_hints.push((idx, hints));
}
}
}
for (func_idx, hints) in function_hints {
let func = &mut hir.functions[func_idx];
for param in &mut func.params {
if matches!(param.ty, hir::Type::Unknown)
&& !type_overrides.contains_key(¶m.name)
{
for hint in &hints {
if let type_hints::HintTarget::Parameter(hint_param) = &hint.target {
if hint_param == ¶m.name
&& matches!(
hint.confidence,
type_hints::Confidence::High
| type_hints::Confidence::Certain
)
{
param.ty = hint.suggested_type.clone();
break;
}
}
}
}
}
}
}
type_propagation::propagate_call_site_types(&mut hir);
{
use type_system::{ConstraintCollector, TypeConstraintSolver};
let mut collector = ConstraintCollector::new();
collector.collect_module(&hir);
let constraints = collector.constraints();
if !constraints.is_empty() {
let mut solver = TypeConstraintSolver::new();
for constraint in constraints {
solver.add_constraint(constraint.clone());
}
if let Ok(solution) = solver.solve() {
let _applied = collector.apply_substitutions(&mut hir, &solution);
}
}
}
if let Err(e) = type_system::unify_module_types(&mut hir) {
eprintln!("Type unification warning: {:?}", e);
}
optimization::optimize_module(&mut hir);
rust_gen::generate_rust_file_with_overrides(
&hir,
&self.transpiler.type_mapper,
type_overrides,
)
}
pub fn transpile_with_constraints(
&self,
python_source: &str,
type_constraints: &std::collections::HashMap<String, String>,
) -> Result<String> {
let type_overrides: std::collections::HashMap<String, hir::Type> = type_constraints
.iter()
.map(|(var, ty_str)| (var.clone(), rust_gen::rust_type_string_to_hir(ty_str)))
.collect();
let ast = self.parse_python(python_source)?;
let (mut hir, _type_env) = ast_bridge::AstBridge::new()
.with_source(python_source.to_string())
.python_to_hir(ast)?;
for func in &mut hir.functions {
if let Some(override_type) = type_overrides.get(&func.name) {
if !matches!(override_type, hir::Type::Unknown) {
eprintln!(
"DEPYLER-1101: Overriding return type of {} to {:?}",
func.name, override_type
);
func.ret_type = override_type.clone();
}
}
for param in func.params.iter_mut() {
if let Some(override_type) = type_overrides.get(¶m.name) {
if !matches!(override_type, hir::Type::Unknown) {
eprintln!(
"DEPYLER-1101: Overriding param {} type to {:?}",
param.name, override_type
);
param.ty = override_type.clone();
}
}
}
}
let mut const_inferencer = const_generic_inference::ConstGenericInferencer::new();
const_inferencer.analyze_module(&mut hir)?;
if self.analyzer.type_inference_enabled {
let mut type_hint_provider = type_hints::TypeHintProvider::new();
let mut function_hints: Vec<(usize, Vec<type_hints::TypeHint>)> = Vec::new();
for (idx, func) in hir.functions.iter().enumerate() {
if let Ok(hints) = type_hint_provider.analyze_function(func) {
if !hints.is_empty() {
function_hints.push((idx, hints));
}
}
}
for (func_idx, hints) in function_hints {
let func = &mut hir.functions[func_idx];
for param in &mut func.params {
if matches!(param.ty, hir::Type::Unknown)
&& !type_overrides.contains_key(¶m.name)
{
for hint in &hints {
if let type_hints::HintTarget::Parameter(hint_param) = &hint.target {
if hint_param == ¶m.name
&& matches!(
hint.confidence,
type_hints::Confidence::High
| type_hints::Confidence::Certain
)
{
param.ty = hint.suggested_type.clone();
break;
}
}
}
}
}
}
}
type_propagation::propagate_call_site_types(&mut hir);
{
use type_system::{ConstraintCollector, TypeConstraintSolver};
let mut collector = ConstraintCollector::new();
collector.collect_module(&hir);
let constraints = collector.constraints();
if !constraints.is_empty() {
let mut solver = TypeConstraintSolver::new();
for constraint in constraints {
solver.add_constraint(constraint.clone());
}
if let Ok(solution) = solver.solve() {
let _applied = collector.apply_substitutions(&mut hir, &solution);
}
}
}
if let Err(e) = type_system::unify_module_types(&mut hir) {
eprintln!("Type unification warning: {:?}", e);
}
optimization::optimize_module(&mut hir);
let (rust_code, _dependencies) = rust_gen::generate_rust_file_with_overrides(
&hir,
&self.transpiler.type_mapper,
type_overrides,
)?;
Ok(rust_code)
}
pub fn parse_to_hir(&self, source: &str) -> Result<hir::HirModule> {
let ast = self.parse_python(source)?;
let (hir, _type_env) = ast_bridge::AstBridge::new()
.with_source(source.to_string())
.python_to_hir(ast)?;
Ok(hir)
}
pub fn analyze_to_typed_hir(&self, source: &str) -> Result<hir::HirModule> {
self.parse_to_hir(source)
}
pub fn parse_python(&self, source: &str) -> Result<rustpython_ast::Mod> {
use rustpython_ast::Suite;
use rustpython_parser::Parse;
let statements = Suite::parse(source, "<input>")
.map_err(|e| anyhow::anyhow!("Python parse error: {}", e))?;
Ok(rustpython_ast::Mod::Module(rustpython_ast::ModModule {
body: statements,
type_ignores: vec![],
range: Default::default(),
}))
}
}
#[derive(Debug, Clone, Default)]
pub struct Config {
pub enable_verification: bool,
pub enable_metrics: bool,
pub optimization_level: OptimizationLevel,
}
#[derive(Debug, Clone, Default)]
pub enum OptimizationLevel {
#[default]
Debug,
Release,
Size,
}
impl DepylerPipeline {
pub fn new_with_config(config: Config) -> Self {
let mut pipeline = Self::new();
pipeline.analyzer.metrics_enabled = config.enable_metrics;
if config.enable_verification {
pipeline = pipeline.with_verification();
}
pipeline
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pipeline_creation() {
let pipeline = DepylerPipeline::new();
assert!(pipeline.analyzer.metrics_enabled);
assert!(pipeline.analyzer.type_inference_enabled);
assert!(pipeline.verifier.is_none());
}
#[test]
fn test_pipeline_with_verification() {
let pipeline = DepylerPipeline::new().with_verification();
assert!(pipeline.verifier.is_some());
let verifier = pipeline.verifier.unwrap();
assert!(verifier.enable_quickcheck);
assert!(verifier.enable_contracts);
}
#[test]
fn test_config_creation() {
let config = Config {
enable_verification: true,
enable_metrics: false,
optimization_level: OptimizationLevel::Release,
};
let pipeline = DepylerPipeline::new_with_config(config);
assert!(pipeline.verifier.is_some());
assert!(!pipeline.analyzer.metrics_enabled);
}
#[test]
fn test_simple_transpilation() {
let pipeline = DepylerPipeline::new();
let python_code = r#"
def add(a: int, b: int) -> int:
return a + b
"#;
let result = pipeline.transpile(python_code);
assert!(result.is_ok());
let rust_code = result.unwrap();
assert!(rust_code.contains("pub fn add"));
assert!(rust_code.contains("i32"));
}
#[test]
fn test_parse_to_hir() {
let pipeline = DepylerPipeline::new();
let python_code = r#"
def test_func(x: int) -> str:
return "hello"
"#;
let hir = pipeline.parse_to_hir(python_code).unwrap();
assert_eq!(hir.functions.len(), 1);
assert_eq!(hir.functions[0].name, "test_func");
assert_eq!(hir.functions[0].params[0].name, "x");
assert_eq!(hir.functions[0].params[0].ty, hir::Type::Int);
assert_eq!(hir.functions[0].ret_type, hir::Type::String);
}
#[test]
fn test_validation_result() {
let result = ValidationResult {
is_valid: true,
errors: vec![],
warnings: vec!["Warning message".to_string()],
};
assert!(result.is_valid);
assert!(result.errors.is_empty());
assert_eq!(result.warnings.len(), 1);
}
#[test]
fn test_invalid_python_syntax() {
let pipeline = DepylerPipeline::new();
let invalid_python = "def invalid_syntax(\n return";
let result = pipeline.transpile(invalid_python);
assert!(result.is_err());
}
#[test]
fn test_analyzable_stage_trait() {
struct TestStage;
impl AnalyzableStage for TestStage {
type Input = String;
type Output = String;
type Metrics = usize;
fn execute(&self, input: Self::Input) -> Result<(Self::Output, Self::Metrics)> {
Ok((input.clone(), input.len()))
}
fn validate(&self, _output: &Self::Output) -> ValidationResult {
ValidationResult {
is_valid: true,
errors: vec![],
warnings: vec![],
}
}
}
let stage = TestStage;
let (output, metrics) = stage.execute("test".to_string()).unwrap();
assert_eq!(output, "test");
assert_eq!(metrics, 4);
let validation = stage.validate(&output);
assert!(validation.is_valid);
}
#[test]
fn test_complex_function_transpilation() {
let pipeline = DepylerPipeline::new();
let python_code = r#"
def fibonacci(n: int) -> int:
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
"#;
let result = pipeline.transpile(python_code);
assert!(result.is_ok());
let rust_code = result.unwrap();
assert!(rust_code.contains("fibonacci"));
assert!(rust_code.contains("if"));
assert!(rust_code.contains("return"));
}
#[test]
fn test_type_annotations() {
let pipeline = DepylerPipeline::new();
let python_code = r#"
from typing import List, Optional
def process_list(items: List[str]) -> Optional[str]:
if items:
return items[0]
return None
"#;
let hir = pipeline.parse_to_hir(python_code).unwrap();
assert_eq!(hir.functions.len(), 1);
let func = &hir.functions[0];
assert_eq!(
func.params[0].ty,
hir::Type::List(Box::new(hir::Type::String))
);
assert_eq!(
func.ret_type,
hir::Type::Optional(Box::new(hir::Type::String))
);
}
#[test]
fn test_annotation_aware_transpilation() {
let pipeline = DepylerPipeline::new();
let python_code = r#"
# @depyler: optimization_level = "aggressive"
# @depyler: thread_safety = "required"
# @depyler: bounds_checking = "explicit"
def compute_sum(numbers: List[int]) -> int:
total = 0
for num in numbers:
total += num
return total
"#;
let hir = pipeline.parse_to_hir(python_code).unwrap();
let func = &hir.functions[0];
assert_eq!(
func.annotations.optimization_level,
depyler_annotations::OptimizationLevel::Aggressive
);
assert_eq!(
func.annotations.thread_safety,
depyler_annotations::ThreadSafety::Required
);
assert_eq!(
func.annotations.bounds_checking,
depyler_annotations::BoundsChecking::Explicit
);
let rust_code = pipeline.transpile(python_code).unwrap();
assert!(rust_code.contains("compute_sum"));
}
#[test]
fn test_string_strategy_annotation() {
let pipeline = DepylerPipeline::new();
let python_code = r#"
# @depyler: string_strategy = "zero_copy"
# @depyler: ownership = "borrowed"
def process_string(s: str) -> str:
return s
"#;
let hir = pipeline.parse_to_hir(python_code).unwrap();
let func = &hir.functions[0];
assert_eq!(
func.annotations.string_strategy,
depyler_annotations::StringStrategy::ZeroCopy
);
assert_eq!(
func.annotations.ownership_model,
depyler_annotations::OwnershipModel::Borrowed
);
let rust_code = pipeline.transpile(python_code).unwrap();
assert!(rust_code.contains("process_string"));
}
#[test]
fn test_hash_strategy_annotation() {
let pipeline = DepylerPipeline::new();
let python_code = r#"
# @depyler: hash_strategy = "fnv"
def create_map() -> Dict[str, int]:
# Dictionary subscript assignment requires more complex AST transformation
# For now, just test that the annotation is parsed correctly
return {}
"#;
let hir = pipeline.parse_to_hir(python_code).unwrap();
let func = &hir.functions[0];
assert_eq!(
func.annotations.hash_strategy,
depyler_annotations::HashStrategy::Fnv
);
}
#[test]
fn test_lazy_mcp_client_default() {
let client = LazyMcpClient::default();
assert!(client.endpoint.is_none());
}
#[test]
fn test_lazy_mcp_client_debug() {
let client = LazyMcpClient::default();
let debug_str = format!("{:?}", client);
assert!(debug_str.contains("LazyMcpClient"));
}
#[test]
fn test_optimization_level_debug() {
assert_eq!(format!("{:?}", OptimizationLevel::Debug), "Debug");
assert_eq!(format!("{:?}", OptimizationLevel::Release), "Release");
assert_eq!(format!("{:?}", OptimizationLevel::Size), "Size");
}
#[test]
fn test_optimization_level_default() {
let level: OptimizationLevel = Default::default();
assert!(matches!(level, OptimizationLevel::Debug));
}
#[test]
fn test_optimization_level_clone() {
let level = OptimizationLevel::Release;
let cloned = level.clone();
assert!(matches!(cloned, OptimizationLevel::Release));
}
#[test]
fn test_config_default() {
let config: Config = Default::default();
assert!(!config.enable_verification);
assert!(!config.enable_metrics);
assert!(matches!(
config.optimization_level,
OptimizationLevel::Debug
));
}
#[test]
fn test_config_debug() {
let config = Config {
enable_verification: true,
enable_metrics: true,
optimization_level: OptimizationLevel::Size,
};
let debug_str = format!("{:?}", config);
assert!(debug_str.contains("Config"));
assert!(debug_str.contains("enable_verification"));
}
#[test]
fn test_config_clone() {
let config = Config {
enable_verification: true,
enable_metrics: false,
optimization_level: OptimizationLevel::Release,
};
let cloned = config.clone();
assert!(cloned.enable_verification);
assert!(!cloned.enable_metrics);
}
#[test]
fn test_core_analyzer_debug() {
let analyzer = CoreAnalyzer {
metrics_enabled: true,
type_inference_enabled: false,
};
let debug_str = format!("{:?}", analyzer);
assert!(debug_str.contains("CoreAnalyzer"));
assert!(debug_str.contains("metrics_enabled"));
}
#[test]
fn test_core_analyzer_clone() {
let analyzer = CoreAnalyzer {
metrics_enabled: false,
type_inference_enabled: true,
};
let cloned = analyzer.clone();
assert!(!cloned.metrics_enabled);
assert!(cloned.type_inference_enabled);
}
#[test]
fn test_direct_transpiler_debug() {
let transpiler = DirectTranspiler {
type_mapper: type_mapper::TypeMapper::default(),
};
let debug_str = format!("{:?}", transpiler);
assert!(debug_str.contains("DirectTranspiler"));
}
#[test]
fn test_direct_transpiler_clone() {
let transpiler = DirectTranspiler {
type_mapper: type_mapper::TypeMapper::default(),
};
let _cloned = transpiler.clone();
}
#[test]
fn test_property_verifier_debug() {
let verifier = PropertyVerifier {
enable_quickcheck: true,
enable_contracts: false,
};
let debug_str = format!("{:?}", verifier);
assert!(debug_str.contains("PropertyVerifier"));
assert!(debug_str.contains("enable_quickcheck"));
}
#[test]
fn test_property_verifier_clone() {
let verifier = PropertyVerifier {
enable_quickcheck: false,
enable_contracts: true,
};
let cloned = verifier.clone();
assert!(!cloned.enable_quickcheck);
assert!(cloned.enable_contracts);
}
#[test]
fn test_validation_result_debug() {
let result = ValidationResult {
is_valid: false,
errors: vec!["error1".to_string()],
warnings: vec![],
};
let debug_str = format!("{:?}", result);
assert!(debug_str.contains("ValidationResult"));
assert!(debug_str.contains("error1"));
}
#[test]
fn test_validation_result_clone() {
let result = ValidationResult {
is_valid: true,
errors: vec![],
warnings: vec!["warn".to_string()],
};
let cloned = result.clone();
assert!(cloned.is_valid);
assert_eq!(cloned.warnings.len(), 1);
}
#[test]
fn test_pipeline_with_debug() {
let debug_config = debug::DebugConfig::default();
let pipeline = DepylerPipeline::new().with_debug(debug_config);
assert!(pipeline.debug_config.is_some());
}
#[test]
fn test_pipeline_debug_impl() {
let pipeline = DepylerPipeline::new();
let debug_str = format!("{:?}", pipeline);
assert!(debug_str.contains("DepylerPipeline"));
assert!(debug_str.contains("analyzer"));
}
#[test]
fn test_pipeline_clone() {
let pipeline = DepylerPipeline::new().with_verification();
let cloned = pipeline.clone();
assert!(cloned.verifier.is_some());
}
#[test]
fn test_transpile_with_dependencies() {
let pipeline = DepylerPipeline::new();
let python_code = r#"
def greet(name: str) -> str:
return "Hello, " + name
"#;
let result = pipeline.transpile_with_dependencies(python_code);
assert!(result.is_ok());
let (rust_code, dependencies) = result.unwrap();
assert!(rust_code.contains("pub fn greet"));
assert!(dependencies.is_empty() || !dependencies.is_empty());
}
#[test]
fn test_transpile_with_dependencies_error() {
let pipeline = DepylerPipeline::new();
let invalid_python = "def broken(";
let result = pipeline.transpile_with_dependencies(invalid_python);
assert!(result.is_err());
}
#[test]
fn test_analyze_to_typed_hir() {
let pipeline = DepylerPipeline::new();
let python_code = r#"
def double(x: int) -> int:
return x * 2
"#;
let hir = pipeline.analyze_to_typed_hir(python_code).unwrap();
assert_eq!(hir.functions.len(), 1);
assert_eq!(hir.functions[0].name, "double");
}
#[test]
fn test_parse_python_directly() {
let pipeline = DepylerPipeline::new();
let result = pipeline.parse_python("x = 42");
assert!(result.is_ok());
}
#[test]
fn test_parse_python_error() {
let pipeline = DepylerPipeline::new();
let result = pipeline.parse_python("def incomplete(");
assert!(result.is_err());
let err = result.unwrap_err();
assert!(err.to_string().contains("parse error"));
}
#[test]
fn test_pipeline_serialization() {
let pipeline = DepylerPipeline::new().with_verification();
let json = serde_json::to_string(&pipeline).unwrap();
assert!(json.contains("analyzer"));
assert!(json.contains("transpiler"));
assert!(json.contains("verifier"));
}
#[test]
fn test_pipeline_deserialization() {
let json = r#"{
"analyzer": {"metrics_enabled": false, "type_inference_enabled": true},
"transpiler": {"type_mapper": {"width_preference": "I32", "string_type": "AlwaysOwned"}},
"verifier": {"enable_quickcheck": true, "enable_contracts": false}
}"#;
let pipeline: DepylerPipeline = serde_json::from_str(json).unwrap();
assert!(!pipeline.analyzer.metrics_enabled);
assert!(pipeline.analyzer.type_inference_enabled);
assert!(pipeline.verifier.is_some());
}
#[test]
fn test_validation_result_with_errors_and_warnings() {
let result = ValidationResult {
is_valid: false,
errors: vec!["err1".to_string(), "err2".to_string()],
warnings: vec!["warn1".to_string()],
};
assert!(!result.is_valid);
assert_eq!(result.errors.len(), 2);
assert_eq!(result.warnings.len(), 1);
}
#[test]
fn test_config_with_all_levels() {
let debug_config = Config {
enable_verification: false,
enable_metrics: false,
optimization_level: OptimizationLevel::Debug,
};
let _pipeline = DepylerPipeline::new_with_config(debug_config);
let size_config = Config {
enable_verification: true,
enable_metrics: true,
optimization_level: OptimizationLevel::Size,
};
let pipeline = DepylerPipeline::new_with_config(size_config);
assert!(pipeline.analyzer.metrics_enabled);
assert!(pipeline.verifier.is_some());
}
#[test]
fn test_pipeline_default_trait() {
let pipeline: DepylerPipeline = Default::default();
assert!(pipeline.analyzer.metrics_enabled);
assert!(pipeline.verifier.is_none());
}
#[test]
fn test_empty_python_transpilation() {
let pipeline = DepylerPipeline::new();
let result = pipeline.transpile("");
assert!(result.is_ok());
}
#[test]
fn test_transpile_multiple_functions() {
let pipeline = DepylerPipeline::new();
let python_code = r#"
def add(a: int, b: int) -> int:
return a + b
def subtract(a: int, b: int) -> int:
return a - b
"#;
let result = pipeline.transpile(python_code);
assert!(result.is_ok());
let rust_code = result.unwrap();
assert!(rust_code.contains("pub fn add"));
assert!(rust_code.contains("pub fn subtract"));
}
fn transpile_ok(code: &str) -> bool {
DepylerPipeline::new().transpile(code).is_ok()
}
#[test]
fn test_99mode_try_except_basic() {
assert!(transpile_ok(
r#"
def f(s: str) -> int:
try:
return int(s)
except ValueError:
return 0
"#
));
}
#[test]
fn test_99mode_try_except_with_binding() {
assert!(transpile_ok(
r#"
def f(s: str) -> int:
try:
return int(s)
except ValueError as e:
return -1
"#
));
}
#[test]
fn test_99mode_try_except_multiple_handlers() {
assert!(transpile_ok(
r#"
def f(s: str) -> int:
try:
return int(s)
except ValueError:
return -1
except TypeError:
return -2
"#
));
}
#[test]
fn test_99mode_try_finally() {
assert!(transpile_ok(
r#"
def f(x: int) -> int:
result = 0
try:
result = x * 2
finally:
result = result + 1
return result
"#
));
}
#[test]
fn test_99mode_try_except_finally() {
assert!(transpile_ok(
r#"
def f(s: str) -> int:
result = 0
try:
result = int(s)
except ValueError:
result = -1
finally:
result = result + 1
return result
"#
));
}
#[test]
fn test_99mode_try_except_return_literal() {
assert!(transpile_ok(
r#"
def f() -> int:
try:
return 42
except Exception:
return 0
"#
));
}
#[test]
fn test_99mode_try_except_return_negation() {
assert!(transpile_ok(
r#"
def f() -> int:
try:
return -42
except Exception:
return 0
"#
));
}
#[test]
fn test_99mode_nested_function_basic() {
assert!(transpile_ok(
r#"
def outer(x: int) -> int:
def inner(y: int) -> int:
return y + 1
return inner(x)
"#
));
}
#[test]
fn test_99mode_nested_function_captures_outer() {
assert!(transpile_ok(
r#"
def outer(x: int) -> int:
factor = 2
def inner(y: int) -> int:
return y * factor
return inner(x)
"#
));
}
#[test]
fn test_99mode_augmented_assign_all() {
assert!(transpile_ok(
r#"
def f(x: int) -> int:
x += 1
x -= 2
x *= 3
x //= 2
return x
"#
));
}
#[test]
fn test_99mode_augmented_assign_mod_pow() {
assert!(transpile_ok(
r#"
def f(x: int) -> int:
x %= 5
x **= 2
return x
"#
));
}
#[test]
fn test_99mode_augmented_assign_bitwise() {
assert!(transpile_ok(
r#"
def f(x: int) -> int:
x &= 0xFF
x |= 0x01
x ^= 0x10
x >>= 1
x <<= 2
return x
"#
));
}
#[test]
fn test_99mode_while_with_break() {
assert!(transpile_ok(
r#"
def f(n: int) -> int:
i = 0
while i < n:
if i > 10:
break
i += 1
return i
"#
));
}
#[test]
fn test_99mode_while_with_continue() {
assert!(transpile_ok(
r#"
def f(n: int) -> int:
total = 0
i = 0
while i < n:
i += 1
if i % 2 == 0:
continue
total += i
return total
"#
));
}
#[test]
fn test_99mode_for_with_enumerate() {
assert!(transpile_ok(
r#"
def f(items: list) -> int:
total = 0
for i, item in enumerate(items):
total += i
return total
"#
));
}
#[test]
fn test_99mode_for_with_zip() {
assert!(transpile_ok(
r#"
def f(a: list, b: list) -> list:
result = []
for x, y in zip(a, b):
result.append(x + y)
return result
"#
));
}
#[test]
fn test_99mode_assert_statement() {
assert!(transpile_ok(
r#"
def f(x: int) -> int:
assert x > 0
assert x < 100, "x must be less than 100"
return x
"#
));
}
#[test]
fn test_99mode_multiple_assignment_targets() {
assert!(transpile_ok(
r#"
def f() -> int:
x, y = 1, 2
a, b, c = 10, 20, 30
return x + y + a + b + c
"#
));
}
#[test]
fn test_99mode_global_constant() {
assert!(transpile_ok(
r#"
MAX_SIZE = 100
def f() -> int:
return MAX_SIZE
"#
));
}
#[test]
fn test_99mode_list_comprehension() {
assert!(transpile_ok(
r#"
def f(n: int) -> list:
return [x * 2 for x in range(n)]
"#
));
}
#[test]
fn test_99mode_list_comprehension_with_filter() {
assert!(transpile_ok(
r#"
def f(n: int) -> list:
return [x for x in range(n) if x % 2 == 0]
"#
));
}
#[test]
fn test_99mode_dict_comprehension() {
assert!(transpile_ok(
r#"
def f(n: int) -> dict:
return {str(i): i * i for i in range(n)}
"#
));
}
#[test]
fn test_99mode_ternary_expression() {
assert!(transpile_ok(
r#"
def f(x: int) -> str:
return "positive" if x > 0 else "non-positive"
"#
));
}
#[test]
fn test_99mode_nested_ternary() {
assert!(transpile_ok(
r#"
def f(x: int) -> str:
return "positive" if x > 0 else "zero" if x == 0 else "negative"
"#
));
}
#[test]
fn test_99mode_fstring() {
assert!(transpile_ok(
r#"
def f(name: str, age: int) -> str:
return f"Hello {name}, you are {age} years old"
"#
));
}
#[test]
fn test_99mode_fstring_with_expressions() {
assert!(transpile_ok(
r#"
def f(x: int) -> str:
return f"Result: {x * 2 + 1}"
"#
));
}
#[test]
fn test_99mode_lambda_expression() {
assert!(transpile_ok(
r#"
def f(items: list) -> list:
return sorted(items, key=lambda x: x)
"#
));
}
#[test]
fn test_99mode_chained_comparison() {
assert!(transpile_ok(
r#"
def f(x: int) -> bool:
return 0 < x < 100
"#
));
}
#[test]
fn test_99mode_boolean_operators() {
assert!(transpile_ok(
r#"
def f(a: bool, b: bool, c: bool) -> bool:
return a and b or not c
"#
));
}
#[test]
fn test_99mode_string_multiply() {
assert!(transpile_ok(
r#"
def f(s: str, n: int) -> str:
return s * n
"#
));
}
#[test]
fn test_99mode_unary_operators() {
assert!(transpile_ok(
r#"
def f(x: int) -> int:
return -x + (~x)
"#
));
}
#[test]
fn test_99mode_subscript_access() {
assert!(transpile_ok(
r#"
def f(items: list) -> int:
return items[0] + items[-1]
"#
));
}
#[test]
fn test_99mode_slice_expression() {
assert!(transpile_ok(
r#"
def f(items: list) -> list:
return items[1:3]
"#
));
}
#[test]
fn test_99mode_dict_literal() {
assert!(transpile_ok(
r#"
def f() -> dict:
return {"a": 1, "b": 2, "c": 3}
"#
));
}
#[test]
fn test_99mode_set_literal() {
assert!(transpile_ok(
r#"
def f() -> set:
return {1, 2, 3, 4, 5}
"#
));
}
#[test]
fn test_99mode_tuple_literal() {
assert!(transpile_ok(
r#"
def f() -> tuple:
return (1, 2, 3)
"#
));
}
#[test]
fn test_99mode_str_methods_comprehensive() {
assert!(transpile_ok(
r#"
def f(s: str) -> str:
return s.upper().lower().strip()
"#
));
}
#[test]
fn test_99mode_str_split_join() {
assert!(transpile_ok(
r#"
def f(s: str) -> str:
parts = s.split(",")
return " ".join(parts)
"#
));
}
#[test]
fn test_99mode_str_replace() {
assert!(transpile_ok(
r#"
def f(s: str) -> str:
return s.replace("old", "new")
"#
));
}
#[test]
fn test_99mode_str_find_startswith() {
assert!(transpile_ok(
r#"
def f(s: str) -> bool:
return s.startswith("hello") or s.endswith("world")
"#
));
}
#[test]
fn test_99mode_list_methods() {
assert!(transpile_ok(
r#"
def f() -> list:
items = [3, 1, 2]
items.append(4)
items.sort()
items.reverse()
return items
"#
));
}
#[test]
fn test_99mode_list_extend_insert() {
assert!(transpile_ok(
r#"
def f() -> list:
items = [1, 2]
items.extend([3, 4])
items.insert(0, 0)
return items
"#
));
}
#[test]
fn test_99mode_dict_methods() {
assert!(transpile_ok(
r#"
def f() -> list:
d = {"a": 1, "b": 2}
keys = list(d.keys())
values = list(d.values())
return keys
"#
));
}
#[test]
fn test_99mode_dict_get_default() {
assert!(transpile_ok(
r#"
def f(d: dict, key: str) -> int:
return d.get(key, 0)
"#
));
}
#[test]
fn test_99mode_dict_items_iteration() {
assert!(transpile_ok(
r#"
def f(d: dict) -> list:
result = []
for k, v in d.items():
result.append(k)
return result
"#
));
}
#[test]
fn test_99mode_str_format_method() {
assert!(transpile_ok(
r#"
def f(name: str) -> str:
return "Hello {}".format(name)
"#
));
}
#[test]
fn test_99mode_str_count() {
assert!(transpile_ok(
r#"
def f(s: str, c: str) -> int:
return s.count(c)
"#
));
}
#[test]
fn test_99mode_str_isdigit_isalpha() {
assert!(transpile_ok(
r#"
def f(s: str) -> bool:
return s.isdigit() or s.isalpha()
"#
));
}
#[test]
fn test_99mode_nested_if_elif() {
assert!(transpile_ok(
r#"
def classify(x: int) -> str:
if x > 100:
return "large"
elif x > 50:
return "medium"
elif x > 0:
return "small"
else:
return "non-positive"
"#
));
}
#[test]
fn test_99mode_nested_loops() {
assert!(transpile_ok(
r#"
def f(n: int) -> int:
total = 0
for i in range(n):
for j in range(n):
total += i * j
return total
"#
));
}
#[test]
fn test_99mode_while_true_break() {
assert!(transpile_ok(
r#"
def f(target: int) -> int:
x = 0
while True:
x += 1
if x >= target:
break
return x
"#
));
}
#[test]
fn test_99mode_power_operator() {
assert!(transpile_ok(
r#"
def f(base: int, exp: int) -> int:
return base ** exp
"#
));
}
#[test]
fn test_99mode_floor_division() {
assert!(transpile_ok(
r#"
def f(a: int, b: int) -> int:
return a // b
"#
));
}
#[test]
fn test_99mode_modulo() {
assert!(transpile_ok(
r#"
def f(a: int, b: int) -> int:
return a % b
"#
));
}
#[test]
fn test_99mode_in_operator_list() {
assert!(transpile_ok(
r#"
def f(x: int, items: list) -> bool:
return x in items
"#
));
}
#[test]
fn test_99mode_not_in_operator() {
assert!(transpile_ok(
r#"
def f(x: int, items: list) -> bool:
return x not in items
"#
));
}
#[test]
fn test_99mode_in_operator_dict() {
assert!(transpile_ok(
r#"
def f(key: str, d: dict) -> bool:
return key in d
"#
));
}
#[test]
fn test_99mode_in_operator_string() {
assert!(transpile_ok(
r#"
def f(sub: str, s: str) -> bool:
return sub in s
"#
));
}
#[test]
fn test_99mode_isinstance_check() {
assert!(transpile_ok(
r#"
def f(x: int) -> bool:
return isinstance(x, int)
"#
));
}
#[test]
fn test_99mode_len_builtin() {
assert!(transpile_ok(
r#"
def f(items: list) -> int:
return len(items)
"#
));
}
#[test]
fn test_99mode_range_variants() {
assert!(transpile_ok(
r#"
def f() -> int:
total = 0
for i in range(10):
total += i
for i in range(1, 10):
total += i
for i in range(0, 10, 2):
total += i
return total
"#
));
}
#[test]
fn test_99mode_print_variants() {
assert!(transpile_ok(
r#"
def f(x: int, s: str):
print(x)
print(s)
print(x, s)
"#
));
}
#[test]
fn test_99mode_type_conversions() {
assert!(transpile_ok(
r#"
def f(x: int) -> str:
s = str(x)
f_val = float(x)
b = bool(x)
return s
"#
));
}
#[test]
fn test_99mode_abs_min_max() {
assert!(transpile_ok(
r#"
def f(a: int, b: int) -> int:
return abs(a) + min(a, b) + max(a, b)
"#
));
}
#[test]
fn test_99mode_sum_builtin() {
assert!(transpile_ok(
r#"
def f(items: list) -> int:
return sum(items)
"#
));
}
#[test]
fn test_99mode_any_all_builtins() {
assert!(transpile_ok(
r#"
def f(items: list) -> bool:
return any(items) and all(items)
"#
));
}
#[test]
fn test_99mode_sorted_reversed() {
assert!(transpile_ok(
r#"
def f(items: list) -> list:
s = sorted(items)
r = list(reversed(items))
return s
"#
));
}
#[test]
fn test_99mode_map_filter() {
assert!(transpile_ok(
r#"
def f(items: list) -> list:
doubled = list(map(lambda x: x * 2, items))
evens = list(filter(lambda x: x % 2 == 0, items))
return doubled
"#
));
}
#[test]
fn test_99mode_optional_return() {
assert!(transpile_ok(
r#"
from typing import Optional
def f(items: list) -> Optional[int]:
if len(items) > 0:
return items[0]
return None
"#
));
}
#[test]
fn test_99mode_multiple_return_types() {
assert!(transpile_ok(
r#"
def f(x: int) -> tuple:
return (x, x * 2, x * 3)
"#
));
}
#[test]
fn test_99mode_string_concatenation() {
assert!(transpile_ok(
r#"
def f(a: str, b: str) -> str:
return a + " " + b
"#
));
}
#[test]
fn test_99mode_list_concatenation() {
assert!(transpile_ok(
r#"
def f(a: list, b: list) -> list:
return a + b
"#
));
}
#[test]
fn test_99mode_nested_data_structures() {
assert!(transpile_ok(
r#"
def f() -> dict:
return {"list": [1, 2, 3], "nested": {"a": 1}}
"#
));
}
#[test]
fn test_99mode_empty_function() {
assert!(transpile_ok(
r#"
def f():
pass
"#
));
}
#[test]
fn test_99mode_docstring_function() {
assert!(transpile_ok(
r#"
def f(x: int) -> int:
"""Doubles the input value."""
return x * 2
"#
));
}
#[test]
fn test_99mode_class_basic() {
assert!(transpile_ok(
r#"
class Point:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def distance(self) -> float:
return (self.x ** 2 + self.y ** 2) ** 0.5
"#
));
}
#[test]
fn test_99mode_class_method() {
assert!(transpile_ok(
r#"
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
def get_count(self) -> int:
return self.count
"#
));
}
#[test]
fn test_99mode_generator_function() {
assert!(transpile_ok(
r#"
def f(n: int) -> list:
def gen():
for i in range(n):
yield i * 2
return list(gen())
"#
));
}
#[test]
fn test_99mode_with_statement() {
assert!(transpile_ok(
r#"
def f(path: str) -> str:
with open(path) as file:
return file.read()
"#
));
}
#[test]
fn test_99mode_complex_dict_operations() {
assert!(transpile_ok(
r#"
def f(data: dict) -> int:
result = 0
for key in data:
result += len(key)
return result
"#
));
}
#[test]
fn test_99mode_string_slicing() {
assert!(transpile_ok(
r#"
def f(s: str) -> str:
return s[:5]
"#
));
}
#[test]
fn test_99mode_walrus_operator() {
assert!(transpile_ok(
r#"
def f(items: list) -> int:
total = 0
for item in items:
total += item
return total
"#
));
}
#[test]
fn test_99mode_multiline_logic() {
assert!(transpile_ok(
r#"
def process(data: list) -> dict:
counts = {}
for item in data:
if item in counts:
counts[item] = counts[item] + 1
else:
counts[item] = 1
return counts
"#
));
}
#[test]
fn test_99mode_early_return_pattern() {
assert!(transpile_ok(
r#"
def f(items: list) -> int:
if not items:
return -1
if len(items) == 1:
return items[0]
return items[0] + items[-1]
"#
));
}
#[test]
fn test_99mode_accumulator_pattern() {
assert!(transpile_ok(
r#"
def f(n: int) -> int:
result = 1
for i in range(1, n + 1):
result *= i
return result
"#
));
}
#[test]
fn test_99mode_str_title_capitalize() {
assert!(transpile_ok(
r#"
def f(s: str) -> str:
return s.title()
"#
));
}
#[test]
fn test_99mode_str_lstrip_rstrip() {
assert!(transpile_ok(
r#"
def f(s: str) -> str:
return s.lstrip().rstrip()
"#
));
}
#[test]
fn test_99mode_list_pop() {
assert!(transpile_ok(
r#"
def f(items: list) -> int:
return items.pop()
"#
));
}
#[test]
fn test_99mode_list_index() {
assert!(transpile_ok(
r#"
def f(items: list, x: int) -> int:
return items.index(x)
"#
));
}
#[test]
fn test_99mode_nested_comprehension() {
assert!(transpile_ok(
r#"
def f(n: int) -> list:
return [i + j for i in range(n) for j in range(n)]
"#
));
}
#[test]
fn test_99mode_complex_boolean_logic() {
assert!(transpile_ok(
r#"
def f(x: int, y: int, z: int) -> bool:
return (x > 0 and y > 0) or (z < 0 and not (x == y))
"#
));
}
#[test]
fn test_99mode_bitwise_operations() {
assert!(transpile_ok(
r#"
def f(x: int, y: int) -> int:
return (x & y) | (x ^ y) | (x << 2) | (y >> 1)
"#
));
}
#[test]
fn test_99mode_recursive_function() {
assert!(transpile_ok(
r#"
def gcd(a: int, b: int) -> int:
if b == 0:
return a
return gcd(b, a % b)
"#
));
}
#[test]
fn test_99mode_complex_return_expression() {
assert!(transpile_ok(
r#"
def f(x: int) -> int:
return x * (x + 1) // 2 if x > 0 else 0
"#
));
}
#[test]
fn test_99mode_multiple_string_operations() {
assert!(transpile_ok(
r#"
def f(s: str) -> list:
words = s.strip().lower().split()
return words
"#
));
}
#[test]
fn test_99mode_dict_update_pattern() {
assert!(transpile_ok(
r#"
def f() -> dict:
d = {}
d["key1"] = 1
d["key2"] = 2
return d
"#
));
}
#[test]
fn test_99mode_list_remove() {
assert!(transpile_ok(
r#"
def f(items: list, x: int) -> list:
items.remove(x)
return items
"#
));
}
#[test]
fn test_99mode_enumerate_with_start() {
assert!(transpile_ok(
r#"
def f(items: list) -> list:
result = []
for i, item in enumerate(items):
result.append(i)
return result
"#
));
}
#[test]
fn test_99mode_complex_comprehension_filter() {
assert!(transpile_ok(
r#"
def f(data: list) -> list:
return [x * 2 for x in data if x > 0 and x < 100]
"#
));
}
#[test]
fn test_99mode_try_except_broad() {
assert!(transpile_ok(
r#"
def f(x: int) -> int:
try:
return 100 // x
except Exception:
return 0
"#
));
}
#[test]
fn test_99mode_nested_try() {
assert!(transpile_ok(
r#"
def f(s: str) -> int:
try:
try:
return int(s)
except ValueError:
return -1
except Exception:
return -2
"#
));
}
#[test]
fn test_99mode_set_operations() {
assert!(transpile_ok(
r#"
def f() -> set:
a = {1, 2, 3}
b = {2, 3, 4}
a.add(5)
return a
"#
));
}
#[test]
fn test_99mode_tuple_unpacking() {
assert!(transpile_ok(
r#"
def f() -> int:
point = (3, 4)
x, y = point
return x + y
"#
));
}
#[test]
fn test_99mode_complex_for_pattern() {
assert!(transpile_ok(
r#"
def f(matrix: list) -> int:
total = 0
for row in matrix:
for val in row:
total += val
return total
"#
));
}
#[test]
fn test_99mode_is_none_check() {
assert!(transpile_ok(
r#"
def f(x: int) -> bool:
result = None
if x > 0:
result = x
return result is None
"#
));
}
#[test]
fn test_99mode_is_not_none_check() {
assert!(transpile_ok(
r#"
def f(x: int) -> bool:
result = None
if x > 0:
result = x
return result is not None
"#
));
}
#[test]
fn test_99mode_comparison_operators() {
assert!(transpile_ok(
r#"
def f(a: int, b: int) -> list:
results = []
results.append(a == b)
results.append(a != b)
results.append(a < b)
results.append(a <= b)
results.append(a > b)
results.append(a >= b)
return results
"#
));
}
}