解决此问题所需的算法

时间:2012-09-18 10:39:33

标签: algorithm shell unix

假设我有一些分支代码,如下所示。

if condition 1
    code_line 1
    code_line 2
    more lines...
    if condition 2
        code_line 3
        code_line 4
        if condition 7   
            code_line 13
            code_line 14
        end if
        more lines...
    end if

    if condition 5
        code_line 6
        code_line 10
        more lines...
    end if
else
    code_line 7
    more lines...
end if

我想要一个可以读取此代码并告诉我给定行的所有前提条件的方法。

示例:

  1. code_line 4 位于条件2 内,条件1
  2. code_line 7 位于条件1 内。
  3. code_line 14 位于条件7 内,条件2 位于条件1 内。
  4. if-else块可以无限次嵌套。

1 个答案:

答案 0 :(得分:1)

首先,为您的语言构建或查找解析器。 然后,解析您的语言,创建abstract syntax tree。对于您的示例,它可能如下所示:

enter image description here

在树中,找到要调查的代码段。 从该节点开始,向上走树,直到到达根节点。每次传递IF节点时,请获取该节点的条件并打印它。

例如,您走 code_line 14 的路径如下所示:

enter image description here

走路时,遇到条件7,2和1.