Coverage for src/rejuvenation/replace_if_with_ternary.py: 88%
17 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-15 10:34 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-15 10:34 +0000
1# Copyright (C) 2024-2026 TNO
2#
3# Licensed under the terms specified in the LICENSE file in the root directory
4# of this repository, also available at:
5# https://github.com/TNO/Renaissance.Py/blob/main/LICENSE
7"""AI: Example script demonstrating replacement of if-else statements with ternary operators in C source."""
9# This script demonstrates the use of the syntax_tree library to parse and rewrite C code.
10# It specifically showcases the replacement of if-else statements with ternary operators.
11from renaissance.integrations.clang import ClangASTNode, CPatternFactory
12from renaissance.syntax_tree import ASTFactory, ASTRewriter
13from renaissance.syntax_tree.match_finder import find_all
15example_code = """
16 int a = 1;
17 int b = 2;
18 int c = 3;
19 int d = 4;
20 void f(){
21 if (a==1) {
22 c++;
23 b = 2;
24 d++;
25 }
26 else {
27 c++;
28 b = 3;
29 d++;
30 }
31 }
32 """
34expected_result = """
35 int a = 1;
36 int b = 2;
37 int c = 3;
38 int d = 4;
39 void f(){
40 c++; b=(a==1) ? 2:3; d++;
41 }
42 """.strip()
45def replace_if_with_ternary():
46 """Replace if-else statements in the given C code with ternary operator expressions.
48 This function performs the following steps:
49 1. Creates an AST factory with the specified arguments.
50 2. Creates a pattern factory using the AST factory.
51 3. Defines a pattern for if-else statements.
52 4. Creates a translation unit from the provided example code.
53 5. Initializes an AST rewriter for the translation unit.
54 6. Searches for matches of the if-else pattern in the translation unit.
55 7. Replaces matched if-else statements with ternary operator expressions.
56 8. Returns the rewritten code as a string.
58 Returns:
59 str: The rewritten C code with if-else statements replaced by ternary operators.
61 """
62 # Create a factory with arguments from the command line, for example, -I/usr/include
63 factory = ASTFactory(ClangASTNode, [])
64 # Create a pattern factory (using the factory (hence also its args)
65 pattern_factory = CPatternFactory(factory)
66 if_else_patterns = pattern_factory.create_statements("if($exp){$$before;b=$d1;$$after;}else{$$before;b=$d2;$$after;}")
68 # Create translation unit
69 atu = factory.create_from_text(example_code, "test.c")
70 # Create an ASTRewriter
71 rewriter = ASTRewriter(atu)
72 # Search matches and replace them
73 for match in find_all(atu.children, if_else_patterns):
74 rewriter.replace("$$before; b=($exp) ? $d1:$d2; $$after;", match)
75 # Return the rewritten code
76 return rewriter.apply_to_string().strip()
79if __name__ == "__main__":
80 result = replace_if_with_ternary()
81 print(result)