Skip to content

Commit 6201f21

Browse files
committed
Complete Rust Language Support (P1-Days3-4)
Add comprehensive Rust examples and documentation: - 5 Rust examples (Result, trait, async, error, tests) - Complete Rust language guide - Update examples README with Rust section - 6 new tests (5 examples + 1 structure) Examples: - 01-function-result: Result<T,E> with error handling - 02-struct-trait: Struct with Display trait impl - 03-async-tokio: Async function with tokio runtime - 04-error-handling: Custom error with thiserror - 05-test-generation: #[test] and #[cfg(test)] modules Documentation covers: - Ownership and borrowing patterns - Lifetime annotations ('a, 'static, 'b) - Generic types with trait bounds - Traits and implementations - Result and Option idioms - Async/await with tokio - Pattern matching - Error types (thiserror) - Builder and newtype patterns - Testing (#[test], #[cfg(test)]) - Cargo integration (check, clippy, test) - Style conventions - Best practices for Rust prompts All examples run successfully ✅ Component: examples/rust/, docs/user-guide/rust-guide.md Tests: 6 tests added to test_examples.py Status: ✅ P1 Rust Support COMPLETE
1 parent e9e8040 commit 6201f21

8 files changed

Lines changed: 803 additions & 0 deletions

File tree

docs/user-guide/rust-guide.md

Lines changed: 416 additions & 0 deletions
Large diffs are not rendered by default.

examples/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,16 @@ Python-specific examples:
2222
4. **[04-fastapi-endpoint.py](python/04-fastapi-endpoint.py)** - FastAPI endpoint with Pydantic
2323
5. **[05-test-generation.py](python/05-test-generation.py)** - Pytest test generation
2424

25+
## Basic Examples - Rust
26+
27+
Rust-specific examples:
28+
29+
1. **[01-function-result.py](rust/01-function-result.py)** - Function with Result type and error handling
30+
2. **[02-struct-trait.py](rust/02-struct-trait.py)** - Struct with Display trait implementation
31+
3. **[03-async-tokio.py](rust/03-async-tokio.py)** - Async function with tokio runtime
32+
4. **[04-error-handling.py](rust/04-error-handling.py)** - Custom error type with thiserror
33+
5. **[05-test-generation.py](rust/05-test-generation.py)** - Test generation with #[test]
34+
2535
## Advanced Examples
2636

2737
Complex real-world scenarios:
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""Example 1: Rust Function with Result Type.
2+
3+
Demonstrates:
4+
- Function generation with Result type
5+
- Error handling patterns
6+
- Type safety with Rust
7+
8+
Usage:
9+
python examples/rust/01-function-result.py
10+
"""
11+
12+
from maze.config import Config
13+
from maze.core.pipeline import Pipeline
14+
15+
16+
def main():
17+
"""Generate Rust function with Result type."""
18+
print("Rust Example 1: Function with Result Type")
19+
print("=" * 60)
20+
21+
config = Config()
22+
config.project.language = "rust"
23+
config.constraints.syntactic_enabled = True
24+
config.constraints.type_enabled = True
25+
26+
pipeline = Pipeline(config)
27+
28+
prompt = """Create a Rust function called 'divide':
29+
- Parameters: a: f64, b: f64
30+
- Returns: Result<f64, String>
31+
- Returns Err if b is 0.0
32+
- Returns Ok(a / b) otherwise
33+
- Include error message in Err
34+
- Add documentation comment"""
35+
36+
print(f"\nPrompt: {prompt}\n")
37+
print("Generating...")
38+
39+
result = pipeline.run(prompt)
40+
41+
print(f"\nResult:")
42+
print(f" Success: {result.success}")
43+
print(f" Duration: {result.total_duration_ms:.0f}ms")
44+
45+
print(f"\nGenerated Code:")
46+
print("-" * 60)
47+
print(result.code)
48+
print("-" * 60)
49+
50+
if result.validation:
51+
print(f"\nValidation:")
52+
print(f" Syntax Valid: {result.validation.syntax_valid}")
53+
print(f" Errors: {result.validation.errors_found}")
54+
55+
pipeline.close()
56+
print("\n✅ Example complete!")
57+
58+
59+
if __name__ == "__main__":
60+
main()

examples/rust/02-struct-trait.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""Example 2: Rust Struct with Trait Implementation.
2+
3+
Demonstrates:
4+
- Struct definition
5+
- Trait implementation
6+
- Method generation
7+
8+
Usage:
9+
python examples/rust/02-struct-trait.py
10+
"""
11+
12+
from maze.config import Config
13+
from maze.core.pipeline import Pipeline
14+
15+
16+
def main():
17+
"""Generate Rust struct with trait implementation."""
18+
print("Rust Example 2: Struct with Trait Implementation")
19+
print("=" * 60)
20+
21+
config = Config()
22+
config.project.language = "rust"
23+
config.constraints.type_enabled = True
24+
25+
pipeline = Pipeline(config)
26+
27+
prompt = """Create Rust struct 'Point' and implement Display:
28+
- Struct Point with x: f64, y: f64 fields
29+
- Implement std::fmt::Display trait
30+
- Format as "(x, y)"
31+
- Add impl block with new() constructor
32+
- Include documentation comments"""
33+
34+
print(f"\nGenerating Point struct with Display...\n")
35+
36+
result = pipeline.run(prompt)
37+
38+
print(f"Status: {'✅ Success' if result.success else '❌ Failed'}")
39+
print(f"Duration: {result.total_duration_ms:.0f}ms")
40+
41+
print(f"\nGenerated Code:")
42+
print("-" * 60)
43+
print(result.code)
44+
print("-" * 60)
45+
46+
pipeline.close()
47+
print("\n✅ Example complete!")
48+
49+
50+
if __name__ == "__main__":
51+
main()

examples/rust/03-async-tokio.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
"""Example 3: Async Function with Tokio.
2+
3+
Demonstrates:
4+
- Async/await in Rust
5+
- Error handling with Result
6+
- External crate usage (tokio, reqwest)
7+
8+
Usage:
9+
python examples/rust/03-async-tokio.py
10+
"""
11+
12+
from maze.config import Config
13+
from maze.core.pipeline import Pipeline
14+
15+
16+
def main():
17+
"""Generate async Rust function with tokio."""
18+
print("Rust Example 3: Async Function with Tokio")
19+
print("=" * 60)
20+
21+
config = Config()
22+
config.project.language = "rust"
23+
config.constraints.syntactic_enabled = True
24+
25+
pipeline = Pipeline(config)
26+
27+
prompt = """Create async Rust function 'fetch_user':
28+
- Parameter: user_id: &str
29+
- Returns: Result<User, reqwest::Error>
30+
- Use reqwest to fetch from API
31+
- Async function with .await
32+
- Error handling with ?
33+
- Assume User struct exists
34+
- Include documentation"""
35+
36+
print(f"\nGenerating async function...\n")
37+
38+
result = pipeline.run(prompt)
39+
40+
print(f"Status: {'✅' if result.success else '❌'}")
41+
print(f"Duration: {result.total_duration_ms:.0f}ms")
42+
43+
print(f"\nGenerated Async Function:")
44+
print("-" * 60)
45+
print(result.code)
46+
print("-" * 60)
47+
48+
pipeline.close()
49+
print("\n✅ Example complete!")
50+
51+
52+
if __name__ == "__main__":
53+
main()

examples/rust/04-error-handling.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""Example 4: Custom Error Type with thiserror.
2+
3+
Demonstrates:
4+
- Custom error enum
5+
- Error trait implementation
6+
- Using thiserror derive
7+
8+
Usage:
9+
python examples/rust/04-error-handling.py
10+
"""
11+
12+
from maze.config import Config
13+
from maze.core.pipeline import Pipeline
14+
15+
16+
def main():
17+
"""Generate Rust custom error type."""
18+
print("Rust Example 4: Custom Error Type")
19+
print("=" * 60)
20+
21+
config = Config()
22+
config.project.language = "rust"
23+
config.constraints.type_enabled = True
24+
25+
pipeline = Pipeline(config)
26+
27+
prompt = """Create Rust error enum using thiserror:
28+
- Name: AppError
29+
- Variants: NotFound(String), Invalid(String), Internal
30+
- Use #[derive(Error, Debug)]
31+
- Use #[error("...")] for display messages
32+
- Implement From<std::io::Error> for AppError
33+
- Include documentation"""
34+
35+
print(f"\nGenerating custom error type...\n")
36+
37+
result = pipeline.run(prompt)
38+
39+
print(f"Status: {'✅' if result.success else '❌'}")
40+
print(f"Duration: {result.total_duration_ms:.0f}ms")
41+
42+
print(f"\nGenerated Error Type:")
43+
print("-" * 60)
44+
print(result.code)
45+
print("-" * 60)
46+
47+
pipeline.close()
48+
print("\n✅ Example complete!")
49+
50+
51+
if __name__ == "__main__":
52+
main()
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
"""Example 5: Rust Test Generation.
2+
3+
Demonstrates:
4+
- Test function generation
5+
- #[test] attributes
6+
- #[cfg(test)] modules
7+
- Assert macros
8+
9+
Usage:
10+
python examples/rust/05-test-generation.py
11+
"""
12+
13+
from maze.config import Config
14+
from maze.core.pipeline import Pipeline
15+
16+
17+
def main():
18+
"""Generate Rust tests."""
19+
print("Rust Example 5: Test Generation")
20+
print("=" * 60)
21+
22+
# Source code to test
23+
source_code = """
24+
pub struct Calculator;
25+
26+
impl Calculator {
27+
pub fn add(&self, a: i32, b: i32) -> i32 {
28+
a + b
29+
}
30+
31+
pub fn subtract(&self, a: i32, b: i32) -> i32 {
32+
a - b
33+
}
34+
}
35+
"""
36+
37+
print("Source Code to Test:")
38+
print("-" * 60)
39+
print(source_code)
40+
print("-" * 60)
41+
42+
config = Config()
43+
config.project.language = "rust"
44+
45+
pipeline = Pipeline(config)
46+
47+
prompt = f"""Generate Rust tests for this Calculator:
48+
49+
{source_code}
50+
51+
Requirements:
52+
- Use #[cfg(test)] module
53+
- Use #[test] attribute
54+
- Test add() method
55+
- Test subtract() method
56+
- Test edge cases (zero, negative numbers)
57+
- Use assert_eq! macro
58+
- Include module documentation"""
59+
60+
print("\nGenerating Rust tests...\n")
61+
62+
result = pipeline.run(prompt)
63+
64+
print(f"Status: {'✅' if result.success else '❌'}")
65+
print(f"Duration: {result.total_duration_ms:.0f}ms")
66+
67+
print(f"\nGenerated Tests:")
68+
print("-" * 60)
69+
print(result.code)
70+
print("-" * 60)
71+
72+
pipeline.close()
73+
print("\n✅ Example complete!")
74+
75+
76+
if __name__ == "__main__":
77+
main()

0 commit comments

Comments
 (0)