portalis-core 0.1.0

Core library for the Portalis Python to Rust/WASM transpiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Feature Detection Engine
//!
//! Detects Python language features and categorizes them by support level.

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

// Re-export types from ingest (to avoid circular dependency, we define minimal types here)
// In production, these would be shared through a common types crate

/// Simplified Python AST (matches portalis_ingest::PythonAst)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PythonAst {
    pub functions: Vec<PythonFunction>,
    pub classes: Vec<PythonClass>,
    pub imports: Vec<PythonImport>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PythonFunction {
    pub name: String,
    pub params: Vec<PythonParameter>,
    pub return_type: Option<String>,
    pub body: String,
    pub decorators: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PythonParameter {
    pub name: String,
    pub type_hint: Option<String>,
    pub default: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PythonClass {
    pub name: String,
    pub bases: Vec<String>,
    pub methods: Vec<PythonFunction>,
    pub attributes: Vec<PythonAttribute>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PythonAttribute {
    pub name: String,
    pub type_hint: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PythonImport {
    pub module: String,
    pub items: Vec<String>,
    pub alias: Option<String>,
}

/// Support level for detected features
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum FeatureSupport {
    /// Fully supported with complete translation
    Full,
    /// Partially supported with limitations
    Partial,
    /// Not supported (blocker)
    None,
}

/// Detected feature in Python code
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetectedFeature {
    pub category: FeatureCategory,
    pub name: String,
    pub support: FeatureSupport,
    pub count: usize,
    pub locations: Vec<FeatureLocation>,
    pub details: Option<String>,
}

/// Feature category
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FeatureCategory {
    Function,
    Class,
    Decorator,
    TypeHint,
    Import,
    AsyncAwait,
    Metaclass,
    DynamicFeature,
    MagicMethod,
    Comprehension,
    Generator,
    ContextManager,
    Other,
}

/// Location of a detected feature
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeatureLocation {
    pub file: String,
    pub line: Option<usize>,
    pub context: String,
}

/// Set of all detected features
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeatureSet {
    pub features: Vec<DetectedFeature>,
    pub summary: FeatureSummary,
}

/// Summary of detected features
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeatureSummary {
    pub total_features: usize,
    pub fully_supported: usize,
    pub partially_supported: usize,
    pub unsupported: usize,
    pub by_category: HashMap<FeatureCategory, usize>,
}

/// Feature detection engine
pub struct FeatureDetector {
    /// Known decorators and their support levels
    decorator_support: HashMap<String, FeatureSupport>,
    /// Known magic methods and their support levels
    magic_method_support: HashMap<String, FeatureSupport>,
}

impl FeatureDetector {
    pub fn new() -> Self {
        let mut decorator_support = HashMap::new();
        // Fully supported decorators
        decorator_support.insert("property".to_string(), FeatureSupport::Full);
        decorator_support.insert("staticmethod".to_string(), FeatureSupport::Full);
        decorator_support.insert("classmethod".to_string(), FeatureSupport::Full);
        // Partially supported
        decorator_support.insert("dataclass".to_string(), FeatureSupport::Partial);
        decorator_support.insert("lru_cache".to_string(), FeatureSupport::Partial);
        // Unsupported
        decorator_support.insert("abstractmethod".to_string(), FeatureSupport::None);

        let mut magic_method_support = HashMap::new();
        // Fully supported magic methods
        magic_method_support.insert("__init__".to_string(), FeatureSupport::Full);
        magic_method_support.insert("__str__".to_string(), FeatureSupport::Full);
        magic_method_support.insert("__repr__".to_string(), FeatureSupport::Full);
        magic_method_support.insert("__eq__".to_string(), FeatureSupport::Full);
        magic_method_support.insert("__ne__".to_string(), FeatureSupport::Full);
        magic_method_support.insert("__add__".to_string(), FeatureSupport::Full);
        magic_method_support.insert("__sub__".to_string(), FeatureSupport::Full);
        magic_method_support.insert("__mul__".to_string(), FeatureSupport::Full);
        magic_method_support.insert("__len__".to_string(), FeatureSupport::Full);
        magic_method_support.insert("__getitem__".to_string(), FeatureSupport::Full);
        magic_method_support.insert("__setitem__".to_string(), FeatureSupport::Full);
        // Partially supported
        magic_method_support.insert("__enter__".to_string(), FeatureSupport::Partial);
        magic_method_support.insert("__exit__".to_string(), FeatureSupport::Partial);
        magic_method_support.insert("__call__".to_string(), FeatureSupport::Partial);
        // Unsupported
        magic_method_support.insert("__metaclass__".to_string(), FeatureSupport::None);
        magic_method_support.insert("__getattr__".to_string(), FeatureSupport::None);
        magic_method_support.insert("__setattr__".to_string(), FeatureSupport::None);

        Self {
            decorator_support,
            magic_method_support,
        }
    }

    /// Detect all features in a Python AST
    pub fn detect(&self, ast: &PythonAst, file_path: &str) -> FeatureSet {
        let mut features = Vec::new();

        // Detect function features
        for func in &ast.functions {
            features.extend(self.detect_function_features(func, file_path));
        }

        // Detect class features
        for class in &ast.classes {
            features.extend(self.detect_class_features(class, file_path));
        }

        // Detect import features
        for import in &ast.imports {
            features.extend(self.detect_import_features(import, file_path));
        }

        // Generate summary
        let summary = self.generate_summary(&features);

        FeatureSet { features, summary }
    }

    /// Detect features in a function
    fn detect_function_features(&self, func: &PythonFunction, file_path: &str) -> Vec<DetectedFeature> {
        let mut features = Vec::new();

        // Basic function detection
        let is_magic = func.name.starts_with("__") && func.name.ends_with("__");
        let is_async = func.name.contains("async"); // Simplified detection

        if is_magic {
            let support = self.magic_method_support
                .get(&func.name)
                .cloned()
                .unwrap_or(FeatureSupport::Partial);

            features.push(DetectedFeature {
                category: FeatureCategory::MagicMethod,
                name: func.name.clone(),
                support,
                count: 1,
                locations: vec![FeatureLocation {
                    file: file_path.to_string(),
                    line: None,
                    context: format!("def {}", func.name),
                }],
                details: Some("Magic method detected".to_string()),
            });
        } else {
            features.push(DetectedFeature {
                category: FeatureCategory::Function,
                name: func.name.clone(),
                support: FeatureSupport::Full,
                count: 1,
                locations: vec![FeatureLocation {
                    file: file_path.to_string(),
                    line: None,
                    context: format!("def {}", func.name),
                }],
                details: None,
            });
        }

        // Detect decorators
        for decorator in &func.decorators {
            let support = self.decorator_support
                .get(decorator)
                .cloned()
                .unwrap_or(FeatureSupport::Partial);

            features.push(DetectedFeature {
                category: FeatureCategory::Decorator,
                name: decorator.clone(),
                support,
                count: 1,
                locations: vec![FeatureLocation {
                    file: file_path.to_string(),
                    line: None,
                    context: format!("@{} on {}", decorator, func.name),
                }],
                details: None,
            });
        }

        // Detect type hints
        if func.return_type.is_some() || func.params.iter().any(|p| p.type_hint.is_some()) {
            features.push(DetectedFeature {
                category: FeatureCategory::TypeHint,
                name: format!("{} type hints", func.name),
                support: FeatureSupport::Full,
                count: 1,
                locations: vec![FeatureLocation {
                    file: file_path.to_string(),
                    line: None,
                    context: format!("Type hints in {}", func.name),
                }],
                details: None,
            });
        }

        // Detect async functions (simplified)
        if is_async {
            features.push(DetectedFeature {
                category: FeatureCategory::AsyncAwait,
                name: "async function".to_string(),
                support: FeatureSupport::Partial,
                count: 1,
                locations: vec![FeatureLocation {
                    file: file_path.to_string(),
                    line: None,
                    context: format!("async def {}", func.name),
                }],
                details: Some("Async/await support is partial".to_string()),
            });
        }

        features
    }

    /// Detect features in a class
    fn detect_class_features(&self, class: &PythonClass, file_path: &str) -> Vec<DetectedFeature> {
        let mut features = Vec::new();

        // Basic class detection
        features.push(DetectedFeature {
            category: FeatureCategory::Class,
            name: class.name.clone(),
            support: FeatureSupport::Full,
            count: 1,
            locations: vec![FeatureLocation {
                file: file_path.to_string(),
                line: None,
                context: format!("class {}", class.name),
            }],
            details: None,
        });

        // Detect metaclasses (unsupported)
        for base in &class.bases {
            if base.contains("metaclass") || base == "type" {
                features.push(DetectedFeature {
                    category: FeatureCategory::Metaclass,
                    name: format!("Metaclass in {}", class.name),
                    support: FeatureSupport::None,
                    count: 1,
                    locations: vec![FeatureLocation {
                        file: file_path.to_string(),
                        line: None,
                        context: format!("class {}({})", class.name, base),
                    }],
                    details: Some("Metaclasses are not supported".to_string()),
                });
            }
        }

        // Detect methods
        for method in &class.methods {
            features.extend(self.detect_function_features(method, file_path));
        }

        features
    }

    /// Detect features in imports
    fn detect_import_features(&self, import: &PythonImport, file_path: &str) -> Vec<DetectedFeature> {
        let mut features = Vec::new();

        // Check for known problematic imports
        let unsupported_modules = ["eval", "exec", "compile", "inspect"];
        let partial_modules = ["asyncio", "typing", "dataclasses"];

        let support = if unsupported_modules.contains(&import.module.as_str()) {
            FeatureSupport::None
        } else if partial_modules.contains(&import.module.as_str()) {
            FeatureSupport::Partial
        } else {
            FeatureSupport::Full
        };

        let details = if support != FeatureSupport::Full {
            Some(format!("Module {} has {:?} support", import.module, support))
        } else {
            None
        };

        features.push(DetectedFeature {
            category: FeatureCategory::Import,
            name: import.module.clone(),
            support,
            count: 1,
            locations: vec![FeatureLocation {
                file: file_path.to_string(),
                line: None,
                context: format!("import {}", import.module),
            }],
            details,
        });

        features
    }

    /// Generate summary from detected features
    fn generate_summary(&self, features: &[DetectedFeature]) -> FeatureSummary {
        let total_features = features.len();
        let fully_supported = features.iter().filter(|f| f.support == FeatureSupport::Full).count();
        let partially_supported = features.iter().filter(|f| f.support == FeatureSupport::Partial).count();
        let unsupported = features.iter().filter(|f| f.support == FeatureSupport::None).count();

        let mut by_category = HashMap::new();
        for feature in features {
            *by_category.entry(feature.category.clone()).or_insert(0) += 1;
        }

        FeatureSummary {
            total_features,
            fully_supported,
            partially_supported,
            unsupported,
            by_category,
        }
    }
}

impl Default for FeatureDetector {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_detect_simple_function() {
        let detector = FeatureDetector::new();
        let ast = PythonAst {
            functions: vec![PythonFunction {
                name: "add".to_string(),
                params: vec![],
                return_type: Some("int".to_string()),
                body: String::new(),
                decorators: vec![],
            }],
            classes: vec![],
            imports: vec![],
        };

        let features = detector.detect(&ast, "test.py");
        assert!(features.summary.total_features > 0);
        assert!(features.summary.fully_supported > 0);
    }

    #[test]
    fn test_detect_magic_method() {
        let detector = FeatureDetector::new();
        let ast = PythonAst {
            functions: vec![PythonFunction {
                name: "__init__".to_string(),
                params: vec![],
                return_type: None,
                body: String::new(),
                decorators: vec![],
            }],
            classes: vec![],
            imports: vec![],
        };

        let features = detector.detect(&ast, "test.py");
        assert!(features.features.iter().any(|f| f.category == FeatureCategory::MagicMethod));
    }

    #[test]
    fn test_detect_unsupported_decorator() {
        let detector = FeatureDetector::new();
        let ast = PythonAst {
            functions: vec![PythonFunction {
                name: "test".to_string(),
                params: vec![],
                return_type: None,
                body: String::new(),
                decorators: vec!["abstractmethod".to_string()],
            }],
            classes: vec![],
            imports: vec![],
        };

        let features = detector.detect(&ast, "test.py");
        assert!(features.summary.unsupported > 0);
    }

    #[test]
    fn test_detect_metaclass() {
        let detector = FeatureDetector::new();
        let ast = PythonAst {
            functions: vec![],
            classes: vec![PythonClass {
                name: "Meta".to_string(),
                bases: vec!["type".to_string()],
                methods: vec![],
                attributes: vec![],
            }],
            imports: vec![],
        };

        let features = detector.detect(&ast, "test.py");
        assert!(features.features.iter().any(|f| f.category == FeatureCategory::Metaclass));
        assert!(features.summary.unsupported > 0);
    }
}