0

I know that Control Flow Graph(CFG) can be built from Abstract Syntax Tree (AST).

However, it is not clear to me whether CFG is a subset of AST?

As an example, given a CFG can we go back to AST?

Exploring
  • 2,493
  • 11
  • 56
  • 97
  • It's not a subset, it's a new structure. But obviously they're related. And you can always design a transformer to be reversible, so "can we go back" is trivially true. (Q.v. functional programming.,) – rici Jun 23 '21 at 08:29
  • How are you defining a CSG? [Wikipedia's page on CFGs](https://en.wikipedia.org/wiki/Control-flow_graph) has an image with some examples which pretty clearly can't be used to recover the AST, because the graph just doesn't contain any information other than a node for each basic block and an edge for each possible transition. – kaya3 Jul 31 '21 at 18:04

1 Answers1

1

However, it is not clear to me whether CFG is a subset of AST?

No, AST is an entirely syntactical construct. But a CST is well integrated with language's semantics. Also they represent different stuff.

As an example, given a CFG can we go back to AST?

It depends on the language, and how the constructs in that language maps to the control flow. For example these 2 snippets would construct entirely different ASTs;

print('a') if a else print('b')
if a:
    print('a')
else:
    print('b')

But the generated CFG would be equal for both of those.