packages feed

snail 0.1.2.2 → 1.0.0

raw patch · 10 files changed

+153/−131 lines, 10 filesdep −mtlPVP ok

version bump matches the API change (PVP)

Dependencies removed: mtl

API changes (from Hackage documentation)

+ Snail.Characters: isValidCharacter :: Char -> Bool
- Snail.Ast: SExpression :: Maybe Char -> Bracket -> [SnailAst] -> SnailAst
+ Snail.Ast: SExpression :: Maybe Text -> Bracket -> [SnailAst] -> SnailAst

Files

CHANGELOG.md view
@@ -1,3 +1,10 @@+### Version 1.0.0++* Fix string termination after escaped backslashes while preserving raw escapes.+* Add an explicit Unicode identifier allowlist.+* Expand `SExpression` prefix support to multiple characters, e.g. `,@(...)`.+* Improve performance of lexer.+ ### Version 0.1.2.2  * Update dependencies upper bounds
README.md view
@@ -117,7 +117,8 @@  I tried to mimic their example (https://github.com/aisamanra/s-cargot/blob/master/example/example.hs) in-./example/Main.hs.+[example/Main.hs](https://github.com/chiroptical/snail/blob/main/example/Main.hs).+Run the example from the repository root with `nix run .`.  ## Resources for implementing interpreters and compilers 
− example/Main.hs
@@ -1,59 +0,0 @@-module Main where--import Snail-import Control.Monad.Except-import Data.Text (Text)-import Data.Text qualified as Text-import Text.Read (readMaybe)--data Operation = Addition | Multiplication -  deriving (Eq, Show)--data Ast-  = AstInt Integer-  | AstOperation Operation Ast Ast-  deriving (Eq, Show)--data LangError -  = UnknownLexeme Text-  | UnknownOperation Text-  | TextLiteralUnsupported-  | EmptyExpression-  deriving (Eq, Show)--parseLeaf :: (MonadError LangError m) => Text -> m Ast-parseLeaf = \case-  txt ->-    case readMaybe @Integer $ Text.unpack txt of-      Nothing -> throwError $ UnknownLexeme txt-      Just int -> pure $ AstInt int--parseOp :: (MonadError LangError m) => Text -> m Operation-parseOp = \case-  "+" -> pure Addition-  "*" -> pure Multiplication-  txt -> throwError $ UnknownOperation txt--fromSnail :: (MonadError LangError m) => SnailAst -> m Ast-fromSnail = \case-  -- no text literals are supported in this language-  TextLiteral _ -> throwError TextLiteralUnsupported-  -- `X` where `X` is a leaf in 'Ast'-  Lexeme (_, leaf) -> parseLeaf leaf-  SExpression _ _ [Lexeme (_, txt), argumentOne, argumentTwo] -> do-    op <- parseOp txt-    one <- fromSnail argumentOne-    two <- fromSnail argumentTwo-    pure $ AstOperation op one two-  -- empty expressions are invalid-  SExpression _ _ [] -> throwError EmptyExpression-  -- expression of expressions, e.g. `((X))` -> `(X)`-  SExpression leading fence exprs ->-    fromSnail . unwrap . SExpression leading fence $ unwrap <$> exprs--main :: IO ()-main = do-  case parseSnail "(+ 1 2)" of-    Left err -> print $ "Unable to parse snail: " <> show err-    Right [snail] -> runExceptT (fromSnail snail) >>= print-    Right _ -> putStrLn "Excepted single expression"
− snail-files/nil.snail
@@ -1,1 +0,0 @@-nil
snail.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack  name:           snail-version:        0.1.2.2+version:        1.0.0 synopsis:       A programming language with no semantics description:    An s-expression parser and abstract syntax tree for a programming language with no semantics. If you wanted to write an interpreter or compiler you convert the AST into your own. category:       Parsing@@ -20,7 +20,6 @@ extra-source-files:     README.md     CHANGELOG.md-data-files:     snail-files/basic.snail     snail-files/fail-comment.snail     snail-files/fail-empty.snail@@ -29,7 +28,6 @@     snail-files/fail-quotes-3.snail     snail-files/fail-quotes.snail     snail-files/fail.snail-    snail-files/nil.snail     test/files/fennel-reference.fnl     test/files/learnxyz.cl     test/files/r5rs_pitfalls.scm@@ -61,34 +59,10 @@     , base >=4.15 && <5     , containers >=0.6.7 && <0.8     , megaparsec >=9.5.0 && <9.9-    , mtl >=2.3.1 && <2.4     , text >=2.0.2 && <2.2     , text-display >=0.0.5 && <0.1 || >=1.0 && <1.1   default-language: Haskell2010 -executable snail-  main-is: Main.hs-  other-modules:-      Paths_snail-  hs-source-dirs:-      example-  default-extensions:-      FlexibleContexts-      ImportQualifiedPost-      LambdaCase-      OverloadedStrings-      TypeApplications-  build-depends:-      QuickCheck >=2.14.3 && <2.20-    , base >=4.15 && <5-    , containers >=0.6.7 && <0.8-    , megaparsec >=9.5.0 && <9.9-    , mtl >=2.3.1 && <2.4-    , snail-    , text >=2.0.2 && <2.2-    , text-display >=0.0.5 && <0.1 || >=1.0 && <1.1-  default-language: Haskell2010- test-suite snail-test   type: exitcode-stdio-1.0   main-is: Spec.hs@@ -115,7 +89,6 @@     , hspec >=2.11.8 && <2.12     , hspec-discover >=2.11.8 && <2.12     , megaparsec >=9.5.0 && <9.9-    , mtl >=2.3.1 && <2.4     , raw-strings-qq ==1.1.*     , snail     , text >=2.0.2 && <2.2
src/Snail/Ast.hs view
@@ -42,7 +42,7 @@ data SnailAst     = Lexeme (SourcePos, Text)     | TextLiteral (SourcePos, Text)-    | SExpression (Maybe Char) Bracket [SnailAst]+    | SExpression (Maybe Text) Bracket [SnailAst]     deriving (Eq, Show)  {- | Unwrap nested s-expressions, this is very useful when you are converting
src/Snail/Characters.hs view
@@ -1,9 +1,17 @@-module Snail.Characters (validCharacter, parenthesisStartingCharacter) where+module Snail.Characters (validCharacter, isValidCharacter, parenthesisStartingCharacter) where +import Data.Set qualified as Set+ -- | The valid character set of Snail validCharacter :: String-validCharacter = ['a' .. 'z'] <> ['A' .. 'Z'] <> digitCharacter <> specialInitialCharacter+validCharacter = ['a' .. 'z'] <> ['A' .. 'Z'] <> digitCharacter <> specialInitialCharacter <> unicodeCharacter +validCharacterSet :: Set.Set Char+validCharacterSet = Set.fromList validCharacter++isValidCharacter :: Char -> Bool+isValidCharacter c = Set.member c validCharacterSet+ -- | Characters allowed in numbers digitCharacter :: String digitCharacter = ['0' .. '9']@@ -11,6 +19,10 @@ -- | Special initial characters specialInitialCharacter :: String specialInitialCharacter = "!$%&*/:=?^_~#,'+-.@\\<>"++-- | A deliberately small set of allowed Unicode characters for identifiers+unicodeCharacter :: String+unicodeCharacter = "λαβγδεθμσφω∀∃→←⇒⇐↔⇔∘≤≥≠∧∨¬⊤⊥∈∉⊆⊂∪∩"  -- | Characters allowed in front of an s-expression parenthesisStartingCharacter :: String
src/Snail/Lexer.hs view
@@ -7,7 +7,7 @@   Here, we implement a structurally aware lexer that supports one token type   (text literals) for convenience. -}-{-# LANGUAGE TupleSections #-}+{-# LANGUAGE BangPatterns #-}  module Snail.Lexer (     sExpression,@@ -18,6 +18,7 @@     textLiteral, ) where +import Data.Char (isSpace) import Data.Text (Text) import Data.Text qualified as Text import Data.Void@@ -46,24 +47,20 @@  'skipBlockComment' -} spaces :: Parser ()-spaces = L.space space1 skipLineComment skipBlockComment+spaces = do+    _ <- takeWhileP (Just "white space") isSpace+    input <- getInput+    case Text.take 2 input of+        "--" -> skipLineComment *> spaces+        "{-" -> skipBlockComment *> spaces+        _ -> pure ()  -- | Parse a 'Text' verbatim symbol :: Text -> Parser Text symbol = L.symbol spaces -roundP :: Parser a -> Parser (Bracket, a)-roundP = fmap (Round,) . between (symbol "(") (symbol ")")--square :: Parser a -> Parser (Bracket, a)-square = fmap (Square,) . between (symbol "[") (symbol "]")--curly :: Parser a -> Parser (Bracket, a)-curly = fmap (Curly,) . between (symbol "{") (symbol "}")---- | Parse an S-Expression bracketed by 'Bracket'-bracket :: Parser a -> Parser (Bracket, a)-bracket inp = roundP inp <|> square inp <|> curly inp+openingBracket :: Parser Bracket+openingBracket = (Round <$ symbol "(") <|> (Square <$ symbol "[") <|> (Curly <$ symbol "{")  {- | Any 'Text' object that starts with an appropriately valid character. This  could be an variable or function name. For example, `hello` is a valid@@ -76,13 +73,19 @@ lexeme :: Parser SnailAst lexeme = do     sourcePosition <- getSourcePos-    txt <- some $ oneOf validCharacter-    pure $ Lexeme (sourcePosition, Text.pack txt)+    txt <- takeWhile1P (Just "identifier character") isValidCharacter+    pure $ Lexeme (sourcePosition, Text.copy txt) --- | An escaped quote to support nesting `"` inside a 'textLiteral'-escapedQuote :: Parser Text-escapedQuote = string "\\\""+-- | Use `\` as an escape character. Capture the next character verbatim.+escapedCharacter :: Parser Text+escapedCharacter = do+    slash <- char '\\'+    character <- anySingle+    pure $ Text.pack [slash, character] +unescapedChunk :: Parser Text+unescapedChunk = takeWhile1P Nothing (\c -> c /= '"' && c /= '\\')+ -- | Matches any non-quote character nonQuoteCharacter :: Parser Text nonQuoteCharacter = do@@ -104,24 +107,55 @@ textLiteral :: Parser SnailAst textLiteral = do     sourcePosition <- getSourcePos-    mText <- quotes . optional $ some $ escapedQuote <|> nonQuoteCharacter-    notFollowedBy (oneOf validCharacter <|> char '\"')-    pure $ case mText of-        Nothing -> TextLiteral (sourcePosition, "")-        Just text -> TextLiteral (sourcePosition, Text.concat text)+    chunks <- quotes $ many (escapedCharacter <|> unescapedChunk)+    notFollowedBy (satisfy isValidCharacter <|> char '\"')+    let !text = case chunks of+            [chunk] -> Text.copy chunk+            _ -> Text.concat chunks+    pure $ TextLiteral (sourcePosition, text)  {- | Parse one of the possible structures in 'SnailAst'. These are parsed  recursively separated by 'spaces' in 'sExpression'. -}-leaves :: Parser SnailAst-leaves = try sExpression <|> lexeme <|> textLiteral+leafStartingWith :: Char -> Parser SnailAst+leafStartingWith next+    | next == '"' = textLiteral+    | next `elem` parenthesisStartingCharacter = try sExpression <|> lexeme+    | otherwise = (openingBracket >>= listStartingWith Nothing) <|> lexeme +listStartingWith :: Maybe Text -> Bracket -> Parser SnailAst+listStartingWith prefix bracket = do+    let closing = case bracket of+            Round -> ')'+            Square -> ']'+            Curly -> '}'+    SExpression prefix bracket <$> listChildren closing++listChildren :: Char -> Parser [SnailAst]+listChildren closing = do+    input <- getInput+    case Text.uncons input of+        Nothing -> fail $ "Unexpected end of input. Expected " <> show closing+        Just (next, _)+            | next == closing -> do+                _ <- char closing+                spaces+                pure []+            | otherwise -> do+                child <- leafStartingWith next+                spaces+                rest <- listChildren closing+                pure (child : rest)++listPrefix :: Parser Text+listPrefix = Text.copy <$> takeWhile1P (Just "list prefix") (`elem` parenthesisStartingCharacter)+ -- | Parse an 'SExpression' sExpression :: Parser SnailAst sExpression = do-    startingChar <- optional (oneOf parenthesisStartingCharacter)-    (bracketType, expr) <- bracket (leaves `sepEndBy` spaces)-    pure $ SExpression startingChar bracketType expr+    prefix <- optional listPrefix+    bracket <- openingBracket+    listStartingWith prefix bracket  -- | Parse a valid snail file snailAst :: Parser [SnailAst]
src/Snail/ToText.hs view
@@ -16,6 +16,6 @@     SExpression Nothing bracketKind exprs ->         let txt = Data.Text.unwords $ toText <$> exprs          in bracket txt bracketKind-    SExpression (Just c) bracketKind exprs ->+    SExpression (Just prefix) bracketKind exprs ->         let txt = Data.Text.unwords $ toText <$> exprs-         in singleton c <> bracket txt bracketKind+         in prefix <> bracket txt bracketKind
test/Snail/LexerSpec.hs view
@@ -3,11 +3,11 @@ module Snail.LexerSpec (spec) where  import Data.Maybe (isJust, isNothing)-import Data.Text+import Data.Text (Text, unpack) import Snail import Test.HUnit (assertBool) import Test.Hspec-import Text.Megaparsec (parseMaybe, parseTest)+import Text.Megaparsec (getInput, parse, parseMaybe, parseTest) import Text.RawString.QQ  foldLexemes :: SnailAst -> [Text]@@ -49,6 +49,15 @@             mSExpr `shouldBe` Just " "      describe "parse text literals" $ do+        it "preserves escaped backslashes and quotes without swallowing the next token" $ do+            [r|("\\" next "\\\"" "\n")|] `sExpressionShouldBe` [[r|\\|], "next", [r|\\\"|], [r|\n|]]++        it "rejects a dangling escape prefix inside an incomplete string literal" $ do+            parseMaybe textLiteral [r|"abc\|] `shouldBe` Nothing++        it "rejects an escaped double quote inside an incomplete string literal" $ do+            parseMaybe textLiteral [r|"abc\"|] `shouldBe` Nothing+         it "successfully parses a basic text literal" $ do             [r|"hello \"world"|] `textLiteralShouldBe` [[r|hello \"world|]] @@ -69,6 +78,39 @@             [r|"    "|] `textLiteralShouldBe` ["    "]      describe "parse sExpression" $ do+        it "consumes a trailing comment and leaves the next token" $+            parse (sExpression *> getInput) "" "(x) -- comment\nrest"+                `shouldBe` Right "rest"++        it "attaches comma-at to the immediately following list" $+            case parseMaybe sExpression "(list ,@(xs))" of+                Just (SExpression Nothing Round [Lexeme (_, "list"), SExpression (Just ",@") Round [Lexeme (_, "xs")]]) -> pure ()+                result -> expectationFailure $ show result++        it "round-trips a comma-at-prefixed list" $+            case parseMaybe sExpression ",@(xs)" of+                Just ast@(SExpression (Just ",@") Round [Lexeme (_, "xs")]) ->+                    toText ast `shouldBe` ",@(xs)"+                result -> expectationFailure $ "Expected a ,@-prefixed list, got " <> show result++        it "preserves a trailing apostrophe in an identifier" $+            "(foldl')" `sExpressionShouldBe` ["foldl'"]++        it "preserves an at sign inside an identifier" $+            "(user@host)" `sExpressionShouldBe` ["user@host"]++        it "preserves a comma inside an identifier" $+            "(a,b)" `sExpressionShouldBe` ["a,b"]++        it "preserves comma-at at the start of an identifier" $+            "(,@x)" `sExpressionShouldBe` [",@x"]++        it "keeps detached comma-at as a lexeme" $+            "(,@ (xs))" `sExpressionShouldBe` [",@", "xs"]++        it "rejects a bare top-level comma-at identifier" $+            parseMaybe sExpression ",@x" `shouldBe` Nothing+         it "successfully lex a basic list" $ do             "(a b c)" `sExpressionShouldBe` ["a", "b", "c"] @@ -165,10 +207,23 @@             let Just [result] = parseMaybe snailAst "(different-char/2 #(inside))"             foldLexemes result `shouldBe` ["different-char/2", "inside"] -        it "fails with two leading characters" $ do-            parseMaybe snailAst "@,(foo)" `shouldSatisfy` isNothing+        it "keeps a run of prefix characters on the inner list" $+            case parseMaybe snailAst "(@,(xs))" of+                Just [SExpression Nothing Round [SExpression (Just "@,") Round [Lexeme (_, "xs")]]] -> pure ()+                result -> expectationFailure $ show result -        -- NOTE: this may or may not be the desired behavior-        it "parses two leading characters as valid lexeme" $ do-            let Just [result] = parseMaybe snailAst "(@,(foo ...))"-            foldLexemes result `shouldBe` ["@,", "foo", "..."]+        it "round-trips a list whose only child has the at-comma prefix" $+            case parseMaybe sExpression "(@,(xs))" of+                Just ast@(SExpression Nothing Round [SExpression (Just "@,") Round [Lexeme (_, "xs")]]) ->+                    toText ast `shouldBe` "(@,(xs))"+                result -> expectationFailure $ "Expected an @,-prefixed inner list, got " <> show result++        it "leaves a space-separated prefix token as a sibling of the list" $+            case parseMaybe snailAst "(@, (xs))" of+                Just [SExpression Nothing Round [Lexeme (_, "@,"), SExpression Nothing Round [Lexeme (_, "xs")]]] -> pure ()+                result -> expectationFailure $ show result++        it "preserves mixed and repeated prefix characters on a top-level list" $+            case parseMaybe snailAst "`''#@,[xs]" of+                Just [SExpression (Just "`''#@,") Square [Lexeme (_, "xs")]] -> pure ()+                result -> expectationFailure $ show result