py2pyd 0.1.5

A Rust-based tool to compile Python modules to pyd files
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Unit tests for the parser module
//!
//! These tests verify Python source code parsing functionality.

use anyhow::Result;
use std::fs;
use tempfile::TempDir;

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

    /// Test parsing a simple function
    #[test]
    fn test_parse_simple_function() -> Result<()> {
        let source = r#"
def add(a, b):
    return a + b
"#;

        let ast = py2pyd::parse_source(source)?;
        let functions = py2pyd::extract_functions(&ast);

        assert_eq!(functions.len(), 1);
        Ok(())
    }

    /// Test parsing multiple functions
    #[test]
    fn test_parse_multiple_functions() -> Result<()> {
        let source = r#"
def func1():
    pass

def func2():
    pass

def func3():
    pass
"#;

        let ast = py2pyd::parse_source(source)?;
        let functions = py2pyd::extract_functions(&ast);

        assert_eq!(functions.len(), 3);
        Ok(())
    }

    /// Test parsing async functions
    #[test]
    fn test_parse_async_function() -> Result<()> {
        let source = r#"
async def async_fetch():
    return await some_operation()

def sync_function():
    pass
"#;

        let ast = py2pyd::parse_source(source)?;
        // Note: async functions are also FunctionDef in rustpython-parser
        let functions = py2pyd::extract_functions(&ast);

        // Should find both sync and async functions
        assert!(!functions.is_empty());
        Ok(())
    }

    /// Test parsing decorated functions
    #[test]
    fn test_parse_decorated_function() -> Result<()> {
        let source = r#"
@decorator
def decorated():
    pass

@decorator1
@decorator2
def multi_decorated():
    pass
"#;

        let ast = py2pyd::parse_source(source)?;
        let functions = py2pyd::extract_functions(&ast);

        assert_eq!(functions.len(), 2);
        Ok(())
    }

    /// Test parsing a simple class
    #[test]
    fn test_parse_simple_class() -> Result<()> {
        let source = r#"
class MyClass:
    pass
"#;

        let ast = py2pyd::parse_source(source)?;
        let classes = py2pyd::extract_classes(&ast);

        assert_eq!(classes.len(), 1);
        Ok(())
    }

    /// Test parsing class with methods
    #[test]
    fn test_parse_class_with_methods() -> Result<()> {
        let source = r#"
class Calculator:
    def __init__(self):
        self.result = 0
    
    def add(self, value):
        self.result += value
        return self
    
    def subtract(self, value):
        self.result -= value
        return self
    
    def get_result(self):
        return self.result
"#;

        let ast = py2pyd::parse_source(source)?;
        let classes = py2pyd::extract_classes(&ast);

        assert_eq!(classes.len(), 1);
        Ok(())
    }

    /// Test parsing class with inheritance
    #[test]
    fn test_parse_class_inheritance() -> Result<()> {
        let source = r#"
class Base:
    pass

class Derived(Base):
    pass

class MultiInherit(Base, object):
    pass
"#;

        let ast = py2pyd::parse_source(source)?;
        let classes = py2pyd::extract_classes(&ast);

        assert_eq!(classes.len(), 3);
        Ok(())
    }

    /// Test parsing imports
    #[test]
    fn test_parse_imports() -> Result<()> {
        let source = r#"
import os
import sys
import json
"#;

        let ast = py2pyd::parse_source(source)?;
        let imports = py2pyd::extract_imports(&ast);

        assert_eq!(imports.len(), 3);
        Ok(())
    }

    /// Test parsing from imports
    #[test]
    fn test_parse_from_imports() -> Result<()> {
        let source = r#"
from os import path
from sys import argv, exit
from typing import List, Dict, Optional
"#;

        let ast = py2pyd::parse_source(source)?;
        let from_imports = py2pyd::extract_from_imports(&ast);

        assert_eq!(from_imports.len(), 3);
        Ok(())
    }

    /// Test parsing relative imports
    #[test]
    fn test_parse_relative_imports() -> Result<()> {
        let source = r#"
from . import module
from .. import parent_module
from .sibling import something
"#;

        let ast = py2pyd::parse_source(source)?;
        let from_imports = py2pyd::extract_from_imports(&ast);

        assert_eq!(from_imports.len(), 3);
        Ok(())
    }

    /// Test parsing module variables
    #[test]
    fn test_parse_module_vars() -> Result<()> {
        let source = r#"
VERSION = "1.0.0"
DEBUG = True
CONFIG = {}
"#;

        let ast = py2pyd::parse_source(source)?;
        let vars = py2pyd::extract_module_vars(&ast);

        assert_eq!(vars.len(), 3);
        Ok(())
    }

    /// Test parsing complex assignments
    #[test]
    fn test_parse_complex_assignments() -> Result<()> {
        let source = r#"
a = 1
b = c = 2
x, y = 1, 2
data = {"key": "value"}
items = [1, 2, 3]
"#;

        let ast = py2pyd::parse_source(source)?;
        let vars = py2pyd::extract_module_vars(&ast);

        // Should capture all assignment statements
        assert!(vars.len() >= 4);
        Ok(())
    }

    /// Test parsing file from disk
    #[test]
    fn test_parse_file_from_disk() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let file_path = temp_dir.path().join("test.py");

        let content = r#"
"""Module docstring."""

import os

VERSION = "1.0"

def main():
    pass

class App:
    pass
"#;

        fs::write(&file_path, content)?;

        let ast = py2pyd::parse_file(&file_path)?;

        let functions = py2pyd::extract_functions(&ast);
        let classes = py2pyd::extract_classes(&ast);
        let imports = py2pyd::extract_imports(&ast);

        assert_eq!(functions.len(), 1);
        assert_eq!(classes.len(), 1);
        assert_eq!(imports.len(), 1);

        Ok(())
    }

    /// Test parsing empty file
    #[test]
    fn test_parse_empty_file() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let file_path = temp_dir.path().join("empty.py");

        fs::write(&file_path, "")?;

        let ast = py2pyd::parse_file(&file_path)?;

        assert!(ast.is_empty());
        Ok(())
    }

    /// Test parsing file with only docstring
    #[test]
    fn test_parse_docstring_only() -> Result<()> {
        let source = r#"
"""
This is a module docstring.
It spans multiple lines.
"""
"#;

        let ast = py2pyd::parse_source(source)?;

        let functions = py2pyd::extract_functions(&ast);
        let classes = py2pyd::extract_classes(&ast);

        assert!(functions.is_empty());
        assert!(classes.is_empty());
        Ok(())
    }

    /// Test parsing syntax error
    #[test]
    fn test_parse_syntax_error() {
        let invalid_source = r#"
def broken(
    # Missing closing paren
"#;

        let result = py2pyd::parse_source(invalid_source);
        assert!(result.is_err());
    }

    /// Test parsing indentation error
    #[test]
    fn test_parse_indentation_error() {
        let invalid_source = r#"
def func():
pass  # Wrong indentation
"#;

        let result = py2pyd::parse_source(invalid_source);
        assert!(result.is_err());
    }

    /// Test parsing lambda expressions (not extracted as functions)
    #[test]
    fn test_parse_lambda() -> Result<()> {
        let source = r#"
add = lambda a, b: a + b
square = lambda x: x ** 2
"#;

        let ast = py2pyd::parse_source(source)?;

        // Lambdas are assigned to variables, not function definitions
        let functions = py2pyd::extract_functions(&ast);
        let vars = py2pyd::extract_module_vars(&ast);

        assert!(functions.is_empty());
        assert_eq!(vars.len(), 2);
        Ok(())
    }

    /// Test parsing nested functions
    #[test]
    fn test_parse_nested_functions() -> Result<()> {
        let source = r#"
def outer():
    def inner():
        pass
    return inner
"#;

        let ast = py2pyd::parse_source(source)?;

        // Only top-level functions are extracted
        let functions = py2pyd::extract_functions(&ast);
        assert_eq!(functions.len(), 1);
        Ok(())
    }

    /// Test parsing nested classes
    #[test]
    fn test_parse_nested_classes() -> Result<()> {
        let source = r#"
class Outer:
    class Inner:
        pass
"#;

        let ast = py2pyd::parse_source(source)?;

        // Only top-level classes are extracted
        let classes = py2pyd::extract_classes(&ast);
        assert_eq!(classes.len(), 1);
        Ok(())
    }

    /// Test parsing type hints
    #[test]
    fn test_parse_type_hints() -> Result<()> {
        let source = r#"
from typing import List, Optional

def process(items: List[int]) -> Optional[int]:
    if items:
        return sum(items)
    return None

class Container:
    items: List[str]
    
    def __init__(self, items: List[str]) -> None:
        self.items = items
"#;

        let ast = py2pyd::parse_source(source)?;

        let functions = py2pyd::extract_functions(&ast);
        let classes = py2pyd::extract_classes(&ast);

        assert_eq!(functions.len(), 1);
        assert_eq!(classes.len(), 1);
        Ok(())
    }

    /// Test parsing dataclass
    #[test]
    fn test_parse_dataclass() -> Result<()> {
        let source = r#"
from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float
    
    def distance(self) -> float:
        return (self.x ** 2 + self.y ** 2) ** 0.5
"#;

        let ast = py2pyd::parse_source(source)?;

        let classes = py2pyd::extract_classes(&ast);
        assert_eq!(classes.len(), 1);
        Ok(())
    }

    /// Test parsing context managers
    #[test]
    fn test_parse_context_manager() -> Result<()> {
        let source = r#"
class FileHandler:
    def __init__(self, filename):
        self.filename = filename
    
    def __enter__(self):
        self.file = open(self.filename)
        return self.file
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.close()
        return False
"#;

        let ast = py2pyd::parse_source(source)?;

        let classes = py2pyd::extract_classes(&ast);
        assert_eq!(classes.len(), 1);
        Ok(())
    }

    /// Test parsing generator function
    #[test]
    fn test_parse_generator() -> Result<()> {
        let source = r#"
def count_up_to(n):
    i = 0
    while i < n:
        yield i
        i += 1
"#;

        let ast = py2pyd::parse_source(source)?;

        let functions = py2pyd::extract_functions(&ast);
        assert_eq!(functions.len(), 1);
        Ok(())
    }

    /// Test parsing property decorator
    #[test]
    fn test_parse_property() -> Result<()> {
        let source = r#"
class Circle:
    def __init__(self, radius):
        self._radius = radius
    
    @property
    def radius(self):
        return self._radius
    
    @radius.setter
    def radius(self, value):
        self._radius = value
    
    @property
    def area(self):
        return 3.14159 * self._radius ** 2
"#;

        let ast = py2pyd::parse_source(source)?;

        let classes = py2pyd::extract_classes(&ast);
        assert_eq!(classes.len(), 1);
        Ok(())
    }

    /// Test parsing static and class methods
    #[test]
    fn test_parse_static_class_methods() -> Result<()> {
        let source = r#"
class Utility:
    @staticmethod
    def static_method():
        return "static"
    
    @classmethod
    def class_method(cls):
        return cls.__name__
    
    def instance_method(self):
        return "instance"
"#;

        let ast = py2pyd::parse_source(source)?;

        let classes = py2pyd::extract_classes(&ast);
        assert_eq!(classes.len(), 1);
        Ok(())
    }

    /// Test parsing walrus operator (Python 3.8+)
    #[test]
    fn test_parse_walrus_operator() -> Result<()> {
        let source = r#"
def process(data):
    if (n := len(data)) > 10:
        return n
    return 0
"#;

        let ast = py2pyd::parse_source(source)?;

        let functions = py2pyd::extract_functions(&ast);
        assert_eq!(functions.len(), 1);
        Ok(())
    }

    /// Test parsing match statement (Python 3.10+)
    #[test]
    fn test_parse_match_statement() -> Result<()> {
        let source = r#"
def handle_command(command):
    match command:
        case "start":
            return "Starting..."
        case "stop":
            return "Stopping..."
        case _:
            return "Unknown command"
"#;

        let ast = py2pyd::parse_source(source)?;

        let functions = py2pyd::extract_functions(&ast);
        assert_eq!(functions.len(), 1);
        Ok(())
    }
}