Coverage for src/rejuvenation/replace_if_with_ternary.py: 88%
16 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-16 16:04 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-16 16:04 +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 """
35def replace_if_with_ternary():
36 """Replace if-else statements in the given C code with ternary operator expressions.
38 This function performs the following steps:
39 1. Creates an AST factory with the specified arguments.
40 2. Creates a pattern factory using the AST factory.
41 3. Defines a pattern for if-else statements.
42 4. Creates a translation unit from the provided example code.
43 5. Initializes an AST rewriter for the translation unit.
44 6. Searches for matches of the if-else pattern in the translation unit.
45 7. Replaces matched if-else statements with ternary operator expressions.
46 8. Returns the rewritten code as a string.
48 Returns:
49 str: The rewritten C code with if-else statements replaced by ternary operators.
51 """
52 # Create a factory with arguments from the command line, for example, -I/usr/include
53 factory = ASTFactory(ClangASTNode, [])
54 # Create a pattern factory (using the factory (hence also its args)
55 pattern_factory = CPatternFactory(factory)
56 if_else_patterns = pattern_factory.create_statements("if($exp){$$before;b=$d1;$$after;}else{$$before;b=$d2;$$after;}")
58 # Create translation unit
59 atu = factory.create_from_text(example_code, "test.c")
60 # Create an ASTRewriter
61 rewriter = ASTRewriter(atu)
62 # Search matches and replace them
63 for match in find_all(atu.children, if_else_patterns):
64 rewriter.replace("$$before; b=($exp) ? $d1:$d2; $$after;", match)
65 # Return the rewritten code
66 return rewriter.apply_to_string().strip()
69if __name__ == "__main__":
70 result = replace_if_with_ternary()
71 print(result)