You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现C++代码条件结构解析器的问题求助

C++条件结构解析器异常修复

我正在用Python编写一款C++代码解析器,已实现函数调用、赋值、数据输入输出等语法结构的识别。现需识别代码中的条件结构(包含多个else if分支、可选else块),获取每个结构的条件与代码体以作后续解析,用于优化大学要求的代码图绘制流程。目前编写的解析代码运行异常,相关信息及修复方案如下:

现有解析代码

from typing import Tuple, List

def raw_parse_if(code_part : str) -> Tuple[List[Tuple[str, str]], str]:
    else_body : str = ""
    statements : List[Tuple[str, str]] = []

    code = code_part.replace(" ", "").replace("\n", "")

    while "if(" in code:
        start_index = code.index("if(") + 2
        end_index = code.index(")", start_index)
        condition = code[start_index:end_index].strip()

        body_start_index = code.index("{", end_index) + 1
        # 匹配对应的闭合大括号,处理嵌套情况
        brace_count = 1
        body_end_index = body_start_index
        while brace_count > 0 and body_end_index < len(code):
            if code[body_end_index] == "{":
                brace_count += 1
            elif code[body_end_index] == "}":
                brace_count -= 1
            body_end_index += 1
        body_end_index -= 1  # 回退到闭合大括号的位置

        body = code[body_start_index:body_end_index].strip()
        statements.append((condition, body))

        # 处理后续的else if或else
        remaining_code = code[body_end_index + 1:].strip()
        if remaining_code.startswith("elseif("):
            code = remaining_code.replace("elseif(", "if(", 1)
        elif remaining_code.startswith("else"):
            # 提取else块
            if "{" in remaining_code:
                else_start = remaining_code.index("{") + 1
                brace_count_else = 1
                else_end = else_start
                while brace_count_else > 0 and else_end < len(remaining_code):
                    if remaining_code[else_end] == "{":
                        brace_count_else += 1
                    elif remaining_code[else_end] == "}":
                        brace_count_else -= 1
                    else_end += 1
                else_end -= 1
                else_body = remaining_code[else_start:else_end].strip()
            code = ""
        else:
            code = ""

    return statements, else_body

输入示例

#include <iostream>

int main() {
    int x = 5;
    if (x > 0) {
        std::cout << "x is positive";
    } else if (x == 0) {
        std::cout << "x is zero";
    } else if (x == 3) {
        std::cout << "x is zero";
    } else if (x == 5) {
        std::cout << "x is zero";
    } 
    else {
        std::cout << "x is negative";
    }
    return 0;
}

预期输出

[("x>0", "std::cout << \"x is positive\""),
("x==0", "std::cout << \"x is zero\""),
("x==3", "std::cout << \"x is zero\""),
("x==5", "std::cout << \"x is zero\"")]
else body: "std::cout << \"x is negative\""

最终目标标记块示例

<if cond="x > 0">
    <branch>
        <process text="std::cout &lt;&lt; &quot;x is positive&quot;"/>
    </branch>
    <branch>
        <if cond="x == 0">
            <branch>
                <process text="std::cout &lt;&lt; &quot;x is zero&quot;"/>
            </branch>
            <branch>
                <if cond="x == 3">
                    <branch>
                        <process text="std::cout &lt;&lt; &quot;x is zero&quot;"/>
                    </branch>
                    <branch>
                        <if cond="x == 5">
                            <branch>
                                <process text="std::cout &lt;&lt; &quot;x is zero&quot;"/>
                            </branch>
                            <branch>
                                <process text="std::cout &lt;&lt; &quot;x is negative&quot;"/>
                            </branch>
                        </if>
                    </branch>
                </if>
            </branch>
        </if>
    </branch>
</if>

问题修复说明

原代码的核心问题包括:

  • 未初始化statements和else_body变量,直接使用会抛出未定义错误
  • 未处理嵌套大括号的情况,简单用index("}")会匹配到第一个闭合大括号,导致代码体截取错误
  • 处理else if的逻辑错误,原代码直接截取到第一个else就停止,无法正确识别后续的else if分支
  • 空格和换行处理过于粗暴,直接全部移除可能导致条件或代码体的语义模糊

修复后的代码做了以下改进:

  1. 初始化statements为空列表、else_body为空字符串
  2. 使用括号计数法匹配对应的闭合大括号,支持嵌套结构
  3. 将else if转换为if循环处理,统一分支解析逻辑
  4. 提取else块时同样使用括号计数法,确保正确获取代码体
  5. 保留代码中的必要空格,仅去除首尾冗余空白

内容的提问来源于stack exchange,提问作者Be4Die

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 11:17:51