packages feed

morley-1.3.0: src/Michelson/Preprocess.hs

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

-- | Apply some transformations to Michelson code.

module Michelson.Preprocess
  ( transformStrings
  , transformBytes
  ) where

import Data.Default (def)

import Michelson.Text (MText)
import Michelson.Typed

-- Note: we may add such transformation for long bytestrings as well if deemed necessary.
-- And for other constants which may be arbitrarily large (e. g. lists).
-- For now we need it only for strings and probably won't need for anything else.

-- | Transform all strings in a typed instructions using given
-- function. The first argument specifies whether we should go into
-- arguments that contain instructions.
transformStrings :: Bool -> (MText -> MText) -> Instr inp out -> Instr inp out
transformStrings goToValues f = transformConstants goToValues mapStr
  where
    mapStr :: Value t -> Value t
    mapStr = \case
      VString str -> VString $ f str
      v -> v

-- | Similar to 'transformStrings' but for bytes.
transformBytes :: Bool -> (ByteString -> ByteString) -> Instr inp out -> Instr inp out
transformBytes goToValues f = transformConstants goToValues mapBytes
  where
    mapBytes :: Value t -> Value t
    mapBytes = \case
      VBytes bytes -> VBytes $ f bytes
      v -> v

transformConstants ::
     forall inp out.
     Bool
  -> (forall t. Value t -> Value t)
  -- ^ Should transform only atomic values, 'dfsValue' will be applied to it.
  -> Instr inp out
  -> Instr inp out
transformConstants dsGoToValues f = fst . dfsInstr def{ dsGoToValues } step
  where
    step :: forall i o. Instr i o -> (Instr i o, ())
    step = (,()) . \case
      PUSH v -> PUSH (dfsModifyValue f v)
      i -> i