-- SPDX-FileCopyrightText: 2020 Tocqueville Group
--
-- SPDX-License-Identifier: LicenseRef-MIT-TQ

module Michelson.TypeCheck.TypeCheck
  ( TcInstrHandler
  , TcOriginatedContracts
  , TcResult
  , TypeCheckEnv (..)
  , TypeCheck
  , runTypeCheck
  , TypeCheckInstr
  , runTypeCheckIsolated
  , runTypeCheckInstrIsolated
  , mapTCError

  , tcExtFramesL
  , tcModeL
  , TypeCheckMode(..)
  , SomeParamType(..)
  , mkSomeParamType
  , mkSomeParamTypeUnsafe
  ) where

import Control.Monad.Except (withExceptT)
import Control.Monad.Reader (mapReaderT)
import Data.Default (def)
import Data.Singletons (Sing)
import Fmt (Buildable, build, pretty)
import qualified Text.Show

import Michelson.ErrorPos (InstrCallStack)
import Michelson.TypeCheck.Error (TCError(..), TCTypeError(..))
import Michelson.TypeCheck.Types
import qualified Michelson.Typed as T
import qualified Michelson.Untyped as U
import Tezos.Address (ContractHash)
import Util.Lens

type TypeCheck =
  ExceptT TCError
    (State TypeCheckEnv)

data SomeParamType = forall t. (T.ParameterScope t) =>
  SomeParamType (Sing t) (T.ParamNotes t)

-- | @Show@ instance of @SomeParamType@, mainly used in test.
instance Show SomeParamType where
  show :: SomeParamType -> String
show = ParameterType -> String
forall b a. (Show a, IsString b) => a -> b
show (ParameterType -> String)
-> (SomeParamType -> ParameterType) -> SomeParamType -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SomeParamType -> ParameterType
someParamToParameterType

-- | @Eq@ instance of @SomeParamType@, mainly used in test.
instance Eq SomeParamType where
  s1 :: SomeParamType
s1 == :: SomeParamType -> SomeParamType -> Bool
== s2 :: SomeParamType
s2 = SomeParamType -> ParameterType
someParamToParameterType SomeParamType
s1 ParameterType -> ParameterType -> Bool
forall a. Eq a => a -> a -> Bool
== SomeParamType -> ParameterType
someParamToParameterType SomeParamType
s2

-- | @Buildable@ instance of @SomeParamType@, mainly used in test.
instance Buildable SomeParamType where
  build :: SomeParamType -> Builder
build = ParameterType -> Builder
forall p. Buildable p => p -> Builder
build (ParameterType -> Builder)
-> (SomeParamType -> ParameterType) -> SomeParamType -> Builder
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SomeParamType -> ParameterType
someParamToParameterType

-- | Helper function means to provide a quick way for creating instance
-- of @SomeParamType@ needed in test.
someParamToParameterType :: SomeParamType -> U.ParameterType
someParamToParameterType :: SomeParamType -> ParameterType
someParamToParameterType (SomeParamType s :: Sing t
s T.ParamNotesUnsafe{..}) =
  Type -> RootAnn -> ParameterType
U.ParameterType (Sing t -> Notes t -> Type
forall (t :: T). KnownT t => Sing t -> Notes t -> Type
T.AsUTypeExt Sing t
s Notes t
pnNotes) RootAnn
pnRootAnn

-- | Construct @SomeParamType@ from @ParameterType@, mainly used in test.
mkSomeParamTypeUnsafe :: HasCallStack => U.ParameterType -> SomeParamType
mkSomeParamTypeUnsafe :: ParameterType -> SomeParamType
mkSomeParamTypeUnsafe p :: ParameterType
p =
  case ParameterType -> Either TCError SomeParamType
mkSomeParamType ParameterType
p of
    Right sp :: SomeParamType
sp ->  SomeParamType
sp
    Left err :: TCError
err -> Text -> SomeParamType
forall a. HasCallStack => Text -> a
error (Text -> SomeParamType) -> Text -> SomeParamType
forall a b. (a -> b) -> a -> b
$ "Illegal type in parameter of env contract: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> TCError -> Text
forall a b. (Buildable a, FromBuilder b) => a -> b
pretty TCError
err

mkSomeParamType :: U.ParameterType -> Either TCError SomeParamType
mkSomeParamType :: ParameterType -> Either TCError SomeParamType
mkSomeParamType (U.ParameterType t :: Type
t ann :: RootAnn
ann) =
  Type
-> (forall (t :: T).
    KnownT t =>
    Notes t -> Either TCError SomeParamType)
-> Either TCError SomeParamType
forall r. Type -> (forall (t :: T). KnownT t => Notes t -> r) -> r
T.withUType Type
t ((forall (t :: T).
  KnownT t =>
  Notes t -> Either TCError SomeParamType)
 -> Either TCError SomeParamType)
-> (forall (t :: T).
    KnownT t =>
    Notes t -> Either TCError SomeParamType)
-> Either TCError SomeParamType
forall a b. (a -> b) -> a -> b
$ \(Notes t
notescp :: T.Notes t) -> do
    case CheckScope (ParameterScope t) =>
Either BadTypeForScope (Dict (ParameterScope t))
forall (c :: Constraint).
CheckScope c =>
Either BadTypeForScope (Dict c)
T.checkScope @(T.ParameterScope t) of
      Right T.Dict ->
        case Notes t -> RootAnn -> Either ParamEpError (ParamNotes t)
forall (t :: T).
Notes t -> RootAnn -> Either ParamEpError (ParamNotes t)
T.mkParamNotes Notes t
notescp RootAnn
ann of
          Right paramNotes :: ParamNotes t
paramNotes -> SomeParamType -> Either TCError SomeParamType
forall a b. b -> Either a b
Right (SomeParamType -> Either TCError SomeParamType)
-> SomeParamType -> Either TCError SomeParamType
forall a b. (a -> b) -> a -> b
$ Sing t -> ParamNotes t -> SomeParamType
forall (t :: T).
ParameterScope t =>
Sing t -> ParamNotes t -> SomeParamType
SomeParamType Sing t
forall k (a :: k). SingI a => Sing a
T.sing ParamNotes t
paramNotes
          Left err :: ParamEpError
err ->
            TCError -> Either TCError SomeParamType
forall a b. a -> Either a b
Left (TCError -> Either TCError SomeParamType)
-> TCError -> Either TCError SomeParamType
forall a b. (a -> b) -> a -> b
$ Text -> Maybe TCTypeError -> TCError
TCContractError "invalid parameter declaration: " (Maybe TCTypeError -> TCError) -> Maybe TCTypeError -> TCError
forall a b. (a -> b) -> a -> b
$ TCTypeError -> Maybe TCTypeError
forall a. a -> Maybe a
Just (TCTypeError -> Maybe TCTypeError)
-> TCTypeError -> Maybe TCTypeError
forall a b. (a -> b) -> a -> b
$ ParamEpError -> TCTypeError
IllegalParamDecl ParamEpError
err
      Left err :: BadTypeForScope
err -> TCError -> Either TCError SomeParamType
forall a b. a -> Either a b
Left (TCError -> Either TCError SomeParamType)
-> TCError -> Either TCError SomeParamType
forall a b. (a -> b) -> a -> b
$ Text -> Maybe TCTypeError -> TCError
TCContractError ("Parameter type is invalid: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> BadTypeForScope -> Text
forall a b. (Buildable a, FromBuilder b) => a -> b
pretty BadTypeForScope
err) Maybe TCTypeError
forall a. Maybe a
Nothing

type TcOriginatedContracts = Map ContractHash SomeParamType

-- | Typechecking mode that tells the type checker whether it is typechecking
-- contract code in actual contract, lambda, or test.
data TypeCheckMode
  = TypeCheckValue (U.Value, T.T)
  | TypeCheckContract SomeParamType
  | TypeCheckTest
  | TypeCheckPack

-- | The typechecking state
data TypeCheckEnv = TypeCheckEnv
  { TypeCheckEnv -> TcExtFrames
tcExtFrames :: ~TcExtFrames
  , TypeCheckEnv -> TypeCheckMode
tcMode :: ~TypeCheckMode
  }

makeLensesWith postfixLFields ''TypeCheckEnv

runTypeCheck :: TypeCheckMode -> TypeCheck a -> Either TCError a
runTypeCheck :: TypeCheckMode -> TypeCheck a -> Either TCError a
runTypeCheck mode :: TypeCheckMode
mode = TypeCheckEnv
-> State TypeCheckEnv (Either TCError a) -> Either TCError a
forall s a. s -> State s a -> a
evaluatingState (TcExtFrames -> TypeCheckMode -> TypeCheckEnv
TypeCheckEnv [] TypeCheckMode
mode) (State TypeCheckEnv (Either TCError a) -> Either TCError a)
-> (TypeCheck a -> State TypeCheckEnv (Either TCError a))
-> TypeCheck a
-> Either TCError a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TypeCheck a -> State TypeCheckEnv (Either TCError a)
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT

-- | Run type checker as if it worked isolated from other world -
-- no access to environment of the current contract is allowed.
--
-- Use this function for test purposes only or for some utilities when
-- environment does not matter. In particular, it is assumed that
-- whatever we typecheck does not depend on the parameter type of the
-- contract which is being typechecked (because there is no contract
-- that we are typechecking).
runTypeCheckIsolated :: TypeCheck a -> Either TCError a
runTypeCheckIsolated :: TypeCheck a -> Either TCError a
runTypeCheckIsolated = TypeCheckMode -> TypeCheck a -> Either TCError a
forall a. TypeCheckMode -> TypeCheck a -> Either TCError a
runTypeCheck TypeCheckMode
TypeCheckTest

type TcResult inp = Either TCError (SomeInstr inp)

type TypeCheckInstr =
       ReaderT InstrCallStack TypeCheck

-- | Similar to 'runTypeCheckIsolated', but for 'TypeCheckInstr.'
runTypeCheckInstrIsolated :: TypeCheckInstr a -> Either TCError a
runTypeCheckInstrIsolated :: TypeCheckInstr a -> Either TCError a
runTypeCheckInstrIsolated =
  TypeCheck a -> Either TCError a
forall a. TypeCheck a -> Either TCError a
runTypeCheckIsolated (TypeCheck a -> Either TCError a)
-> (TypeCheckInstr a -> TypeCheck a)
-> TypeCheckInstr a
-> Either TCError a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TypeCheckInstr a -> InstrCallStack -> TypeCheck a)
-> InstrCallStack -> TypeCheckInstr a -> TypeCheck a
forall a b c. (a -> b -> c) -> b -> a -> c
flip TypeCheckInstr a -> InstrCallStack -> TypeCheck a
forall r (m :: * -> *) a. ReaderT r m a -> r -> m a
runReaderT InstrCallStack
forall a. Default a => a
def

-- | Run 'TypeCheckInstr' and modify thrown errors using given functions.
mapTCError :: (TCError -> TCError) -> TypeCheckInstr a -> TypeCheckInstr a
mapTCError :: (TCError -> TCError) -> TypeCheckInstr a -> TypeCheckInstr a
mapTCError f :: TCError -> TCError
f = (ExceptT TCError (State TypeCheckEnv) a
 -> ExceptT TCError (State TypeCheckEnv) a)
-> TypeCheckInstr a -> TypeCheckInstr a
forall (m :: * -> *) a (n :: * -> *) b r.
(m a -> n b) -> ReaderT r m a -> ReaderT r n b
mapReaderT ((TCError -> TCError)
-> ExceptT TCError (State TypeCheckEnv) a
-> ExceptT TCError (State TypeCheckEnv) a
forall (m :: * -> *) e e' a.
Functor m =>
(e -> e') -> ExceptT e m a -> ExceptT e' m a
withExceptT TCError -> TCError
f)

-- pva701: it's really painful to add arguments to TcInstrHandler
-- due to necessity to refactor @typeCheckInstr@.
-- Also functions which are being called from @typeCheckInstr@ would
-- have to be refactored too.
-- Therefore, I am using ReaderT over TypeCheck.
type TcInstrHandler
   = forall inp. (Typeable inp, HasCallStack)
      => U.ExpandedInstr
      -> HST inp
      -> TypeCheckInstr (SomeInstr inp)