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

17 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-09-09 14:04 +0000

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

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

3from renaissance.integrations.clang import ClangASTNode, CPatternFactory 

4from renaissance.syntax_tree import ASTFactory, ASTRewriter 

5from renaissance.syntax_tree.match_finder import find_all 

6 

7example_code = """ 

8 int a = 1; 

9 int b = 2; 

10 int c = 3; 

11 int d = 4; 

12 void f(){ 

13 if (a==1) { 

14 c++; 

15 b = 2; 

16 d++; 

17 } 

18 else { 

19 c++; 

20 b = 3; 

21 d++; 

22 } 

23 } 

24 """ 

25 

26expected_result = """ 

27 int a = 1; 

28 int b = 2; 

29 int c = 3; 

30 int d = 4; 

31 void f(){ 

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

33 } 

34 """.strip() 

35 

36 

37def replace_if_with_ternary(): 

38 """Replaces if-else statements in the given C code with ternary operator expressions. 

39 This function performs the following steps: 

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

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

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

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

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

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

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

47 8. Returns the rewritten code as a string. 

48 

49 Returns: 

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

51 

52 """ 

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

54 factory = ASTFactory(ClangASTNode, []) 

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

56 pattern_factory = CPatternFactory(factory) 

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

58 

59 # Create translation unit 

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

61 # Create an ASTRewriter 

62 rewriter = ASTRewriter(atu) 

63 # Search matches and replace them 

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

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

66 # Return the rewritten code 

67 return rewriter.apply_to_string().strip() 

68 

69 

70if __name__ == "__main__": 

71 result = replace_if_with_ternary() 

72 print(result)