packages feed

dhall-lex (empty) → 0.1.0.0

raw patch · 11 files changed

+521/−0 lines, 11 filesdep +arraydep +basedep +bytestringsetup-changed

Dependencies added: array, base, bytestring, criterion, deepseq, dhall-lex, hspec, hspec-dirstream

Files

+ LICENSE view
@@ -0,0 +1,11 @@+Copyright Vanessa McHale (c) 2018++Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:++1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.++2. 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.++3. Neither the name of the copyright holder nor the names of its 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 HOLDER 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.
+ README.md view
@@ -0,0 +1,4 @@+# dhall-lex++This is a library containing a lexer for the+[Dhall](http://hackage.haskell.org/package/dhall) language.
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ bench/Bench.hs view
@@ -0,0 +1,14 @@+module Main where++import           Criterion.Main+import qualified Data.ByteString.Lazy as BSL+import           Language.Dhall.Lexer++main :: IO ()+main =+    defaultMain [ env l $ \file ->+                  bgroup "lexDhall"+                      [ bench "lexer" $ nf lexDhall file+                      ]+                ]+    where l = BSL.readFile "test/data/sample.dhall"
+ cabal.project.local view
@@ -0,0 +1,5 @@+-- constraints: dhall-lex +development+documentation: True++program-options+  alex-options: -g
+ dhall-lex.cabal view
@@ -0,0 +1,90 @@+cabal-version: 1.18+name: dhall-lex+version: 0.1.0.0+license: BSD3+license-file: LICENSE+copyright: Copyright: (c) 2018 Vanessa McHale+maintainer: vamchale@gmail.com+author: Vanessa McHale+bug-reports: https://hub.darcs.net/vmchale/dhall-lex/issues+synopsis: Lexer for the Dhall language+description:+    Lexer for Dhall written with [Alex](https://www.haskell.org/alex/doc/html/index.html). This package has few dependencies and is fast.+category: Lexers, Language, Dhall+build-type: Simple+data-files:+    test/data/sample.dhall+extra-source-files:+    cabal.project.local+extra-doc-files: README.md++source-repository head+    type: darcs+    location: https://hub.darcs.net/vmchale/dhall-lex++flag development+    description:+        Enable `-Werror`+    default: False+    manual: True++library+    exposed-modules:+        Language.Dhall.Lexer+    hs-source-dirs: src+    other-modules:+        Language.Dhall.Lexer.Mod+        Language.Dhall.Lexer.Types+    default-language: Haskell2010+    ghc-options: -Wall+    build-depends:+        base >=4.8 && <5,+        array -any,+        bytestring -any,+        deepseq -any+    +    if flag(development)+        ghc-options: -Werror+    +    if impl(ghc >=8.0)+        ghc-options: -Wincomplete-uni-patterns -Wincomplete-record-updates+                     -Wcompat++test-suite dhall-lex-test+    type: exitcode-stdio-1.0+    main-is: Spec.hs+    hs-source-dirs: test+    default-language: Haskell2010+    ghc-options: -threaded -rtsopts -with-rtsopts=-N -Wall+    build-depends:+        base -any,+        dhall-lex -any,+        hspec -any,+        bytestring -any,+        hspec-dirstream >=1.0.0.0+    +    if flag(development)+        ghc-options: -Werror+    +    if impl(ghc >=8.0)+        ghc-options: -Wincomplete-uni-patterns -Wincomplete-record-updates+                     -Wcompat++benchmark dhall-lex-bench+    type: exitcode-stdio-1.0+    main-is: Bench.hs+    hs-source-dirs: bench+    default-language: Haskell2010+    ghc-options: -Wall+    build-depends:+        base -any,+        dhall-lex -any,+        criterion -any,+        bytestring -any+    +    if flag(development)+        ghc-options: -Werror+    +    if impl(ghc >=8.0)+        ghc-options: -Wincomplete-uni-patterns -Wincomplete-record-updates+                     -Wcompat
+ src/Language/Dhall/Lexer.hs view
@@ -0,0 +1,18 @@+-- | This module contains a dhall lexer.+module Language.Dhall.Lexer ( -- * User functions+                              lexDhall+                            -- * Types+                            , Token+                            , AlexPosn (..)+                            , TokenType (..)+                            , Keyword (..)+                            , Operator (..)+                            , Ann (..)+                            -- * Internal+                            , step+                            , Alex (..)+                            , AlexState (..)+                            ) where++import           Language.Dhall.Lexer.Mod+import           Language.Dhall.Lexer.Types
+ src/Language/Dhall/Lexer/Mod.x view
@@ -0,0 +1,203 @@+{+    {-# OPTIONS_GHC -fno-warn-name-shadowing #-}+    {-# LANGUAGE DeriveGeneric #-}+    {-# LANGUAGE DeriveAnyClass #-}+    {-# LANGUAGE StandaloneDeriving #-}+    {-# LANGUAGE OverloadedStrings #-}+    {-# LANGUAGE FlexibleContexts #-}++    module Language.Dhall.Lexer.Mod+        ( lexDhall+        , step+        , Alex (..)+        , AlexPosn (..)+        , Ann (..)+        , Token+        , AlexState (..)+        ) where++import Control.Arrow ((&&&))+import Control.DeepSeq (NFData)+import Control.Monad+import Data.Bool (bool)+import qualified Data.ByteString.Lazy as BSL+import qualified Data.ByteString.Lazy.Char8 as ASCII+import GHC.Generics (Generic)+import GHC.Natural (Natural)+import Language.Dhall.Lexer.Types++}++%wrapper "monad-bytestring"++$digit = 0-9++@natural = \+ $digit++@integer = (\- | "") $digit++@double = (\- | "") $digit+ \. $digit+++-- TODO // for lambdas?+$special = [\{\}\,\=\:\[\]\<\>\|\(\)\.\+\*\#]++$lowercase = [a-z]+$uppercase = [A-Z]+$letter = [$lowercase $uppercase]++@type = $uppercase $letter*+@quoted = \` @type \`+@identifier = ($lowercase | _ | @type \/) $letter*++@loc = "http://" | "https://" | "./" | "../" | "/"++$url_contents = [\:\/\-\.\_ $letter]++@url = @loc $url_contents+++$string_char = $printable # [\"\\\$]++$esc_char = [\"\$\\]++-- Deficiency: what if $ is followed by "?+@string_in = (\\ $esc_char | $string_char | \$ [^\{\"])*++tokens :-++    <0,splice> $white+           ;++    <0,splice> "--".*            ;+    "{-"                         { \_ _ -> nested_comment }++    -- keywords+    <0,splice> if                { tok (\p _ -> alex p $ Keyword KwIf) }+    <0,splice> then              { tok (\p _ -> alex p $ Keyword KwThen) }+    <0,splice> else              { tok (\p _ -> alex p $ Keyword KwElse) }+    <0,splice> let               { tok (\p _ -> alex p $ Keyword KwLet) }+    <0,splice> in                { tok (\p _ -> alex p $ Keyword KwIn) }+    <0,splice> forall            { tok (\p _ -> alex p $ Keyword KwForall) }+    <0,splice> ∀                 { tok (\p _ -> alex p $ Keyword KwForall) }+    <0,splice> constructors      { tok (\p _ -> alex p $ Keyword KwConstructors) }+    <0,splice> merge             { tok (\p _ -> alex p $ Keyword KwMerge) }++    -- builtin specials+    <0,splice> "//"              { tok (\p _ -> alex p $ Operator CombineTok) }+    <0,splice> "⫽"               { tok (\p _ -> alex p $ Operator CombineTok) }+    <0,splice> "/"\\             { tok (\p _ -> alex p $ Operator PreferTok) }+    <0,splice> "∧"               { tok (\p _ -> alex p $ Operator PreferTok) }+    <0,splice> "→"               { tok (\p _ -> alex p $ Operator ArrowTok) }+    <0,splice> "->"              { tok (\p _ -> alex p $ Operator ArrowTok) }+    <0,splice> "λ"               { tok (\p _ -> alex p $ Operator LambdaTok) }+    <0,splice> \\                { tok (\p _ -> alex p $ Operator LambdaTok) }+    <0,splice> \&\&              { tok (\p _ -> alex p $ Operator AndTok) }+    <0,splice> \|\|              { tok (\p _ -> alex p $ Operator OrTok) }+    <0,splice> \=\=              { tok (\p _ -> alex p $ Operator EqTok) }+    <0,splice> \!\=              { tok (\p _ -> alex p $ Operator NeqTok) }+    <0,splice> \+\+              { tok (\p _ -> alex p $ Operator AppendTok) }++    -- Path literals+    <0,splice> @url              { tok (\p s -> alex p $ Embedded s) }++    -- Various special characters+    <0> $special                 { tok (\p s -> alex p $ Special s) }++    -- Numeric literals+    <0,splice> @natural          { tok (\p s -> Ann p <$> fmap NatLit (readNatural s)) }+    <0,splice> @integer          { tok (\p s -> Ann p <$> fmap IntLit (readInteger s)) }++    -- Boolean literals+    <0,splice> True              { tok (\p _ -> alex p $ BoolLit True) }+    <0,splice> False             { tok (\p _ -> alex p $ BoolLit False) }++    -- Identifiers+    <0,splice> @quoted           { tok (\p s -> alex p $ QuotedId s) }+    <0,splice> @identifier       { tok (\p s -> alex p $ Identifier s) }+    <0,splice> @type             { tok (\p s -> alex p $ TypeId s) }++    -- Strings & string splices+    <0,splice> \"                { begin string }+    <string> @string_in \$ / \"  { tok (\p s -> alex p $ StringChunk s) }+    <string> @string_in          { tok (\p s -> alex p $ StringChunk s) }+    <string> \$\{                { tok (\p _ -> alex p $ BeginSplice) `andBegin` splice }+    <splice> \}                  { tok (\p _ -> alex p $ EndSplice) `andBegin` string }+    <splice> $special # \}       { tok (\p s -> alex p $ Special s) }+    <string> \"                  { begin 0 }++{++-- Taken from example by Simon Marlow.+nested_comment :: Alex Token+nested_comment = go 1 =<< alexGetInput++    where go :: Int -> AlexInput -> Alex Token+          go 0 input = alexSetInput input >> alexMonadScan+          go n input = do+            case alexGetByte input of+                Nothing -> err input+                Just (c, input') -> do+                    case Data.Char.chr (fromIntegral c) of+                        '-' -> do+                            case alexGetByte input' of+                                Nothing -> err input'+                                Just (125,input_) -> go (n-1) input_+                                Just (_,input_) -> go n input_+                        '{' -> do+                            case alexGetByte input' of+                                Nothing -> err input'+                                Just (c',input_) -> go (bool id (+1) (c'==45) $ n) input_+                        _ -> go n input'++          err (pos,_,_,_) =+            let (AlexPn _ line col) = pos in+                alexError ("Error in nested comment at line " ++ show line ++ ", column " ++ show col)++readNatural :: BSL.ByteString -> Alex Natural+readNatural = go <=< readInteger . BSL.tail+    where go x | x < 0 = alexError "Internal lexer error"+          go x = pure (fromIntegral x)++readDouble :: BSL.ByteString -> Alex Double+readDouble str = pure $ read (ASCII.unpack str)++readInteger :: BSL.ByteString -> Alex Integer+readInteger str =+    case ASCII.readInteger str of+        Just (i, "") -> pure i+        _ -> alexError "Not a valid integer"++get_pos :: Alex AlexPosn+get_pos = Alex (Right . (id &&& alex_pos))++alex :: AlexPosn -> a -> Alex (Ann AlexPosn a)+alex = (pure .) . Ann++tok f (p,_,s,_) len = f p (BSL.take len s)++deriving instance Generic AlexPosn+deriving instance NFData AlexPosn++-- | Data type for values with annotations.+data Ann a b = Ann { loc   :: a+                   , inner :: b+                   }+           deriving (Eq, Show, Generic, NFData)++-- | A token with location information.+type Token = Ann AlexPosn TokenType++alexEOF :: Alex Token+alexEOF = Ann <$> get_pos <*> pure End++lexDhall :: BSL.ByteString -> Either String [Token]+lexDhall str = runAlex str loop++-- | Get the next token. This is provided in case you want to thread the lexer+-- through the parser. Returns @End@ token when out of input.+step :: Alex Token+step = alexMonadScan++loop :: Alex [Token]+loop = do+    tok' <- step+    if inner tok' == End then pure mempty+        else (tok' :) <$> loop++}
+ src/Language/Dhall/Lexer/Types.hs view
@@ -0,0 +1,54 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric  #-}++module Language.Dhall.Lexer.Types ( Operator (..)+                                  , Keyword (..)+                                  , TokenType (..)+                                  ) where++import           Control.DeepSeq      (NFData)+import qualified Data.ByteString.Lazy as BSL+import           GHC.Generics         (Generic)+import           GHC.Natural          (Natural)++-- | The operator type holds some special builtin symbols.+data Operator = CombineTok+              | PreferTok+              | ArrowTok -- @→@ or @->@+              | LambdaTok -- @λ@ or @\\@+              | AndTok -- @&&@+              | OrTok -- @||@+              | EqTok -- @==@+              | NeqTok -- @!=@+              | AppendTok -- @++@+              deriving (Eq, Show, Generic, NFData)++-- | Data type for reserved keywords.+data Keyword = KwLet+             | KwIn+             | KwConstructors+             | KwMerge+             | KwForall -- @forall@ or @∀@+             | KwIf+             | KwThen+             | KwElse+             deriving (Eq, Show, Generic, NFData)++-- | This is a data type for tokens, stripped of any annotation.+data TokenType = IntLit !Integer+               | DoubleLit !Double+               | NatLit !Natural+               | BoolLit !Bool+               | Embedded !BSL.ByteString+               | StringLit !BSL.ByteString+               | TypeId !BSL.ByteString+               | QuotedId !BSL.ByteString+               | Identifier !BSL.ByteString+               | Keyword !Keyword+               | Special !BSL.ByteString+               | Operator !Operator+               | BeginSplice -- @${@, only occurs inside a string+               | EndSplice -- @}@+               | StringChunk !BSL.ByteString+               | End+               deriving (Eq, Show, Generic, NFData)
+ test/Spec.hs view
@@ -0,0 +1,15 @@+{-# LANGUAGE OverloadedStrings #-}++import qualified Data.ByteString.Lazy as BSL+import           Language.Dhall.Lexer+import           Test.Hspec+import           Test.Hspec.Dirstream++isRight :: Either a b -> Bool+isRight Right{} = True+isRight _       = False++main :: IO ()+main = hspec $+    describe "lexDhall" $ parallel $+        testFilesPure "test/data" (hasExtension "dhall") allFiles (FileProc BSL.readFile lexDhall isRight)
+ test/data/sample.dhall view
@@ -0,0 +1,105 @@+let relative = ./local.dhall+in++let Product = { first : Text, second : Optional (List Integer) }+in++let Sum = < Tag : Text | IntTag : Integer >+in++let ConstructorSum = constructors < None : {} | Some : Integer >+in++let quotedRecord = +  { `Field` = 2 }+in++let constructorExpression =+  ConstructorSum.None {=}+in++let doubleLit = 2.234329+in++let boolLit = False+in++let intLit = -121+in++let natLit = +223+in++let string =+  "string"+in++let typedFunction : ∀(x : Integer) → Integer =+  λ(x : Integer) → x+in++let plebTypedFunctions : forall (x : Integer) -> Integer =+  \(x : Integer) -> x+in++let list =+  [0,1,2]+in++let option =+  [ "tag" ] : Optional Text+in++let record =+  { first = "text", second = [ list ] : Optional (List Integer) } : Product+in++let sumValue =+  < Tag : {} | IntTag = 2 >+in++let update = +  record // { isSpecial = True }+in++let escapedStr =+  "escape\""+in++let uUpdate =+  record ⫽ { isSpecial = True }+in++let squish =+  record /\ { isSpecial = True }+in++let uSquish =+  record ∧ { isSpecial = True }+in++let tuple =+  { _1 = True, _2 = "false" }+in++let multExpr =+  +3 * +4+in++let duplicateString =+  λ(x : Text) → x ++ x+in++let simpleSplice =+  "something ${update.first}"+in++let fancySplice =+  "fancy ${duplicateString simpleSplice} status:${relative}"+in++let spliceSpecial =+  "${fancySplice} @#$%#$@$"+in++spliceSpecial