Skip to content

Commit c1c8441

Browse files
committed
Automatic Code Transformation Module #4
1 parent 56ae87b commit c1c8441

File tree

5 files changed

+84
-3
lines changed

5 files changed

+84
-3
lines changed

input.c

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
// Pointer Usage
5+
void pointer_example() {
6+
int a = 10;
7+
int* ptr = &a;
8+
printf("%d\n", *ptr);
9+
}
10+
11+
// Dynamic Memory Allocation
12+
void memory_example() {
13+
int* arr = (int*)malloc(5 * sizeof(int));
14+
for (int i = 0; i < 5; i++) {
15+
arr[i] = i * 2;
16+
printf("%d ", arr[i]);
17+
}
18+
free(arr);
19+
}
20+
21+
// Struct Example
22+
struct Point {
23+
int x;
24+
int y;
25+
};
26+
27+
// Function Example
28+
void function_example(struct Point p) {
29+
printf("Point(%d, %d)\n", p.x, p.y);
30+
}
31+
32+
int main() {
33+
pointer_example();
34+
memory_example();
35+
struct Point p = {10, 20};
36+
function_example(p);
37+
return 0;
38+
}

src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
pub mod parser;
2-
2+
pub mod rewriting;

src/parser/clang_parser.rs

-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
use clang_sys::support::Clang;
21
use std::path::Path;
3-
use std::ffi::CString;
42
use std::process::{Command, Stdio};
53
use std::io::Write; // وارد کردن Write برای استفاده از متد write_all
64

src/rewriting.rs

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// src/rewriting.rs
2+
3+
pub fn rewrite_c_to_rust(ast: &str) -> String {
4+
let mut result = ast.to_string();
5+
6+
// تبدیل اشاره‌گرها به مرجع در Rust
7+
result = result.replace("int* ", "&i32 "); // نمونه ساده برای اشاره‌گرها
8+
9+
// تبدیل malloc به Box
10+
result = result.replace("malloc(", "Box::new(");
11+
// حذف free
12+
result = result.replace("free(", "");
13+
14+
// تبدیل sizeof(int) به sizeof(i32) به شکل مورد نظر شما
15+
result = result.replace("sizeof(int)", "sizeof(i32)");
16+
17+
// تبدیل حلقه‌های for به Rust
18+
result = result.replace("for (int i = 0; i < n; i++)", "for i in 0..n");
19+
20+
result
21+
}

tests/rewriting_test.rs

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// tests/rewriting_test.rs
2+
3+
use crown::rewriting::rewrite_c_to_rust;
4+
5+
#[test]
6+
fn test_rewrite_pointer() {
7+
let c_code = "int* ptr;";
8+
let rust_code = rewrite_c_to_rust(c_code);
9+
assert_eq!(rust_code, "&i32 ptr;");
10+
}
11+
12+
#[test]
13+
fn test_rewrite_malloc() {
14+
let c_code = "malloc(sizeof(int));";
15+
let rust_code = rewrite_c_to_rust(c_code);
16+
assert_eq!(rust_code, "Box::new(sizeof(i32));");
17+
}
18+
19+
#[test]
20+
fn test_rewrite_for_loop() {
21+
let c_code = "for (int i = 0; i < n; i++) { ... }";
22+
let rust_code = rewrite_c_to_rust(c_code);
23+
assert_eq!(rust_code, "for i in 0..n { ... }");
24+
}

0 commit comments

Comments
 (0)