Skip to content

A peer-to-peer stack for code collaboration

Initial commit.

Julian K. Arni34cd5c8bcd81
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..f44ee4b
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,10 @@
+dist
+cabal-dev
+*.o
+*.hi
+*.chi
+*.chs.h
+.virthualenv
+.hsenv
+.cabal-sandbox/
+cabal.sandbox.config
diff --git a/.stylish-haskell.yaml b/.stylish-haskell.yaml
new file mode 100644
index 0000000..9d33231
--- /dev/null
+++ b/.stylish-haskell.yaml
@@ -0,0 +1,187 @@
+# stylish-haskell configuration file
+
+steps:
+ - simple_align:
+ cases: true
+ top_level_patterns: true
+ records: true
+
+ - imports:
+ # There are different ways we can align names and lists.
+ #
+ # - global: Align the import names and import list throughout the entire
+ # file.
+ #
+ # - file: Like global, but don't add padding when there are no qualified
+ # imports in the file.
+ #
+ # - group: Only align the imports per group (a group is formed by adjacent
+ # import lines).
+ #
+ # - none: Do not perform any alignment.
+ #
+ # Default: global.
+ align: global
+
+ # The following options affect only import list alignment.
+ #
+ # List align has following options:
+ #
+ # - after_alias: Import list is aligned with end of import including
+ # 'as' and 'hiding' keywords.
+ #
+ # > import qualified Data.List as List (concat, foldl, foldr, head,
+ # > init, last, length)
+ #
+ # - with_alias: Import list is aligned with start of alias or hiding.
+ #
+ # > import qualified Data.List as List (concat, foldl, foldr, head,
+ # > init, last, length)
+ #
+ # - new_line: Import list starts always on new line.
+ #
+ # > import qualified Data.List as List
+ # > (concat, foldl, foldr, head, init, last, length)
+ #
+ # Default: after_alias
+ list_align: after_alias
+
+ # Right-pad the module names to align imports in a group:
+ #
+ # - true: a little more readable
+ #
+ # > import qualified Data.List as List (concat, foldl, foldr,
+ # > init, last, length)
+ # > import qualified Data.List.Extra as List (concat, foldl, foldr,
+ # > init, last, length)
+ #
+ # - false: diff-safe
+ #
+ # > import qualified Data.List as List (concat, foldl, foldr, init,
+ # > last, length)
+ # > import qualified Data.List.Extra as List (concat, foldl, foldr,
+ # > init, last, length)
+ #
+ # Default: true
+ pad_module_names: false
+
+ # Long list align style takes effect when import is too long. This is
+ # determined by 'columns' setting.
+ #
+ # - inline: This option will put as much specs on same line as possible.
+ #
+ # - new_line: Import list will start on new line.
+ #
+ # - new_line_multiline: Import list will start on new line when it's
+ # short enough to fit to single line. Otherwise it'll be multiline.
+ #
+ # - multiline: One line per import list entry.
+ # Type with constructor list acts like single import.
+ #
+ # > import qualified Data.Map as M
+ # > ( empty
+ # > , singleton
+ # > , ...
+ # > , delete
+ # > )
+ #
+ # Default: inline
+ long_list_align: inline
+
+ # Align empty list (importing instances)
+ #
+ # Empty list align has following options
+ #
+ # - inherit: inherit list_align setting
+ #
+ # - right_after: () is right after the module name:
+ #
+ # > import Vector.Instances ()
+ #
+ # Default: inherit
+ empty_list_align: inherit
+
+ # List padding determines indentation of import list on lines after import.
+ # This option affects 'long_list_align'.
+ #
+ # - <integer>: constant value
+ #
+ # - module_name: align under start of module name.
+ # Useful for 'file' and 'group' align settings.
+ list_padding: module_name
+
+ # Separate lists option affects formatting of import list for type
+ # or class. The only difference is single space between type and list
+ # of constructors, selectors and class functions.
+ #
+ # - true: There is single space between Foldable type and list of it's
+ # functions.
+ #
+ # > import Data.Foldable (Foldable (fold, foldl, foldMap))
+ #
+ # - false: There is no space between Foldable type and list of it's
+ # functions.
+ #
+ # > import Data.Foldable (Foldable(fold, foldl, foldMap))
+ #
+ # Default: true
+ separate_lists: false
+
+ # Space surround option affects formatting of import lists on a single
+ # line. The only difference is single space after the initial
+ # parenthesis and a single space before the terminal parenthesis.
+ #
+ # - true: There is single space associated with the enclosing
+ # parenthesis.
+ #
+ # > import Data.Foo ( foo )
+ #
+ # - false: There is no space associated with the enclosing parenthesis
+ #
+ # > import Data.Foo (foo)
+ #
+ # Default: false
+ space_surround: false
+
+ - language_pragmas:
+ # We can generate different styles of language pragma lists.
+ #
+ # - vertical: Vertical-spaced language pragmas, one per line.
+ #
+ # - compact: A more compact style.
+ #
+ # - compact_line: Similar to compact, but wrap each line with
+ # `{-#LANGUAGE #-}'.
+ #
+ # Default: vertical.
+ style: vertical
+
+ # Align affects alignment of closing pragma brackets.
+ #
+ # - true: Brackets are aligned in same column.
+ #
+ # - false: Brackets are not aligned together. There is only one space
+ # between actual import and closing bracket.
+ #
+ # Default: true
+ align: false
+
+ # stylish-haskell can detect redundancy of some language pragmas. If this
+ # is set to true, it will remove those redundant pragmas. Default: true.
+ remove_redundant: true
+
+ - trailing_whitespace: {}
+
+columns: 80
+
+newline: native
+
+language_extensions:
+ - FlexibleContexts
+ - MultiWayIf
+ - RecordWildCards
+ - ScopedTypeVariables
+ - TupleSections
+ - TypeApplications
+ - TypeFamilies
+ - ViewPatterns
diff --git a/ChangeLog.md b/ChangeLog.md
new file mode 100644
index 0000000..95a6f47
--- /dev/null
+++ b/ChangeLog.md
@@ -0,0 +1,5 @@
+# Revision history for radicle
+
+## 0.0.0 -- YYYY-mm-dd
+
+* First version. Released on an unsuspecting world.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..5e77931
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,30 @@
+Copyright (c) 2018, Monadic
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+
+ * Neither the name of Julian K. Arni nor the names of other
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..6d18d96
--- /dev/null
+++ b/README.md
@@ -0,0 +1,21 @@
+# radicle
+
+TODO: Write description here
+
+## Installation
+
+TODO: Write installation instructions here
+
+## Usage
+
+TODO: Write usage instructions here
+
+## How to run tests
+
+```
+cabal configure --enable-tests && cabal build && cabal test
+```
+
+## Contributing
+
+TODO: Write contribution instructions here
diff --git a/package.yaml b/package.yaml
new file mode 100644
index 0000000..9e5396a
--- /dev/null
+++ b/package.yaml
@@ -0,0 +1,53 @@
+name: radicle
+version: '0.0.0'
+author: Monadic <[email protected]>
+maintainer: Monadic <[email protected]>
+license: BSD3
+git: oscoin/radicle
+extra-source-files:
+- README.md
+- ChangeLog.md
+
+dependencies:
+- base >=4 && <5
+- containers
+- megaparsec
+- mmorph
+- mtl
+- prettyprinter
+- text
+
+library:
+ source-dirs: src
+ ghc-options: -Wall
+
+tests:
+ spec:
+ main: Main.hs
+ source-dirs:
+ - test
+ ghc-options: -Wall
+ dependencies:
+ - base
+ - radicle
+ - QuickCheck
+ - quickcheck-instances
+ - string-qq
+ - tasty
+ - tasty-discover
+ - tasty-hunit
+ - tasty-quickcheck
+
+default-extensions:
+- AutoDeriveTypeable
+- DeriveDataTypeable
+- DeriveFunctor
+- DeriveGeneric
+- GeneralizedNewtypeDeriving
+- FlexibleContexts
+- OverloadedStrings
+- TupleSections
+- TypeFamilies
+- TypeOperators
+- RankNTypes
+- RecordWildCards
diff --git a/radicle.cabal b/radicle.cabal
new file mode 100644
index 0000000..706bc6f
--- /dev/null
+++ b/radicle.cabal
@@ -0,0 +1,75 @@
+-- This file has been generated from package.yaml by hpack version 0.20.0.
+--
+-- see: https://github.com/sol/hpack
+--
+-- hash: fd7a7108d97bdcf99bc499773b87517e72a468ea57d246e1cf78558c72d6922f
+
+name: radicle
+version: 0.0.0
+author: Monadic <[email protected]>
+maintainer: Monadic <[email protected]>
+license: BSD3
+license-file: LICENSE
+build-type: Simple
+cabal-version: >= 1.10
+
+extra-source-files:
+ ChangeLog.md
+ README.md
+
+source-repository head
+ type: git
+ location: oscoin/radicle
+
+library
+ hs-source-dirs:
+ src
+ default-extensions: AutoDeriveTypeable DeriveDataTypeable DeriveFunctor DeriveGeneric GeneralizedNewtypeDeriving FlexibleContexts OverloadedStrings TupleSections TypeFamilies TypeOperators RankNTypes RecordWildCards
+ ghc-options: -Wall
+ build-depends:
+ base >=4 && <5
+ , containers
+ , megaparsec
+ , mmorph
+ , mtl
+ , prettyprinter
+ , text
+ exposed-modules:
+ Radicle
+ Radicle.Internal
+ Radicle.Internal.Chain
+ Radicle.Internal.Core
+ Radicle.Internal.Parse
+ Radicle.Internal.Pretty
+ other-modules:
+ Paths_radicle
+ default-language: Haskell2010
+
+test-suite spec
+ type: exitcode-stdio-1.0
+ main-is: Main.hs
+ hs-source-dirs:
+ test
+ default-extensions: AutoDeriveTypeable DeriveDataTypeable DeriveFunctor DeriveGeneric GeneralizedNewtypeDeriving FlexibleContexts OverloadedStrings TupleSections TypeFamilies TypeOperators RankNTypes RecordWildCards
+ ghc-options: -Wall
+ build-depends:
+ QuickCheck
+ , base
+ , containers
+ , megaparsec
+ , mmorph
+ , mtl
+ , prettyprinter
+ , quickcheck-instances
+ , radicle
+ , string-qq
+ , tasty
+ , tasty-discover
+ , tasty-hunit
+ , tasty-quickcheck
+ , text
+ other-modules:
+ Radicle.Internal.Arbitrary
+ Radicle.Tests
+ Paths_radicle
+ default-language: Haskell2010
diff --git a/src/Radicle.hs b/src/Radicle.hs
new file mode 100644
index 0000000..045ae6a
--- /dev/null
+++ b/src/Radicle.hs
@@ -0,0 +1,35 @@
+module Radicle
+ (
+ -- * Language
+ Value(..)
+ , interpret
+ , LangError(..)
+ , ($$)
+ , Ident
+ , fromIdent
+ , makeIdent
+ , Env(..)
+ , primops
+
+ -- * Chains
+ , Chain(..)
+ , genesisChain
+ , foldChain
+ , foldChainFromSrc
+
+ -- * Subscribers
+ , Subscriber(..)
+ , makeSubscriber
+ , addSubscriber
+ , removeSubscribers
+
+ -- * Parsing
+ , parse
+ , parseTest
+
+ -- * Pretty-printing
+ , compactPretty
+
+ ) where
+
+import Radicle.Internal
diff --git a/src/Radicle/Internal.hs b/src/Radicle/Internal.hs
new file mode 100644
index 0000000..ebd85b8
--- /dev/null
+++ b/src/Radicle/Internal.hs
@@ -0,0 +1,30 @@
+module Radicle.Internal
+ ( module X
+ , makeIdent
+ , parse
+ , parseTest
+ ) where
+
+import Radicle.Internal.Chain as X
+import Radicle.Internal.Core as X
+import Radicle.Internal.Parse as X
+import Radicle.Internal.Pretty as X
+
+import Control.Monad.Except
+import Data.Text (Text)
+import qualified Text.Megaparsec as M
+
+-- | Smart constructor for Ident.
+makeIdent :: Text -> Maybe Ident
+makeIdent = M.parseMaybe identP
+
+-- | Parse a value, using the String as source name, and calling 'fail' with a
+-- pretty error in case of a parse error.
+parse :: MonadError String m => String -> Text -> m Value
+parse file src = case M.parse valueP file src of
+ Left err -> throwError $ M.parseErrorPretty' src err
+ Right v -> return v
+
+-- | Like 'parse', but uses "(test)" as the source name
+parseTest :: MonadError String m => Text -> m Value
+parseTest = parse "(test)"
diff --git a/src/Radicle/Internal/Chain.hs b/src/Radicle/Internal/Chain.hs
new file mode 100644
index 0000000..429c385
--- /dev/null
+++ b/src/Radicle/Internal/Chain.hs
@@ -0,0 +1,111 @@
+{-# LANGUAGE ScopedTypeVariables #-}
+module Radicle.Internal.Chain where
+
+import Control.Applicative (Alternative)
+import Control.Monad (foldM)
+import Control.Monad.Except (ExceptT(..), throwError)
+import Control.Monad.Fail (MonadFail)
+import Control.Monad.Identity (Identity, MonadFix, MonadPlus)
+import Control.Monad.Morph (MFunctor(hoist), MMonad)
+import Control.Monad.Reader (MonadReader, ReaderT(..), ask)
+import Control.Monad.Trans
+import Control.Monad.Writer (WriterT(..), writer)
+import Data.Bifunctor (first)
+import Data.Proxy (Proxy)
+import Data.Semigroup (Semigroup, (<>))
+import Data.Text (Text)
+import GHC.Generics (Generic)
+
+import Radicle.Internal.Core
+import Radicle.Internal.Parse
+
+-- | Subscribers receive (evaluated) values from a chain, and can perform
+-- side-effects.
+newtype Subscriber m a = Subscriber { fromSubscriber :: ReaderT Value m a }
+ deriving ( Generic, Functor, Monad, Applicative, MonadIO, MonadReader Value
+ , Alternative, MonadPlus, MonadFix, MonadTrans, MonadFail, MFunctor
+ , MMonad)
+
+instance Semigroup (m a) => Semigroup (Subscriber m a) where
+ Subscriber a <> Subscriber b = Subscriber . ReaderT $ \v ->
+ runReaderT a v <> runReaderT b v
+
+instance (Semigroup (m a), Monoid (m a)) => Monoid (Subscriber m a) where
+ mempty = Subscriber . ReaderT $ const mempty
+ mappend = (<>)
+
+runSubscriber :: Subscriber m a -> Value -> m a
+runSubscriber = runReaderT . fromSubscriber
+
+makeSubscriber :: (Value -> m a) -> Subscriber m a
+makeSubscriber = Subscriber . ReaderT
+
+-- | A blockchain definition.
+data Chain m a = Chain
+ { chainName :: [Text]
+ -- | The fold function.
+ , chainStep :: Env -> Value -> Either LangError Value
+ , chainEnv :: Env
+ -- | How to update the env, given a new value.
+ , chainUpdateEnv :: Value -> Env -> Env
+ -- | 'chainSubscriber' is called with each new Env and with evaluated
+ -- Value.
+ , chainSubscriber :: Subscriber m a
+ } deriving (Functor, Generic)
+
+
+instance MFunctor Chain where
+ hoist nat chain =
+ chain { chainSubscriber = hoist nat $ chainSubscriber chain }
+
+-- | A simple chain is one where we can ignore all subscribers.
+type SimpleChain a = Chain Proxy a
+
+-- | Add a subscriber to a chain. The values are combined with mappend for 'm
+-- a'.
+addSubscriber :: Semigroup (m a) => Chain m a -> Subscriber m a -> Chain m a
+addSubscriber chain newCB
+ = chain { chainSubscriber = chainSubscriber chain <> newCB }
+
+-- | Removes all subscribers.
+removeSubscribers :: (Semigroup (n b), Monoid (n b)) => Chain m a -> Chain n b
+removeSubscribers chain = chain { chainSubscriber = mempty }
+
+-- | The default genesis chain.
+genesisChain :: Chain Identity Value
+genesisChain = Chain
+ { chainName = []
+ , chainEnv = mempty
+ , chainStep = \env val -> runLangM env (eval val)
+ , chainUpdateEnv = updateEnv
+ , chainSubscriber = Subscriber ask
+ }
+
+updateEnv :: Value -> Env -> Env
+updateEnv v = case v of
+ List [Atom "set!", Atom a, val] -> setEnv a val
+ _ -> id
+
+
+-- | Fold a chain. All effects are accumulated with a monoid instance.
+foldChain :: forall m a t. (Monoid (m a), Foldable t)
+ => Chain m a -> t Value -> Either LangError (Chain m a, m a)
+foldChain chain vals = runWriterT $ foldM runChainStep chain vals
+ where
+ runChainStep :: Chain m a -> Value -> WriterT (m a) (Either LangError) (Chain m a)
+ runChainStep chain'@Chain{..} val = do
+ let mEvaled = chainStep chainEnv val
+ case mEvaled of
+ Left err -> throwError err
+ Right evaled ->
+ let newChain = chain' { chainEnv = chainUpdateEnv evaled chainEnv }
+ in writer (newChain, runSubscriber chainSubscriber evaled)
+
+
+-- | Fold a chain from a source file. The String argument is the name of the
+-- source file/block, used for error reporting.
+foldChainFromSrc :: Monoid (m a)
+ => String -> Text -> Chain m a -> Either LangError (Chain m a, m a)
+foldChainFromSrc sourceName srcCode chain =
+ let exprs = first ParseError <$> parseValues sourceName srcCode
+ in foldChain chain $ ExceptT exprs
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
new file mode 100644
index 0000000..cdf575d
--- /dev/null
+++ b/src/Radicle/Internal/Core.hs
@@ -0,0 +1,167 @@
+{-# LANGUAGE ScopedTypeVariables #-}
+module Radicle.Internal.Core where
+
+import Control.Monad.Except (ExceptT, MonadError, runExceptT,
+ throwError)
+import Control.Monad.Reader (MonadReader, Reader, ask, local,
+ runReader)
+import Data.Data (Data)
+import Data.Map (Map)
+import qualified Data.Map as Map
+import Data.Semigroup (Semigroup, (<>))
+import Data.Text (Text)
+import qualified Data.Text as T
+import Data.Void (Void)
+import GHC.Exts (IsList(..), IsString)
+import GHC.Generics (Generic)
+import qualified Text.Megaparsec.Error as Par
+
+-- * Value
+
+-- | An error throw during parsing or evaluating expressions in the language.
+data LangError =
+ UnknownIdentifier Ident
+ | Impossible Text
+ | TypeError Text
+ | WrongNumberOfArgs
+ Text -- ^ function name
+ Int -- ^ expected
+ Int -- ^ actual
+ | OtherError Text
+ | ParseError (Par.ParseError Char Void)
+ deriving (Eq, Show, Read, Generic)
+
+-- | An identifier in the language.
+--
+-- Not all Texts are valid identifiers, so you should not be using the Ident
+-- constructor directly. Instead, use makeIdent from Oscoin.Language
+newtype Ident = Ident { fromIdent :: Text }
+ deriving (Eq, Show, Read, Ord, Generic, IsString, Data)
+
+
+-- | An expression or value in the language.
+data Value =
+ Atom Ident
+ | String Text
+ | Boolean Bool
+ | List [Value]
+ | Primop Ident
+ | Apply Value [Value]
+ | SortedMap (Map.Map Ident Value)
+ -- | Since there are no side-effects, there is no point having a list of
+ -- values for the body of a lambda.
+ | Lambda
+ [Ident] -- ^ parameters
+ Value -- ^ body.
+ (Maybe Env) -- ^ closure
+ deriving (Eq, Ord, Show, Read, Generic, Data)
+
+-- | The environment, which keeps all known bindings.
+newtype Env = Env { fromEnv :: Map Ident Value }
+ deriving (Eq, Show, Ord, Read, Semigroup, Monoid, Generic, Data)
+
+instance IsList Env where
+ type Item Env = (Ident, Value)
+ fromList = Env . fromList
+ toList = GHC.Exts.toList . fromEnv
+
+-- | Set the value of an identifier in the Env.
+setEnv :: Ident -> Value -> Env -> Env
+setEnv i v (Env e) = Env $ Map.insert i v e
+
+-- | The environment in which expressions are evaluated. We use Reader rather
+-- than State since modifications to the environment (modulo lambdas, which use
+-- 'local') are factored out.
+newtype LangM a = LangM
+ { fromLangM :: ExceptT LangError (Reader Env) a }
+ deriving (Functor, Applicative, Monad, MonadError LangError, MonadReader Env)
+
+runLangM :: Env -> LangM a -> Either LangError a
+runLangM e l = runReader (runExceptT $ fromLangM l) e
+
+-- | Lookup an atom in the environment
+lookupAtom :: Ident -> LangM Value
+lookupAtom i = ask >>= \(Env env) -> case Map.lookup i env of
+ Nothing -> throwError $ UnknownIdentifier i
+ Just v -> pure v
+
+-- | Lookup a primop.
+lookupPrimop :: Ident -> LangM ([Value] -> LangM Value)
+lookupPrimop i = case Map.lookup i primops of
+ Nothing -> throwError $ Impossible "Unknown primop"
+ Just v -> pure v
+
+-- | The universal primops. These are available in chain evaluation, and are
+-- not shadowable.
+primops :: Map Ident ([Value] -> LangM Value)
+primops = Map.fromList
+ [ ("eval", \args -> case args of
+ [List (v:vs)] -> eval (Apply v vs)
+ [Apply fn v ] -> eval =<< Apply <$> eval fn <*> traverse eval v
+ [x] -> eval x
+ x -> throwError $
+ OtherError . T.pack $ "'eval' requires list as argument: " <> show x)
+ , ("quote", \args -> case args of
+ [v] -> pure v
+ xs -> throwError $ WrongNumberOfArgs "quote" 1 (length xs))
+ , ("define", \args -> case args of
+ [Atom name, val] -> do
+ val' <- eval val
+ pure $ List [Atom "set!", Atom name, val']
+ [_, _] -> throwError $ OtherError "define expects atom for first arg"
+ xs -> throwError $ WrongNumberOfArgs "define" 2 (length xs))
+ , ("string?", \args -> case args of
+ [String _] -> pure $ Boolean True
+ [_] -> pure $ Boolean False
+ xs -> throwError $ WrongNumberOfArgs "string?" 1 (length xs))
+ , ("boolean?", \args -> case args of
+ [Boolean _] -> pure $ Boolean True
+ [_] -> pure $ Boolean False
+ xs -> throwError $ WrongNumberOfArgs "boolean?" 1 (length xs))
+ , ("if", \args -> case args of
+ [cond, t, f] -> do
+ b <- eval cond
+ -- I hate this as much as everyone that might ever read Haskell, but
+ -- in Lisps a lot of things that one might object to are True...
+ if b == Boolean False then eval f else eval t
+ xs -> throwError $ WrongNumberOfArgs "if" 3 (length xs))
+ ]
+
+-- * Eval
+
+-- | Evaluate a Value.
+eval :: Value -> LangM Value
+eval val = case val of
+ Atom i -> lookupAtom i
+ List vals -> List <$> traverse eval vals
+ String s -> pure $ String s
+ Boolean b -> pure $ Boolean b
+ Apply mfn vs -> do
+ mfn' <- eval mfn
+ case mfn' of
+ Primop i -> do
+ fn <- lookupPrimop i
+ -- Primops get to decide whether and how their args are
+ -- evaluated.
+ fn vs
+ Lambda _ _ Nothing -> throwError $ Impossible
+ "lambda should already have an env"
+ Lambda bnds body (Just closure) -> do
+ vs' <- traverse eval vs
+ let mappings = GHC.Exts.fromList (zip bnds vs')
+ modEnv = const $ mappings <> closure
+ local modEnv (eval body)
+ _ -> throwError $ TypeError "Trying to apply a non-function"
+ Primop i -> pure $ Primop i
+ e@(Lambda _ _ (Just _)) -> pure e
+ Lambda args body Nothing -> Lambda args body . Just <$> ask
+ SortedMap mp -> do
+ let evalSnd (a,b) = (a ,) <$> eval b
+ SortedMap . Map.fromList <$> traverse (evalSnd) (Map.toList mp)
+
+-- * Helpers
+
+-- | Infix function application
+infixr 1 $$
+($$) :: Value -> [Value] -> Value
+($$) = Apply
diff --git a/src/Radicle/Internal/Parse.hs b/src/Radicle/Internal/Parse.hs
new file mode 100644
index 0000000..2e738a1
--- /dev/null
+++ b/src/Radicle/Internal/Parse.hs
@@ -0,0 +1,145 @@
+{-# LANGUAGE ScopedTypeVariables #-}
+module Radicle.Internal.Parse where
+
+import Control.Applicative (many, (<|>))
+import Control.Monad (void)
+import Data.Bifunctor (first)
+import Data.Char (isAlphaNum, isLetter)
+import Data.List.NonEmpty (NonEmpty((:|)))
+import qualified Data.Map as Map
+import Data.Text (Text)
+import qualified Data.Text as T
+import Data.Void (Void)
+import GHC.Exts (IsString(..))
+import Text.Megaparsec (ParsecT, State(..), between, choice,
+ defaultTabWidth, initialPos, manyTill, parse,
+ runParser', sepBy, sepBy1, try, (<?>))
+import Text.Megaparsec.Char (char, satisfy, space1)
+import qualified Text.Megaparsec.Char.Lexer as L
+import qualified Text.Megaparsec.Error as Par
+
+import Radicle.Internal.Core
+
+-- * The parser
+
+type Parser m a = ParsecT Void Text m a
+
+spaceConsumer :: Parser m ()
+spaceConsumer = L.space space1 lineComment blockComment
+ where
+ lineComment = L.skipLineComment ";;"
+ blockComment = L.skipBlockComment "#|" "|#" -- R6RS
+
+
+symbol :: Text -> Parser m Text
+symbol = L.symbol spaceConsumer
+
+parensP :: Parser m a -> Parser m a
+parensP = between (symbol "(" >> spaceConsumer) (spaceConsumer >> symbol ")")
+
+primopP :: Parser m Value
+primopP = Primop . Ident <$> (choice $ symbol . fromIdent <$> Map.keys primops)
+
+stringLiteralP :: Parser m Value
+stringLiteralP = String . T.pack <$> (char '"' >> manyTill L.charLiteral (char '"'))
+
+boolLiteralP :: Parser m Value
+boolLiteralP = Boolean <$> (char '#' >>
+ (char 't' >> pure True) <|> (char 'f' >> pure False))
+
+identP :: Parser m Ident
+identP = do
+ l <- satisfy isValidIdentFirst
+ r <- many (satisfy isValidIdentRest)
+ pure . Ident $ fromString (l:r)
+
+atomP :: Parser m Value
+atomP = Atom <$> identP
+
+applyP :: Monad m => Parser m Value
+applyP = do
+ fn:args <- valueP `sepBy1` spaceConsumer
+ pure $ fn $$ args
+
+listP :: Monad m => Parser m Value
+listP = List <$> (char '\'' >> parensP (valueP `sepBy` spaceConsumer))
+
+sortedMapP :: Monad m => Parser m Value
+sortedMapP = do
+ void $ symbol "sorted-map"
+ SortedMap . Map.fromList <$> pairP `sepBy` spaceConsumer
+ where
+ pairP = do
+ (,) <$> identP <*> valueP
+
+lambdaP :: Monad m => Parser m Value
+lambdaP = do
+ void $ symbol "lambda"
+ vars <- parensP $ fmap atomToIdent <$> atomP `sepBy` spaceConsumer
+ body <- valueP
+ return $ Lambda vars body Nothing
+ where
+ atomToIdent (Atom i) = i
+ atomToIdent _ = error "impossible"
+
+valueP :: Monad m => Parser m Value
+valueP = do
+ spaceConsumer
+ v <- choice
+ [ stringLiteralP <?> "string"
+ , boolLiteralP <?> "boolean"
+ , try primopP <?> "primop"
+ , atomP <?> "atom"
+ , listP <?> "list"
+ , parensP appLike <?> "application"
+ ]
+ spaceConsumer
+ return v
+ where
+ appLike = choice
+ [ lambdaP <?> "lambda"
+ , sortedMapP <?> "sorted-map"
+ , applyP <?> "application"
+ ]
+
+-- * Utilities
+
+-- | Parse and evaluate a Text.
+interpret :: String -> Text -> Either LangError Value
+interpret sourceName expr = do
+ parsed <- first ParseError $ parse valueP sourceName expr
+ runLangM mempty $ eval parsed
+
+-- | Parse a Text as a series of values.
+-- 'sourceName' is used for error reporting.
+--
+-- Note that parsing continues even if one value fails to parse.
+parseValues :: String -> Text -> [Either (Par.ParseError Char Void) Value]
+parseValues sourceName srcCode = go $ initial
+ where
+ initial = State
+ { stateInput = T.strip srcCode
+ , statePos = initialPos sourceName :| []
+ , stateTokensProcessed = 0
+ , stateTabWidth = defaultTabWidth
+ }
+ go s = let (s', v) = runParser' valueP s
+ in if T.null (stateInput s') then [v] else v:go s'
+
+-- ** Valid identifiers
+-- These are made top-level so construction of arbitrary instances that matches
+-- parsing is easier
+
+-- | A predicate which returns true if the character is valid as the first
+-- character of an identifier.
+isValidIdentFirst :: Char -> Bool
+isValidIdentFirst x = isLetter x || x `elem` extendedChar
+
+-- | A predicate which returns true if the character is valid as the second or
+-- later character of an identifier.
+isValidIdentRest :: Char -> Bool
+isValidIdentRest x = isAlphaNum x || x `elem` extendedChar
+
+extendedChar :: [Char]
+extendedChar = ['!', '$', '%', '&', '*', '+', '-', '.', '/', ':', '<' , '=', '>'
+ , '?', '@', '^', '_', '~']
diff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hs
new file mode 100644
index 0000000..71c547e
--- /dev/null
+++ b/src/Radicle/Internal/Pretty.hs
@@ -0,0 +1,34 @@
+{-# OPTIONS_GHC -fno-warn-orphans #-}
+module Radicle.Internal.Pretty where
+
+import qualified Data.Map as Map
+import qualified Data.Text as T
+import Data.Text (Text)
+import Data.Text.Prettyprint.Doc
+import Data.Text.Prettyprint.Doc.Render.Text
+
+import Radicle.Internal.Core
+
+instance Pretty Ident where
+ pretty (Ident i) = pretty i
+
+instance Pretty Value where
+ pretty v = case v of
+ Atom i -> pretty i
+ String t -> "\"" <> pretty (escapeStr t) <> "\""
+ Boolean True -> "#t"
+ Boolean False -> "#f"
+ List vs -> "'" <> (parens . sep $ pretty <$> vs)
+ Primop i -> pretty i
+ Apply fn vs -> parens $ pretty fn <+> sep (pretty <$> vs)
+ SortedMap mp -> parens $
+ "sorted-map" <+> sep [ pretty k <+> pretty val
+ | (k, val) <- Map.toList mp ]
+ Lambda ids val _ -> parens $
+ "lambda" <+> parens (sep $ pretty <$> ids)
+ <+> pretty val
+ where
+ escapeStr = T.replace "\"" "\\\"" . T.replace "\\" "\\\\"
+
+compactPretty :: Value -> Text
+compactPretty = renderStrict . layoutCompact . pretty
diff --git a/stack.yaml b/stack.yaml
new file mode 100644
index 0000000..b4d7d51
--- /dev/null
+++ b/stack.yaml
@@ -0,0 +1,66 @@
+# This file was automatically generated by 'stack init'
+#
+# Some commonly used options have been documented as comments in this file.
+# For advanced use and comprehensive documentation of the format, please see:
+# https://docs.haskellstack.org/en/stable/yaml_configuration/
+
+# Resolver to choose a 'specific' stackage snapshot or a compiler version.
+# A snapshot resolver dictates the compiler version and the set of packages
+# to be used for project dependencies. For example:
+#
+# resolver: lts-3.5
+# resolver: nightly-2015-09-21
+# resolver: ghc-7.10.2
+# resolver: ghcjs-0.1.0_ghc-7.10.2
+# resolver:
+# name: custom-snapshot
+# location: "./custom-snapshot.yaml"
+resolver: lts-11.9
+
+# User packages to be built.
+# Various formats can be used as shown in the example below.
+#
+# packages:
+# - some-directory
+# - https://example.com/foo/bar/baz-0.0.2.tar.gz
+# - location:
+# git: https://github.com/commercialhaskell/stack.git
+# commit: e7b331f14bcffb8367cd58fbfc8b40ec7642100a
+# - location: https://github.com/commercialhaskell/stack/commit/e7b331f14bcffb8367cd58fbfc8b40ec7642100a
+# extra-dep: true
+# subdirs:
+# - auto-update
+# - wai
+#
+# A package marked 'extra-dep: true' will only be built if demanded by a
+# non-dependency (i.e. a user package), and its test suites and benchmarks
+# will not be run. This is useful for tweaking upstream packages.
+packages:
+- .
+# Dependency packages to be pulled from upstream that are not in the resolver
+# (e.g., acme-missiles-0.3)
+# extra-deps: []
+
+# Override default flag values for local packages and extra-deps
+# flags: {}
+
+# Extra package databases containing global packages
+# extra-package-dbs: []
+
+# Control whether we use the GHC we find on the path
+# system-ghc: true
+#
+# Require a specific version of stack, using version ranges
+# require-stack-version: -any # Default
+# require-stack-version: ">=1.6"
+#
+# Override the architecture used by stack, especially useful on Windows
+# arch: i386
+# arch: x86_64
+#
+# Extra directories used by stack for building
+# extra-include-dirs: [/path/to/dir]
+# extra-lib-dirs: [/path/to/dir]
+#
+# Allow a newer minor version of GHC than the snapshot specifies
+# compiler-check: newer-minor
\ No newline at end of file
diff --git a/test/Main.hs b/test/Main.hs
new file mode 100644
index 0000000..70c55f5
--- /dev/null
+++ b/test/Main.hs
@@ -0,0 +1 @@
+{-# OPTIONS_GHC -F -pgmF tasty-discover #-}
diff --git a/test/Radicle/Internal/Arbitrary.hs b/test/Radicle/Internal/Arbitrary.hs
new file mode 100644
index 0000000..32e02c7
--- /dev/null
+++ b/test/Radicle/Internal/Arbitrary.hs
@@ -0,0 +1,45 @@
+{-# OPTIONS_GHC -fno-warn-orphans #-}
+module Radicle.Internal.Arbitrary where
+
+import Data.Bifunctor (first)
+import qualified Data.Map as Map
+import qualified Data.Text as T
+import Test.QuickCheck
+import Test.QuickCheck.Instances ()
+
+import Radicle
+import Radicle.Internal.Parse (isValidIdentFirst, isValidIdentRest)
+
+instance Arbitrary Env where
+ arbitrary = Env <$> arbitrary
+
+instance Arbitrary Value where
+ arbitrary = sized go
+ where
+ freqs = [ (3, Atom <$> arbitrary)
+ , (3, String <$> arbitrary)
+ , (3, Boolean <$> arbitrary)
+ , (1, List <$> sizedList)
+ , (3, Primop <$> elements (Map.keys primops))
+ , (1, Apply <$> scale (`div` 2) arbitrary <*> sizedList)
+ , (3, SortedMap . Map.fromList <$> sizedList)
+ , (1, Lambda <$> sizedList
+ <*> scale (`div` 3) arbitrary
+ <*> scale (`div` 3) arbitrary)
+ ]
+ go n | n == 0 = frequency $ first pred <$> freqs
+ | otherwise = frequency freqs
+ sizedList :: Arbitrary a => Gen [a]
+ sizedList = sized $ \n -> do
+ k <- choose (0, n)
+ scale (`div` (k + 1)) $ vectorOf k arbitrary
+
+
+instance Arbitrary Ident where
+ arbitrary = ((:) <$> firstL <*> rest) `suchThatMap` (makeIdent . T.pack)
+ where
+ allChars = take 100 ['!' .. maxBound]
+ firstL = elements $ filter isValidIdentFirst allChars
+ rest = sized $ \n -> do
+ k <- choose (0, n)
+ vectorOf k . elements $ filter isValidIdentRest allChars
diff --git a/test/Radicle/Tests.hs b/test/Radicle/Tests.hs
new file mode 100644
index 0000000..cc8038e
--- /dev/null
+++ b/test/Radicle/Tests.hs
@@ -0,0 +1,172 @@
+{-# LANGUAGE QuasiQuotes #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+module Radicle.Tests where
+
+import Data.Data ((:~:)(Refl), Data, cast, eqT, gmapT)
+import Data.Semigroup (Semigroup, (<>))
+import Data.String.QQ (s)
+import Data.Text (Text)
+import qualified Data.Text as T
+import GHC.Exts (fromList, toList)
+import Test.Tasty
+import Test.Tasty.HUnit
+import Test.Tasty.QuickCheck (testProperty, counterexample)
+import Control.Monad.Morph (generalize, hoist)
+
+import Radicle.Internal.Arbitrary ()
+
+import Radicle
+
+test_eval :: [TestTree]
+test_eval =
+ [ testCase "Fails for undefined atoms" $
+ [s|blah|] `failsWith` UnknownIdentifier "blah"
+
+ , testCase "Succeeds for defined atoms" $ do
+ let prog = [s|
+ (define rocky-clark "Steve Wozniak")
+ rocky-clark
+ |]
+ prog `succeedsWith` String "Steve Wozniak"
+
+ , testCase "'sorted-map' creates a SortedMap with given key/vals" $ do
+ let prog = [s|(sorted-map why "not")|]
+ prog `succeedsWith` SortedMap (fromList [("why", String "not")])
+
+ , testCase "'eval' evaluates the list" $ do
+ let prog = [s|(eval (quote #t))|]
+ prog `succeedsWith` Boolean True
+
+ , testCase "lambdas work" $ do
+ let prog = [s|((lambda (x) x) #t)|]
+ prog `succeedsWith` Boolean True
+
+ , testCase "lambda does not have access to future definitions" $ do
+ let prog = [s|
+ (define y "a")
+ (define lam (lambda () y))
+ (define y "b")
+ (lam)
+ |]
+ prog `succeedsWith` String "a"
+
+ , testCase "'if' works with three arguments and true cond" $ do
+ let prog = [s|(if #t "a" "b")|]
+ prog `succeedsWith` String "a"
+
+ , testCase "'if' works with three arguments and false cond" $ do
+ let prog = [s|(if #f "a" "b")|]
+ prog `succeedsWith` String "b"
+
+ , testCase "'if' is lazy" $ do
+ let prog = [s|(if #t "a" (#t "non-sense"))|]
+ prog `succeedsWith` String "a"
+
+ , testCase "'string?' is true for strings" $ do
+ let prog = [s|(string? "hi")|]
+ prog `succeedsWith` Boolean True
+
+ , testCase "'string?' is false for nonStrings" $ do
+ let prog = [s|(string? #f)|]
+ prog `succeedsWith` Boolean False
+
+ , testCase "'string?' is false for nonStrings" $ do
+ let prog = [s|(string? #f)|]
+ prog `succeedsWith` Boolean False
+
+ , testCase "'boolean?' is true for booleans" $ do
+ let prog = [s|(boolean? #t)|]
+ prog `succeedsWith` Boolean True
+
+ , testCase "'boolean?' is true for non-booleans" $ do
+ let prog = [s|(boolean? "hi")|]
+ prog `succeedsWith` Boolean False
+
+ , testCase "'define' fails when first arg is not an atom" $ do
+ let prog = [s|(define "hi" "there")|]
+ prog `failsWith` OtherError "define expects atom for first arg"
+ ]
+ where
+ run :: Text -> Either LangError [Value]
+ run src = fmap snd $ foldChainFromSrc "test" src
+ $ hoist generalize genesisChain
+ failsWith src err = run src @?= Left err
+ succeedsWith src val = (last <$> run src) @?= Right val
+
+test_parser :: [TestTree]
+test_parser =
+ [ testCase "parses strings" $ do
+ "\"hi\"" ==> String "hi"
+
+ , testCase "parses booleans" $ do
+ "#t" ==> Boolean True
+ "#f" ==> Boolean False
+
+ , testCase "parses primops" $ do
+ "boolean?" ==> Primop "boolean?"
+ "eval" ==> Primop "eval"
+
+ , testCase "parses identifiers" $ do
+ "++" ==> Atom "++"
+ "what?crazy!" ==> Atom "what?crazy!"
+
+ , testCase "parses function application" $ do
+ "(++)" ==> (Atom "++" $$ [])
+ "(++ \"merge\" \"d\")" ==> (Atom "++" $$ [String "merge", String "d"])
+ ]
+ where
+ x ==> y = parseTest x @?= Right y
+
+test_binding :: [TestTree]
+test_binding =
+ [ testCase "handles shadowing correctly" $ do
+ [s|(((lambda (x) (lambda (x) x)) "inner") "outer")|] ==> String "outer"
+ ]
+ where
+ x ==> y = interpret "test" x @?= Right y
+
+test_subscriber :: [TestTree]
+test_subscriber =
+ [ testCase "have all effects returned in the right order" $ do
+ let sub = makeSubscriber $ \v -> case v of
+ Boolean True -> [Boolean True]
+ Boolean False -> [Boolean False]
+ _ -> error "should not happen"
+ ("#t #f", sub) ==> [Boolean True, Boolean False]
+ ]
+ where
+ run :: (Monoid (m Value), Semigroup (m Value))
+ => Text -> Subscriber m Value -> Either LangError (m Value)
+ run src subs = fmap snd $ foldChainFromSrc "test" src
+ $ addSubscriber (removeSubscribers genesisChain) subs
+ (val, subs) ==> y = run val subs @?= Right y
+
+test_pretty :: [TestTree]
+test_pretty =
+ [ testProperty "pretty . parse == identity" $ \val ->
+ let rendered = compactPretty val
+ actual = parseTest rendered
+ original = everywhere removeEnv val
+ info = case actual of
+ Left e -> "parse error in: " <> T.unpack rendered <> "\n"
+ <> e
+ Right v -> "pretty: " <> T.unpack rendered <> "\n"
+ <> "reparsed: " <> show v <> "\n"
+ <> "original: " <> show original <> "\n"
+ in counterexample info $ actual == Right original
+ ]
+ where
+ everywhere :: Data a => (forall b. Data b => b -> b) -> a -> a
+ everywhere f x = f (gmapT (everywhere f) x)
+ -- | Environments are neither printed nor parsed, but are generated by the
+ -- arbitrary instance.
+ removeEnv :: forall b. Data b => (b -> b)
+ removeEnv x = case (cast x, eqT :: Maybe (b :~: Value)) of
+ (Just (Lambda arg body _), Just Refl) -> Lambda arg body Nothing
+ _ -> x
+
+test_env :: [TestTree]
+test_env =
+ [ testProperty "fromList . toList == identity" $ \(env :: Env) ->
+ fromList (toList env) == env
+ ]