May be you want to check how it's done in Postgres-XC. Postgres-XC works on plans being created by PostgreSQL and "reverse-engineers" queries (for parts of the plans which are "shippable".) The notions of "shippability" may not be of interest to you, but the code to "reverse-engineer" most of the plan nodes is there in Postgres-XC.