Team Ai
Apppublic

typicaleoxx/code-explainer-ai

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
static_analyzer.py65 linesDownload Raw Back to root
1# this module performs static code analysis using Python's AST module2# it extracts structural information about the program before sending it to the LLM3 4import ast5 6 7def analyze_code_structure(code: str):8    """9    Parse the input code into an AST and extract structural metrics.10    """11 12    analysis = {13        "functions": 0,14        "loops": 0,15        "conditionals": 0,16        "assignments": 0,17        "function_calls": 0,18        "imports": 0,19        "security_warnings": [],20    }21 22    try:23        # convert the code string into an abstract syntax tree24        tree = ast.parse(code)25 26    except SyntaxError as e:27        return {"error": f"Syntax error in code: {e}"}28 29    # walk through every node in the syntax tree30    for node in ast.walk(tree):31 32        # count function definitions33        if isinstance(node, ast.FunctionDef):34            analysis["functions"] += 135 36        # count loops37        if isinstance(node, (ast.For, ast.While)):38            analysis["loops"] += 139 40        # count if statements41        if isinstance(node, ast.If):42            analysis["conditionals"] += 143 44        # count assignments45        if isinstance(node, ast.Assign):46            analysis["assignments"] += 147 48        # count imports49        if isinstance(node, (ast.Import, ast.ImportFrom)):50            analysis["imports"] += 151 52        # detect function calls53        if isinstance(node, ast.Call):54            analysis["function_calls"] += 155 56            # detect potentially dangerous calls57            if isinstance(node.func, ast.Name):58 59                if node.func.id in ["eval", "exec"]:60                    analysis["security_warnings"].append(61                        f"Use of dangerous function: {node.func.id}"62                    )63 64    return analysis65