aboutsummaryrefslogtreecommitdiff
path: root/tp-bbcode
diff options
context:
space:
mode:
authorGregor Kleen <gkleen@yggdrasil.li>2016-01-18 12:09:36 +0000
committerGregor Kleen <gkleen@yggdrasil.li>2016-01-18 12:09:36 +0000
commit57c56564d15cd5c83a4f1d1bab5490e6b75e8656 (patch)
tree55ea741665155b46b9e599b149dee3323fe479c0 /tp-bbcode
parent9435083465a487553b21c599c1340aa5e5ed8a1c (diff)
downloadthermoprint-57c56564d15cd5c83a4f1d1bab5490e6b75e8656.tar
thermoprint-57c56564d15cd5c83a4f1d1bab5490e6b75e8656.tar.gz
thermoprint-57c56564d15cd5c83a4f1d1bab5490e6b75e8656.tar.bz2
thermoprint-57c56564d15cd5c83a4f1d1bab5490e6b75e8656.tar.xz
thermoprint-57c56564d15cd5c83a4f1d1bab5490e6b75e8656.zip
Moved Printout.BBCode to own module
Diffstat (limited to 'tp-bbcode')
-rw-r--r--tp-bbcode/LICENSE27
-rw-r--r--tp-bbcode/Setup.hs2
-rw-r--r--tp-bbcode/src/Thermoprint/Printout/BBCode.hs145
-rw-r--r--tp-bbcode/src/Thermoprint/Printout/BBCode/Attribute.hs39
-rw-r--r--tp-bbcode/test/Spec.hs1
-rw-r--r--tp-bbcode/test/Thermoprint/Printout/BBCodeSpec.hs42
-rw-r--r--tp-bbcode/thermoprint-bbcode.cabal50
-rw-r--r--tp-bbcode/thermoprint-bbcode.nix19
8 files changed, 325 insertions, 0 deletions
diff --git a/tp-bbcode/LICENSE b/tp-bbcode/LICENSE
new file mode 100644
index 0000000..4ad71e2
--- /dev/null
+++ b/tp-bbcode/LICENSE
@@ -0,0 +1,27 @@
1Statement of Purpose
2
3The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work").
4
5Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others.
6
7For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights.
8
91. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following:
10
11the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work;
12moral rights retained by the original author(s) and/or performer(s);
13publicity and privacy rights pertaining to a person's image or likeness depicted in a Work;
14rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below;
15rights protecting the extraction, dissemination, use and reuse of data in a Work;
16database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and
17other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof.
182. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose.
19
203. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose.
21
224. Limitations and Disclaimers.
23
24No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document.
25Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law.
26Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work.
27Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. \ No newline at end of file
diff --git a/tp-bbcode/Setup.hs b/tp-bbcode/Setup.hs
new file mode 100644
index 0000000..9a994af
--- /dev/null
+++ b/tp-bbcode/Setup.hs
@@ -0,0 +1,2 @@
1import Distribution.Simple
2main = defaultMain
diff --git a/tp-bbcode/src/Thermoprint/Printout/BBCode.hs b/tp-bbcode/src/Thermoprint/Printout/BBCode.hs
new file mode 100644
index 0000000..ce2aa43
--- /dev/null
+++ b/tp-bbcode/src/Thermoprint/Printout/BBCode.hs
@@ -0,0 +1,145 @@
1{-# LANGUAGE OverloadedStrings #-}
2{-# LANGUAGE DeriveGeneric #-}
3{-# LANGUAGE GADTs #-}
4
5-- | Use 'Text.BBCode' to parse BBCode
6module Thermoprint.Printout.BBCode
7 ( bbcode
8 , BBCodeError(..)
9 , TreeError(..)
10 , SemanticError(..)
11 ) where
12
13import Data.Text (Text)
14import Data.Map (Map)
15
16import qualified Data.Text.Lazy as Lazy (Text)
17import qualified Data.Text.Lazy as TL (fromStrict)
18
19import Data.Sequence (Seq)
20import qualified Data.Sequence as Seq (fromList, singleton)
21
22import Data.CaseInsensitive (CI)
23import qualified Data.CaseInsensitive as CI
24
25import GHC.Generics (Generic)
26import Control.Exception (Exception)
27import Data.Typeable (Typeable)
28
29import Data.Bifunctor (bimap, first)
30import Control.Monad (join)
31
32import Data.List (groupBy)
33
34import Text.BBCode (DomForest, DomTree(..), TreeError(..))
35import qualified Text.BBCode as Raw (bbcode, BBCodeError(..))
36
37import Thermoprint.Printout
38
39import Thermoprint.Printout.BBCode.Attribute
40
41-- ^ We replicate 'Raw.BBCodeError' but add a new failure mode documenting incompatibly of the parsed syntax tree with our document format
42data BBCodeError = LexerError String -- ^ Error while parsing input to stream of tokens
43 | TreeError TreeError -- ^ Error while parsing stream of tokens to syntax tree
44 | SemanticError SemanticError -- ^ Error while mapping syntax tree to document format
45 deriving (Show, Eq, Generic, Typeable)
46
47instance Exception BBCodeError
48
49morph' :: Raw.BBCodeError -> BBCodeError
50-- ^ Transform 'Raw.BBCodeError' to 'BBCodeError'
51morph' (Raw.LexerError x) = LexerError x
52morph' (Raw.TreeError x) = TreeError x
53
54-- | An error ocurred while parsing the DOM-Forest (`['DomTree']`)
55data SemanticError = BlockInLineContext -- ^ A 'Block' structure was encountered when a 'Line' was expected
56 | LineInBlockContext -- ^ A 'Line' structure was encountered when a 'Block' was expected
57 | UnmappedBlockElement Text -- ^ We encountered an 'Element' that, in a 'Block' context, does not map to any structure
58 | UnmappedLineElement Text -- ^ We encountered an 'Element' that, in a 'Line' context, does not map to any structure
59 deriving (Show, Eq, Generic, Typeable)
60
61instance Exception SemanticError
62
63-- | Result of parsing a single 'DomTree'
64data ParseResult = RBlock Block -- ^ Parses only as 'Block'
65 | RLine Line -- ^ Parses only as 'Line'
66 | RAmbiguous Block Line -- ^ Parses as either 'Block' or 'Line' depending on context
67 | RNoParse SemanticError SemanticError -- ^ Does not parse as either 'Block' or 'Line'
68 deriving (Show)
69
70-- | Current parser context
71data Context a where
72 BlockCtx :: Context Block
73 LineCtx :: Context Line
74
75extract :: Context a -> ParseResult -> Either SemanticError a
76-- ^ Extract information from a 'ParseResult' given 'Context'
77extract BlockCtx (RBlock b) = Right b
78extract LineCtx (RLine l) = Right l
79extract BlockCtx (RAmbiguous b _) = Right b
80extract LineCtx (RAmbiguous _ l) = Right l
81extract BlockCtx (RNoParse bErr _) = Left bErr
82extract LineCtx (RNoParse _ lErr) = Left lErr
83extract BlockCtx _ = Left LineInBlockContext
84extract LineCtx _ = Left BlockInLineContext
85
86hasBlockCtx :: ParseResult -> Bool
87-- ^ Result can be 'extract'ed in a 'Block' 'Context'
88hasBlockCtx (RLine _) = False
89hasBlockCtx _ = True
90
91hasLineCtx :: ParseResult -> Bool
92-- ^ Result can be 'extract'ed in a 'Line' 'Context'
93hasLineCtx (RBlock _) = False
94hasLineCtx _ = True
95
96bbcode :: Text -> Either BBCodeError Printout
97-- ^ Parse BBCode
98bbcode = join . fmap (first SemanticError) . bimap morph' morph . Raw.bbcode
99
100morph :: DomForest -> Either SemanticError Printout
101-- ^ Parse a list of paragraphs
102--
103-- Since we permit only cooked input via 'Raw' 'Paragraph' is identical to 'Block'
104morph = fmap Seq.fromList . mapM (\t -> Seq.singleton . Cooked <$> parse BlockCtx t)
105
106parseDom :: DomTree -> ParseResult
107-- ^ Invoke 'asLine' and 'asBlock' to parse a single 'DomTree'
108parseDom (Content t) = either RBlock (\l -> RAmbiguous (Line l) l) . text . TL.fromStrict $ t
109parseDom (Element t attrs cs)
110 | Right blockParse' <- blockParse
111 , Right lineParse' <- lineParse = RAmbiguous blockParse' lineParse'
112 | Right blockParse' <- blockParse = RBlock blockParse'
113 | Right lineParse' <- lineParse = RLine lineParse'
114 | Left bErr <- blockParse
115 , Left lErr <- lineParse = RNoParse bErr lErr
116 where
117 blockParse = asBlock t cs attrs
118 lineParse = asLine t cs attrs
119
120mergeResult :: Monoid a => Context a -> [ParseResult] -> Either SemanticError a
121-- ^ Merge a list of 'ParseResults' in a certain 'Context'
122mergeResult _ [] = Right mempty
123mergeResult ctx (amb@(RAmbiguous _ _):xs) = mappend <$> extract ctx amb <*> mergeResult ctx xs
124mergeResult ctx (err@(RNoParse _ _):_) = extract ctx err
125mergeResult ctx (x:xs) = mappend <$> extract ctx x <*> mergeResult ctx xs
126
127parse :: Monoid a => Context a -> [DomTree] -> Either SemanticError a
128-- ^ Parse a list of 'DomTree's in a certain 'Context'
129--
130-- @parse ctx = 'mergeResult' ctx . map 'parseDom'@
131parse BlockCtx = fmap mconcat . mapM mergeResult' . groupBy sameCtx . map parseDom
132 where
133 sameCtx a b = (hasLineCtx a && hasLineCtx b) || (hasBlockCtx a && hasBlockCtx b)
134 mergeResult' xs
135 | hasLineCtx `all` xs = Line <$> mergeResult LineCtx xs
136 | otherwise = mergeResult BlockCtx xs
137parse ctx = mergeResult ctx . map parseDom
138
139asBlock :: CI Text -> [DomTree] -> Map (CI Text) Text -> Either SemanticError Block
140asBlock "VSpace" _ = Right . VSpace . lookupAttr "height" True 1
141asBlock t _ = const $ Left . UnmappedBlockElement . CI.original $ t
142
143asLine :: CI Text -> [DomTree] -> Map (CI Text) Text -> Either SemanticError Line
144asLine "HSpace" _ = Right . HSpace . lookupAttr "width" True 1
145asLine t _ = const $ Left . UnmappedLineElement . CI.original $ t
diff --git a/tp-bbcode/src/Thermoprint/Printout/BBCode/Attribute.hs b/tp-bbcode/src/Thermoprint/Printout/BBCode/Attribute.hs
new file mode 100644
index 0000000..538cca2
--- /dev/null
+++ b/tp-bbcode/src/Thermoprint/Printout/BBCode/Attribute.hs
@@ -0,0 +1,39 @@
1{-# LANGUAGE DefaultSignatures #-}
2
3-- | Parsing attributes
4module Thermoprint.Printout.BBCode.Attribute
5 ( Attribute(..)
6 , lookupAttr
7 ) where
8
9import Data.Text (Text)
10import qualified Data.Text as T (unpack, empty)
11
12import Data.Map (Map)
13import qualified Data.Map as Map (lookup)
14
15import Data.CaseInsensitive (CI)
16import qualified Data.CaseInsensitive as CI
17
18import Text.Read (readMaybe)
19import Data.Maybe (fromMaybe)
20
21import Control.Applicative (Alternative(..))
22
23-- | We build our own version of 'Read' so we can override the presentation used
24--
25-- We provide a default implementation for 'Read a => Attribute a'
26class Attribute a where
27 attrRead :: Text -> Maybe a
28 default attrRead :: Read a => Text -> Maybe a
29 attrRead = readMaybe . T.unpack
30
31instance Attribute Integer
32
33lookupAttr :: Attribute a => CI Text -> Bool -> a -> Map (CI Text) Text -> a
34-- ^ Extract an attribute by name -- the 'Bool' attribute specifies whether we additionally accept the empty string as key
35lookupAttr t emptyOk def attrs = fromMaybe def $ (emptyOk' $ Map.lookup t attrs) >>= attrRead
36 where
37 emptyOk'
38 | emptyOk = (<|> Map.lookup (CI.mk T.empty) attrs)
39 | otherwise = id
diff --git a/tp-bbcode/test/Spec.hs b/tp-bbcode/test/Spec.hs
new file mode 100644
index 0000000..a824f8c
--- /dev/null
+++ b/tp-bbcode/test/Spec.hs
@@ -0,0 +1 @@
{-# OPTIONS_GHC -F -pgmF hspec-discover #-}
diff --git a/tp-bbcode/test/Thermoprint/Printout/BBCodeSpec.hs b/tp-bbcode/test/Thermoprint/Printout/BBCodeSpec.hs
new file mode 100644
index 0000000..f3f1840
--- /dev/null
+++ b/tp-bbcode/test/Thermoprint/Printout/BBCodeSpec.hs
@@ -0,0 +1,42 @@
1{-# LANGUAGE OverloadedStrings, OverloadedLists #-}
2{-# LANGUAGE StandaloneDeriving #-}
3
4module Thermoprint.Printout.BBCodeSpec (spec) where
5
6import Test.Hspec
7import Test.Hspec.QuickCheck (prop)
8import Test.QuickCheck.Instances
9
10import Thermoprint.Printout.BBCode
11import Thermoprint.Printout
12
13import Data.Text (Text)
14
15import Control.Monad (zipWithM_)
16import Data.Monoid ((<>))
17import Data.Function (on)
18
19import qualified Data.Sequence as Seq (fromList)
20
21instance Eq Block where
22 (==) = (==) `on` cotext
23deriving instance Eq Chunk
24
25spec :: Spec
26spec = do
27 zipWithM_ example [1..] examples
28 where
29 example n (s, ts) = let str = "Example " <> show n
30 in specify str $ bbcode s == (pOut <$> ts)
31
32pOut :: [Block] -> Printout
33pOut = pure . Seq.fromList . map Cooked
34
35examples :: [(Text, Either BBCodeError [Block])]
36examples = [ ("Hello World!"
37 , Right [Line (JuxtaPos [word "Hello", HSpace 1, word "World!"])])
38 , ("Hello [hspace width=2/] World!"
39 , Right [Line (JuxtaPos [word "Hello", HSpace 4, word "World!"])])
40 ]
41 where
42 word = (\(Right l) -> l) . text
diff --git a/tp-bbcode/thermoprint-bbcode.cabal b/tp-bbcode/thermoprint-bbcode.cabal
new file mode 100644
index 0000000..b9cb655
--- /dev/null
+++ b/tp-bbcode/thermoprint-bbcode.cabal
@@ -0,0 +1,50 @@
1-- Initial thermoprint-bbcode.cabal generated by cabal init. For further
2-- documentation, see http://haskell.org/cabal/users-guide/
3
4name: thermoprint-bbcode
5version: 0.0.0
6synopsis: Parse bbcode for use in thermoprint
7-- description:
8homepage: http://dirty-haskell.org/tags/thermoprint.html
9license: PublicDomain
10license-file: LICENSE
11author: Gregor Kleen
12maintainer: aethoago@141.li
13-- copyright:
14category: Text
15build-type: Simple
16-- extra-source-files:
17cabal-version: >=1.10
18
19library
20 exposed-modules: Thermoprint.Printout.BBCode
21 other-modules: Thermoprint.Printout.BBCode.Attribute
22 extensions: OverloadedStrings
23 , OverloadedLists
24 -- other-extensions:
25 build-depends: base >=4.8.1 && <5
26 , thermoprint-spec ==2.0.*
27 , bbcode >=3.0 && <4
28 , containers -any
29 , text -any
30 , case-insensitive -any
31 hs-source-dirs: src
32 default-language: Haskell2010
33
34Test-Suite tests
35 type: exitcode-stdio-1.0
36 hs-source-dirs: test
37 main-is: Spec.hs
38 ghc-options: -threaded -with-rtsopts=-N
39 extensions: StandaloneDeriving
40 , OverloadedStrings
41 , OverloadedLists
42 build-depends: base >=4.8.1 && <5
43 , thermoprint-bbcode -any
44 , thermoprint-spec ==2.0.*
45 , hspec >=2.2.1 && <3
46 , QuickCheck >=2.8.1 && <3
47 , quickcheck-instances >=0.3.11 && <4
48 , aeson >=0.9.0 && <1
49 , containers -any
50 , text -any \ No newline at end of file
diff --git a/tp-bbcode/thermoprint-bbcode.nix b/tp-bbcode/thermoprint-bbcode.nix
new file mode 100644
index 0000000..9a48152
--- /dev/null
+++ b/tp-bbcode/thermoprint-bbcode.nix
@@ -0,0 +1,19 @@
1{ mkDerivation, aeson, base, bbcode, case-insensitive, containers
2, hspec, QuickCheck, quickcheck-instances, stdenv, text
3, thermoprint-spec
4}:
5mkDerivation {
6 pname = "thermoprint-bbcode";
7 version = "0.0.0";
8 src = ./.;
9 libraryHaskellDepends = [
10 base bbcode case-insensitive containers text thermoprint-spec
11 ];
12 testHaskellDepends = [
13 aeson base containers hspec QuickCheck quickcheck-instances text
14 thermoprint-spec
15 ];
16 homepage = "http://dirty-haskell.org/tags/thermoprint.html";
17 description = "Parse bbcode for use in thermoprint";
18 license = stdenv.lib.licenses.publicDomain;
19}