Coverage for src/rejuvenation/replace_if_with_ternary.py: 88%

17 statements  

« prev     ^ index     » next       coverage.py v7.16.1, created at 2026-10-02 13:12 +0000

1"""AI: Example script demonstrating replacement of if-else statements with ternary operators in C source.""" 

2 

3# This script demonstrates the use of the syntax_tree library to parse and rewrite C code. 

4# It specifically showcases the replacement of if-else statements with ternary operators. 

5from renaissance.integrations.clang import ClangASTNode, CPatternFactory 

6from renaissance.syntax_tree import ASTFactory, ASTRewriter 

7from renaissance.syntax_tree.match_finder import find_all 

8 

9example_code = """ 

10 int a = 1; 

11 int b = 2; 

12 int c = 3; 

13 int d = 4; 

14 void f(){ 

15 if (a==1) { 

16 c++; 

17 b = 2; 

18 d++; 

19 } 

20 else { 

21 c++; 

22 b = 3; 

23 d++; 

24 } 

25 } 

26 """ 

27 

28expected_result = """ 

29 int a = 1; 

30 int b = 2; 

31 int c = 3; 

32 int d = 4; 

33 void f(){ 

34 c++; b=(a==1) ? 2:3; d++; 

35 } 

36 """.strip() 

37 

38 

39def replace_if_with_ternary(): 

40 """Replace if-else statements in the given C code with ternary operator expressions. 

41 

42 This function performs the following steps: 

43 1. Creates an AST factory with the specified arguments. 

44 2. Creates a pattern factory using the AST factory. 

45 3. Defines a pattern for if-else statements. 

46 4. Creates a translation unit from the provided example code. 

47 5. Initializes an AST rewriter for the translation unit. 

48 6. Searches for matches of the if-else pattern in the translation unit. 

49 7. Replaces matched if-else statements with ternary operator expressions. 

50 8. Returns the rewritten code as a string. 

51 

52 Returns: 

53 str: The rewritten C code with if-else statements replaced by ternary operators. 

54 

55 """ 

56 # Create a factory with arguments from the command line, for example, -I/usr/include 

57 factory = ASTFactory(ClangASTNode, []) 

58 # Create a pattern factory (using the factory (hence also its args) 

59 pattern_factory = CPatternFactory(factory) 

60 if_else_patterns = pattern_factory.create_statements("if($exp){$$before;b=$d1;$$after;}else{$$before;b=$d2;$$after;}") 

61 

62 # Create translation unit 

63 atu = factory.create_from_text(example_code, "test.c") 

64 # Create an ASTRewriter 

65 rewriter = ASTRewriter(atu) 

66 # Search matches and replace them 

67 for match in find_all(atu.children, if_else_patterns): 

68 rewriter.replace("$$before; b=($exp) ? $d1:$d2; $$after;", match) 

69 # Return the rewritten code 

70 return rewriter.apply_to_string().strip() 

71 

72 

73if __name__ == "__main__": 

74 result = replace_if_with_ternary() 

75 print(result)