packages feed

cimple 0.0.32 → 0.0.33

raw patch · 19 files changed

+223/−16 lines, 19 filesdep +directorydep +happy-arbitraryPVP: major bump suggested

API removals or changes: PVP suggests a major version bump

Dependencies added: directory, happy-arbitrary

API changes (from Hackage documentation)

+ Language.Cimple: ($dmconcats) :: (Concats t a, Generic t, GenConcats (Rep t) a) => t -> [a]
+ Language.Cimple: AttrAllocSize :: [lexeme] -> a -> NodeF lexeme a
+ Language.Cimple: DocGuardedBy :: lexeme -> CommentF lexeme a
+ Language.Cimple: DocRequires :: lexeme -> lexeme -> CommentF lexeme a
+ Language.Cimple: DocThread :: lexeme -> CommentF lexeme a
+ Language.Cimple: KwGnuAllocSize :: LexemeClass
- Language.Cimple: concats :: (Concats t a, Generic t, GenConcats (Rep t) a) => t -> [a]
+ Language.Cimple: concats :: Concats t a => t -> [a]
- Language.Cimple: type AnnotNode lexeme = Fix (AnnotF () `Compose` NodeF lexeme)
+ Language.Cimple: type AnnotNode lexeme = Fix Compose AnnotF () NodeF lexeme
- Language.Cimple: type Comment lexeme = Fix (CommentF lexeme)
+ Language.Cimple: type Comment lexeme = Fix CommentF lexeme
- Language.Cimple: type DefaultActions a = IdentityActions (State a) Text
+ Language.Cimple: type DefaultActions a = IdentityActions State a Text
- Language.Cimple: type Node lexeme = Fix (NodeF lexeme)
+ Language.Cimple: type Node lexeme = Fix NodeF lexeme
- Language.Cimple.MapAst: data AstActions f itext otext
+ Language.Cimple.MapAst: data AstActions (f :: Type -> Type) itext otext
- Language.Cimple.MapAst: identityActions :: Applicative f => AstActions f text text
+ Language.Cimple.MapAst: identityActions :: forall (f :: Type -> Type) text. Applicative f => AstActions f text text
- Language.Cimple.MapAst: type IdentityActions f text = AstActions f text text
+ Language.Cimple.MapAst: type IdentityActions (f :: Type -> Type) text = AstActions f text text
- Language.Cimple.MapAst: type TextActions f itext otext = AstActions f itext otext
+ Language.Cimple.MapAst: type TextActions (f :: Type -> Type) itext otext = AstActions f itext otext
- Language.Cimple.TranslationUnit: type TranslationUnit text = (FilePath, [Node (Lexeme text)])
+ Language.Cimple.TranslationUnit: type TranslationUnit text = (FilePath, [Node Lexeme text])
- Language.Cimple.TraverseAst: astActions :: Applicative f => AstActions f text
+ Language.Cimple.TraverseAst: astActions :: forall (f :: Type -> Type) text. Applicative f => AstActions f text
- Language.Cimple.TraverseAst: data AstActions f text
+ Language.Cimple.TraverseAst: data AstActions (f :: Type -> Type) text

Files

cimple.cabal view
@@ -1,5 +1,5 @@ name:          cimple-version:       0.0.32+version:       0.0.33 synopsis:      Simple C-like programming language homepage:      https://toktok.github.io/ license:       GPL-3@@ -120,6 +120,7 @@   hs-source-dirs:     test   main-is:            testsuite.hs   other-modules:+    Language.Cimple.ArbitrarySpec     Language.Cimple.AstSpec     Language.Cimple.CommentParserSpec     Language.Cimple.ParserSpec@@ -133,10 +134,13 @@   build-depends:       QuickCheck     , base                 <5+    , bytestring     , cimple     , containers     , data-fix+    , directory     , extra+    , happy-arbitrary     , hspec     , mtl     , prettyprinter
src/Language/Cimple/Ast.hs view
@@ -125,6 +125,7 @@     | TyUserDefined lexeme     -- Functions     | AttrPrintf lexeme lexeme a+    | AttrAllocSize [lexeme] a     | FunctionDecl Scope a     | FunctionDefn Scope a a     | FunctionPrototype a lexeme [a]@@ -223,6 +224,7 @@         TyStd l -> TyStd (f l)         TyUserDefined l -> TyUserDefined (f l)         AttrPrintf l l' a -> AttrPrintf (f l) (f l') (g a)+        AttrAllocSize ls a -> AttrAllocSize (map f ls) (g a)         FunctionDecl s a -> FunctionDecl s (g a)         FunctionDefn s a a' -> FunctionDefn s (g a) (g a')         FunctionPrototype a l as -> FunctionPrototype (g a) (f l) (map g as)@@ -256,6 +258,9 @@     | DocSection lexeme     | DocSecurityRank lexeme (Maybe lexeme) lexeme     | DocSee lexeme+    | DocThread lexeme+    | DocGuardedBy lexeme+    | DocRequires lexeme lexeme     | DocSubsection lexeme      | DocPrivate@@ -285,6 +290,9 @@         DocSection l            -> DocSection (f l)         DocSecurityRank l ml l' -> DocSecurityRank (f l) (fmap f ml) (f l')         DocSee l                -> DocSee (f l)+        DocThread l             -> DocThread (f l)+        DocGuardedBy l          -> DocGuardedBy (f l)+        DocRequires l l'        -> DocRequires (f l) (f l')         DocSubsection l         -> DocSubsection (f l)         DocPrivate              -> DocPrivate         DocLine as              -> DocLine (map g as)
src/Language/Cimple/CommentParser.y view
@@ -41,6 +41,9 @@     '@subsection'		{ L _ CmtCommand "@subsection"		}     '@see'			{ L _ CmtCommand "@see"			}     '@security_rank'		{ L _ CmtCommand "@security_rank"	}+    '@thread'			{ L _ CmtCommand "@thread"		}+    '@guarded_by'		{ L _ CmtCommand "@guarded_by"	}+    '@requires'			{ L _ CmtCommand "@requires"		}     '@code'			{ L _ CmtCode	 "@code"		}     '@endcode'			{ L _ CmtCode	 "@endcode"		} @@ -109,6 +112,9 @@ |	'@section' ' ' TOKEN				{ Fix $ DocSection $3 } |	'@subsection' ' ' TOKEN				{ Fix $ DocSubsection $3 } |	'@see' ' ' TOKEN				{ Fix $ DocSee $3 }+|	'@thread' ' ' TOKEN				{ Fix $ DocThread $3 }+|	'@guarded_by' ' ' TOKEN				{ Fix $ DocGuardedBy $3 }+|	'@requires' '(' TOKEN ',' ' ' TOKEN ')'		{ Fix $ DocRequires $3 $6 } |	'@security_rank' '(' TOKEN ',' ' ' TOKEN ')'	{ Fix $ DocSecurityRank $3 Nothing $6 } |	'@security_rank' '(' TOKEN ',' ' ' TOKEN ',' ' ' TOKEN ')'	{ Fix $ DocSecurityRank $3 (Just $6) $9 } |	'@code' Words '@endcode'			{ Fix $ DocCode $1 $2 $3 }
src/Language/Cimple/Flatten.hs view
@@ -78,6 +78,9 @@     gconcatsFlatten (Fix (DocRetval)) = []     gconcatsFlatten (Fix (DocSection s)) = [s]     gconcatsFlatten (Fix (DocSee r)) = [r]+    gconcatsFlatten (Fix (DocThread t)) = [t]+    gconcatsFlatten (Fix (DocGuardedBy g)) = [g]+    gconcatsFlatten (Fix (DocRequires p f)) = [p, f]     gconcatsFlatten (Fix (DocSecurityRank s p r)) = s : maybeToList p ++ [r]     gconcatsFlatten (Fix (DocSubsection s)) = [s]     gconcatsFlatten (Fix (DocWord x)) = [x]
src/Language/Cimple/Lexer.x view
@@ -68,6 +68,7 @@ tokens :-  -- Ignore attributes.+<0>		"GNU_ALLOC_SIZE"			{ mkL KwGnuAllocSize } <0>		"GNU_PRINTF"				{ mkL KwGnuPrintf } <0>		"VLA"					{ mkL KwVla } @@ -143,8 +144,8 @@ <0>		"/** @{"				{ mkL CmtStartDocSection `andBegin` cmtSC } <0>		"/** @} */"				{ mkL CmtEndDocSection } <0>		"/**""*"+				{ mkL CmtStartBlock `andBegin` cmtSC }-<0,cmtSC>	\"(\\.|[^\"])*\"			{ mkL LitString }-<0>		'(\\|[^'])*'				{ mkL LitChar }+<0,cmtSC>	\"(\\.|[^\"\\])*\"			{ mkL LitString }+<0>		'(\\.|[^'\\])*'				{ mkL LitChar } <0>		"<"[a-z0-9\.\/_]+">"			{ mkL LitSysInclude } <0>		"#if"					{ mkL PpIf `andBegin` ppSC } <0>		"#ifdef"				{ mkL PpIfdef }@@ -281,6 +282,7 @@ <cmtSC>		"*"[A-Za-z][A-Za-z0-9_']*"*"		{ mkL CmtWord } <cmtSC>		"#"[A-Za-z][A-Za-z0-9_]*		{ mkL CmtRef } <cmtSC>		"_"*[A-Za-z][A-Za-z0-9_']*		{ mkL CmtWord }+<cmtSC>		"_"[A-Za-z0-9_']*			{ mkL CmtWord } <cmtSC>		"#"[0-9]+				{ mkL CmtWord } <cmtSC>		"http://"[^\ ]+				{ mkL CmtWord } <cmtSC>		[0-9]+"%"				{ mkL LitInteger }
src/Language/Cimple/MapAst.hs view
@@ -131,6 +131,12 @@             Fix <$> (DocSection <$> recurse sec)         DocSee ref ->             Fix <$> (DocSee <$> recurse ref)+        DocThread role ->+            Fix <$> (DocThread <$> recurse role)+        DocGuardedBy lock ->+            Fix <$> (DocGuardedBy <$> recurse lock)+        DocRequires param field ->+            Fix <$> (DocRequires <$> recurse param <*> recurse field)         DocSecurityRank kw param rank ->             Fix <$> (DocSecurityRank <$> recurse kw <*> recurse param <*> recurse rank)         DocSubsection subsec ->@@ -333,6 +339,8 @@             Fix <$> (TyUserDefined <$> recurse name)         AttrPrintf fmt ellipsis fun ->             Fix <$> (AttrPrintf <$> recurse fmt <*> recurse ellipsis <*> recurse fun)+        AttrAllocSize sizes fun ->+            Fix <$> (AttrAllocSize <$> recurse sizes <*> recurse fun)         FunctionDecl scope proto ->             Fix <$> (FunctionDecl scope <$> recurse proto)         FunctionDefn scope proto body ->
src/Language/Cimple/Parser.y view
@@ -55,6 +55,7 @@     extern			{ L _ KwExtern			_ }     for				{ L _ KwFor			_ }     force			{ L _ KwForce			_ }+    GNU_ALLOC_SIZE		{ L _ KwGnuAllocSize		_ }     GNU_PRINTF			{ L _ KwGnuPrintf		_ }     goto			{ L _ KwGoto			_ }     if				{ L _ KwIf			_ }@@ -448,7 +449,7 @@  VarDecl :: { NonTerm } VarDecl-:	QualType(LocalLeafType) ID_VAR DeclSpecArrays		{ Fix $ VarDecl $1 $2 $3 }+:	QualType(LocalLeafType) ID_VAR DeclSpecArrays		{ Fix $ VarDecl $1 $2 (reverse $3) }  DeclSpecArrays :: { [NonTerm] } DeclSpecArrays@@ -459,7 +460,11 @@ DeclSpecArray :	'[' Nullability ']'					{ Fix $ DeclSpecArray $2 Nothing } |	'[' Nullability Expr ']'				{ Fix $ DeclSpecArray $2 (Just $3) }-|	'[' Nullability '/*!' Expr '*/' ']'			{ Fix $ DeclSpecArray $2 (Just $4) }+|	'[' '/*!' Expr '*/' ']'					{ Fix $ DeclSpecArray NullabilityUnspecified (Just $3) }+|	'[' nullable '/*!' Expr '*/' ']'			{ Fix $ DeclSpecArray Nullable (Just $4) }+|	'[' nonnull '/*!' Expr '*/' ']'				{ Fix $ DeclSpecArray Nonnull (Just $4) }+|	'[' CommentNullability ']'				{ Fix $ DeclSpecArray $2 Nothing }+|	'[' CommentNullability Expr ']'				{ Fix $ DeclSpecArray $2 (Just $3) }  InitialiserExpr :: { NonTerm } InitialiserExpr@@ -685,8 +690,9 @@  TypedefDecl :: { NonTerm } TypedefDecl-:	typedef QualType(GlobalLeafType) ID_SUE_TYPE DeclSpecArrays ';'	{ Fix $ Typedef $2 $3 $4 }+:	typedef QualType(GlobalLeafType) ID_SUE_TYPE DeclSpecArrays ';'	{ Fix $ Typedef $2 $3 (reverse $4) } |	typedef FunctionPrototype(ID_FUNC_TYPE) ';'		{ Fix $ TypedefFunction $2 }+|	Attrs typedef FunctionPrototype(ID_FUNC_TYPE) ';'	{ $1 $ Fix $ TypedefFunction $3 } |	struct ID_SUE_TYPE ';'					{ Fix $ Typedef (Fix (TyStruct $2)) $2 [] }  QualType(leafType)@@ -701,7 +707,7 @@  QualList :: { NonTerm -> NonTerm } QualList-:	Qual QualList						{ $1 . $2 }+:	Qual QualList						{ $2 . $1 } |	Qual							{ $1 }  QualMaybe :: { NonTerm -> NonTerm }@@ -715,7 +721,15 @@ |	nonnull							{ tyNonnull } |	nullable						{ tyNullable } |	owner							{ tyOwner }+|	'/*!' nonnull '*/'					{ tyNonnull }+|	'/*!' nullable '*/'					{ tyNullable } +-- | A header's nullability before it can say @_Nullable@: @/*! _Nullable */@.+CommentNullability :: { Nullability }+CommentNullability+:	'/*!' nullable '*/'					{ Nullable }+|	'/*!' nonnull '*/'					{ Nonnull }+ Nullability :: { Nullability } Nullability :								{ NullabilityUnspecified }@@ -744,6 +758,8 @@ Attrs :: { NonTerm -> NonTerm } Attrs :	GNU_PRINTF '(' LIT_INTEGER ',' LIT_INTEGER ')'		{ Fix . AttrPrintf $3 $5 }+|	GNU_ALLOC_SIZE '(' LIT_INTEGER ')'			{ Fix . AttrAllocSize [$3] }+|	GNU_ALLOC_SIZE '(' LIT_INTEGER ',' LIT_INTEGER ')'	{ Fix . AttrAllocSize [$3, $5] }  FunctionDeclarator :: { Scope -> NonTerm } FunctionDeclarator@@ -757,7 +773,7 @@  FunctionPrototype(id) :	QualType(GlobalLeafType) id FunctionParamList		{ Fix $ FunctionPrototype $1 $2 $3 }-|	ID_FUNC_TYPE '*' id FunctionParamList			{ Fix $ FunctionPrototype (Fix $ TyPointer $ Fix $ TyFunc $1) $3 $4 }+|	ID_FUNC_TYPE '*' QualMaybe id FunctionParamList		{ Fix $ FunctionPrototype ($3 (Fix $ TyPointer $ Fix $ TyFunc $1)) $4 $5 }  FunctionParamList :: { [NonTerm] } FunctionParamList
src/Language/Cimple/Pretty.hs view
@@ -11,10 +11,12 @@     , showNodePlain     ) where -import           Data.Fix                      (foldFix)+import qualified Data.ByteString.Lazy          as LBS+import           Data.Fix                      (Fix (..), foldFix) import qualified Data.List.Split               as List import           Data.Text                     (Text) import qualified Data.Text                     as Text+import qualified Data.Text.Encoding            as Text import qualified Data.Text.Lazy                as TL import           Language.Cimple               (AssignOp (..), BinaryOp (..),                                                 Comment, CommentF (..),@@ -22,6 +24,7 @@                                                 LexemeClass (..), Node,                                                 NodeF (..), Nullability (..),                                                 Scope (..), UnaryOp (..),+                                                alexScanTokens, lexemeClass,                                                 lexemeLine, lexemeText) import           Language.Cimple.PrettyColor   (black, blue, cyan, dullcyan,                                                 dullgreen, dullmagenta, dullred,@@ -46,6 +49,19 @@     Nullable               -> kwNullable     Nonnull                -> kwNonnull +-- | The condition of an @#if@ as a comment after its @#endif@. Cimple needs a+-- comment there, so if we can't read the condition back as one, it just says+-- @#if@.+endifComment :: Doc AnsiStyle -> Doc AnsiStyle+endifComment cond+    | readable = pretty "  /*" <+> cond <+> pretty "*/"+    | otherwise = pretty "  /* #if */"+  where+    comment = Text.pack "/* " <> render (plain cond) <> Text.pack " */"+    readable = case alexScanTokens (LBS.fromStrict (Text.encodeUtf8 comment)) of+        Right tokens -> ErrorToken `notElem` map lexemeClass tokens && map lexemeClass (take 1 (reverse tokens)) == [CmtEnd]+        Left _       -> False+ ppCommentStart :: CommentStyle -> Doc AnsiStyle ppCommentStart = dullyellow . \case     Block   -> pretty "/***"@@ -90,7 +106,8 @@  ppComment :: CommentStyle -> [Lexeme (Doc AnsiStyle)] -> Lexeme (Doc AnsiStyle) -> Doc AnsiStyle ppComment Ignore cs _ =-    ppCommentStart Ignore <> hcat (map ppWord cs) <> dullyellow (pretty "//!TOKSTYLE+" <> line)+    -- The ignored code keeps its own indentation, or every print would add to it.+    ppCommentStart Ignore <> nesting (\i -> nest (negate i) (hcat (map ppWord cs))) <> dullyellow (pretty "//!TOKSTYLE+" <> line) ppComment style cs end =     nest 1 $ ppCommentStart style <> ppCommentBody (cs ++ [end]) @@ -201,8 +218,16 @@     . plain  ppNode :: Pretty a => Node (Lexeme a) -> Doc AnsiStyle-ppNode = foldFix ppNodeF+ppNode = snd . foldFix (\n -> (Fix (fst <$> n), ppNodeWith (fst <$> n) (snd <$> n))) +-- | Like 'ppNodeF', but also sees the children's nodes.+ppNodeWith :: Pretty a => NodeF (Lexeme a) (Node (Lexeme a)) -> NodeF (Lexeme a) (Doc AnsiStyle) -> Doc AnsiStyle+ppNodeWith (UnaryExpr outer (Fix (UnaryExpr inner _))) (UnaryExpr _ e)+    -- Otherwise @& &x@ prints as @&&x@ and @- -x@ as @--x@.+    | (outer, inner) `elem` [(UopAddress, UopAddress), (UopMinus, UopMinus), (UopMinus, UopDecr)] =+        ppUnaryOp outer <+> e+ppNodeWith _ doc = ppNodeF doc+ ppNodeF :: Pretty a => NodeF (Lexeme a) (Doc AnsiStyle) -> Doc AnsiStyle ppNodeF = \case     StaticAssert cond msg ->@@ -302,7 +327,7 @@         dullmagenta (pretty "#if" <+> cond) <> line <>         ppToplevel decls <>         elseBranch <> line <>-        dullmagenta (pretty "#endif  /*" <+> cond <+> pretty "*/")+        dullmagenta (pretty "#endif" <> endifComment cond)     PreprocIfdef name decls elseBranch ->         dullmagenta (pretty "#ifdef" <+> ppLexeme name) <> line <>         ppToplevel decls <>@@ -326,6 +351,8 @@      AttrPrintf fmt ellipsis fun ->         kwGnuPrintf <> ppIntList [fmt, ellipsis] <> line <> fun+    AttrAllocSize sizes fun ->+        kwGnuAllocSize <> ppIntList sizes <> line <> fun     CallbackDecl ty name ->         ppLexeme ty <+> ppLexeme name     FunctionPrototype ty name params ->
src/Language/Cimple/PrettyComment.hs view
@@ -69,6 +69,9 @@     DocReturn         -> kwDocReturn     DocRetval         -> kwDocRetval     DocSee name       -> kwDocSee        <+> ppRef name+    DocThread role    -> kwDocThread     <+> ppLexeme role+    DocGuardedBy lock -> kwDocGuardedBy  <+> ppLexeme lock+    DocRequires p f   -> kwDocRequires <> pretty '(' <> ppLexeme p <> pretty ',' <+> ppLexeme f <> pretty ')'     DocRef name         -> kwDocRef        <+> ppRef name     DocP name           -> kwDocP          <+> ppRef name     DocExtends feat     -> kwDocExtends    <+> ppLexeme feat
src/Language/Cimple/PrettyCommon.hs view
@@ -31,6 +31,7 @@ kwFor             = dullred   $ pretty "for" kwForce           = dullgreen $ pretty "force" kwGnuPrintf       = dullgreen $ pretty "GNU_PRINTF"+kwGnuAllocSize    = dullgreen $ pretty "GNU_ALLOC_SIZE" kwGoto            = dullred   $ pretty "goto" kwIf              = dullred   $ pretty "if" kwNonnull         = dullgreen $ pretty "_Nonnull"@@ -59,6 +60,9 @@ kwDocRetval       = dullcyan $ pretty "@retval" kwDocP            = dullcyan $ pretty "@p" kwDocSee          = dullcyan $ pretty "@see"+kwDocThread       = dullcyan $ pretty "@thread"+kwDocGuardedBy    = dullcyan $ pretty "@guarded_by"+kwDocRequires     = dullcyan $ pretty "@requires" kwDocSecurityRank = dullcyan $ pretty "@security_rank" kwDocNote         = dullcyan $ pretty "@note" kwDocSection      = dullcyan $ pretty "@section"@@ -77,8 +81,8 @@     AopBitOr  -> pretty "|="     AopBitXor -> pretty "^="     AopMod    -> pretty "%="-    AopLsh    -> pretty ">>="-    AopRsh    -> pretty "<<="+    AopLsh    -> pretty "<<="+    AopRsh    -> pretty ">>="  ppBinaryOp :: BinaryOp -> Doc AnsiStyle ppBinaryOp = \case
src/Language/Cimple/Tokens.hs view
@@ -28,6 +28,7 @@     | KwExtern     | KwFor     | KwForce+    | KwGnuAllocSize     | KwGnuPrintf     | KwGoto     | KwIf
src/Language/Cimple/TraverseAst.hs view
@@ -118,6 +118,16 @@         DocSee ref -> do             _ <- recurse ref             pure ()+        DocThread role -> do+            _ <- recurse role+            pure ()+        DocGuardedBy lock -> do+            _ <- recurse lock+            pure ()+        DocRequires param field -> do+            _ <- recurse param+            _ <- recurse field+            pure ()         DocSecurityRank kw mparam rank -> do             _ <- recurse kw             _ <- recurse mparam@@ -423,6 +433,10 @@         AttrPrintf fmt ellipsis fun -> do             _ <- recurse fmt             _ <- recurse ellipsis+            _ <- recurse fun+            pure ()+        AttrAllocSize sizes fun -> do+            _ <- recurse sizes             _ <- recurse fun             pure ()         FunctionDecl _scope proto ->
src/Language/Cimple/TreeParser.y view
@@ -123,6 +123,7 @@     ellipsis		{ Fix (Ellipsis) }     nonNull		{ Fix (NonNull{}) }     attrPrintf		{ Fix (AttrPrintf{}) }+    attrAllocSize	{ Fix (AttrAllocSize{}) }     -- Constants     constDecl		{ Fix (ConstDecl{}) }     constDefn		{ Fix (ConstDefn{}) }@@ -151,6 +152,7 @@ |	functionDefn						{ $1 } |	nonNull							{ $1 } |	attrPrintf						{ $1 }+|	attrAllocSize						{ $1 } |	aggregateDecl						{% processAggregate $1 } |	struct							{% processAggregate $1 } |	union							{% processAggregate $1 }
+ test/Language/Cimple/ArbitrarySpec.hs view
@@ -0,0 +1,44 @@+{-# LANGUAGE OverloadedStrings #-}+module Language.Cimple.ArbitrarySpec (spec) where++import qualified Data.ByteString.Lazy   as LBS+import qualified Data.Text              as Text+import qualified Data.Text.Encoding     as Text+import           Language.Alex.Parser   (parseAlex)+import           Language.Cimple        (alexScanTokens, lexemeClass)+import           Language.Cimple.IO     (parseText)+import           Language.Cimple.Pretty (plain, ppTranslationUnit, render)+import qualified Language.Happy         as Happy+import           Language.Happy.Linker  (Lexer, defaultLinkConfig,+                                         generateChecked)+import           System.Directory       (doesFileExist)+import           Test.Hspec             (Spec, describe, it, runIO, shouldBe)+import           Test.QuickCheck        (forAll, suchThatMap)++-- | Finds a source file from Bazel's or cabal's working directory.+sourceFile :: FilePath -> IO FilePath+sourceFile path = do+    let bazelPath = "hs-cimple/" ++ path+    inBazel <- doesFileExist bazelPath+    return $ if inBazel then bazelPath else path++cimpleLexer :: Lexer+cimpleLexer =+    either (const Nothing) (Just . map (Text.pack . show . lexemeClass))+    . alexScanTokens . LBS.fromStrict . Text.encodeUtf8++spec :: Spec+spec = describe "arbitrary programs" $ do+    alex <- runIO $ either error id . parseAlex . Text.decodeUtf8 . LBS.toStrict <$> (LBS.readFile =<< sourceFile "src/Language/Cimple/Lexer.x")+    grammar <- runIO $ LBS.readFile =<< sourceFile "src/Language/Cimple/Parser.y"+    let happy = either error id $ Happy.runAlex grammar Happy.parseGrammar+        -- The grammar doesn't have the checks in the parser's actions and the+        -- tree pass, so we drop the programs they reject.+        programs = generateChecked defaultLinkConfig alex cimpleLexer "TranslationUnit" happy+            `suchThatMap` \code -> (,) code <$> either (const Nothing) Just (parseText code)++    it "print the same after parsing what they printed" $+        forAll programs $ \(_, ast) ->+            let printed = pp ast in pp <$> parseText printed `shouldBe` Right printed+  where+    pp = render . plain . ppTranslationUnit
test/Language/Cimple/AstSpec.hs view
@@ -147,6 +147,7 @@              -- Functions             test (AttrPrintf "l" "l'" "a") (AttrPrintf "l-l" "l-l'" "a-a")+            test (AttrAllocSize ["l"] "a") (AttrAllocSize ["l-l"] "a-a")             test (FunctionDecl Global "a") (FunctionDecl Global "a-a")             test (FunctionDefn Global "a" "a'") (FunctionDefn Global "a-a" "a-a'")             test (FunctionPrototype "a" "l" ["as"]) (FunctionPrototype "a-a" "l-l" ["a-as"])
test/Language/Cimple/CommentParserSpec.hs view
@@ -203,6 +203,33 @@                 ]             `shouldSatisfy` isRight1 +        it "should parse @thread" $+            parseLines+                [ "/**"+                , " * @thread any"+                , " */"+                , "void send_frame(void);"+                ]+            `shouldSatisfy` isRight1++        it "should parse @guarded_by" $+            parseLines+                [ "struct Call {"+                , "  /** @guarded_by mutex */"+                , "  int bit_rate;"+                , "};"+                ]+            `shouldSatisfy` isRight1++        it "should parse @requires" $+            parseLines+                [ "/**"+                , " * @requires(call, mutex)"+                , " */"+                , "void call_send(Call *call);"+                ]+            `shouldSatisfy` isRight1+         it "should parse a complex comment" $             parseLines                 [ "/**"
test/Language/Cimple/ParserSpec.hs view
@@ -10,8 +10,9 @@ import qualified Data.Text           as Text import           Language.Cimple     (AlexPosn (..), Lexeme (..),                                       LexemeClass (..), Node, NodeF (..),-                                      Scope (..), UnaryOp (..),-                                      formatParseError, preprocessorEnabled)+                                      Nullability (..), Scope (..),+                                      UnaryOp (..), formatParseError,+                                      preprocessorEnabled) import           Language.Cimple.IO  (parseExpr, parseStmt, parseText) import           Language.CimpleSpec (sampleToken) import           Test.Hspec          (Spec, describe, expectationFailure, it,@@ -146,6 +147,25 @@             case ast of                 Right [Fix (FunctionDecl _ (Fix (FunctionPrototype _ _ [Fix (VarDecl (Fix (TyPointer (Fix (TyNonnull (Fix (TyStd _)))))) (L _ _ "p") [])])))] -> return ()                 _ -> expectationFailure $ "Unexpected AST: " ++ show ast++        it "reads /*! _Nullable */ and /*! _Nonnull */ as the qualifiers" $ do+            case parseText "char * /*! _Nonnull */ f(const int * /*! _Nullable */ p);" of+                Right [Fix (FunctionDecl _ (Fix (FunctionPrototype+                    (Fix (TyNonnull (Fix (TyPointer _)))) _+                    [Fix (VarDecl (Fix (TyNullable (Fix (TyPointer _)))) (L _ _ "p") [])])))] -> return ()+                ast -> expectationFailure $ "Unexpected AST: " ++ show ast++        it "reads /*! _Nullable */ in an array parameter as its nullability" $ do+            case parseText "void f(const uint8_t a[/*! _Nullable */ 32], const uint8_t b[/*! _Nonnull */]);" of+                Right [Fix (FunctionDecl _ (Fix (FunctionPrototype _ _+                    [ Fix (VarDecl _ (L _ _ "a") [Fix (DeclSpecArray Nullable (Just _))])+                    , Fix (VarDecl _ (L _ _ "b") [Fix (DeclSpecArray Nonnull Nothing)])+                    ])))] -> return ()+                ast -> expectationFailure $ "Unexpected AST: " ++ show ast++        it "should parse a function returning a nullable callback" $ do+            let ast = parseText "tox_log_cb *_Nullable tox_options_get_log_callback(void);"+            ast `shouldSatisfy` isRight1          it "supports single declarators" $ do             let ast = parseText "int main() { int a; }"
test/Language/Cimple/PrettySpec.hs view
@@ -95,6 +95,22 @@                 , "} Foo;"                 ] +        it "pretty-prints an allocation size attribute" $ do+            pretty "GNU_ALLOC_SIZE(2) void *mem_balloc(const Memory *mem, uint32_t size);" `shouldBe` unlines+                [ "GNU_ALLOC_SIZE(2)"+                , "void* mem_balloc(Memory const* mem, uint32_t size);"+                ]+            pretty "GNU_ALLOC_SIZE(2, 3) void *mem_valloc(const Memory *mem, uint32_t nmemb, uint32_t size);" `shouldBe` unlines+                [ "GNU_ALLOC_SIZE(2, 3)"+                , "void* mem_valloc(Memory const* mem, uint32_t nmemb, uint32_t size);"+                ]++        it "pretty-prints an allocation size attribute on a function type" $ do+            pretty "GNU_ALLOC_SIZE(3) typedef void *realloc_cb(void *self, void *ptr, uint32_t size);" `shouldBe` unlines+                [ "GNU_ALLOC_SIZE(3)"+                , "typedef void* realloc_cb(void* self, void* ptr, uint32_t size);"+                ]+     describe "renderCompact" $ do         it "pretty-prints a simple C function" $ do             let pp = compact "int a(void) { return 3; }"
test/Language/CimpleSpec.hs view
@@ -28,6 +28,7 @@     KwExtern              -> "extern"     KwFor                 -> "for"     KwForce               -> "force"+    KwGnuAllocSize        -> "gnu_alloc_size"     KwGnuPrintf           -> "gnu_printf"     KwGoto                -> "goto"     KwIf                  -> "if"