module Lib.TCO

import Prelude
import Data.Graph
import Lib.Ref2
import Lib.Common
import Lib.Types
import Lib.CompileExp

-- We need CompileExp here, so we know if it's
-- fully applied, needs eta, etc.
-- Maybe we should move Ref2 Defs over to CExp?
-- But we'll need CExp for constructors, etc.
-- I _could_ collect a stack and look up arity, but
-- at the next stage, we'd need to fake up constructor
-- records

tailNames : CExp → List Name
-- This is tricky, we need to skip the first CLam, but
-- a deeper one is a return value
tailNames (CApp (CRef name) args 0) = name :: Nil
tailNames (CCase _ alts) = join $ map altTailNames alts
  where
    altTailNames : CAlt → List Name
    altTailNames (CConAlt _ _ exp) = tailNames exp
    altTailNames (CDefAlt exp) = tailNames exp
    altTailNames (CLitAlt _ exp) = tailNames exp
tailNames (CLet _ _ t) = tailNames t
tailNames (CLetRec _ _ t) = tailNames t
tailNames (CConstr _ args) = join $ map tailNames args
tailNames (CBnd _) = Nil
tailNames (CFun _ _) = Nil
tailNames (CLam _ _) = Nil
tailNames (CApp t args n) = Nil
tailNames (CRef _) = Nil
tailNames CErased = Nil
tailNames (CLit _) = Nil
tailNames (CMeta _) = Nil
tailNames (CRaw _) = Nil

tailCallOpt : {{Ref2 Defs St}} → M Unit
tailCallOpt = do
  defs <- getRef Defs
  putStrLn "TODO TCO"
