freesTermF :: TermF BitSet -> BitSet
freesTermF tf =
    case tf of
      FTermF ftf -> bitwiseOrOf folded ftf
      App l r -> l .|. r
      Lambda _name tp rhs -> tp .|. rhs `shiftR` 1
      Pi _name lhs rhs -> lhs .|. rhs `shiftR` 1
      Let lcls rhs ->
          bitwiseOrOf (folded . folded) lcls' .|. rhs `shiftR` n
        where n = length lcls
              freesLocalDef :: LocalDef BitSet -> [BitSet]
              freesLocalDef (Def _ _ tp eqs) = 
                tp : fmap ((`shiftR` n) . freesDefEqn) eqs
              lcls' = freesLocalDef <$> lcls
      LocalVar i -> bit i
      Constant _ _ _ -> 0 -- assume rhs is a closed term
freesTermF :: TermF BitSet -> BitSet
freesTermF tf =
    case tf of
      FTermF ftf -> bitwiseOrOf folded ftf
      App l r -> l .|. r
      Lambda _name tp rhs -> tp .|. rhs `shiftR` 1
      Pi _name lhs rhs -> lhs .|. rhs `shiftR` 1
      Let lcls rhs ->
          bitwiseOrOf (folded . folded) lcls' .|. rhs `shiftR` n
        where n = length lcls
              freesLocalDef :: LocalDef BitSet -> [BitSet]
              freesLocalDef (Def _ _ tp eqs) = 
                tp : fmap ((`shiftR` n) . freesDefEqn) eqs
              lcls' = freesLocalDef <$> lcls
      LocalVar i -> bit i
      Constant _ _ _ -> 0 -- assume rhs is a closed term
freesTermF tf =
    case tf of
      FTermF ftf -> bitwiseOrOf folded ftf
      App l r -> l .|. r
      Lambda _name tp rhs -> tp .|. rhs `shiftR` 1
      Pi _name lhs rhs -> lhs .|. rhs `shiftR` 1
      Let lcls rhs ->
          bitwiseOrOf (folded . folded) lcls' .|. rhs `shiftR` n
        where n = length lcls
              freesLocalDef :: LocalDef BitSet -> [BitSet]
              freesLocalDef (Def _ _ tp eqs) = 
                tp : fmap ((`shiftR` n) . freesDefEqn) eqs
              lcls' = freesLocalDef <$> lcls
      LocalVar i -> bit i
      Constant _ _ _ -> 0 -- assume rhs is a closed term