packages feed

liquidhaskell-boot-0.9.14.1.2: src/Language/Haskell/Liquid/RefCore/SpecToLH.hs

{-# OPTIONS_GHC -Wall #-}

module Language.Haskell.Liquid.RefCore.SpecToLH (transSig, transType, showppStripped, bops, builtinDCs, builtinTCs, InternalCont (..)) where

import Control.Monad (filterM)
import Control.Monad.Extra (allM, ifM)
import Control.Monad.Reader (Reader, asks, runReader)
import Data.Char (isUpper)
import Data.List (isInfixOf)
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe)

import           Language.Fixpoint.Types (PPrint)
import qualified Language.Fixpoint.Types as F
import           Language.Haskell.Liquid.Types.RType (PVarBV (PV), RTVar (RTVar), RTyCon (RTyCon), RTyVar (RTV), RTypeBV (..), SpecType, UReft, UReftBV (MkUReft))

import           Language.Haskell.Liquid.RefCore.Misc
import           Language.Haskell.Liquid.RefCore.Names (Id, ttTmName, ffTmName)
import qualified Language.Haskell.Liquid.RefCore.Calculus as Calc

-- | Helper for unsupported constructs
unsupported :: String -> a
unsupported msg = error $ "[SpecToLH] " ++ msg

-- | Translation of an RTyCon as a builtin or as a type constructor
transCon :: Id -> RTyCon -> Calc.BaseType
transCon modId (RTyCon tc [] _) = M.findWithDefault (Calc.TC name) name builtinTCs
  where
    name = showppStripped modId tc
transCon _ c = unsupported $ "Type constructor with type args not supported (no polymorphism): " ++ show c

showppStripped :: (PPrint a) => Id -> a -> String
showppStripped modId = stripLegalName modId . F.showpp

data InternalCont = ConstrArgsCtx (Maybe Id) [Id]
  deriving (Show)

-- TODO: replace with something that uses notations as defined in liquidhaskell source
internalConstrRef :: (PPrint a) => Id -> a -> Reader InternalCont Bool
internalConstrRef modId s = asks go
  where
    go (ConstrArgsCtx Nothing _) = False
    go (ConstrArgsCtx (Just c) args) = checkPred (parseConstrPred modId s)
      where
        checkPred (Just "is", _) = True
        checkPred _ = checkArg (getFuncArgName modId s)
        checkArg (Just c', _) | stripLegalName modId c' == c = True
        checkArg (Just x, _) | x `elem` args = False
        checkArg (Just c', x) = showppStripped modId c' `elem` c : args && x `elem` args
        checkArg (Nothing, "") = True
        checkArg _ = False

getFuncArgName :: (PPrint a) => Id -> a -> (Maybe Id, Id)
getFuncArgName modId symb = go sym
  where
    -- \| local name generated by parser
    go s | length (filter ('$' ==) s) == 1 && "$db##" `isInfixOf` s = case split '$' s of
      [n, s'] -> (Nothing, stripLegalName modId res)
        where
          res :: Id
          res = case split '#' s' of
            ["db", "", num] -> n ++ num
            _ -> n ++ s'
      _ -> error "Impossible case"
    go s | length (filter ('$' ==) s) > 1 = (Nothing, "")
    go s = case split '#' s of
      [n, "", func] -> (Just (stripLegalName modId n), stripLegalName modId func)
      [func] -> (Nothing, stripLegalName modId func)
      [_, "", n, "", func] -> (Just (stripLegalName modId n), stripLegalName modId func)
      other | length other > 6 -> (Nothing, "") -- go . concat . drop 2 $ split '#' s
      _ -> (Nothing, "")
    sym = F.showpp symb

transVarName :: (PPrint a) => Id -> a -> String
transVarName modId x = case getFuncArgName modId x of
  (Just n, func) -> stripLegalName modId $ func ++ "." ++ n
  (Nothing, "") -> "illegalInternalName"
  (Nothing, func) -> func

parseConstrPred :: (PPrint a) => Id -> a -> (Maybe Id, Id)
parseConstrPred modId symb = case split '$' $ F.showpp symb of
  [n, func] -> (Just (stripLegalName modId n), stripLegalName modId func)
  [func] -> (Nothing, stripLegalName modId func)
  _ -> (Nothing, F.showpp symb)

-- | Translation of a LH SpecType to a refined argument {x: A | r}
--
-- > transType(RVar n ref) = {x: x | transRef(x,ref)} -- where x = showName n
-- > transType({f: (arg -> ret) | ref}) = {f: (x:transType(arg) -> transType(ret)) | transRef(x,ref)} -- where transType(arg) = {x:_ | _}
-- > transType(RAllT (RVar n _) typ ref) = {x:tp | transRef(x,ref)} -- where transType(typ) = {_:tp | _} and x = showName n
-- > transType(PType (PV n _ _ _) typ) = {n:tp | true} -- where transType(typ) = {_:tp | _}
-- > transType(RApp f _ _ reft) = {x: (transCon f) | transRef(x,reft)} -- where reft = {x: _ | _}
transType :: Id -> InternalCont -> SpecType -> Calc.RefType
-- \| Type variables
transType modId intCont (RVar n ref) = case x of
  "()" -> Calc.RefType x Calc.unitTp reft
  _ -> Calc.RefType x (Calc.TC x) reft
  where
    x = showName modId n
    reft = transRef modId intCont x ref
-- \| Functions
transType modId intCont (RFun f _ arg ret _) =
  --  trace ("transType RFun" ++ show (ur_reft ref)) $
  Calc.ArrType x argTp' retTp'
  where
    x = transVarName modId f
    argTp' = transType modId intCont arg
    retTp' = transType modId intCont ret
-- \| Forall?
transType modId intCont (RAllT (RTVar (RTV n) _) typ ref) =
  wrapWith x r (transType modId intCont typ)
  where
    x = showName modId n
    r = transRef modId intCont x ref
-- \| Abstract refinements
transType modId intCont (RAllP (PV n _ _) typ) =
  wrapWith x Calc.ttTm (transType modId intCont typ)
  where
    x = showName modId n
-- \| Application of type constructor/builtin to types
transType modId intCont (RApp f _ _ reft) = Calc.RefType x transT r
  where
    transT = transCon modId f
    x = refVar modId intCont reft
    r = transRef modId intCont x reft
transType _ _ (REx {}) = unsupported "transType: unsupported REx"
transType _ _ (RExprArg {}) = unsupported "transType: unsupported RExprArg"
transType _ _ (RAppTy {}) = unsupported "transType: unsupported RAppTy"
transType _ _ (RRTy {}) = unsupported "transType: unsupported RRTy"
transType _ _ (RHole {}) = unsupported "transType: unsupported RHole"

-- | Re-bind a translated type under the name @x@ with refinement @reft@:
-- on a base type it replaces the refinement, on an arrow it wraps the whole
-- arrow as a unit-typed refined argument.
wrapWith :: Id -> Calc.Reft -> Calc.RefType -> Calc.RefType
wrapWith x reft (Calc.RefType _ tp _) = Calc.RefType x tp reft
wrapWith x reft arr@Calc.ArrType {} = Calc.ArrType x arr (Calc.RefType "_" Calc.unitTp reft)

showName :: (Show a) => Id -> a -> String
showName modId = transVarName modId . show

-- MkUReft (F.Reft (s, tm)) is the representation of {s:_ | tm}
transRefType :: Id -> InternalCont -> UReft -> (F.Symbol, Calc.Reft)
transRefType modId intCont (MkUReft (F.Reft (s, tm)) _) = (s, runReader (transExp modId binder tm) intCont)
  where
    binder = transVarName modId s

transRef :: Id -> InternalCont -> String -> UReft -> Calc.Reft
transRef modId intCont x r =
  let (s, ref') = transRefType modId intCont r
   in Calc.subst (Calc.mkVar x) (transVarName modId s) ref'

refVar :: Id -> InternalCont -> UReft -> String
refVar modId intCont = transVarName modId . fst . transRefType modId intCont

internal :: Id -> F.Expr -> Reader InternalCont Bool
internal modId = go
  where
    go (F.PAtom _ e1 e2) = (||) <$> go e1 <*> go e2
    go (F.EApp f t') = (||) <$> go f <*> go t'
    go (F.EVar sym) = internalConstrRef modId sym
    go (F.PAnd es) = allM go es
    go (F.PNot form) = go form
    go F.EBin {} = pure False
    go _ = pure False

-- | Translation of an LH-fixpoint Types.Expr (predicates used for refinements)
--
-- > transExpr(e) = tt -- if e is internal
-- > transExpr(brel e1 e2) = brel (transExpr e1) (transExpr e2)
-- > transExpr((…(x e1)…) en) = x [transExpr(e1), …, transExpr(en)]
-- > transExpr(x) = x
-- > transExpr(e1 && … && en) = &&_{ei not internal} trans(ei)
-- > transExpr(e1 <=> e2) = transExpr(e1) == transExpr(e2)
-- > transExpr(e1 => e2) = transExpr(e1) => transExpr(e2)
-- > transExpr(sym) = sym
-- > transExpr(i ∈ Int) = i
-- > transExpr(f ∈ Float) = f
-- > transExpr(s ∈ String) = s
-- > transExpr(not e) = not (transExpr e)
-- > transExpr(Ebin f e1 e2) = Ebin (transExpr e1) (transExpr e2)
-- > transExpr(if e1 then e2 else e3) = (e1 && e2) || (not e1 && e3)
-- > transExpr(or [e1,…,en])= ||_{ei} trans(ei)
transExp :: Id -> Id -> F.Expr -> Reader InternalCont Calc.Reft
transExp modId binder = transExpr
  where
    -- Construct a Var or DC depending on whether the name looks like
    -- a Haskell data constructor (starts with uppercase) and is not
    -- the current refinement binder (e.g. "VV").
    mkVarOrDC :: Id -> Calc.Reft
    mkVarOrDC s = M.findWithDefault dflt s builtinDCs
      where
        dflt
          | s /= binder, c : _ <- s, isUpper c = Calc.DC s
          | otherwise = Calc.mkVar s
    transExpr :: F.Expr -> Reader InternalCont Calc.Reft
    transExpr term = ifM (internal modId term) (pure Calc.ttTm) (go term)
    go :: F.Expr -> Reader InternalCont Calc.Reft
    go (F.PAtom brel e1 e2) =
      Calc.Bop (transBrel brel) <$> transExpr e1 <*> transExpr e2
    go app@(F.EApp {}) = goApp (flattenFixApp app)
    go (F.EVar sym) = pure $ mkVarOrDC (transVarName modId sym)
    go (F.PAnd es) = foldAnds <$> (mapM transExpr =<< filterM (fmap not . internalConstrRef modId) es)
    go (F.POr es) = foldOrs <$> mapM transExpr es
    go (F.PIff ante concl) = Calc.Bop Calc.Iff <$> transExpr ante <*> transExpr concl
    go (F.PImp ante concl) = Calc.Bop Calc.Impl <$> transExpr ante <*> transExpr concl
    go (F.ECon (F.I i)) = pure $ Calc.IntLit i
    go (F.ECon (F.R d)) = pure $ Calc.FloatLit d
    go (F.ECon (F.L str _)) = pure . Calc.StringLit $ show str
    go (F.PNot form) = Calc.Neg <$> transExpr form
    go (F.EBin f e1 e2)
      | Just bop <- M.lookup (F.showpp f) bops =
          Calc.Bop bop <$> transExpr e1 <*> transExpr e2
    go (F.EIte cond thenE elseE) = do
      cTm <- transExpr cond
      tTm <- transExpr thenE
      eTm <- transExpr elseE
      pure $ Calc.Bop Calc.Or (Calc.Bop Calc.And cTm tTm) (Calc.Bop Calc.And (Calc.Neg cTm) eTm)
    go (F.ESym sym) = unsupported $ "Uninterpreted symbol encountered: " ++ show sym
    go term = unsupported $ "Undefined expr translation: \n" ++ F.showpp term
    goApp (F.EVar f, ts) = foldl Calc.App (mkVarOrDC (transVarName modId f)) <$> mapM transExpr ts
    goApp (other, _) = unsupported $ "Expected variable at head of application in transExp, got: " ++ F.showpp other
    foldAnds [] = Calc.ttTm
    foldAnds rs = foldl1 (Calc.Bop Calc.And) rs
    foldOrs [] = Calc.ttTm -- TODO: [LP] An empty disjunction should be false no?
    foldOrs rs = foldl1 (Calc.Bop Calc.Or) rs

flattenFixApp :: F.Expr -> (F.Expr, [F.Expr])
flattenFixApp = go []
  where
    go acc v@F.EVar {} = (v, acc)
    go acc (F.EApp f t) = go (t : acc) f
    go _ _ = unsupported "Application expected in flattenFixApp."

-- | Translation of an arrow type
--
-- > transFun({f_1: t1 → {f_2: t_2 → {… → {f_n: t_n → t | _} … } | _} | _}) = ([(f_1, transType t_1), …, (f_n, transType t_n)], transType t) -- where n ≥ 0
-- > -- with some subtleties on the names, that relies on an additional context parameter
transFun :: Id -> Maybe Id -> SpecType -> Calc.RefType
transFun modId fO spTp@(RFun g _ _ _ _) = go spTp [showppStripped modId g]
  where
    go :: SpecType -> [Id] -> Calc.RefType
    -- TODO: put an error or a warning if the ignored refinement is not trivial
    go (RFun f _ tin tout _) vars = Calc.ArrType n (trans tin) (go tout (n : vars))
      where
        (nO, func) = getFuncArgName modId f
        n = fromMaybe func nO
        trans = transType modId (ConstrArgsCtx (Just n) vars)
    go spTp' vars = transType modId (ConstrArgsCtx (Just f) vars) spTp'
      where
        f = maybe (showppStripped modId g) (stripLegalName modId) fO
transFun modId fO spTp = transType modId intCont spTp
  where
    intCont = ConstrArgsCtx (stripLegalName modId <$> fO) []

-- | Translation of a specification of LH SpecType
transSig :: Id -> Maybe Id -> SpecType -> Calc.RefType
transSig = transFun

-- | Trivial translation of binary relations
transBrel :: F.Brel -> Calc.Bop
transBrel F.Eq = Calc.Eq
transBrel F.Ne = Calc.Neq
transBrel F.Ge = Calc.Geq
transBrel F.Le = Calc.Leq
transBrel F.Gt = Calc.Gt
transBrel F.Lt = Calc.Lt
transBrel rel = unsupported $ "Undefined brel translation: " ++ show rel

-- | LH builtin binary operators (on Int) (in Fixpoint, also RTimes (*.) and RDiv (/.), but not in CoreToLogic)
bops :: M.Map String Calc.Bop
bops =
  M.fromList
    [ ("+", Calc.Plus),
      ("-", Calc.Minus),
      ("*", Calc.Times),
      ("/", Calc.Div),
      ("%", Calc.Mod),
      ("==", Calc.Eq),
      ("/=", Calc.Neq),
      (">=", Calc.Geq),
      (">", Calc.Gt),
      ("<=", Calc.Leq),
      ("<", Calc.Lt)
    ]

-- | LH builtin data constructors
builtinDCs :: M.Map String Calc.Reft
builtinDCs =
  M.fromList
    [ ("()", Calc.unitTm),
      ("trivial", Calc.unitTm),
      (ttTmName, Calc.ttTm),
      (ffTmName, Calc.ffTm)
    ]

-- | LH builtin types: the base types and the unit type constructor
builtinTCs :: M.Map String Calc.BaseType
builtinTCs =
  M.fromList
    [ ("Integer", Calc.Builtin Calc.Integer),
      ("Int", Calc.Builtin Calc.Integer),
      ("Float", Calc.Builtin Calc.Double),
      ("()", Calc.unitTp)
    ]